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
41using namespace llvm;
42using namespace MIPatternMatch;
43
44Register llvm::constrainRegToClass(MachineRegisterInfo &MRI,
45 const TargetInstrInfo &TII,
46 const RegisterBankInfo &RBI, Register Reg,
47 const TargetRegisterClass &RegClass) {
48 if (!RBI.constrainGenericRegister(Reg, RC: RegClass, MRI))
49 return MRI.createVirtualRegister(RegClass: &RegClass);
50
51 return Reg;
52}
53
54Register 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(BB&: MBB, I: InsertIt, MIMD: InsertPt.getDebugLoc(),
78 MCID: TII.get(Opcode: TargetOpcode::COPY), DestReg: ConstrainedReg)
79 .addReg(RegNo: Reg);
80 } else {
81 assert(RegMO.isDef() && "Must be a definition");
82 BuildMI(BB&: MBB, I: std::next(x: InsertIt), MIMD: InsertPt.getDebugLoc(),
83 MCID: TII.get(Opcode: TargetOpcode::COPY), DestReg: Reg)
84 .addReg(RegNo: ConstrainedReg);
85 }
86 if (GISelChangeObserver *Observer = MF.getObserver()) {
87 Observer->changingInstr(MI&: *RegMO.getParent());
88 }
89 RegMO.setReg(ConstrainedReg);
90 if (GISelChangeObserver *Observer = MF.getObserver()) {
91 Observer->changedInstr(MI&: *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(MI&: *RegDef);
98 }
99 Observer->changingAllUsesOfReg(MRI, Reg);
100 Observer->finishedChangingAllUsesOfReg();
101 }
102 }
103 return ConstrainedReg;
104}
105
106Register 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(MCID: II, OpNum: OpIdx, TRI: &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 A: OpRC, B: TRI.getConstrainedRegClassForOperand(MO: RegMO, MRI)))
128 OpRC = SubRC;
129
130 OpRC = TRI.getAllocatableClass(RC: 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, RegClass: *OpRC,
150 RegMO);
151}
152
153bool 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(i: 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, InsertPt&: I, II: I.getDesc(), RegMO&: MO, OpIdx: 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(OpNum: OpI, Constraint: MCOI::TIED_TO);
192 if (DefIdx != -1 && !I.isRegTiedToUseOperand(DefOpIdx: DefIdx))
193 I.tieOperands(DefIdx, UseIdx: OpI);
194 }
195 }
196 return true;
197}
198
199bool 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(Reg: DstReg) != MRI.getType(Reg: SrcReg))
206 return false;
207 // Replace if either DstReg has no constraints or the register
208 // constraints match.
209 const auto &DstRBC = MRI.getRegClassOrRegBank(Reg: DstReg);
210 if (!DstRBC || DstRBC == MRI.getRegClassOrRegBank(Reg: 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(Reg: SrcReg) &&
216 DstRBC.get<const RegisterBank *>()->covers(
217 RC: *MRI.getRegClassOrNull(Reg: SrcReg));
218}
219
220bool 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(RegNo: Reg))
244 return false;
245 }
246 return true;
247}
248
249static 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(reason: Twine(R.getMsg()));
263 else
264 MORE.emit(OptDiag&: R);
265}
266
267void llvm::reportGISelWarning(MachineFunction &MF, const TargetPassConfig &TPC,
268 MachineOptimizationRemarkEmitter &MORE,
269 MachineOptimizationRemarkMissed &R) {
270 reportGISelDiagnostic(Severity: DS_Warning, MF, TPC, MORE, R);
271}
272
273void llvm::reportGISelFailure(MachineFunction &MF, const TargetPassConfig &TPC,
274 MachineOptimizationRemarkEmitter &MORE,
275 MachineOptimizationRemarkMissed &R) {
276 MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
277 reportGISelDiagnostic(Severity: DS_Error, MF, TPC, MORE, R);
278}
279
280void 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
293std::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
304std::optional<int64_t>
305llvm::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
312namespace {
313
314typedef std::function<bool(const MachineInstr *)> IsOpcodeFn;
315typedef std::function<std::optional<APInt>(const MachineInstr *MI)> GetAPCstFn;
316
317std::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(Reg: 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(Elt: std::make_pair(
335 x: MI->getOpcode(),
336 y: MRI.getType(Reg: MI->getOperand(i: 0).getReg()).getSizeInBits()));
337 VReg = MI->getOperand(i: 1).getReg();
338 break;
339 case TargetOpcode::COPY:
340 VReg = MI->getOperand(i: 1).getReg();
341 if (VReg.isPhysical())
342 return std::nullopt;
343 break;
344 case TargetOpcode::G_INTTOPTR:
345 VReg = MI->getOperand(i: 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(width: OpcodeAndSize.second);
363 break;
364 case TargetOpcode::G_ANYEXT:
365 case TargetOpcode::G_SEXT:
366 Val = Val.sext(width: OpcodeAndSize.second);
367 break;
368 case TargetOpcode::G_ZEXT:
369 Val = Val.zext(width: OpcodeAndSize.second);
370 break;
371 }
372 }
373
374 return ValueAndVReg{.Value: Val, .VReg: VReg};
375}
376
377bool isIConstant(const MachineInstr *MI) {
378 if (!MI)
379 return false;
380 return MI->getOpcode() == TargetOpcode::G_CONSTANT;
381}
382
383bool isFConstant(const MachineInstr *MI) {
384 if (!MI)
385 return false;
386 return MI->getOpcode() == TargetOpcode::G_FCONSTANT;
387}
388
389bool 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
396std::optional<APInt> getCImmAsAPInt(const MachineInstr *MI) {
397 const MachineOperand &CstVal = MI->getOperand(i: 1);
398 if (CstVal.isCImm())
399 return CstVal.getCImm()->getValue();
400 return std::nullopt;
401}
402
403std::optional<APInt> getCImmOrFPImmAsAPInt(const MachineInstr *MI) {
404 const MachineOperand &CstVal = MI->getOperand(i: 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
414std::optional<ValueAndVReg> llvm::getIConstantVRegValWithLookThrough(
415 Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs) {
416 return getConstantVRegValWithLookThrough(VReg, MRI, IsConstantOpcode: isIConstant,
417 getAPCstValue: getCImmAsAPInt, LookThroughInstrs);
418}
419
420std::optional<ValueAndVReg> llvm::getAnyConstantVRegValWithLookThrough(
421 Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs,
422 bool LookThroughAnyExt) {
423 return getConstantVRegValWithLookThrough(
424 VReg, MRI, IsConstantOpcode: isAnyConstant, getAPCstValue: getCImmOrFPImmAsAPInt, LookThroughInstrs,
425 LookThroughAnyExt);
426}
427
428std::optional<FPValueAndVReg> llvm::getFConstantVRegValWithLookThrough(
429 Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs) {
430 auto Reg = getConstantVRegValWithLookThrough(
431 VReg, MRI, IsConstantOpcode: isFConstant, getAPCstValue: getCImmOrFPImmAsAPInt, LookThroughInstrs);
432 if (!Reg)
433 return std::nullopt;
434 return FPValueAndVReg{.Value: getConstantFPVRegVal(VReg: Reg->VReg, MRI)->getValueAPF(),
435 .VReg: Reg->VReg};
436}
437
438const ConstantFP *
439llvm::getConstantFPVRegVal(Register VReg, const MachineRegisterInfo &MRI) {
440 MachineInstr *MI = MRI.getVRegDef(Reg: VReg);
441 if (TargetOpcode::G_FCONSTANT != MI->getOpcode())
442 return nullptr;
443 return MI->getOperand(i: 1).getFPImm();
444}
445
446std::optional<DefinitionAndSourceRegister>
447llvm::getDefSrcRegIgnoringCopies(Register Reg, const MachineRegisterInfo &MRI) {
448 Register DefSrcReg = Reg;
449 auto *DefMI = MRI.getVRegDef(Reg);
450 auto DstTy = MRI.getType(Reg: DefMI->getOperand(i: 0).getReg());
451 if (!DstTy.isValid())
452 return std::nullopt;
453 unsigned Opc = DefMI->getOpcode();
454 while (Opc == TargetOpcode::COPY || isPreISelGenericOptimizationHint(Opcode: Opc)) {
455 Register SrcReg = DefMI->getOperand(i: 1).getReg();
456 auto SrcTy = MRI.getType(Reg: SrcReg);
457 if (!SrcTy.isValid())
458 break;
459 DefMI = MRI.getVRegDef(Reg: SrcReg);
460 DefSrcReg = SrcReg;
461 Opc = DefMI->getOpcode();
462 }
463 return DefinitionAndSourceRegister{.MI: DefMI, .Reg: DefSrcReg};
464}
465
466MachineInstr *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
473Register 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
480void 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(Elt: MRI.createGenericVirtualRegister(Ty));
486 MIRBuilder.buildUnmerge(Res: VRegs, Op: Reg);
487}
488
489bool 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(Elt: MRI.createGenericVirtualRegister(Ty: MainTy));
505 MIRBuilder.buildUnmerge(Res: VRegs, Op: 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(NumElements: LeftoverNumElts, ScalarSizeInBits: RegTy.getScalarSizeInBits());
525
526 // Unmerge the SrcReg to LeftoverTy vectors
527 SmallVector<Register, 4> UnmergeValues;
528 extractParts(Reg, Ty: LeftoverTy, NumParts: RegNumElts / LeftoverNumElts, VRegs&: 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(Elt: UnmergeValues[I]);
540 if (MergeValues.size() == LeftoverPerMain) {
541 VRegs.push_back(
542 Elt: MIRBuilder.buildMergeLikeInstr(Res: MainTy, Ops: MergeValues).getReg(Idx: 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(Elt: 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, NumElts: MainTy.getNumElements(), VRegs&: RegPieces, MIRBuilder,
558 MRI);
559 for (unsigned i = 0; i < RegPieces.size() - 1; ++i)
560 VRegs.push_back(Elt: RegPieces[i]);
561 LeftoverRegs.push_back(Elt: RegPieces[RegPieces.size() - 1]);
562 LeftoverTy = MRI.getType(Reg: LeftoverRegs[0]);
563 return true;
564 }
565
566 LeftoverTy = LLT::scalar(SizeInBits: LeftoverSize);
567 // For irregular sizes, extract the individual parts.
568 for (unsigned I = 0; I != NumParts; ++I) {
569 Register NewReg = MRI.createGenericVirtualRegister(Ty: MainTy);
570 VRegs.push_back(Elt: NewReg);
571 MIRBuilder.buildExtract(Res: NewReg, Src: Reg, Index: MainSize * I);
572 }
573
574 for (unsigned Offset = MainSize * NumParts; Offset < RegSize;
575 Offset += LeftoverSize) {
576 Register NewReg = MRI.createGenericVirtualRegister(Ty: LeftoverTy);
577 LeftoverRegs.push_back(Elt: NewReg);
578 MIRBuilder.buildExtract(Res: NewReg, Src: Reg, Index: Offset);
579 }
580
581 return true;
582}
583
584void 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(NumElements: NumElts, ScalarTy: 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, Ty: NarrowTy, NumParts: 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, Ty: EltTy, NumParts: RegNumElts, VRegs&: 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(Elt: MIRBuilder.buildMergeLikeInstr(Res: NarrowTy, Ops: Pieces).getReg(Idx: 0));
613 }
614
615 // Leftover element(s).
616 if (LeftoverNumElts == 1) {
617 VRegs.push_back(Elt: Elts[Offset]);
618 } else {
619 LLT LeftoverTy = LLT::fixed_vector(NumElements: LeftoverNumElts, ScalarTy: EltTy);
620 ArrayRef<Register> Pieces(&Elts[Offset], LeftoverNumElts);
621 VRegs.push_back(
622 Elt: MIRBuilder.buildMergeLikeInstr(Res: LeftoverTy, Ops: Pieces).getReg(Idx: 0));
623 }
624}
625
626MachineInstr *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
632APFloat 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(ToSemantics: APFloat::IEEEhalf(), RM: APFloat::rmNearestTiesToEven, losesInfo: &Ignored);
642 return APF;
643}
644
645std::optional<APInt> llvm::ConstantFoldBinOp(unsigned Opcode,
646 const Register Op1,
647 const Register Op2,
648 const MachineRegisterInfo &MRI) {
649 auto MaybeOp2Cst = getAnyConstantVRegValWithLookThrough(VReg: Op2, MRI, LookThroughInstrs: false);
650 if (!MaybeOp2Cst)
651 return std::nullopt;
652
653 auto MaybeOp1Cst = getAnyConstantVRegValWithLookThrough(VReg: Op1, MRI, LookThroughInstrs: 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 case TargetOpcode::G_PTR_ADD:
664 return C1 + C2;
665 case TargetOpcode::G_AND:
666 return C1 & C2;
667 case TargetOpcode::G_ASHR:
668 return C1.ashr(ShiftAmt: C2);
669 case TargetOpcode::G_LSHR:
670 return C1.lshr(ShiftAmt: C2);
671 case TargetOpcode::G_MUL:
672 return C1 * C2;
673 case TargetOpcode::G_OR:
674 return C1 | C2;
675 case TargetOpcode::G_SHL:
676 return C1 << C2;
677 case TargetOpcode::G_SUB:
678 return C1 - C2;
679 case TargetOpcode::G_XOR:
680 return C1 ^ C2;
681 case TargetOpcode::G_UDIV:
682 if (!C2.getBoolValue())
683 break;
684 return C1.udiv(RHS: C2);
685 case TargetOpcode::G_SDIV:
686 if (!C2.getBoolValue())
687 break;
688 return C1.sdiv(RHS: C2);
689 case TargetOpcode::G_UREM:
690 if (!C2.getBoolValue())
691 break;
692 return C1.urem(RHS: C2);
693 case TargetOpcode::G_SREM:
694 if (!C2.getBoolValue())
695 break;
696 return C1.srem(RHS: C2);
697 case TargetOpcode::G_SMIN:
698 return APIntOps::smin(A: C1, B: C2);
699 case TargetOpcode::G_SMAX:
700 return APIntOps::smax(A: C1, B: C2);
701 case TargetOpcode::G_UMIN:
702 return APIntOps::umin(A: C1, B: C2);
703 case TargetOpcode::G_UMAX:
704 return APIntOps::umax(A: C1, B: C2);
705 }
706
707 return std::nullopt;
708}
709
710std::optional<APFloat>
711llvm::ConstantFoldFPBinOp(unsigned Opcode, const Register Op1,
712 const Register Op2, const MachineRegisterInfo &MRI) {
713 const ConstantFP *Op2Cst = getConstantFPVRegVal(VReg: Op2, MRI);
714 if (!Op2Cst)
715 return std::nullopt;
716
717 const ConstantFP *Op1Cst = getConstantFPVRegVal(VReg: Op1, MRI);
718 if (!Op1Cst)
719 return std::nullopt;
720
721 APFloat C1 = Op1Cst->getValueAPF();
722 const APFloat &C2 = Op2Cst->getValueAPF();
723 switch (Opcode) {
724 case TargetOpcode::G_FADD:
725 C1.add(RHS: C2, RM: APFloat::rmNearestTiesToEven);
726 return C1;
727 case TargetOpcode::G_FSUB:
728 C1.subtract(RHS: C2, RM: APFloat::rmNearestTiesToEven);
729 return C1;
730 case TargetOpcode::G_FMUL:
731 C1.multiply(RHS: C2, RM: APFloat::rmNearestTiesToEven);
732 return C1;
733 case TargetOpcode::G_FDIV:
734 C1.divide(RHS: C2, RM: APFloat::rmNearestTiesToEven);
735 return C1;
736 case TargetOpcode::G_FREM:
737 C1.mod(RHS: C2);
738 return C1;
739 case TargetOpcode::G_FCOPYSIGN:
740 C1.copySign(RHS: C2);
741 return C1;
742 case TargetOpcode::G_FMINNUM:
743 return minnum(A: C1, B: C2);
744 case TargetOpcode::G_FMAXNUM:
745 return maxnum(A: C1, B: C2);
746 case TargetOpcode::G_FMINIMUM:
747 return minimum(A: C1, B: C2);
748 case TargetOpcode::G_FMAXIMUM:
749 return maximum(A: C1, B: C2);
750 case TargetOpcode::G_FMINNUM_IEEE:
751 case TargetOpcode::G_FMAXNUM_IEEE:
752 // FIXME: These operations were unfortunately named. fminnum/fmaxnum do not
753 // follow the IEEE behavior for signaling nans and follow libm's fmin/fmax,
754 // and currently there isn't a nice wrapper in APFloat for the version with
755 // correct snan handling.
756 break;
757 default:
758 break;
759 }
760
761 return std::nullopt;
762}
763
764SmallVector<APInt>
765llvm::ConstantFoldVectorBinop(unsigned Opcode, const Register Op1,
766 const Register Op2,
767 const MachineRegisterInfo &MRI) {
768 auto *SrcVec2 = getOpcodeDef<GBuildVector>(Reg: Op2, MRI);
769 if (!SrcVec2)
770 return SmallVector<APInt>();
771
772 auto *SrcVec1 = getOpcodeDef<GBuildVector>(Reg: Op1, MRI);
773 if (!SrcVec1)
774 return SmallVector<APInt>();
775
776 SmallVector<APInt> FoldedElements;
777 for (unsigned Idx = 0, E = SrcVec1->getNumSources(); Idx < E; ++Idx) {
778 auto MaybeCst = ConstantFoldBinOp(Opcode, Op1: SrcVec1->getSourceReg(I: Idx),
779 Op2: SrcVec2->getSourceReg(I: Idx), MRI);
780 if (!MaybeCst)
781 return SmallVector<APInt>();
782 FoldedElements.push_back(Elt: *MaybeCst);
783 }
784 return FoldedElements;
785}
786
787bool llvm::isKnownNeverNaN(Register Val, const MachineRegisterInfo &MRI,
788 bool SNaN) {
789 const MachineInstr *DefMI = MRI.getVRegDef(Reg: Val);
790 if (!DefMI)
791 return false;
792
793 const TargetMachine& TM = DefMI->getMF()->getTarget();
794 if (DefMI->getFlag(Flag: MachineInstr::FmNoNans) || TM.Options.NoNaNsFPMath)
795 return true;
796
797 // If the value is a constant, we can obviously see if it is a NaN or not.
798 if (const ConstantFP *FPVal = getConstantFPVRegVal(VReg: Val, MRI)) {
799 return !FPVal->getValueAPF().isNaN() ||
800 (SNaN && !FPVal->getValueAPF().isSignaling());
801 }
802
803 if (DefMI->getOpcode() == TargetOpcode::G_BUILD_VECTOR) {
804 for (const auto &Op : DefMI->uses())
805 if (!isKnownNeverNaN(Val: Op.getReg(), MRI, SNaN))
806 return false;
807 return true;
808 }
809
810 switch (DefMI->getOpcode()) {
811 default:
812 break;
813 case TargetOpcode::G_FADD:
814 case TargetOpcode::G_FSUB:
815 case TargetOpcode::G_FMUL:
816 case TargetOpcode::G_FDIV:
817 case TargetOpcode::G_FREM:
818 case TargetOpcode::G_FSIN:
819 case TargetOpcode::G_FCOS:
820 case TargetOpcode::G_FMA:
821 case TargetOpcode::G_FMAD:
822 if (SNaN)
823 return true;
824
825 // TODO: Need isKnownNeverInfinity
826 return false;
827 case TargetOpcode::G_FMINNUM_IEEE:
828 case TargetOpcode::G_FMAXNUM_IEEE: {
829 if (SNaN)
830 return true;
831 // This can return a NaN if either operand is an sNaN, or if both operands
832 // are NaN.
833 return (isKnownNeverNaN(Val: DefMI->getOperand(i: 1).getReg(), MRI) &&
834 isKnownNeverSNaN(Val: DefMI->getOperand(i: 2).getReg(), MRI)) ||
835 (isKnownNeverSNaN(Val: DefMI->getOperand(i: 1).getReg(), MRI) &&
836 isKnownNeverNaN(Val: DefMI->getOperand(i: 2).getReg(), MRI));
837 }
838 case TargetOpcode::G_FMINNUM:
839 case TargetOpcode::G_FMAXNUM: {
840 // Only one needs to be known not-nan, since it will be returned if the
841 // other ends up being one.
842 return isKnownNeverNaN(Val: DefMI->getOperand(i: 1).getReg(), MRI, SNaN) ||
843 isKnownNeverNaN(Val: DefMI->getOperand(i: 2).getReg(), MRI, SNaN);
844 }
845 }
846
847 if (SNaN) {
848 // FP operations quiet. For now, just handle the ones inserted during
849 // legalization.
850 switch (DefMI->getOpcode()) {
851 case TargetOpcode::G_FPEXT:
852 case TargetOpcode::G_FPTRUNC:
853 case TargetOpcode::G_FCANONICALIZE:
854 return true;
855 default:
856 return false;
857 }
858 }
859
860 return false;
861}
862
863Align llvm::inferAlignFromPtrInfo(MachineFunction &MF,
864 const MachinePointerInfo &MPO) {
865 auto PSV = dyn_cast_if_present<const PseudoSourceValue *>(Val: MPO.V);
866 if (auto FSPV = dyn_cast_or_null<FixedStackPseudoSourceValue>(Val: PSV)) {
867 MachineFrameInfo &MFI = MF.getFrameInfo();
868 return commonAlignment(A: MFI.getObjectAlign(ObjectIdx: FSPV->getFrameIndex()),
869 Offset: MPO.Offset);
870 }
871
872 if (const Value *V = dyn_cast_if_present<const Value *>(Val: MPO.V)) {
873 const Module *M = MF.getFunction().getParent();
874 return V->getPointerAlignment(DL: M->getDataLayout());
875 }
876
877 return Align(1);
878}
879
880Register llvm::getFunctionLiveInPhysReg(MachineFunction &MF,
881 const TargetInstrInfo &TII,
882 MCRegister PhysReg,
883 const TargetRegisterClass &RC,
884 const DebugLoc &DL, LLT RegTy) {
885 MachineBasicBlock &EntryMBB = MF.front();
886 MachineRegisterInfo &MRI = MF.getRegInfo();
887 Register LiveIn = MRI.getLiveInVirtReg(PReg: PhysReg);
888 if (LiveIn) {
889 MachineInstr *Def = MRI.getVRegDef(Reg: LiveIn);
890 if (Def) {
891 // FIXME: Should the verifier check this is in the entry block?
892 assert(Def->getParent() == &EntryMBB && "live-in copy not in entry block");
893 return LiveIn;
894 }
895
896 // It's possible the incoming argument register and copy was added during
897 // lowering, but later deleted due to being/becoming dead. If this happens,
898 // re-insert the copy.
899 } else {
900 // The live in register was not present, so add it.
901 LiveIn = MF.addLiveIn(PReg: PhysReg, RC: &RC);
902 if (RegTy.isValid())
903 MRI.setType(VReg: LiveIn, Ty: RegTy);
904 }
905
906 BuildMI(BB&: EntryMBB, I: EntryMBB.begin(), MIMD: DL, MCID: TII.get(Opcode: TargetOpcode::COPY), DestReg: LiveIn)
907 .addReg(RegNo: PhysReg);
908 if (!EntryMBB.isLiveIn(Reg: PhysReg))
909 EntryMBB.addLiveIn(PhysReg);
910 return LiveIn;
911}
912
913std::optional<APInt> llvm::ConstantFoldExtOp(unsigned Opcode,
914 const Register Op1, uint64_t Imm,
915 const MachineRegisterInfo &MRI) {
916 auto MaybeOp1Cst = getIConstantVRegVal(VReg: Op1, MRI);
917 if (MaybeOp1Cst) {
918 switch (Opcode) {
919 default:
920 break;
921 case TargetOpcode::G_SEXT_INREG: {
922 LLT Ty = MRI.getType(Reg: Op1);
923 return MaybeOp1Cst->trunc(width: Imm).sext(width: Ty.getScalarSizeInBits());
924 }
925 }
926 }
927 return std::nullopt;
928}
929
930std::optional<APInt> llvm::ConstantFoldCastOp(unsigned Opcode, LLT DstTy,
931 const Register Op0,
932 const MachineRegisterInfo &MRI) {
933 std::optional<APInt> Val = getIConstantVRegVal(VReg: Op0, MRI);
934 if (!Val)
935 return Val;
936
937 const unsigned DstSize = DstTy.getScalarSizeInBits();
938
939 switch (Opcode) {
940 case TargetOpcode::G_SEXT:
941 return Val->sext(width: DstSize);
942 case TargetOpcode::G_ZEXT:
943 case TargetOpcode::G_ANYEXT:
944 // TODO: DAG considers target preference when constant folding any_extend.
945 return Val->zext(width: DstSize);
946 default:
947 break;
948 }
949
950 llvm_unreachable("unexpected cast opcode to constant fold");
951}
952
953std::optional<APFloat>
954llvm::ConstantFoldIntToFloat(unsigned Opcode, LLT DstTy, Register Src,
955 const MachineRegisterInfo &MRI) {
956 assert(Opcode == TargetOpcode::G_SITOFP || Opcode == TargetOpcode::G_UITOFP);
957 if (auto MaybeSrcVal = getIConstantVRegVal(VReg: Src, MRI)) {
958 APFloat DstVal(getFltSemanticForLLT(Ty: DstTy));
959 DstVal.convertFromAPInt(Input: *MaybeSrcVal, IsSigned: Opcode == TargetOpcode::G_SITOFP,
960 RM: APFloat::rmNearestTiesToEven);
961 return DstVal;
962 }
963 return std::nullopt;
964}
965
966std::optional<SmallVector<unsigned>>
967llvm::ConstantFoldCTLZ(Register Src, const MachineRegisterInfo &MRI) {
968 LLT Ty = MRI.getType(Reg: Src);
969 SmallVector<unsigned> FoldedCTLZs;
970 auto tryFoldScalar = [&](Register R) -> std::optional<unsigned> {
971 auto MaybeCst = getIConstantVRegVal(VReg: R, MRI);
972 if (!MaybeCst)
973 return std::nullopt;
974 return MaybeCst->countl_zero();
975 };
976 if (Ty.isVector()) {
977 // Try to constant fold each element.
978 auto *BV = getOpcodeDef<GBuildVector>(Reg: Src, MRI);
979 if (!BV)
980 return std::nullopt;
981 for (unsigned SrcIdx = 0; SrcIdx < BV->getNumSources(); ++SrcIdx) {
982 if (auto MaybeFold = tryFoldScalar(BV->getSourceReg(I: SrcIdx))) {
983 FoldedCTLZs.emplace_back(Args&: *MaybeFold);
984 continue;
985 }
986 return std::nullopt;
987 }
988 return FoldedCTLZs;
989 }
990 if (auto MaybeCst = tryFoldScalar(Src)) {
991 FoldedCTLZs.emplace_back(Args&: *MaybeCst);
992 return FoldedCTLZs;
993 }
994 return std::nullopt;
995}
996
997bool llvm::isKnownToBeAPowerOfTwo(Register Reg, const MachineRegisterInfo &MRI,
998 GISelKnownBits *KB) {
999 std::optional<DefinitionAndSourceRegister> DefSrcReg =
1000 getDefSrcRegIgnoringCopies(Reg, MRI);
1001 if (!DefSrcReg)
1002 return false;
1003
1004 const MachineInstr &MI = *DefSrcReg->MI;
1005 const LLT Ty = MRI.getType(Reg);
1006
1007 switch (MI.getOpcode()) {
1008 case TargetOpcode::G_CONSTANT: {
1009 unsigned BitWidth = Ty.getScalarSizeInBits();
1010 const ConstantInt *CI = MI.getOperand(i: 1).getCImm();
1011 return CI->getValue().zextOrTrunc(width: BitWidth).isPowerOf2();
1012 }
1013 case TargetOpcode::G_SHL: {
1014 // A left-shift of a constant one will have exactly one bit set because
1015 // shifting the bit off the end is undefined.
1016
1017 // TODO: Constant splat
1018 if (auto ConstLHS = getIConstantVRegVal(VReg: MI.getOperand(i: 1).getReg(), MRI)) {
1019 if (*ConstLHS == 1)
1020 return true;
1021 }
1022
1023 break;
1024 }
1025 case TargetOpcode::G_LSHR: {
1026 if (auto ConstLHS = getIConstantVRegVal(VReg: MI.getOperand(i: 1).getReg(), MRI)) {
1027 if (ConstLHS->isSignMask())
1028 return true;
1029 }
1030
1031 break;
1032 }
1033 case TargetOpcode::G_BUILD_VECTOR: {
1034 // TODO: Probably should have a recursion depth guard since you could have
1035 // bitcasted vector elements.
1036 for (const MachineOperand &MO : llvm::drop_begin(RangeOrContainer: MI.operands()))
1037 if (!isKnownToBeAPowerOfTwo(Reg: MO.getReg(), MRI, KB))
1038 return false;
1039
1040 return true;
1041 }
1042 case TargetOpcode::G_BUILD_VECTOR_TRUNC: {
1043 // Only handle constants since we would need to know if number of leading
1044 // zeros is greater than the truncation amount.
1045 const unsigned BitWidth = Ty.getScalarSizeInBits();
1046 for (const MachineOperand &MO : llvm::drop_begin(RangeOrContainer: MI.operands())) {
1047 auto Const = getIConstantVRegVal(VReg: MO.getReg(), MRI);
1048 if (!Const || !Const->zextOrTrunc(width: BitWidth).isPowerOf2())
1049 return false;
1050 }
1051
1052 return true;
1053 }
1054 default:
1055 break;
1056 }
1057
1058 if (!KB)
1059 return false;
1060
1061 // More could be done here, though the above checks are enough
1062 // to handle some common cases.
1063
1064 // Fall back to computeKnownBits to catch other known cases.
1065 KnownBits Known = KB->getKnownBits(R: Reg);
1066 return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
1067}
1068
1069void llvm::getSelectionDAGFallbackAnalysisUsage(AnalysisUsage &AU) {
1070 AU.addPreserved<StackProtector>();
1071}
1072
1073LLT llvm::getLCMType(LLT OrigTy, LLT TargetTy) {
1074 if (OrigTy.getSizeInBits() == TargetTy.getSizeInBits())
1075 return OrigTy;
1076
1077 if (OrigTy.isVector() && TargetTy.isVector()) {
1078 LLT OrigElt = OrigTy.getElementType();
1079 LLT TargetElt = TargetTy.getElementType();
1080
1081 // TODO: The docstring for this function says the intention is to use this
1082 // function to build MERGE/UNMERGE instructions. It won't be the case that
1083 // we generate a MERGE/UNMERGE between fixed and scalable vector types. We
1084 // could implement getLCMType between the two in the future if there was a
1085 // need, but it is not worth it now as this function should not be used in
1086 // that way.
1087 assert(((OrigTy.isScalableVector() && !TargetTy.isFixedVector()) ||
1088 (OrigTy.isFixedVector() && !TargetTy.isScalableVector())) &&
1089 "getLCMType not implemented between fixed and scalable vectors.");
1090
1091 if (OrigElt.getSizeInBits() == TargetElt.getSizeInBits()) {
1092 int GCDMinElts = std::gcd(m: OrigTy.getElementCount().getKnownMinValue(),
1093 n: TargetTy.getElementCount().getKnownMinValue());
1094 // Prefer the original element type.
1095 ElementCount Mul = OrigTy.getElementCount().multiplyCoefficientBy(
1096 RHS: TargetTy.getElementCount().getKnownMinValue());
1097 return LLT::vector(EC: Mul.divideCoefficientBy(RHS: GCDMinElts),
1098 ScalarTy: OrigTy.getElementType());
1099 }
1100 unsigned LCM = std::lcm(m: OrigTy.getSizeInBits().getKnownMinValue(),
1101 n: TargetTy.getSizeInBits().getKnownMinValue());
1102 return LLT::vector(
1103 EC: ElementCount::get(MinVal: LCM / OrigElt.getSizeInBits(), Scalable: OrigTy.isScalable()),
1104 ScalarTy: OrigElt);
1105 }
1106
1107 // One type is scalar, one type is vector
1108 if (OrigTy.isVector() || TargetTy.isVector()) {
1109 LLT VecTy = OrigTy.isVector() ? OrigTy : TargetTy;
1110 LLT ScalarTy = OrigTy.isVector() ? TargetTy : OrigTy;
1111 LLT EltTy = VecTy.getElementType();
1112 LLT OrigEltTy = OrigTy.isVector() ? OrigTy.getElementType() : OrigTy;
1113
1114 // Prefer scalar type from OrigTy.
1115 if (EltTy.getSizeInBits() == ScalarTy.getSizeInBits())
1116 return LLT::vector(EC: VecTy.getElementCount(), ScalarTy: OrigEltTy);
1117
1118 // Different size scalars. Create vector with the same total size.
1119 // LCM will take fixed/scalable from VecTy.
1120 unsigned LCM = std::lcm(m: EltTy.getSizeInBits().getFixedValue() *
1121 VecTy.getElementCount().getKnownMinValue(),
1122 n: ScalarTy.getSizeInBits().getFixedValue());
1123 // Prefer type from OrigTy
1124 return LLT::vector(EC: ElementCount::get(MinVal: LCM / OrigEltTy.getSizeInBits(),
1125 Scalable: VecTy.getElementCount().isScalable()),
1126 ScalarTy: OrigEltTy);
1127 }
1128
1129 // At this point, both types are scalars of different size
1130 unsigned LCM = std::lcm(m: OrigTy.getSizeInBits().getFixedValue(),
1131 n: TargetTy.getSizeInBits().getFixedValue());
1132 // Preserve pointer types.
1133 if (LCM == OrigTy.getSizeInBits())
1134 return OrigTy;
1135 if (LCM == TargetTy.getSizeInBits())
1136 return TargetTy;
1137 return LLT::scalar(SizeInBits: LCM);
1138}
1139
1140LLT llvm::getCoverTy(LLT OrigTy, LLT TargetTy) {
1141
1142 if ((OrigTy.isScalableVector() && TargetTy.isFixedVector()) ||
1143 (OrigTy.isFixedVector() && TargetTy.isScalableVector()))
1144 llvm_unreachable(
1145 "getCoverTy not implemented between fixed and scalable vectors.");
1146
1147 if (!OrigTy.isVector() || !TargetTy.isVector() || OrigTy == TargetTy ||
1148 (OrigTy.getScalarSizeInBits() != TargetTy.getScalarSizeInBits()))
1149 return getLCMType(OrigTy, TargetTy);
1150
1151 unsigned OrigTyNumElts = OrigTy.getElementCount().getKnownMinValue();
1152 unsigned TargetTyNumElts = TargetTy.getElementCount().getKnownMinValue();
1153 if (OrigTyNumElts % TargetTyNumElts == 0)
1154 return OrigTy;
1155
1156 unsigned NumElts = alignTo(Value: OrigTyNumElts, Align: TargetTyNumElts);
1157 return LLT::scalarOrVector(EC: ElementCount::getFixed(MinVal: NumElts),
1158 ScalarTy: OrigTy.getElementType());
1159}
1160
1161LLT llvm::getGCDType(LLT OrigTy, LLT TargetTy) {
1162 if (OrigTy.getSizeInBits() == TargetTy.getSizeInBits())
1163 return OrigTy;
1164
1165 if (OrigTy.isVector() && TargetTy.isVector()) {
1166 LLT OrigElt = OrigTy.getElementType();
1167
1168 // TODO: The docstring for this function says the intention is to use this
1169 // function to build MERGE/UNMERGE instructions. It won't be the case that
1170 // we generate a MERGE/UNMERGE between fixed and scalable vector types. We
1171 // could implement getGCDType between the two in the future if there was a
1172 // need, but it is not worth it now as this function should not be used in
1173 // that way.
1174 assert(((OrigTy.isScalableVector() && !TargetTy.isFixedVector()) ||
1175 (OrigTy.isFixedVector() && !TargetTy.isScalableVector())) &&
1176 "getGCDType not implemented between fixed and scalable vectors.");
1177
1178 unsigned GCD = std::gcd(m: OrigTy.getSizeInBits().getKnownMinValue(),
1179 n: TargetTy.getSizeInBits().getKnownMinValue());
1180 if (GCD == OrigElt.getSizeInBits())
1181 return LLT::scalarOrVector(EC: ElementCount::get(MinVal: 1, Scalable: OrigTy.isScalable()),
1182 ScalarTy: OrigElt);
1183
1184 // Cannot produce original element type, but both have vscale in common.
1185 if (GCD < OrigElt.getSizeInBits())
1186 return LLT::scalarOrVector(EC: ElementCount::get(MinVal: 1, Scalable: OrigTy.isScalable()),
1187 ScalarSize: GCD);
1188
1189 return LLT::vector(
1190 EC: ElementCount::get(MinVal: GCD / OrigElt.getSizeInBits().getFixedValue(),
1191 Scalable: OrigTy.isScalable()),
1192 ScalarTy: OrigElt);
1193 }
1194
1195 // If one type is vector and the element size matches the scalar size, then
1196 // the gcd is the scalar type.
1197 if (OrigTy.isVector() &&
1198 OrigTy.getElementType().getSizeInBits() == TargetTy.getSizeInBits())
1199 return OrigTy.getElementType();
1200 if (TargetTy.isVector() &&
1201 TargetTy.getElementType().getSizeInBits() == OrigTy.getSizeInBits())
1202 return OrigTy;
1203
1204 // At this point, both types are either scalars of different type or one is a
1205 // vector and one is a scalar. If both types are scalars, the GCD type is the
1206 // GCD between the two scalar sizes. If one is vector and one is scalar, then
1207 // the GCD type is the GCD between the scalar and the vector element size.
1208 LLT OrigScalar = OrigTy.getScalarType();
1209 LLT TargetScalar = TargetTy.getScalarType();
1210 unsigned GCD = std::gcd(m: OrigScalar.getSizeInBits().getFixedValue(),
1211 n: TargetScalar.getSizeInBits().getFixedValue());
1212 return LLT::scalar(SizeInBits: GCD);
1213}
1214
1215std::optional<int> llvm::getSplatIndex(MachineInstr &MI) {
1216 assert(MI.getOpcode() == TargetOpcode::G_SHUFFLE_VECTOR &&
1217 "Only G_SHUFFLE_VECTOR can have a splat index!");
1218 ArrayRef<int> Mask = MI.getOperand(i: 3).getShuffleMask();
1219 auto FirstDefinedIdx = find_if(Range&: Mask, P: [](int Elt) { return Elt >= 0; });
1220
1221 // If all elements are undefined, this shuffle can be considered a splat.
1222 // Return 0 for better potential for callers to simplify.
1223 if (FirstDefinedIdx == Mask.end())
1224 return 0;
1225
1226 // Make sure all remaining elements are either undef or the same
1227 // as the first non-undef value.
1228 int SplatValue = *FirstDefinedIdx;
1229 if (any_of(Range: make_range(x: std::next(x: FirstDefinedIdx), y: Mask.end()),
1230 P: [&SplatValue](int Elt) { return Elt >= 0 && Elt != SplatValue; }))
1231 return std::nullopt;
1232
1233 return SplatValue;
1234}
1235
1236static bool isBuildVectorOp(unsigned Opcode) {
1237 return Opcode == TargetOpcode::G_BUILD_VECTOR ||
1238 Opcode == TargetOpcode::G_BUILD_VECTOR_TRUNC;
1239}
1240
1241namespace {
1242
1243std::optional<ValueAndVReg> getAnyConstantSplat(Register VReg,
1244 const MachineRegisterInfo &MRI,
1245 bool AllowUndef) {
1246 MachineInstr *MI = getDefIgnoringCopies(Reg: VReg, MRI);
1247 if (!MI)
1248 return std::nullopt;
1249
1250 bool isConcatVectorsOp = MI->getOpcode() == TargetOpcode::G_CONCAT_VECTORS;
1251 if (!isBuildVectorOp(Opcode: MI->getOpcode()) && !isConcatVectorsOp)
1252 return std::nullopt;
1253
1254 std::optional<ValueAndVReg> SplatValAndReg;
1255 for (MachineOperand &Op : MI->uses()) {
1256 Register Element = Op.getReg();
1257 // If we have a G_CONCAT_VECTOR, we recursively look into the
1258 // vectors that we're concatenating to see if they're splats.
1259 auto ElementValAndReg =
1260 isConcatVectorsOp
1261 ? getAnyConstantSplat(VReg: Element, MRI, AllowUndef)
1262 : getAnyConstantVRegValWithLookThrough(VReg: Element, MRI, LookThroughInstrs: true, LookThroughAnyExt: true);
1263
1264 // If AllowUndef, treat undef as value that will result in a constant splat.
1265 if (!ElementValAndReg) {
1266 if (AllowUndef && isa<GImplicitDef>(Val: MRI.getVRegDef(Reg: Element)))
1267 continue;
1268 return std::nullopt;
1269 }
1270
1271 // Record splat value
1272 if (!SplatValAndReg)
1273 SplatValAndReg = ElementValAndReg;
1274
1275 // Different constant than the one already recorded, not a constant splat.
1276 if (SplatValAndReg->Value != ElementValAndReg->Value)
1277 return std::nullopt;
1278 }
1279
1280 return SplatValAndReg;
1281}
1282
1283} // end anonymous namespace
1284
1285bool llvm::isBuildVectorConstantSplat(const Register Reg,
1286 const MachineRegisterInfo &MRI,
1287 int64_t SplatValue, bool AllowUndef) {
1288 if (auto SplatValAndReg = getAnyConstantSplat(VReg: Reg, MRI, AllowUndef))
1289 return mi_match(R: SplatValAndReg->VReg, MRI, P: m_SpecificICst(RequestedValue: SplatValue));
1290 return false;
1291}
1292
1293bool llvm::isBuildVectorConstantSplat(const MachineInstr &MI,
1294 const MachineRegisterInfo &MRI,
1295 int64_t SplatValue, bool AllowUndef) {
1296 return isBuildVectorConstantSplat(Reg: MI.getOperand(i: 0).getReg(), MRI, SplatValue,
1297 AllowUndef);
1298}
1299
1300std::optional<APInt>
1301llvm::getIConstantSplatVal(const Register Reg, const MachineRegisterInfo &MRI) {
1302 if (auto SplatValAndReg =
1303 getAnyConstantSplat(VReg: Reg, MRI, /* AllowUndef */ false)) {
1304 if (std::optional<ValueAndVReg> ValAndVReg =
1305 getIConstantVRegValWithLookThrough(VReg: SplatValAndReg->VReg, MRI))
1306 return ValAndVReg->Value;
1307 }
1308
1309 return std::nullopt;
1310}
1311
1312std::optional<APInt>
1313llvm::getIConstantSplatVal(const MachineInstr &MI,
1314 const MachineRegisterInfo &MRI) {
1315 return getIConstantSplatVal(Reg: MI.getOperand(i: 0).getReg(), MRI);
1316}
1317
1318std::optional<int64_t>
1319llvm::getIConstantSplatSExtVal(const Register Reg,
1320 const MachineRegisterInfo &MRI) {
1321 if (auto SplatValAndReg =
1322 getAnyConstantSplat(VReg: Reg, MRI, /* AllowUndef */ false))
1323 return getIConstantVRegSExtVal(VReg: SplatValAndReg->VReg, MRI);
1324 return std::nullopt;
1325}
1326
1327std::optional<int64_t>
1328llvm::getIConstantSplatSExtVal(const MachineInstr &MI,
1329 const MachineRegisterInfo &MRI) {
1330 return getIConstantSplatSExtVal(Reg: MI.getOperand(i: 0).getReg(), MRI);
1331}
1332
1333std::optional<FPValueAndVReg>
1334llvm::getFConstantSplat(Register VReg, const MachineRegisterInfo &MRI,
1335 bool AllowUndef) {
1336 if (auto SplatValAndReg = getAnyConstantSplat(VReg, MRI, AllowUndef))
1337 return getFConstantVRegValWithLookThrough(VReg: SplatValAndReg->VReg, MRI);
1338 return std::nullopt;
1339}
1340
1341bool llvm::isBuildVectorAllZeros(const MachineInstr &MI,
1342 const MachineRegisterInfo &MRI,
1343 bool AllowUndef) {
1344 return isBuildVectorConstantSplat(MI, MRI, SplatValue: 0, AllowUndef);
1345}
1346
1347bool llvm::isBuildVectorAllOnes(const MachineInstr &MI,
1348 const MachineRegisterInfo &MRI,
1349 bool AllowUndef) {
1350 return isBuildVectorConstantSplat(MI, MRI, SplatValue: -1, AllowUndef);
1351}
1352
1353std::optional<RegOrConstant>
1354llvm::getVectorSplat(const MachineInstr &MI, const MachineRegisterInfo &MRI) {
1355 unsigned Opc = MI.getOpcode();
1356 if (!isBuildVectorOp(Opcode: Opc))
1357 return std::nullopt;
1358 if (auto Splat = getIConstantSplatSExtVal(MI, MRI))
1359 return RegOrConstant(*Splat);
1360 auto Reg = MI.getOperand(i: 1).getReg();
1361 if (any_of(Range: drop_begin(RangeOrContainer: MI.operands(), N: 2),
1362 P: [&Reg](const MachineOperand &Op) { return Op.getReg() != Reg; }))
1363 return std::nullopt;
1364 return RegOrConstant(Reg);
1365}
1366
1367static bool isConstantScalar(const MachineInstr &MI,
1368 const MachineRegisterInfo &MRI,
1369 bool AllowFP = true,
1370 bool AllowOpaqueConstants = true) {
1371 switch (MI.getOpcode()) {
1372 case TargetOpcode::G_CONSTANT:
1373 case TargetOpcode::G_IMPLICIT_DEF:
1374 return true;
1375 case TargetOpcode::G_FCONSTANT:
1376 return AllowFP;
1377 case TargetOpcode::G_GLOBAL_VALUE:
1378 case TargetOpcode::G_FRAME_INDEX:
1379 case TargetOpcode::G_BLOCK_ADDR:
1380 case TargetOpcode::G_JUMP_TABLE:
1381 return AllowOpaqueConstants;
1382 default:
1383 return false;
1384 }
1385}
1386
1387bool llvm::isConstantOrConstantVector(MachineInstr &MI,
1388 const MachineRegisterInfo &MRI) {
1389 Register Def = MI.getOperand(i: 0).getReg();
1390 if (auto C = getIConstantVRegValWithLookThrough(VReg: Def, MRI))
1391 return true;
1392 GBuildVector *BV = dyn_cast<GBuildVector>(Val: &MI);
1393 if (!BV)
1394 return false;
1395 for (unsigned SrcIdx = 0; SrcIdx < BV->getNumSources(); ++SrcIdx) {
1396 if (getIConstantVRegValWithLookThrough(VReg: BV->getSourceReg(I: SrcIdx), MRI) ||
1397 getOpcodeDef<GImplicitDef>(Reg: BV->getSourceReg(I: SrcIdx), MRI))
1398 continue;
1399 return false;
1400 }
1401 return true;
1402}
1403
1404bool llvm::isConstantOrConstantVector(const MachineInstr &MI,
1405 const MachineRegisterInfo &MRI,
1406 bool AllowFP, bool AllowOpaqueConstants) {
1407 if (isConstantScalar(MI, MRI, AllowFP, AllowOpaqueConstants))
1408 return true;
1409
1410 if (!isBuildVectorOp(Opcode: MI.getOpcode()))
1411 return false;
1412
1413 const unsigned NumOps = MI.getNumOperands();
1414 for (unsigned I = 1; I != NumOps; ++I) {
1415 const MachineInstr *ElementDef = MRI.getVRegDef(Reg: MI.getOperand(i: I).getReg());
1416 if (!isConstantScalar(MI: *ElementDef, MRI, AllowFP, AllowOpaqueConstants))
1417 return false;
1418 }
1419
1420 return true;
1421}
1422
1423std::optional<APInt>
1424llvm::isConstantOrConstantSplatVector(MachineInstr &MI,
1425 const MachineRegisterInfo &MRI) {
1426 Register Def = MI.getOperand(i: 0).getReg();
1427 if (auto C = getIConstantVRegValWithLookThrough(VReg: Def, MRI))
1428 return C->Value;
1429 auto MaybeCst = getIConstantSplatSExtVal(MI, MRI);
1430 if (!MaybeCst)
1431 return std::nullopt;
1432 const unsigned ScalarSize = MRI.getType(Reg: Def).getScalarSizeInBits();
1433 return APInt(ScalarSize, *MaybeCst, true);
1434}
1435
1436bool llvm::isNullOrNullSplat(const MachineInstr &MI,
1437 const MachineRegisterInfo &MRI, bool AllowUndefs) {
1438 switch (MI.getOpcode()) {
1439 case TargetOpcode::G_IMPLICIT_DEF:
1440 return AllowUndefs;
1441 case TargetOpcode::G_CONSTANT:
1442 return MI.getOperand(i: 1).getCImm()->isNullValue();
1443 case TargetOpcode::G_FCONSTANT: {
1444 const ConstantFP *FPImm = MI.getOperand(i: 1).getFPImm();
1445 return FPImm->isZero() && !FPImm->isNegative();
1446 }
1447 default:
1448 if (!AllowUndefs) // TODO: isBuildVectorAllZeros assumes undef is OK already
1449 return false;
1450 return isBuildVectorAllZeros(MI, MRI);
1451 }
1452}
1453
1454bool llvm::isAllOnesOrAllOnesSplat(const MachineInstr &MI,
1455 const MachineRegisterInfo &MRI,
1456 bool AllowUndefs) {
1457 switch (MI.getOpcode()) {
1458 case TargetOpcode::G_IMPLICIT_DEF:
1459 return AllowUndefs;
1460 case TargetOpcode::G_CONSTANT:
1461 return MI.getOperand(i: 1).getCImm()->isAllOnesValue();
1462 default:
1463 if (!AllowUndefs) // TODO: isBuildVectorAllOnes assumes undef is OK already
1464 return false;
1465 return isBuildVectorAllOnes(MI, MRI);
1466 }
1467}
1468
1469bool llvm::matchUnaryPredicate(
1470 const MachineRegisterInfo &MRI, Register Reg,
1471 std::function<bool(const Constant *ConstVal)> Match, bool AllowUndefs) {
1472
1473 const MachineInstr *Def = getDefIgnoringCopies(Reg, MRI);
1474 if (AllowUndefs && Def->getOpcode() == TargetOpcode::G_IMPLICIT_DEF)
1475 return Match(nullptr);
1476
1477 // TODO: Also handle fconstant
1478 if (Def->getOpcode() == TargetOpcode::G_CONSTANT)
1479 return Match(Def->getOperand(i: 1).getCImm());
1480
1481 if (Def->getOpcode() != TargetOpcode::G_BUILD_VECTOR)
1482 return false;
1483
1484 for (unsigned I = 1, E = Def->getNumOperands(); I != E; ++I) {
1485 Register SrcElt = Def->getOperand(i: I).getReg();
1486 const MachineInstr *SrcDef = getDefIgnoringCopies(Reg: SrcElt, MRI);
1487 if (AllowUndefs && SrcDef->getOpcode() == TargetOpcode::G_IMPLICIT_DEF) {
1488 if (!Match(nullptr))
1489 return false;
1490 continue;
1491 }
1492
1493 if (SrcDef->getOpcode() != TargetOpcode::G_CONSTANT ||
1494 !Match(SrcDef->getOperand(i: 1).getCImm()))
1495 return false;
1496 }
1497
1498 return true;
1499}
1500
1501bool llvm::isConstTrueVal(const TargetLowering &TLI, int64_t Val, bool IsVector,
1502 bool IsFP) {
1503 switch (TLI.getBooleanContents(isVec: IsVector, isFloat: IsFP)) {
1504 case TargetLowering::UndefinedBooleanContent:
1505 return Val & 0x1;
1506 case TargetLowering::ZeroOrOneBooleanContent:
1507 return Val == 1;
1508 case TargetLowering::ZeroOrNegativeOneBooleanContent:
1509 return Val == -1;
1510 }
1511 llvm_unreachable("Invalid boolean contents");
1512}
1513
1514bool llvm::isConstFalseVal(const TargetLowering &TLI, int64_t Val,
1515 bool IsVector, bool IsFP) {
1516 switch (TLI.getBooleanContents(isVec: IsVector, isFloat: IsFP)) {
1517 case TargetLowering::UndefinedBooleanContent:
1518 return ~Val & 0x1;
1519 case TargetLowering::ZeroOrOneBooleanContent:
1520 case TargetLowering::ZeroOrNegativeOneBooleanContent:
1521 return Val == 0;
1522 }
1523 llvm_unreachable("Invalid boolean contents");
1524}
1525
1526int64_t llvm::getICmpTrueVal(const TargetLowering &TLI, bool IsVector,
1527 bool IsFP) {
1528 switch (TLI.getBooleanContents(isVec: IsVector, isFloat: IsFP)) {
1529 case TargetLowering::UndefinedBooleanContent:
1530 case TargetLowering::ZeroOrOneBooleanContent:
1531 return 1;
1532 case TargetLowering::ZeroOrNegativeOneBooleanContent:
1533 return -1;
1534 }
1535 llvm_unreachable("Invalid boolean contents");
1536}
1537
1538bool llvm::shouldOptForSize(const MachineBasicBlock &MBB,
1539 ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) {
1540 const auto &F = MBB.getParent()->getFunction();
1541 return F.hasOptSize() || F.hasMinSize() ||
1542 llvm::shouldOptimizeForSize(BB: MBB.getBasicBlock(), PSI, BFI);
1543}
1544
1545void llvm::saveUsesAndErase(MachineInstr &MI, MachineRegisterInfo &MRI,
1546 LostDebugLocObserver *LocObserver,
1547 SmallInstListTy &DeadInstChain) {
1548 for (MachineOperand &Op : MI.uses()) {
1549 if (Op.isReg() && Op.getReg().isVirtual())
1550 DeadInstChain.insert(I: MRI.getVRegDef(Reg: Op.getReg()));
1551 }
1552 LLVM_DEBUG(dbgs() << MI << "Is dead; erasing.\n");
1553 DeadInstChain.remove(I: &MI);
1554 MI.eraseFromParent();
1555 if (LocObserver)
1556 LocObserver->checkpoint(CheckDebugLocs: false);
1557}
1558
1559void llvm::eraseInstrs(ArrayRef<MachineInstr *> DeadInstrs,
1560 MachineRegisterInfo &MRI,
1561 LostDebugLocObserver *LocObserver) {
1562 SmallInstListTy DeadInstChain;
1563 for (MachineInstr *MI : DeadInstrs)
1564 saveUsesAndErase(MI&: *MI, MRI, LocObserver, DeadInstChain);
1565
1566 while (!DeadInstChain.empty()) {
1567 MachineInstr *Inst = DeadInstChain.pop_back_val();
1568 if (!isTriviallyDead(MI: *Inst, MRI))
1569 continue;
1570 saveUsesAndErase(MI&: *Inst, MRI, LocObserver, DeadInstChain);
1571 }
1572}
1573
1574void llvm::eraseInstr(MachineInstr &MI, MachineRegisterInfo &MRI,
1575 LostDebugLocObserver *LocObserver) {
1576 return eraseInstrs(DeadInstrs: {&MI}, MRI, LocObserver);
1577}
1578
1579void llvm::salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI) {
1580 for (auto &Def : MI.defs()) {
1581 assert(Def.isReg() && "Must be a reg");
1582
1583 SmallVector<MachineOperand *, 16> DbgUsers;
1584 for (auto &MOUse : MRI.use_operands(Reg: Def.getReg())) {
1585 MachineInstr *DbgValue = MOUse.getParent();
1586 // Ignore partially formed DBG_VALUEs.
1587 if (DbgValue->isNonListDebugValue() && DbgValue->getNumOperands() == 4) {
1588 DbgUsers.push_back(Elt: &MOUse);
1589 }
1590 }
1591
1592 if (!DbgUsers.empty()) {
1593 salvageDebugInfoForDbgValue(MRI, MI, DbgUsers);
1594 }
1595 }
1596}
1597

source code of llvm/lib/CodeGen/GlobalISel/Utils.cpp