1//===-- SIFoldOperands.cpp - Fold operands --- ----------------------------===//
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/// \file
8//===----------------------------------------------------------------------===//
9//
10
11#include "SIFoldOperands.h"
12#include "AMDGPU.h"
13#include "GCNSubtarget.h"
14#include "MCTargetDesc/AMDGPUMCTargetDesc.h"
15#include "SIInstrInfo.h"
16#include "SIMachineFunctionInfo.h"
17#include "SIRegisterInfo.h"
18#include "llvm/ADT/DepthFirstIterator.h"
19#include "llvm/CodeGen/MachineFunction.h"
20#include "llvm/CodeGen/MachineFunctionPass.h"
21#include "llvm/CodeGen/MachineOperand.h"
22
23#define DEBUG_TYPE "si-fold-operands"
24using namespace llvm;
25
26namespace {
27
28/// Track a value we may want to fold into downstream users, applying
29/// subregister extracts along the way.
30struct FoldableDef {
31 union {
32 MachineOperand *OpToFold = nullptr;
33 uint64_t ImmToFold;
34 int FrameIndexToFold;
35 };
36
37 /// Register class of the originally defined value.
38 const TargetRegisterClass *DefRC = nullptr;
39
40 /// Track the original defining instruction for the value.
41 const MachineInstr *DefMI = nullptr;
42
43 /// Subregister to apply to the value at the use point.
44 unsigned DefSubReg = AMDGPU::NoSubRegister;
45
46 /// Kind of value stored in the union.
47 MachineOperand::MachineOperandType Kind;
48
49 FoldableDef() = delete;
50 FoldableDef(MachineOperand &FoldOp, const TargetRegisterClass *DefRC,
51 unsigned DefSubReg = AMDGPU::NoSubRegister)
52 : DefRC(DefRC), DefSubReg(DefSubReg), Kind(FoldOp.getType()) {
53
54 if (FoldOp.isImm()) {
55 ImmToFold = FoldOp.getImm();
56 } else if (FoldOp.isFI()) {
57 FrameIndexToFold = FoldOp.getIndex();
58 } else {
59 assert(FoldOp.isReg() || FoldOp.isGlobal());
60 OpToFold = &FoldOp;
61 }
62
63 DefMI = FoldOp.getParent();
64 }
65
66 FoldableDef(int64_t FoldImm, const TargetRegisterClass *DefRC,
67 unsigned DefSubReg = AMDGPU::NoSubRegister)
68 : ImmToFold(FoldImm), DefRC(DefRC), DefSubReg(DefSubReg),
69 Kind(MachineOperand::MO_Immediate) {}
70
71 /// Copy the current def and apply \p SubReg to the value.
72 FoldableDef getWithSubReg(const SIRegisterInfo &TRI, unsigned SubReg) const {
73 FoldableDef Copy(*this);
74 Copy.DefSubReg = TRI.composeSubRegIndices(a: DefSubReg, b: SubReg);
75 return Copy;
76 }
77
78 bool isReg() const { return Kind == MachineOperand::MO_Register; }
79
80 Register getReg() const {
81 assert(isReg());
82 return OpToFold->getReg();
83 }
84
85 unsigned getSubReg() const {
86 assert(isReg());
87 return OpToFold->getSubReg();
88 }
89
90 bool isImm() const { return Kind == MachineOperand::MO_Immediate; }
91
92 bool isFI() const {
93 return Kind == MachineOperand::MO_FrameIndex;
94 }
95
96 int getFI() const {
97 assert(isFI());
98 return FrameIndexToFold;
99 }
100
101 bool isGlobal() const { return Kind == MachineOperand::MO_GlobalAddress; }
102
103 /// Return the effective immediate value defined by this instruction, after
104 /// application of any subregister extracts which may exist between the use
105 /// and def instruction.
106 std::optional<int64_t> getEffectiveImmVal() const {
107 assert(isImm());
108 return SIInstrInfo::extractSubregFromImm(ImmVal: ImmToFold, SubRegIndex: DefSubReg);
109 }
110
111 /// Check if it is legal to fold this effective value into \p MI's \p OpNo
112 /// operand.
113 bool isOperandLegal(const SIInstrInfo &TII, const MachineInstr &MI,
114 unsigned OpIdx) const {
115 switch (Kind) {
116 case MachineOperand::MO_Immediate: {
117 std::optional<int64_t> ImmToFold = getEffectiveImmVal();
118 if (!ImmToFold)
119 return false;
120
121 // TODO: Should verify the subregister index is supported by the class
122 // TODO: Avoid the temporary MachineOperand
123 MachineOperand TmpOp = MachineOperand::CreateImm(Val: *ImmToFold);
124 return TII.isOperandLegal(MI, OpIdx, MO: &TmpOp);
125 }
126 case MachineOperand::MO_FrameIndex: {
127 if (DefSubReg != AMDGPU::NoSubRegister)
128 return false;
129 MachineOperand TmpOp = MachineOperand::CreateFI(Idx: FrameIndexToFold);
130 return TII.isOperandLegal(MI, OpIdx, MO: &TmpOp);
131 }
132 default:
133 // TODO: Try to apply DefSubReg, for global address we can extract
134 // low/high.
135 if (DefSubReg != AMDGPU::NoSubRegister)
136 return false;
137 return TII.isOperandLegal(MI, OpIdx, MO: OpToFold);
138 }
139
140 llvm_unreachable("covered MachineOperand kind switch");
141 }
142};
143
144struct FoldCandidate {
145 MachineInstr *UseMI;
146 FoldableDef Def;
147 int ShrinkOpcode;
148 unsigned UseOpNo;
149 bool Commuted;
150
151 FoldCandidate(MachineInstr *MI, unsigned OpNo, FoldableDef Def,
152 bool Commuted = false, int ShrinkOp = -1)
153 : UseMI(MI), Def(Def), ShrinkOpcode(ShrinkOp), UseOpNo(OpNo),
154 Commuted(Commuted) {}
155
156 bool isFI() const { return Def.isFI(); }
157
158 int getFI() const {
159 assert(isFI());
160 return Def.FrameIndexToFold;
161 }
162
163 bool isImm() const { return Def.isImm(); }
164
165 bool isReg() const { return Def.isReg(); }
166
167 Register getReg() const { return Def.getReg(); }
168
169 bool isGlobal() const { return Def.isGlobal(); }
170
171 bool needsShrink() const { return ShrinkOpcode != -1; }
172};
173
174class SIFoldOperandsImpl {
175public:
176 MachineFunction *MF;
177 MachineRegisterInfo *MRI;
178 const SIInstrInfo *TII;
179 const SIRegisterInfo *TRI;
180 const GCNSubtarget *ST;
181 const SIMachineFunctionInfo *MFI;
182
183 bool frameIndexMayFold(const MachineInstr &UseMI, int OpNo,
184 const FoldableDef &OpToFold) const;
185
186 // TODO: Just use TII::getVALUOp
187 unsigned convertToVALUOp(unsigned Opc, bool UseVOP3 = false) const {
188 switch (Opc) {
189 case AMDGPU::S_ADD_I32: {
190 if (ST->hasAddNoCarryInsts())
191 return UseVOP3 ? AMDGPU::V_ADD_U32_e64 : AMDGPU::V_ADD_U32_e32;
192 return UseVOP3 ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_ADD_CO_U32_e32;
193 }
194 case AMDGPU::S_OR_B32:
195 return UseVOP3 ? AMDGPU::V_OR_B32_e64 : AMDGPU::V_OR_B32_e32;
196 case AMDGPU::S_AND_B32:
197 return UseVOP3 ? AMDGPU::V_AND_B32_e64 : AMDGPU::V_AND_B32_e32;
198 case AMDGPU::S_MUL_I32:
199 return AMDGPU::V_MUL_LO_U32_e64;
200 default:
201 return AMDGPU::INSTRUCTION_LIST_END;
202 }
203 }
204
205 bool foldCopyToVGPROfScalarAddOfFrameIndex(Register DstReg, Register SrcReg,
206 MachineInstr &MI) const;
207
208 bool updateOperand(FoldCandidate &Fold) const;
209
210 bool canUseImmWithOpSel(const MachineInstr *MI, unsigned UseOpNo,
211 int64_t ImmVal) const;
212
213 /// Try to fold immediate \p ImmVal into \p MI's operand at index \p UseOpNo.
214 bool tryFoldImmWithOpSel(MachineInstr *MI, unsigned UseOpNo,
215 int64_t ImmVal) const;
216
217 bool tryAddToFoldList(SmallVectorImpl<FoldCandidate> &FoldList,
218 MachineInstr *MI, unsigned OpNo,
219 const FoldableDef &OpToFold) const;
220 bool isUseSafeToFold(const MachineInstr &MI,
221 const MachineOperand &UseMO) const;
222
223 const TargetRegisterClass *getRegSeqInit(
224 MachineInstr &RegSeq,
225 SmallVectorImpl<std::pair<MachineOperand *, unsigned>> &Defs) const;
226
227 const TargetRegisterClass *
228 getRegSeqInit(SmallVectorImpl<std::pair<MachineOperand *, unsigned>> &Defs,
229 Register UseReg) const;
230
231 std::pair<int64_t, const TargetRegisterClass *>
232 isRegSeqSplat(MachineInstr &RegSeg) const;
233
234 bool tryFoldRegSeqSplat(MachineInstr *UseMI, unsigned UseOpIdx,
235 int64_t SplatVal,
236 const TargetRegisterClass *SplatRC) const;
237
238 bool tryToFoldACImm(const FoldableDef &OpToFold, MachineInstr *UseMI,
239 unsigned UseOpIdx,
240 SmallVectorImpl<FoldCandidate> &FoldList) const;
241 void foldOperand(FoldableDef OpToFold, MachineInstr *UseMI, int UseOpIdx,
242 SmallVectorImpl<FoldCandidate> &FoldList,
243 SmallVectorImpl<MachineInstr *> &CopiesToReplace) const;
244
245 bool tryConstantFoldOp(MachineInstr *MI) const;
246 bool tryFoldCndMask(MachineInstr &MI) const;
247 bool tryFoldZeroHighBits(MachineInstr &MI) const;
248 bool foldInstOperand(MachineInstr &MI, const FoldableDef &OpToFold) const;
249
250 bool foldCopyToAGPRRegSequence(MachineInstr *CopyMI) const;
251 bool tryFoldFoldableCopy(MachineInstr &MI,
252 MachineOperand *&CurrentKnownM0Val) const;
253
254 const MachineOperand *isClamp(const MachineInstr &MI) const;
255 bool tryFoldClamp(MachineInstr &MI);
256
257 std::pair<const MachineOperand *, int> isOMod(const MachineInstr &MI) const;
258 bool tryFoldOMod(MachineInstr &MI);
259 bool tryFoldRegSequence(MachineInstr &MI);
260 bool tryFoldPhiAGPR(MachineInstr &MI);
261 bool tryFoldLoad(MachineInstr &MI);
262
263 bool tryOptimizeAGPRPhis(MachineBasicBlock &MBB);
264
265public:
266 SIFoldOperandsImpl() = default;
267
268 bool run(MachineFunction &MF);
269};
270
271class SIFoldOperandsLegacy : public MachineFunctionPass {
272public:
273 static char ID;
274
275 SIFoldOperandsLegacy() : MachineFunctionPass(ID) {}
276
277 bool runOnMachineFunction(MachineFunction &MF) override {
278 if (skipFunction(F: MF.getFunction()))
279 return false;
280 return SIFoldOperandsImpl().run(MF);
281 }
282
283 StringRef getPassName() const override { return "SI Fold Operands"; }
284
285 void getAnalysisUsage(AnalysisUsage &AU) const override {
286 AU.setPreservesCFG();
287 MachineFunctionPass::getAnalysisUsage(AU);
288 }
289
290 MachineFunctionProperties getRequiredProperties() const override {
291 return MachineFunctionProperties().setIsSSA();
292 }
293};
294
295} // End anonymous namespace.
296
297INITIALIZE_PASS(SIFoldOperandsLegacy, DEBUG_TYPE, "SI Fold Operands", false,
298 false)
299
300char SIFoldOperandsLegacy::ID = 0;
301
302char &llvm::SIFoldOperandsLegacyID = SIFoldOperandsLegacy::ID;
303
304static const TargetRegisterClass *getRegOpRC(const MachineRegisterInfo &MRI,
305 const TargetRegisterInfo &TRI,
306 const MachineOperand &MO) {
307 const TargetRegisterClass *RC = MRI.getRegClass(Reg: MO.getReg());
308 if (const TargetRegisterClass *SubRC =
309 TRI.getSubRegisterClass(SuperRC: RC, SubRegIdx: MO.getSubReg()))
310 RC = SubRC;
311 return RC;
312}
313
314// Map multiply-accumulate opcode to corresponding multiply-add opcode if any.
315static unsigned macToMad(unsigned Opc) {
316 switch (Opc) {
317 case AMDGPU::V_MAC_F32_e64:
318 return AMDGPU::V_MAD_F32_e64;
319 case AMDGPU::V_MAC_F16_e64:
320 return AMDGPU::V_MAD_F16_e64;
321 case AMDGPU::V_FMAC_F32_e64:
322 return AMDGPU::V_FMA_F32_e64;
323 case AMDGPU::V_FMAC_F16_e64:
324 return AMDGPU::V_FMA_F16_gfx9_e64;
325 case AMDGPU::V_FMAC_F16_t16_e64:
326 return AMDGPU::V_FMA_F16_gfx9_t16_e64;
327 case AMDGPU::V_FMAC_F16_fake16_e64:
328 return AMDGPU::V_FMA_F16_gfx9_fake16_e64;
329 case AMDGPU::V_FMAC_LEGACY_F32_e64:
330 return AMDGPU::V_FMA_LEGACY_F32_e64;
331 case AMDGPU::V_FMAC_F64_e64:
332 return AMDGPU::V_FMA_F64_e64;
333 }
334 return AMDGPU::INSTRUCTION_LIST_END;
335}
336
337// TODO: Add heuristic that the frame index might not fit in the addressing mode
338// immediate offset to avoid materializing in loops.
339bool SIFoldOperandsImpl::frameIndexMayFold(const MachineInstr &UseMI, int OpNo,
340 const FoldableDef &OpToFold) const {
341 if (!OpToFold.isFI())
342 return false;
343
344 const unsigned Opc = UseMI.getOpcode();
345 switch (Opc) {
346 case AMDGPU::S_ADD_I32:
347 case AMDGPU::S_ADD_U32:
348 case AMDGPU::V_ADD_U32_e32:
349 case AMDGPU::V_ADD_CO_U32_e32:
350 // TODO: Possibly relax hasOneUse. It matters more for mubuf, since we have
351 // to insert the wave size shift at every point we use the index.
352 // TODO: Fix depending on visit order to fold immediates into the operand
353 return UseMI.getOperand(i: OpNo == 1 ? 2 : 1).isImm() &&
354 MRI->hasOneNonDBGUse(RegNo: UseMI.getOperand(i: OpNo).getReg());
355 case AMDGPU::V_ADD_U32_e64:
356 case AMDGPU::V_ADD_CO_U32_e64:
357 return UseMI.getOperand(i: OpNo == 2 ? 3 : 2).isImm() &&
358 MRI->hasOneNonDBGUse(RegNo: UseMI.getOperand(i: OpNo).getReg());
359 default:
360 break;
361 }
362
363 if (TII->isMUBUF(MI: UseMI))
364 return OpNo == AMDGPU::getNamedOperandIdx(Opcode: Opc, Name: AMDGPU::OpName::vaddr);
365 if (!TII->isFLATScratch(MI: UseMI))
366 return false;
367
368 int SIdx = AMDGPU::getNamedOperandIdx(Opcode: Opc, Name: AMDGPU::OpName::saddr);
369 if (OpNo == SIdx)
370 return true;
371
372 int VIdx = AMDGPU::getNamedOperandIdx(Opcode: Opc, Name: AMDGPU::OpName::vaddr);
373 return OpNo == VIdx && SIdx == -1;
374}
375
376/// Fold %vgpr = COPY (S_ADD_I32 x, frameindex)
377///
378/// => %vgpr = V_ADD_U32 x, frameindex
379bool SIFoldOperandsImpl::foldCopyToVGPROfScalarAddOfFrameIndex(
380 Register DstReg, Register SrcReg, MachineInstr &MI) const {
381 if (TRI->isVGPR(MRI: *MRI, Reg: DstReg) && TRI->isSGPRReg(MRI: *MRI, Reg: SrcReg) &&
382 MRI->hasOneNonDBGUse(RegNo: SrcReg)) {
383 MachineInstr *Def = MRI->getVRegDef(Reg: SrcReg);
384 if (!Def || Def->getNumOperands() != 4)
385 return false;
386
387 MachineOperand *Src0 = &Def->getOperand(i: 1);
388 MachineOperand *Src1 = &Def->getOperand(i: 2);
389
390 // TODO: This is profitable with more operand types, and for more
391 // opcodes. But ultimately this is working around poor / nonexistent
392 // regbankselect.
393 if (!Src0->isFI() && !Src1->isFI())
394 return false;
395
396 if (Src0->isFI())
397 std::swap(a&: Src0, b&: Src1);
398
399 const bool UseVOP3 = !Src0->isImm() || TII->isInlineConstant(MO: *Src0);
400 unsigned NewOp = convertToVALUOp(Opc: Def->getOpcode(), UseVOP3);
401 if (NewOp == AMDGPU::INSTRUCTION_LIST_END ||
402 !Def->getOperand(i: 3).isDead()) // Check if scc is dead
403 return false;
404
405 MachineBasicBlock *MBB = Def->getParent();
406 const DebugLoc &DL = Def->getDebugLoc();
407 if (NewOp != AMDGPU::V_ADD_CO_U32_e32) {
408 MachineInstrBuilder Add =
409 BuildMI(BB&: *MBB, I&: *Def, MIMD: DL, MCID: TII->get(Opcode: NewOp), DestReg: DstReg);
410
411 if (Add->getDesc().getNumDefs() == 2) {
412 Register CarryOutReg = MRI->createVirtualRegister(RegClass: TRI->getBoolRC());
413 Add.addDef(RegNo: CarryOutReg, Flags: RegState::Dead);
414 MRI->setRegAllocationHint(VReg: CarryOutReg, Type: 0, PrefReg: TRI->getVCC());
415 }
416
417 Add.add(MO: *Src0).add(MO: *Src1).setMIFlags(Def->getFlags());
418 if (AMDGPU::hasNamedOperand(Opcode: NewOp, NamedIdx: AMDGPU::OpName::clamp))
419 Add.addImm(Val: 0);
420
421 Def->eraseFromParent();
422 MI.eraseFromParent();
423 return true;
424 }
425
426 assert(NewOp == AMDGPU::V_ADD_CO_U32_e32);
427
428 MachineBasicBlock::LivenessQueryResult Liveness =
429 MBB->computeRegisterLiveness(TRI, Reg: AMDGPU::VCC, Before: *Def, Neighborhood: 16);
430 if (Liveness == MachineBasicBlock::LQR_Dead) {
431 // TODO: If src1 satisfies operand constraints, use vop3 version.
432 BuildMI(BB&: *MBB, I&: *Def, MIMD: DL, MCID: TII->get(Opcode: NewOp), DestReg: DstReg)
433 .add(MO: *Src0)
434 .add(MO: *Src1)
435 .setOperandDead(3) // implicit-def $vcc
436 .setMIFlags(Def->getFlags());
437 Def->eraseFromParent();
438 MI.eraseFromParent();
439 return true;
440 }
441 }
442
443 return false;
444}
445
446FunctionPass *llvm::createSIFoldOperandsLegacyPass() {
447 return new SIFoldOperandsLegacy();
448}
449
450bool SIFoldOperandsImpl::canUseImmWithOpSel(const MachineInstr *MI,
451 unsigned UseOpNo,
452 int64_t ImmVal) const {
453 const uint64_t TSFlags = MI->getDesc().TSFlags;
454
455 if (!(TSFlags & SIInstrFlags::IsPacked) || (TSFlags & SIInstrFlags::IsMAI) ||
456 (TSFlags & SIInstrFlags::IsWMMA) || (TSFlags & SIInstrFlags::IsSWMMAC) ||
457 (ST->hasDOTOpSelHazard() && (TSFlags & SIInstrFlags::IsDOT)))
458 return false;
459
460 const MachineOperand &Old = MI->getOperand(i: UseOpNo);
461 int OpNo = MI->getOperandNo(I: &Old);
462
463 unsigned Opcode = MI->getOpcode();
464 uint8_t OpType = TII->get(Opcode).operands()[OpNo].OperandType;
465 switch (OpType) {
466 default:
467 return false;
468 case AMDGPU::OPERAND_REG_IMM_V2FP16:
469 case AMDGPU::OPERAND_REG_IMM_V2BF16:
470 case AMDGPU::OPERAND_REG_IMM_V2INT16:
471 case AMDGPU::OPERAND_REG_IMM_NOINLINE_V2FP16:
472 case AMDGPU::OPERAND_REG_INLINE_C_V2FP16:
473 case AMDGPU::OPERAND_REG_INLINE_C_V2BF16:
474 case AMDGPU::OPERAND_REG_INLINE_C_V2INT16:
475 // VOP3 packed instructions ignore op_sel source modifiers, we cannot encode
476 // two different constants.
477 if ((TSFlags & SIInstrFlags::VOP3) && !(TSFlags & SIInstrFlags::VOP3P) &&
478 static_cast<uint16_t>(ImmVal) != static_cast<uint16_t>(ImmVal >> 16))
479 return false;
480 break;
481 }
482
483 return true;
484}
485
486bool SIFoldOperandsImpl::tryFoldImmWithOpSel(MachineInstr *MI, unsigned UseOpNo,
487 int64_t ImmVal) const {
488 MachineOperand &Old = MI->getOperand(i: UseOpNo);
489 unsigned Opcode = MI->getOpcode();
490 int OpNo = MI->getOperandNo(I: &Old);
491 uint8_t OpType = TII->get(Opcode).operands()[OpNo].OperandType;
492
493 // If the literal can be inlined as-is, apply it and short-circuit the
494 // tests below. The main motivation for this is to avoid unintuitive
495 // uses of opsel.
496 if (AMDGPU::isInlinableLiteralV216(Literal: ImmVal, OpType)) {
497 Old.ChangeToImmediate(ImmVal);
498 return true;
499 }
500
501 // Refer to op_sel/op_sel_hi and check if we can change the immediate and
502 // op_sel in a way that allows an inline constant.
503 AMDGPU::OpName ModName = AMDGPU::OpName::NUM_OPERAND_NAMES;
504 unsigned SrcIdx = ~0;
505 if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, Name: AMDGPU::OpName::src0)) {
506 ModName = AMDGPU::OpName::src0_modifiers;
507 SrcIdx = 0;
508 } else if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, Name: AMDGPU::OpName::src1)) {
509 ModName = AMDGPU::OpName::src1_modifiers;
510 SrcIdx = 1;
511 } else if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, Name: AMDGPU::OpName::src2)) {
512 ModName = AMDGPU::OpName::src2_modifiers;
513 SrcIdx = 2;
514 }
515 assert(ModName != AMDGPU::OpName::NUM_OPERAND_NAMES);
516 int ModIdx = AMDGPU::getNamedOperandIdx(Opcode, Name: ModName);
517 MachineOperand &Mod = MI->getOperand(i: ModIdx);
518 unsigned ModVal = Mod.getImm();
519
520 uint16_t ImmLo =
521 static_cast<uint16_t>(ImmVal >> (ModVal & SISrcMods::OP_SEL_0 ? 16 : 0));
522 uint16_t ImmHi =
523 static_cast<uint16_t>(ImmVal >> (ModVal & SISrcMods::OP_SEL_1 ? 16 : 0));
524 uint32_t Imm = (static_cast<uint32_t>(ImmHi) << 16) | ImmLo;
525 unsigned NewModVal = ModVal & ~(SISrcMods::OP_SEL_0 | SISrcMods::OP_SEL_1);
526
527 // Helper function that attempts to inline the given value with a newly
528 // chosen opsel pattern.
529 auto tryFoldToInline = [&](uint32_t Imm) -> bool {
530 if (AMDGPU::isInlinableLiteralV216(Literal: Imm, OpType)) {
531 Mod.setImm(NewModVal | SISrcMods::OP_SEL_1);
532 Old.ChangeToImmediate(ImmVal: Imm);
533 return true;
534 }
535
536 // Try to shuffle the halves around and leverage opsel to get an inline
537 // constant.
538 uint16_t Lo = static_cast<uint16_t>(Imm);
539 uint16_t Hi = static_cast<uint16_t>(Imm >> 16);
540 if (Lo == Hi) {
541 if (AMDGPU::isInlinableLiteralV216(Literal: Lo, OpType)) {
542 Mod.setImm(NewModVal);
543 Old.ChangeToImmediate(ImmVal: Lo);
544 return true;
545 }
546
547 if (static_cast<int16_t>(Lo) < 0) {
548 int32_t SExt = static_cast<int16_t>(Lo);
549 if (AMDGPU::isInlinableLiteralV216(Literal: SExt, OpType)) {
550 Mod.setImm(NewModVal);
551 Old.ChangeToImmediate(ImmVal: SExt);
552 return true;
553 }
554 }
555
556 // This check is only useful for integer instructions
557 if (OpType == AMDGPU::OPERAND_REG_IMM_V2INT16) {
558 if (AMDGPU::isInlinableLiteralV216(Literal: Lo << 16, OpType)) {
559 Mod.setImm(NewModVal | SISrcMods::OP_SEL_0 | SISrcMods::OP_SEL_1);
560 Old.ChangeToImmediate(ImmVal: static_cast<uint32_t>(Lo) << 16);
561 return true;
562 }
563 }
564 } else {
565 uint32_t Swapped = (static_cast<uint32_t>(Lo) << 16) | Hi;
566 if (AMDGPU::isInlinableLiteralV216(Literal: Swapped, OpType)) {
567 Mod.setImm(NewModVal | SISrcMods::OP_SEL_0);
568 Old.ChangeToImmediate(ImmVal: Swapped);
569 return true;
570 }
571 }
572
573 return false;
574 };
575
576 if (tryFoldToInline(Imm))
577 return true;
578
579 // Replace integer addition by subtraction and vice versa if it allows
580 // folding the immediate to an inline constant.
581 //
582 // We should only ever get here for SrcIdx == 1 due to canonicalization
583 // earlier in the pipeline, but we double-check here to be safe / fully
584 // general.
585 bool IsUAdd = Opcode == AMDGPU::V_PK_ADD_U16;
586 bool IsUSub = Opcode == AMDGPU::V_PK_SUB_U16;
587 if (SrcIdx == 1 && (IsUAdd || IsUSub)) {
588 unsigned ClampIdx =
589 AMDGPU::getNamedOperandIdx(Opcode, Name: AMDGPU::OpName::clamp);
590 bool Clamp = MI->getOperand(i: ClampIdx).getImm() != 0;
591
592 if (!Clamp) {
593 uint16_t NegLo = -static_cast<uint16_t>(Imm);
594 uint16_t NegHi = -static_cast<uint16_t>(Imm >> 16);
595 uint32_t NegImm = (static_cast<uint32_t>(NegHi) << 16) | NegLo;
596
597 if (tryFoldToInline(NegImm)) {
598 unsigned NegOpcode =
599 IsUAdd ? AMDGPU::V_PK_SUB_U16 : AMDGPU::V_PK_ADD_U16;
600 MI->setDesc(TII->get(Opcode: NegOpcode));
601 return true;
602 }
603 }
604 }
605
606 return false;
607}
608
609bool SIFoldOperandsImpl::updateOperand(FoldCandidate &Fold) const {
610 MachineInstr *MI = Fold.UseMI;
611 MachineOperand &Old = MI->getOperand(i: Fold.UseOpNo);
612 assert(Old.isReg());
613
614 std::optional<int64_t> ImmVal;
615 if (Fold.isImm())
616 ImmVal = Fold.Def.getEffectiveImmVal();
617
618 if (ImmVal && canUseImmWithOpSel(MI: Fold.UseMI, UseOpNo: Fold.UseOpNo, ImmVal: *ImmVal)) {
619 if (tryFoldImmWithOpSel(MI: Fold.UseMI, UseOpNo: Fold.UseOpNo, ImmVal: *ImmVal))
620 return true;
621
622 // We can't represent the candidate as an inline constant. Try as a literal
623 // with the original opsel, checking constant bus limitations.
624 MachineOperand New = MachineOperand::CreateImm(Val: *ImmVal);
625 int OpNo = MI->getOperandNo(I: &Old);
626 if (!TII->isOperandLegal(MI: *MI, OpIdx: OpNo, MO: &New))
627 return false;
628 Old.ChangeToImmediate(ImmVal: *ImmVal);
629 return true;
630 }
631
632 if ((Fold.isImm() || Fold.isFI() || Fold.isGlobal()) && Fold.needsShrink()) {
633 MachineBasicBlock *MBB = MI->getParent();
634 auto Liveness = MBB->computeRegisterLiveness(TRI, Reg: AMDGPU::VCC, Before: MI, Neighborhood: 16);
635 if (Liveness != MachineBasicBlock::LQR_Dead) {
636 LLVM_DEBUG(dbgs() << "Not shrinking " << MI << " due to vcc liveness\n");
637 return false;
638 }
639
640 int Op32 = Fold.ShrinkOpcode;
641 MachineOperand &Dst0 = MI->getOperand(i: 0);
642 MachineOperand &Dst1 = MI->getOperand(i: 1);
643 assert(Dst0.isDef() && Dst1.isDef());
644
645 bool HaveNonDbgCarryUse = !MRI->use_nodbg_empty(RegNo: Dst1.getReg());
646
647 const TargetRegisterClass *Dst0RC = MRI->getRegClass(Reg: Dst0.getReg());
648 Register NewReg0 = MRI->createVirtualRegister(RegClass: Dst0RC);
649
650 MachineInstr *Inst32 = TII->buildShrunkInst(MI&: *MI, NewOpcode: Op32);
651
652 if (HaveNonDbgCarryUse) {
653 BuildMI(BB&: *MBB, I: MI, MIMD: MI->getDebugLoc(), MCID: TII->get(Opcode: AMDGPU::COPY),
654 DestReg: Dst1.getReg())
655 .addReg(RegNo: AMDGPU::VCC, Flags: RegState::Kill);
656 }
657
658 // Keep the old instruction around to avoid breaking iterators, but
659 // replace it with a dummy instruction to remove uses.
660 //
661 // FIXME: We should not invert how this pass looks at operands to avoid
662 // this. Should track set of foldable movs instead of looking for uses
663 // when looking at a use.
664 Dst0.setReg(NewReg0);
665 for (unsigned I = MI->getNumOperands() - 1; I > 0; --I)
666 MI->removeOperand(OpNo: I);
667 MI->setDesc(TII->get(Opcode: AMDGPU::IMPLICIT_DEF));
668
669 if (Fold.Commuted)
670 TII->commuteInstruction(MI&: *Inst32, NewMI: false);
671 return true;
672 }
673
674 assert(!Fold.needsShrink() && "not handled");
675
676 if (ImmVal) {
677 if (Old.isTied()) {
678 int NewMFMAOpc = AMDGPU::getMFMAEarlyClobberOp(Opcode: MI->getOpcode());
679 if (NewMFMAOpc == -1)
680 return false;
681 MI->setDesc(TII->get(Opcode: NewMFMAOpc));
682 MI->untieRegOperand(OpIdx: 0);
683 const MCInstrDesc &MCID = MI->getDesc();
684 for (unsigned I = 0; I < MI->getNumDefs(); ++I)
685 if (MCID.getOperandConstraint(OpNum: I, Constraint: MCOI::EARLY_CLOBBER) != -1)
686 MI->getOperand(i: I).setIsEarlyClobber(true);
687 }
688
689 // TODO: Should we try to avoid adding this to the candidate list?
690 MachineOperand New = MachineOperand::CreateImm(Val: *ImmVal);
691 int OpNo = MI->getOperandNo(I: &Old);
692 if (!TII->isOperandLegal(MI: *MI, OpIdx: OpNo, MO: &New))
693 return false;
694
695 Old.ChangeToImmediate(ImmVal: *ImmVal);
696 return true;
697 }
698
699 if (Fold.isGlobal()) {
700 Old.ChangeToGA(GV: Fold.Def.OpToFold->getGlobal(),
701 Offset: Fold.Def.OpToFold->getOffset(),
702 TargetFlags: Fold.Def.OpToFold->getTargetFlags());
703 return true;
704 }
705
706 if (Fold.isFI()) {
707 Old.ChangeToFrameIndex(Idx: Fold.getFI());
708 return true;
709 }
710
711 MachineOperand *New = Fold.Def.OpToFold;
712
713 // Verify the register is compatible with the operand.
714 if (const TargetRegisterClass *OpRC =
715 TII->getRegClass(MCID: MI->getDesc(), OpNum: Fold.UseOpNo)) {
716 const TargetRegisterClass *NewRC =
717 TRI->getRegClassForReg(MRI: *MRI, Reg: New->getReg());
718
719 const TargetRegisterClass *ConstrainRC = OpRC;
720 if (New->getSubReg()) {
721 ConstrainRC =
722 TRI->getMatchingSuperRegClass(A: NewRC, B: OpRC, Idx: New->getSubReg());
723
724 if (!ConstrainRC)
725 return false;
726 }
727
728 if (New->getReg().isVirtual() &&
729 !MRI->constrainRegClass(Reg: New->getReg(), RC: ConstrainRC)) {
730 LLVM_DEBUG(dbgs() << "Cannot constrain " << printReg(New->getReg(), TRI)
731 << TRI->getRegClassName(ConstrainRC) << '\n');
732 return false;
733 }
734 }
735
736 // Rework once the VS_16 register class is updated to include proper
737 // 16-bit SGPRs instead of 32-bit ones.
738 if (Old.getSubReg() == AMDGPU::lo16 && TRI->isSGPRReg(MRI: *MRI, Reg: New->getReg()))
739 Old.setSubReg(AMDGPU::NoSubRegister);
740 if (New->getReg().isPhysical()) {
741 Old.substPhysReg(Reg: New->getReg(), *TRI);
742 } else {
743 Register OldReg = Old.getReg();
744 Old.substVirtReg(Reg: New->getReg(), SubIdx: New->getSubReg(), *TRI);
745 Old.setIsUndef(New->isUndef());
746
747 // If MI is in a BUNDLE, also update header's matching implicit use.
748 if (MI->isBundledWithPred()) {
749 MachineInstr &Header = *getBundleStart(I: MI->getIterator());
750 for (MachineOperand &MO : Header.operands()) {
751 if (MO.getReg() == OldReg) {
752 MO.setReg(New->getReg());
753 MO.setSubReg(New->getSubReg());
754 }
755 }
756 }
757 }
758 return true;
759}
760
761static void appendFoldCandidate(SmallVectorImpl<FoldCandidate> &FoldList,
762 FoldCandidate &&Entry) {
763 // Skip additional folding on the same operand.
764 for (FoldCandidate &Fold : FoldList)
765 if (Fold.UseMI == Entry.UseMI && Fold.UseOpNo == Entry.UseOpNo)
766 return;
767 LLVM_DEBUG(dbgs() << "Append " << (Entry.Commuted ? "commuted" : "normal")
768 << " operand " << Entry.UseOpNo << "\n " << *Entry.UseMI);
769 FoldList.push_back(Elt: Entry);
770}
771
772static void appendFoldCandidate(SmallVectorImpl<FoldCandidate> &FoldList,
773 MachineInstr *MI, unsigned OpNo,
774 const FoldableDef &FoldOp,
775 bool Commuted = false, int ShrinkOp = -1) {
776 appendFoldCandidate(FoldList,
777 Entry: FoldCandidate(MI, OpNo, FoldOp, Commuted, ShrinkOp));
778}
779
780// Returns true if the instruction is a packed F32 instruction and the
781// corresponding scalar operand reads 32 bits and replicates the bits to both
782// channels.
783static bool isPKF32InstrReplicatesLower32BitsOfScalarOperand(
784 const GCNSubtarget *ST, MachineInstr *MI, unsigned OpNo) {
785 if (!ST->hasPKF32InstsReplicatingLower32BitsOfScalarInput())
786 return false;
787 const MCOperandInfo &OpDesc = MI->getDesc().operands()[OpNo];
788 return OpDesc.OperandType == AMDGPU::OPERAND_REG_IMM_V2FP32;
789}
790
791// Packed FP32 instructions only read 32 bits from a scalar operand (SGPR or
792// literal) and replicates the bits to both channels. Therefore, if the hi and
793// lo are not same, we can't fold it.
794static bool checkImmOpForPKF32InstrReplicatesLower32BitsOfScalarOperand(
795 const FoldableDef &OpToFold) {
796 assert(OpToFold.isImm() && "Expected immediate operand");
797 uint64_t ImmVal = OpToFold.getEffectiveImmVal().value();
798 uint32_t Lo = Lo_32(Value: ImmVal);
799 uint32_t Hi = Hi_32(Value: ImmVal);
800 return Lo == Hi;
801}
802
803bool SIFoldOperandsImpl::tryAddToFoldList(
804 SmallVectorImpl<FoldCandidate> &FoldList, MachineInstr *MI, unsigned OpNo,
805 const FoldableDef &OpToFold) const {
806 const unsigned Opc = MI->getOpcode();
807
808 auto tryToFoldAsFMAAKorMK = [&]() {
809 if (!OpToFold.isImm())
810 return false;
811
812 const bool TryAK = OpNo == 3;
813 const unsigned NewOpc = TryAK ? AMDGPU::S_FMAAK_F32 : AMDGPU::S_FMAMK_F32;
814 MI->setDesc(TII->get(Opcode: NewOpc));
815
816 // We have to fold into operand which would be Imm not into OpNo.
817 bool FoldAsFMAAKorMK =
818 tryAddToFoldList(FoldList, MI, OpNo: TryAK ? 3 : 2, OpToFold);
819 if (FoldAsFMAAKorMK) {
820 // Untie Src2 of fmac.
821 MI->untieRegOperand(OpIdx: 3);
822 // For fmamk swap operands 1 and 2 if OpToFold was meant for operand 1.
823 if (OpNo == 1) {
824 MachineOperand &Op1 = MI->getOperand(i: 1);
825 MachineOperand &Op2 = MI->getOperand(i: 2);
826 Register OldReg = Op1.getReg();
827 // Operand 2 might be an inlinable constant
828 if (Op2.isImm()) {
829 Op1.ChangeToImmediate(ImmVal: Op2.getImm());
830 Op2.ChangeToRegister(Reg: OldReg, isDef: false);
831 } else {
832 Op1.setReg(Op2.getReg());
833 Op2.setReg(OldReg);
834 }
835 }
836 return true;
837 }
838 MI->setDesc(TII->get(Opcode: Opc));
839 return false;
840 };
841
842 bool IsLegal = OpToFold.isOperandLegal(TII: *TII, MI: *MI, OpIdx: OpNo);
843 if (!IsLegal && OpToFold.isImm()) {
844 if (std::optional<int64_t> ImmVal = OpToFold.getEffectiveImmVal())
845 IsLegal = canUseImmWithOpSel(MI, UseOpNo: OpNo, ImmVal: *ImmVal);
846 }
847
848 if (!IsLegal) {
849 // Special case for v_mac_{f16, f32}_e64 if we are trying to fold into src2
850 unsigned NewOpc = macToMad(Opc);
851 if (NewOpc != AMDGPU::INSTRUCTION_LIST_END) {
852 // Check if changing this to a v_mad_{f16, f32} instruction will allow us
853 // to fold the operand.
854 MI->setDesc(TII->get(Opcode: NewOpc));
855 bool AddOpSel = !AMDGPU::hasNamedOperand(Opcode: Opc, NamedIdx: AMDGPU::OpName::op_sel) &&
856 AMDGPU::hasNamedOperand(Opcode: NewOpc, NamedIdx: AMDGPU::OpName::op_sel);
857 if (AddOpSel)
858 MI->addOperand(Op: MachineOperand::CreateImm(Val: 0));
859 bool FoldAsMAD = tryAddToFoldList(FoldList, MI, OpNo, OpToFold);
860 if (FoldAsMAD) {
861 MI->untieRegOperand(OpIdx: OpNo);
862 return true;
863 }
864 if (AddOpSel)
865 MI->removeOperand(OpNo: MI->getNumExplicitOperands() - 1);
866 MI->setDesc(TII->get(Opcode: Opc));
867 }
868
869 // Special case for s_fmac_f32 if we are trying to fold into Src2.
870 // By transforming into fmaak we can untie Src2 and make folding legal.
871 if (Opc == AMDGPU::S_FMAC_F32 && OpNo == 3) {
872 if (tryToFoldAsFMAAKorMK())
873 return true;
874 }
875
876 // Special case for s_setreg_b32
877 if (OpToFold.isImm()) {
878 unsigned ImmOpc = 0;
879 if (Opc == AMDGPU::S_SETREG_B32)
880 ImmOpc = AMDGPU::S_SETREG_IMM32_B32;
881 else if (Opc == AMDGPU::S_SETREG_B32_mode)
882 ImmOpc = AMDGPU::S_SETREG_IMM32_B32_mode;
883 if (ImmOpc) {
884 MI->setDesc(TII->get(Opcode: ImmOpc));
885 appendFoldCandidate(FoldList, MI, OpNo, FoldOp: OpToFold);
886 return true;
887 }
888 }
889
890 // Operand is not legal, so try to commute the instruction to
891 // see if this makes it possible to fold.
892 unsigned CommuteOpNo = TargetInstrInfo::CommuteAnyOperandIndex;
893 bool CanCommute = TII->findCommutedOpIndices(MI: *MI, SrcOpIdx0&: OpNo, SrcOpIdx1&: CommuteOpNo);
894 if (!CanCommute)
895 return false;
896
897 MachineOperand &Op = MI->getOperand(i: OpNo);
898 MachineOperand &CommutedOp = MI->getOperand(i: CommuteOpNo);
899
900 // One of operands might be an Imm operand, and OpNo may refer to it after
901 // the call of commuteInstruction() below. Such situations are avoided
902 // here explicitly as OpNo must be a register operand to be a candidate
903 // for memory folding.
904 if (!Op.isReg() || !CommutedOp.isReg())
905 return false;
906
907 // The same situation with an immediate could reproduce if both inputs are
908 // the same register.
909 if (Op.isReg() && CommutedOp.isReg() &&
910 (Op.getReg() == CommutedOp.getReg() &&
911 Op.getSubReg() == CommutedOp.getSubReg()))
912 return false;
913
914 if (!TII->commuteInstruction(MI&: *MI, NewMI: false, OpIdx1: OpNo, OpIdx2: CommuteOpNo))
915 return false;
916
917 int Op32 = -1;
918 if (!OpToFold.isOperandLegal(TII: *TII, MI: *MI, OpIdx: CommuteOpNo)) {
919 if ((Opc != AMDGPU::V_ADD_CO_U32_e64 && Opc != AMDGPU::V_SUB_CO_U32_e64 &&
920 Opc != AMDGPU::V_SUBREV_CO_U32_e64) || // FIXME
921 (!OpToFold.isImm() && !OpToFold.isFI() && !OpToFold.isGlobal())) {
922 TII->commuteInstruction(MI&: *MI, NewMI: false, OpIdx1: OpNo, OpIdx2: CommuteOpNo);
923 return false;
924 }
925
926 // Verify the other operand is a VGPR, otherwise we would violate the
927 // constant bus restriction.
928 MachineOperand &OtherOp = MI->getOperand(i: OpNo);
929 if (!OtherOp.isReg() ||
930 !TII->getRegisterInfo().isVGPR(MRI: *MRI, Reg: OtherOp.getReg()))
931 return false;
932
933 assert(MI->getOperand(1).isDef());
934
935 // Make sure to get the 32-bit version of the commuted opcode.
936 unsigned MaybeCommutedOpc = MI->getOpcode();
937 Op32 = AMDGPU::getVOPe32(Opcode: MaybeCommutedOpc);
938 }
939
940 appendFoldCandidate(FoldList, MI, OpNo: CommuteOpNo, FoldOp: OpToFold, /*Commuted=*/true,
941 ShrinkOp: Op32);
942 return true;
943 }
944
945 // Special case for s_fmac_f32 if we are trying to fold into Src0 or Src1.
946 // By changing into fmamk we can untie Src2.
947 // If folding for Src0 happens first and it is identical operand to Src1 we
948 // should avoid transforming into fmamk which requires commuting as it would
949 // cause folding into Src1 to fail later on due to wrong OpNo used.
950 if (Opc == AMDGPU::S_FMAC_F32 &&
951 (OpNo != 1 || !MI->getOperand(i: 1).isIdenticalTo(Other: MI->getOperand(i: 2)))) {
952 if (tryToFoldAsFMAAKorMK())
953 return true;
954 }
955
956 // Special case for PK_F32 instructions if we are trying to fold an imm to
957 // src0 or src1.
958 if (OpToFold.isImm() &&
959 isPKF32InstrReplicatesLower32BitsOfScalarOperand(ST, MI, OpNo) &&
960 !checkImmOpForPKF32InstrReplicatesLower32BitsOfScalarOperand(OpToFold))
961 return false;
962
963 appendFoldCandidate(FoldList, MI, OpNo, FoldOp: OpToFold);
964 return true;
965}
966
967bool SIFoldOperandsImpl::isUseSafeToFold(const MachineInstr &MI,
968 const MachineOperand &UseMO) const {
969 // Operands of SDWA instructions must be registers.
970 return !TII->isSDWA(MI);
971}
972
973static MachineOperand *lookUpCopyChain(const SIInstrInfo &TII,
974 const MachineRegisterInfo &MRI,
975 Register SrcReg) {
976 MachineOperand *Sub = nullptr;
977 for (MachineInstr *SubDef = MRI.getVRegDef(Reg: SrcReg);
978 SubDef && TII.isFoldableCopy(MI: *SubDef);
979 SubDef = MRI.getVRegDef(Reg: Sub->getReg())) {
980 unsigned SrcIdx = TII.getFoldableCopySrcIdx(MI: *SubDef);
981 MachineOperand &SrcOp = SubDef->getOperand(i: SrcIdx);
982
983 if (SrcOp.isImm())
984 return &SrcOp;
985 if (!SrcOp.isReg() || SrcOp.getReg().isPhysical())
986 break;
987 Sub = &SrcOp;
988 // TODO: Support compose
989 if (SrcOp.getSubReg())
990 break;
991 }
992
993 return Sub;
994}
995
996const TargetRegisterClass *SIFoldOperandsImpl::getRegSeqInit(
997 MachineInstr &RegSeq,
998 SmallVectorImpl<std::pair<MachineOperand *, unsigned>> &Defs) const {
999
1000 assert(RegSeq.isRegSequence());
1001
1002 const TargetRegisterClass *RC = nullptr;
1003
1004 for (unsigned I = 1, E = RegSeq.getNumExplicitOperands(); I != E; I += 2) {
1005 MachineOperand &SrcOp = RegSeq.getOperand(i: I);
1006 unsigned SubRegIdx = RegSeq.getOperand(i: I + 1).getImm();
1007
1008 // Only accept reg_sequence with uniform reg class inputs for simplicity.
1009 const TargetRegisterClass *OpRC = getRegOpRC(MRI: *MRI, TRI: *TRI, MO: SrcOp);
1010 if (!RC)
1011 RC = OpRC;
1012 else if (!TRI->getCommonSubClass(A: RC, B: OpRC))
1013 return nullptr;
1014
1015 if (SrcOp.getSubReg()) {
1016 // TODO: Handle subregister compose
1017 Defs.emplace_back(Args: &SrcOp, Args&: SubRegIdx);
1018 continue;
1019 }
1020
1021 MachineOperand *DefSrc = lookUpCopyChain(TII: *TII, MRI: *MRI, SrcReg: SrcOp.getReg());
1022 if (DefSrc && (DefSrc->isReg() || DefSrc->isImm())) {
1023 Defs.emplace_back(Args&: DefSrc, Args&: SubRegIdx);
1024 continue;
1025 }
1026
1027 Defs.emplace_back(Args: &SrcOp, Args&: SubRegIdx);
1028 }
1029
1030 return RC;
1031}
1032
1033// Find a def of the UseReg, check if it is a reg_sequence and find initializers
1034// for each subreg, tracking it to an immediate if possible. Returns the
1035// register class of the inputs on success.
1036const TargetRegisterClass *SIFoldOperandsImpl::getRegSeqInit(
1037 SmallVectorImpl<std::pair<MachineOperand *, unsigned>> &Defs,
1038 Register UseReg) const {
1039 MachineInstr *Def = MRI->getVRegDef(Reg: UseReg);
1040 if (!Def || !Def->isRegSequence())
1041 return nullptr;
1042
1043 return getRegSeqInit(RegSeq&: *Def, Defs);
1044}
1045
1046std::pair<int64_t, const TargetRegisterClass *>
1047SIFoldOperandsImpl::isRegSeqSplat(MachineInstr &RegSeq) const {
1048 SmallVector<std::pair<MachineOperand *, unsigned>, 32> Defs;
1049 const TargetRegisterClass *SrcRC = getRegSeqInit(RegSeq, Defs);
1050 if (!SrcRC)
1051 return {};
1052
1053 bool TryToMatchSplat64 = false;
1054
1055 int64_t Imm;
1056 for (unsigned I = 0, E = Defs.size(); I != E; ++I) {
1057 const MachineOperand *Op = Defs[I].first;
1058 if (!Op->isImm())
1059 return {};
1060
1061 int64_t SubImm = Op->getImm();
1062 if (!I) {
1063 Imm = SubImm;
1064 continue;
1065 }
1066
1067 if (Imm != SubImm) {
1068 if (I == 1 && (E & 1) == 0) {
1069 // If we have an even number of inputs, there's a chance this is a
1070 // 64-bit element splat broken into 32-bit pieces.
1071 TryToMatchSplat64 = true;
1072 break;
1073 }
1074
1075 return {}; // Can only fold splat constants
1076 }
1077 }
1078
1079 if (!TryToMatchSplat64)
1080 return {Defs[0].first->getImm(), SrcRC};
1081
1082 // Fallback to recognizing 64-bit splats broken into 32-bit pieces
1083 // (i.e. recognize every other other element is 0 for 64-bit immediates)
1084 int64_t SplatVal64;
1085 for (unsigned I = 0, E = Defs.size(); I != E; I += 2) {
1086 const MachineOperand *Op0 = Defs[I].first;
1087 const MachineOperand *Op1 = Defs[I + 1].first;
1088
1089 if (!Op0->isImm() || !Op1->isImm())
1090 return {};
1091
1092 unsigned SubReg0 = Defs[I].second;
1093 unsigned SubReg1 = Defs[I + 1].second;
1094
1095 // Assume we're going to generally encounter reg_sequences with sorted
1096 // subreg indexes, so reject any that aren't consecutive.
1097 if (TRI->getChannelFromSubReg(SubReg: SubReg0) + 1 !=
1098 TRI->getChannelFromSubReg(SubReg: SubReg1))
1099 return {};
1100
1101 if (TRI->getSubRegIdxSize(Idx: SubReg0) != 32)
1102 return {};
1103
1104 int64_t MergedVal = Make_64(High: Op1->getImm(), Low: Op0->getImm());
1105 if (I == 0)
1106 SplatVal64 = MergedVal;
1107 else if (SplatVal64 != MergedVal)
1108 return {};
1109 }
1110
1111 const TargetRegisterClass *RC64 = TRI->getSubRegisterClass(
1112 MRI->getRegClass(Reg: RegSeq.getOperand(i: 0).getReg()), AMDGPU::sub0_sub1);
1113
1114 return {SplatVal64, RC64};
1115}
1116
1117bool SIFoldOperandsImpl::tryFoldRegSeqSplat(
1118 MachineInstr *UseMI, unsigned UseOpIdx, int64_t SplatVal,
1119 const TargetRegisterClass *SplatRC) const {
1120 const MCInstrDesc &Desc = UseMI->getDesc();
1121 if (UseOpIdx >= Desc.getNumOperands())
1122 return false;
1123
1124 // Filter out unhandled pseudos.
1125 if (!AMDGPU::isSISrcOperand(Desc, OpNo: UseOpIdx))
1126 return false;
1127
1128 int16_t RCID = TII->getOpRegClassID(OpInfo: Desc.operands()[UseOpIdx]);
1129 if (RCID == -1)
1130 return false;
1131
1132 const TargetRegisterClass *OpRC = TRI->getRegClass(i: RCID);
1133
1134 // Special case 0/-1, since when interpreted as a 64-bit element both halves
1135 // have the same bits. These are the only cases where a splat has the same
1136 // interpretation for 32-bit and 64-bit splats.
1137 if (SplatVal != 0 && SplatVal != -1) {
1138 // We need to figure out the scalar type read by the operand. e.g. the MFMA
1139 // operand will be AReg_128, and we want to check if it's compatible with an
1140 // AReg_32 constant.
1141 uint8_t OpTy = Desc.operands()[UseOpIdx].OperandType;
1142 switch (OpTy) {
1143 case AMDGPU::OPERAND_REG_INLINE_AC_INT32:
1144 case AMDGPU::OPERAND_REG_INLINE_AC_FP32:
1145 case AMDGPU::OPERAND_REG_INLINE_C_INT32:
1146 case AMDGPU::OPERAND_REG_INLINE_C_FP32:
1147 OpRC = TRI->getSubRegisterClass(OpRC, AMDGPU::sub0);
1148 break;
1149 case AMDGPU::OPERAND_REG_INLINE_AC_FP64:
1150 case AMDGPU::OPERAND_REG_INLINE_C_FP64:
1151 case AMDGPU::OPERAND_REG_IMM_V2FP64:
1152 case AMDGPU::OPERAND_REG_INLINE_C_INT64:
1153 case AMDGPU::OPERAND_REG_IMM_V2INT64:
1154 OpRC = TRI->getSubRegisterClass(OpRC, AMDGPU::sub0_sub1);
1155 break;
1156 default:
1157 return false;
1158 }
1159
1160 if (!TRI->getCommonSubClass(A: OpRC, B: SplatRC))
1161 return false;
1162 }
1163
1164 MachineOperand TmpOp = MachineOperand::CreateImm(Val: SplatVal);
1165 if (!TII->isOperandLegal(MI: *UseMI, OpIdx: UseOpIdx, MO: &TmpOp))
1166 return false;
1167
1168 return true;
1169}
1170
1171bool SIFoldOperandsImpl::tryToFoldACImm(
1172 const FoldableDef &OpToFold, MachineInstr *UseMI, unsigned UseOpIdx,
1173 SmallVectorImpl<FoldCandidate> &FoldList) const {
1174 const MCInstrDesc &Desc = UseMI->getDesc();
1175 if (UseOpIdx >= Desc.getNumOperands())
1176 return false;
1177
1178 // Filter out unhandled pseudos.
1179 if (!AMDGPU::isSISrcOperand(Desc, OpNo: UseOpIdx))
1180 return false;
1181
1182 if (OpToFold.isImm() && OpToFold.isOperandLegal(TII: *TII, MI: *UseMI, OpIdx: UseOpIdx)) {
1183 if (isPKF32InstrReplicatesLower32BitsOfScalarOperand(ST, MI: UseMI, OpNo: UseOpIdx) &&
1184 !checkImmOpForPKF32InstrReplicatesLower32BitsOfScalarOperand(OpToFold))
1185 return false;
1186 appendFoldCandidate(FoldList, MI: UseMI, OpNo: UseOpIdx, FoldOp: OpToFold);
1187 return true;
1188 }
1189
1190 return false;
1191}
1192
1193void SIFoldOperandsImpl::foldOperand(
1194 FoldableDef OpToFold, MachineInstr *UseMI, int UseOpIdx,
1195 SmallVectorImpl<FoldCandidate> &FoldList,
1196 SmallVectorImpl<MachineInstr *> &CopiesToReplace) const {
1197 const MachineOperand *UseOp = &UseMI->getOperand(i: UseOpIdx);
1198
1199 if (!isUseSafeToFold(MI: *UseMI, UseMO: *UseOp))
1200 return;
1201
1202 // FIXME: Fold operands with subregs.
1203 if (UseOp->isReg() && OpToFold.isReg()) {
1204 if (UseOp->isImplicit())
1205 return;
1206 // Allow folding from SGPRs to 16-bit VGPRs.
1207 if (UseOp->getSubReg() != AMDGPU::NoSubRegister &&
1208 (UseOp->getSubReg() != AMDGPU::lo16 ||
1209 !TRI->isSGPRReg(MRI: *MRI, Reg: OpToFold.getReg())))
1210 return;
1211 }
1212
1213 // Special case for REG_SEQUENCE: We can't fold literals into
1214 // REG_SEQUENCE instructions, so we have to fold them into the
1215 // uses of REG_SEQUENCE.
1216 if (UseMI->isRegSequence()) {
1217 Register RegSeqDstReg = UseMI->getOperand(i: 0).getReg();
1218 unsigned RegSeqDstSubReg = UseMI->getOperand(i: UseOpIdx + 1).getImm();
1219
1220 int64_t SplatVal;
1221 const TargetRegisterClass *SplatRC;
1222 std::tie(args&: SplatVal, args&: SplatRC) = isRegSeqSplat(RegSeq&: *UseMI);
1223
1224 // Grab the use operands first
1225 SmallVector<MachineOperand *, 4> UsesToProcess(
1226 llvm::make_pointer_range(Range: MRI->use_nodbg_operands(Reg: RegSeqDstReg)));
1227 for (unsigned I = 0; I != UsesToProcess.size(); ++I) {
1228 MachineOperand *RSUse = UsesToProcess[I];
1229 MachineInstr *RSUseMI = RSUse->getParent();
1230 unsigned OpNo = RSUseMI->getOperandNo(I: RSUse);
1231
1232 if (SplatRC) {
1233 if (RSUseMI->isCopy()) {
1234 Register DstReg = RSUseMI->getOperand(i: 0).getReg();
1235 append_range(C&: UsesToProcess,
1236 R: make_pointer_range(Range: MRI->use_nodbg_operands(Reg: DstReg)));
1237 continue;
1238 }
1239 if (tryFoldRegSeqSplat(UseMI: RSUseMI, UseOpIdx: OpNo, SplatVal, SplatRC)) {
1240 FoldableDef SplatDef(SplatVal, SplatRC);
1241 appendFoldCandidate(FoldList, MI: RSUseMI, OpNo, FoldOp: SplatDef);
1242 continue;
1243 }
1244 }
1245
1246 // TODO: Handle general compose
1247 if (RSUse->getSubReg() != RegSeqDstSubReg)
1248 continue;
1249
1250 // FIXME: We should avoid recursing here. There should be a cleaner split
1251 // between the in-place mutations and adding to the fold list.
1252 foldOperand(OpToFold, UseMI: RSUseMI, UseOpIdx: RSUseMI->getOperandNo(I: RSUse), FoldList,
1253 CopiesToReplace);
1254 }
1255
1256 return;
1257 }
1258
1259 if (tryToFoldACImm(OpToFold, UseMI, UseOpIdx, FoldList))
1260 return;
1261
1262 if (frameIndexMayFold(UseMI: *UseMI, OpNo: UseOpIdx, OpToFold)) {
1263 // Verify that this is a stack access.
1264 // FIXME: Should probably use stack pseudos before frame lowering.
1265
1266 if (TII->isMUBUF(MI: *UseMI)) {
1267 if (TII->getNamedOperand(MI&: *UseMI, OperandName: AMDGPU::OpName::srsrc)->getReg() !=
1268 MFI->getScratchRSrcReg())
1269 return;
1270
1271 // Ensure this is either relative to the current frame or the current
1272 // wave.
1273 MachineOperand &SOff =
1274 *TII->getNamedOperand(MI&: *UseMI, OperandName: AMDGPU::OpName::soffset);
1275 if (!SOff.isImm() || SOff.getImm() != 0)
1276 return;
1277 }
1278
1279 const unsigned Opc = UseMI->getOpcode();
1280 if (TII->isFLATScratch(MI: *UseMI) &&
1281 AMDGPU::hasNamedOperand(Opcode: Opc, NamedIdx: AMDGPU::OpName::vaddr) &&
1282 !AMDGPU::hasNamedOperand(Opcode: Opc, NamedIdx: AMDGPU::OpName::saddr)) {
1283 unsigned NewOpc = AMDGPU::getFlatScratchInstSSfromSV(Opcode: Opc);
1284 unsigned CPol =
1285 TII->getNamedOperand(MI&: *UseMI, OperandName: AMDGPU::OpName::cpol)->getImm();
1286 if ((CPol & AMDGPU::CPol::SCAL) &&
1287 !AMDGPU::supportsScaleOffset(MII: *TII, Opcode: NewOpc))
1288 return;
1289
1290 UseMI->setDesc(TII->get(Opcode: NewOpc));
1291 }
1292
1293 // A frame index will resolve to a positive constant, so it should always be
1294 // safe to fold the addressing mode, even pre-GFX9.
1295 UseMI->getOperand(i: UseOpIdx).ChangeToFrameIndex(Idx: OpToFold.getFI());
1296
1297 return;
1298 }
1299
1300 bool FoldingImmLike =
1301 OpToFold.isImm() || OpToFold.isFI() || OpToFold.isGlobal();
1302
1303 if (FoldingImmLike && UseMI->isCopy()) {
1304 Register DestReg = UseMI->getOperand(i: 0).getReg();
1305 Register SrcReg = UseMI->getOperand(i: 1).getReg();
1306 unsigned UseSubReg = UseMI->getOperand(i: 1).getSubReg();
1307 assert(SrcReg.isVirtual());
1308
1309 const TargetRegisterClass *SrcRC = MRI->getRegClass(Reg: SrcReg);
1310
1311 // Don't fold into a copy to a physical register with the same class. Doing
1312 // so would interfere with the register coalescer's logic which would avoid
1313 // redundant initializations.
1314 if (DestReg.isPhysical() && SrcRC->contains(Reg: DestReg))
1315 return;
1316
1317 const TargetRegisterClass *DestRC = TRI->getRegClassForReg(MRI: *MRI, Reg: DestReg);
1318 // In order to fold immediates into copies, we need to change the copy to a
1319 // MOV. Find a compatible mov instruction with the value.
1320 for (unsigned MovOp :
1321 {AMDGPU::S_MOV_B32, AMDGPU::V_MOV_B32_e32, AMDGPU::S_MOV_B64,
1322 AMDGPU::V_MOV_B64_PSEUDO, AMDGPU::V_MOV_B16_t16_e64,
1323 AMDGPU::V_ACCVGPR_WRITE_B32_e64, AMDGPU::AV_MOV_B32_IMM_PSEUDO,
1324 AMDGPU::AV_MOV_B64_IMM_PSEUDO}) {
1325 const MCInstrDesc &MovDesc = TII->get(Opcode: MovOp);
1326 const TargetRegisterClass *MovDstRC =
1327 TRI->getRegClass(i: TII->getOpRegClassID(OpInfo: MovDesc.operands()[0]));
1328
1329 // Fold if the destination register class of the MOV instruction (ResRC)
1330 // is a superclass of (or equal to) the destination register class of the
1331 // COPY (DestRC). If this condition fails, folding would be illegal.
1332 if (!DestRC->hasSuperClassEq(RC: MovDstRC))
1333 continue;
1334
1335 const int SrcIdx = MovOp == AMDGPU::V_MOV_B16_t16_e64 ? 2 : 1;
1336
1337 int16_t RegClassID = TII->getOpRegClassID(OpInfo: MovDesc.operands()[SrcIdx]);
1338 if (RegClassID != -1) {
1339 const TargetRegisterClass *MovSrcRC = TRI->getRegClass(i: RegClassID);
1340
1341 if (UseSubReg)
1342 MovSrcRC = TRI->getMatchingSuperRegClass(A: SrcRC, B: MovSrcRC, Idx: UseSubReg);
1343
1344 // FIXME: We should be able to directly check immediate operand legality
1345 // for all cases, but gfx908 hacks break.
1346 if (MovOp == AMDGPU::AV_MOV_B32_IMM_PSEUDO &&
1347 (!OpToFold.isImm() ||
1348 !TII->isImmOperandLegal(InstDesc: MovDesc, OpNo: SrcIdx,
1349 ImmVal: *OpToFold.getEffectiveImmVal())))
1350 break;
1351
1352 if (!MRI->constrainRegClass(Reg: SrcReg, RC: MovSrcRC))
1353 break;
1354
1355 // FIXME: This is mutating the instruction only and deferring the actual
1356 // fold of the immediate
1357 } else {
1358 // For the _IMM_PSEUDO cases, there can be value restrictions on the
1359 // immediate to verify. Technically we should always verify this, but it
1360 // only matters for these concrete cases.
1361 // TODO: Handle non-imm case if it's useful.
1362 if (!OpToFold.isImm() ||
1363 !TII->isImmOperandLegal(InstDesc: MovDesc, OpNo: 1, ImmVal: *OpToFold.getEffectiveImmVal()))
1364 break;
1365 }
1366
1367 MachineInstr::mop_iterator ImpOpI = UseMI->implicit_operands().begin();
1368 MachineInstr::mop_iterator ImpOpE = UseMI->implicit_operands().end();
1369 while (ImpOpI != ImpOpE) {
1370 MachineInstr::mop_iterator Tmp = ImpOpI;
1371 ImpOpI++;
1372 UseMI->removeOperand(OpNo: UseMI->getOperandNo(I: Tmp));
1373 }
1374 UseMI->setDesc(MovDesc);
1375
1376 if (MovOp == AMDGPU::V_MOV_B16_t16_e64) {
1377 const auto &SrcOp = UseMI->getOperand(i: UseOpIdx);
1378 MachineOperand NewSrcOp(SrcOp);
1379 MachineFunction *MF = UseMI->getMF();
1380 UseMI->removeOperand(OpNo: 1);
1381 UseMI->addOperand(MF&: *MF, Op: MachineOperand::CreateImm(Val: 0)); // src0_modifiers
1382 UseMI->addOperand(Op: NewSrcOp); // src0
1383 UseMI->addOperand(MF&: *MF, Op: MachineOperand::CreateImm(Val: 0)); // op_sel
1384 UseOpIdx = SrcIdx;
1385 UseOp = &UseMI->getOperand(i: UseOpIdx);
1386 }
1387 CopiesToReplace.push_back(Elt: UseMI);
1388 break;
1389 }
1390
1391 // We failed to replace the copy, so give up.
1392 if (UseMI->getOpcode() == AMDGPU::COPY)
1393 return;
1394
1395 } else {
1396 if (UseMI->isCopy() && OpToFold.isReg() &&
1397 UseMI->getOperand(i: 0).getReg().isVirtual() &&
1398 !UseMI->getOperand(i: 1).getSubReg() &&
1399 OpToFold.DefMI->implicit_operands().empty()) {
1400 LLVM_DEBUG(dbgs() << "Folding " << OpToFold.OpToFold << "\n into "
1401 << *UseMI);
1402 unsigned Size = TII->getOpSize(MI: *UseMI, OpNo: 1);
1403 Register UseReg = OpToFold.getReg();
1404 UseMI->getOperand(i: 1).setReg(UseReg);
1405 unsigned SubRegIdx = OpToFold.getSubReg();
1406 // Hack to allow 32-bit SGPRs to be folded into True16 instructions
1407 // Remove this if 16-bit SGPRs (i.e. SGPR_LO16) are added to the
1408 // VS_16RegClass
1409 //
1410 // Excerpt from AMDGPUGenRegisterInfoEnums.inc
1411 // NoSubRegister, //0
1412 // hi16, // 1
1413 // lo16, // 2
1414 // sub0, // 3
1415 // ...
1416 // sub1, // 11
1417 // sub1_hi16, // 12
1418 // sub1_lo16, // 13
1419 static_assert(AMDGPU::sub1_hi16 == 12, "Subregister layout has changed");
1420 if (Size == 2 && TRI->isVGPR(MRI: *MRI, Reg: UseMI->getOperand(i: 0).getReg()) &&
1421 TRI->isSGPRReg(MRI: *MRI, Reg: UseReg)) {
1422 // Produce the 32 bit subregister index to which the 16-bit subregister
1423 // is aligned.
1424 if (SubRegIdx > AMDGPU::sub1) {
1425 LaneBitmask M = TRI->getSubRegIndexLaneMask(SubIdx: SubRegIdx);
1426 M |= M.getLane(Lane: M.getHighestLane() - 1);
1427 SmallVector<unsigned, 4> Indexes;
1428 TRI->getCoveringSubRegIndexes(RC: TRI->getRegClassForReg(MRI: *MRI, Reg: UseReg), LaneMask: M,
1429 Indexes);
1430 assert(Indexes.size() == 1 && "Expected one 32-bit subreg to cover");
1431 SubRegIdx = Indexes[0];
1432 // 32-bit registers do not have a sub0 index
1433 } else if (TII->getOpSize(MI: *UseMI, OpNo: 1) == 4)
1434 SubRegIdx = 0;
1435 else
1436 SubRegIdx = AMDGPU::sub0;
1437 }
1438 UseMI->getOperand(i: 1).setSubReg(SubRegIdx);
1439 UseMI->getOperand(i: 1).setIsKill(false);
1440 CopiesToReplace.push_back(Elt: UseMI);
1441 OpToFold.OpToFold->setIsKill(false);
1442
1443 // Remove kill flags as kills may now be out of order with uses.
1444 MRI->clearKillFlags(Reg: UseReg);
1445 if (foldCopyToAGPRRegSequence(CopyMI: UseMI))
1446 return;
1447 }
1448
1449 unsigned UseOpc = UseMI->getOpcode();
1450 if (UseOpc == AMDGPU::V_READFIRSTLANE_B32 ||
1451 (UseOpc == AMDGPU::V_READLANE_B32 &&
1452 (int)UseOpIdx ==
1453 AMDGPU::getNamedOperandIdx(Opcode: UseOpc, Name: AMDGPU::OpName::src0))) {
1454 // %vgpr = V_MOV_B32 imm
1455 // %sgpr = V_READFIRSTLANE_B32 %vgpr
1456 // =>
1457 // %sgpr = S_MOV_B32 imm
1458 if (FoldingImmLike) {
1459 if (execMayBeModifiedBeforeUse(MRI: *MRI,
1460 VReg: UseMI->getOperand(i: UseOpIdx).getReg(),
1461 DefMI: *OpToFold.DefMI, UseMI: *UseMI))
1462 return;
1463
1464 UseMI->setDesc(TII->get(Opcode: AMDGPU::S_MOV_B32));
1465 UseMI->clearFlag(Flag: MachineInstr::NoConvergent);
1466
1467 if (OpToFold.isImm()) {
1468 UseMI->getOperand(i: 1).ChangeToImmediate(
1469 ImmVal: *OpToFold.getEffectiveImmVal());
1470 } else if (OpToFold.isFI())
1471 UseMI->getOperand(i: 1).ChangeToFrameIndex(Idx: OpToFold.getFI());
1472 else {
1473 assert(OpToFold.isGlobal());
1474 UseMI->getOperand(i: 1).ChangeToGA(GV: OpToFold.OpToFold->getGlobal(),
1475 Offset: OpToFold.OpToFold->getOffset(),
1476 TargetFlags: OpToFold.OpToFold->getTargetFlags());
1477 }
1478 UseMI->removeOperand(OpNo: 2); // Remove exec read (or src1 for readlane)
1479 return;
1480 }
1481
1482 if (OpToFold.isReg() && TRI->isSGPRReg(MRI: *MRI, Reg: OpToFold.getReg())) {
1483 if (execMayBeModifiedBeforeUse(MRI: *MRI,
1484 VReg: UseMI->getOperand(i: UseOpIdx).getReg(),
1485 DefMI: *OpToFold.DefMI, UseMI: *UseMI))
1486 return;
1487
1488 // %vgpr = COPY %sgpr0
1489 // %sgpr1 = V_READFIRSTLANE_B32 %vgpr
1490 // =>
1491 // %sgpr1 = COPY %sgpr0
1492 UseMI->setDesc(TII->get(Opcode: AMDGPU::COPY));
1493 UseMI->getOperand(i: 1).setReg(OpToFold.getReg());
1494 UseMI->getOperand(i: 1).setSubReg(OpToFold.getSubReg());
1495 UseMI->getOperand(i: 1).setIsKill(false);
1496 UseMI->removeOperand(OpNo: 2); // Remove exec read (or src1 for readlane)
1497 UseMI->clearFlag(Flag: MachineInstr::NoConvergent);
1498 return;
1499 }
1500 }
1501
1502 const MCInstrDesc &UseDesc = UseMI->getDesc();
1503
1504 // Don't fold into target independent nodes. Target independent opcodes
1505 // don't have defined register classes.
1506 if (UseDesc.isVariadic() || UseOp->isImplicit() ||
1507 UseDesc.operands()[UseOpIdx].RegClass == -1)
1508 return;
1509 }
1510
1511 // FIXME: We could try to change the instruction from 64-bit to 32-bit
1512 // to enable more folding opportunities. The shrink operands pass
1513 // already does this.
1514
1515 tryAddToFoldList(FoldList, MI: UseMI, OpNo: UseOpIdx, OpToFold);
1516}
1517
1518static bool evalBinaryInstruction(unsigned Opcode, int32_t &Result,
1519 uint32_t LHS, uint32_t RHS) {
1520 switch (Opcode) {
1521 case AMDGPU::S_ADD_I32:
1522 case AMDGPU::S_ADD_U32:
1523 Result = LHS + RHS;
1524 return true;
1525 case AMDGPU::S_SUB_I32:
1526 case AMDGPU::S_SUB_U32:
1527 Result = LHS - RHS;
1528 return true;
1529 case AMDGPU::V_AND_B32_e64:
1530 case AMDGPU::V_AND_B32_e32:
1531 case AMDGPU::S_AND_B32:
1532 Result = LHS & RHS;
1533 return true;
1534 case AMDGPU::V_OR_B32_e64:
1535 case AMDGPU::V_OR_B32_e32:
1536 case AMDGPU::S_OR_B32:
1537 Result = LHS | RHS;
1538 return true;
1539 case AMDGPU::V_XOR_B32_e64:
1540 case AMDGPU::V_XOR_B32_e32:
1541 case AMDGPU::S_XOR_B32:
1542 Result = LHS ^ RHS;
1543 return true;
1544 case AMDGPU::S_XNOR_B32:
1545 Result = ~(LHS ^ RHS);
1546 return true;
1547 case AMDGPU::S_NAND_B32:
1548 Result = ~(LHS & RHS);
1549 return true;
1550 case AMDGPU::S_NOR_B32:
1551 Result = ~(LHS | RHS);
1552 return true;
1553 case AMDGPU::S_ANDN2_B32:
1554 Result = LHS & ~RHS;
1555 return true;
1556 case AMDGPU::S_ORN2_B32:
1557 Result = LHS | ~RHS;
1558 return true;
1559 case AMDGPU::V_LSHL_B32_e64:
1560 case AMDGPU::V_LSHL_B32_e32:
1561 case AMDGPU::S_LSHL_B32:
1562 // The instruction ignores the high bits for out of bounds shifts.
1563 Result = LHS << (RHS & 31);
1564 return true;
1565 case AMDGPU::V_LSHLREV_B32_e64:
1566 case AMDGPU::V_LSHLREV_B32_e32:
1567 Result = RHS << (LHS & 31);
1568 return true;
1569 case AMDGPU::V_LSHR_B32_e64:
1570 case AMDGPU::V_LSHR_B32_e32:
1571 case AMDGPU::S_LSHR_B32:
1572 Result = LHS >> (RHS & 31);
1573 return true;
1574 case AMDGPU::V_LSHRREV_B32_e64:
1575 case AMDGPU::V_LSHRREV_B32_e32:
1576 Result = RHS >> (LHS & 31);
1577 return true;
1578 case AMDGPU::V_ASHR_I32_e64:
1579 case AMDGPU::V_ASHR_I32_e32:
1580 case AMDGPU::S_ASHR_I32:
1581 Result = static_cast<int32_t>(LHS) >> (RHS & 31);
1582 return true;
1583 case AMDGPU::V_ASHRREV_I32_e64:
1584 case AMDGPU::V_ASHRREV_I32_e32:
1585 Result = static_cast<int32_t>(RHS) >> (LHS & 31);
1586 return true;
1587 default:
1588 return false;
1589 }
1590}
1591
1592static unsigned getMovOpc(bool IsScalar) {
1593 return IsScalar ? AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32;
1594}
1595
1596// Try to simplify operations with a constant that may appear after instruction
1597// selection.
1598// TODO: See if a frame index with a fixed offset can fold.
1599bool SIFoldOperandsImpl::tryConstantFoldOp(MachineInstr *MI) const {
1600 if (!MI->allImplicitDefsAreDead())
1601 return false;
1602
1603 unsigned Opc = MI->getOpcode();
1604
1605 int Src0Idx = AMDGPU::getNamedOperandIdx(Opcode: Opc, Name: AMDGPU::OpName::src0);
1606 if (Src0Idx == -1)
1607 return false;
1608
1609 MachineOperand *Src0 = &MI->getOperand(i: Src0Idx);
1610 std::optional<int64_t> Src0Imm = TII->getImmOrMaterializedImm(Op&: *Src0);
1611
1612 if ((Opc == AMDGPU::V_NOT_B32_e64 || Opc == AMDGPU::V_NOT_B32_e32 ||
1613 Opc == AMDGPU::S_NOT_B32) &&
1614 Src0Imm) {
1615 MI->getOperand(i: 1).ChangeToImmediate(ImmVal: ~*Src0Imm);
1616 TII->mutateAndCleanupImplicit(
1617 MI&: *MI, NewDesc: TII->get(Opcode: getMovOpc(IsScalar: Opc == AMDGPU::S_NOT_B32)));
1618 return true;
1619 }
1620
1621 int Src1Idx = AMDGPU::getNamedOperandIdx(Opcode: Opc, Name: AMDGPU::OpName::src1);
1622 if (Src1Idx == -1)
1623 return false;
1624
1625 MachineOperand *Src1 = &MI->getOperand(i: Src1Idx);
1626 std::optional<int64_t> Src1Imm = TII->getImmOrMaterializedImm(Op&: *Src1);
1627
1628 if (!Src0Imm && !Src1Imm)
1629 return false;
1630
1631 // and k0, k1 -> v_mov_b32 (k0 & k1)
1632 // or k0, k1 -> v_mov_b32 (k0 | k1)
1633 // xor k0, k1 -> v_mov_b32 (k0 ^ k1)
1634 if (Src0Imm && Src1Imm) {
1635 int32_t NewImm;
1636 if (!evalBinaryInstruction(Opcode: Opc, Result&: NewImm, LHS: *Src0Imm, RHS: *Src1Imm))
1637 return false;
1638
1639 bool IsSGPR = TRI->isSGPRReg(MRI: *MRI, Reg: MI->getOperand(i: 0).getReg());
1640
1641 // Be careful to change the right operand, src0 may belong to a different
1642 // instruction.
1643 MI->getOperand(i: Src0Idx).ChangeToImmediate(ImmVal: NewImm);
1644 MI->removeOperand(OpNo: Src1Idx);
1645 TII->mutateAndCleanupImplicit(MI&: *MI, NewDesc: TII->get(Opcode: getMovOpc(IsScalar: IsSGPR)));
1646 return true;
1647 }
1648
1649 // S_SUB_* is not commutable, so handle it before the commutability gate.
1650 // Only `x - 0 -> copy x` is valid; `0 - x` is a negation, not a copy.
1651 if (Opc == AMDGPU::S_SUB_I32 || Opc == AMDGPU::S_SUB_U32) {
1652 if (Src1Imm && static_cast<int32_t>(*Src1Imm) == 0) {
1653 // y = sub x, 0 => y = copy x
1654 MI->removeOperand(OpNo: Src1Idx);
1655 TII->mutateAndCleanupImplicit(MI&: *MI, NewDesc: TII->get(Opcode: AMDGPU::COPY));
1656 return true;
1657 }
1658 return false;
1659 }
1660
1661 if (!MI->isCommutable())
1662 return false;
1663
1664 if (Src0Imm && !Src1Imm) {
1665 std::swap(a&: Src0, b&: Src1);
1666 std::swap(a&: Src0Idx, b&: Src1Idx);
1667 std::swap(lhs&: Src0Imm, rhs&: Src1Imm);
1668 }
1669
1670 int32_t Src1Val = static_cast<int32_t>(*Src1Imm);
1671 if (Opc == AMDGPU::S_ADD_I32 || Opc == AMDGPU::S_ADD_U32) {
1672 if (Src1Val == 0) {
1673 // y = add x, 0 => y = copy x
1674 MI->removeOperand(OpNo: Src1Idx);
1675 TII->mutateAndCleanupImplicit(MI&: *MI, NewDesc: TII->get(Opcode: AMDGPU::COPY));
1676 return true;
1677 }
1678 return false;
1679 }
1680
1681 if (Opc == AMDGPU::V_OR_B32_e64 ||
1682 Opc == AMDGPU::V_OR_B32_e32 ||
1683 Opc == AMDGPU::S_OR_B32) {
1684 if (Src1Val == 0) {
1685 // y = or x, 0 => y = copy x
1686 MI->removeOperand(OpNo: Src1Idx);
1687 TII->mutateAndCleanupImplicit(MI&: *MI, NewDesc: TII->get(Opcode: AMDGPU::COPY));
1688 } else if (Src1Val == -1) {
1689 // y = or x, -1 => y = v_mov_b32 -1
1690 MI->removeOperand(OpNo: Src0Idx);
1691 TII->mutateAndCleanupImplicit(
1692 MI&: *MI, NewDesc: TII->get(Opcode: getMovOpc(IsScalar: Opc == AMDGPU::S_OR_B32)));
1693 } else
1694 return false;
1695
1696 return true;
1697 }
1698
1699 if (Opc == AMDGPU::V_AND_B32_e64 || Opc == AMDGPU::V_AND_B32_e32 ||
1700 Opc == AMDGPU::S_AND_B32) {
1701 if (Src1Val == 0) {
1702 // y = and x, 0 => y = v_mov_b32 0
1703 MI->removeOperand(OpNo: Src0Idx);
1704 TII->mutateAndCleanupImplicit(
1705 MI&: *MI, NewDesc: TII->get(Opcode: getMovOpc(IsScalar: Opc == AMDGPU::S_AND_B32)));
1706 } else if (Src1Val == -1) {
1707 // y = and x, -1 => y = copy x
1708 MI->removeOperand(OpNo: Src1Idx);
1709 TII->mutateAndCleanupImplicit(MI&: *MI, NewDesc: TII->get(Opcode: AMDGPU::COPY));
1710 } else
1711 return false;
1712
1713 return true;
1714 }
1715
1716 if (Opc == AMDGPU::V_XOR_B32_e64 || Opc == AMDGPU::V_XOR_B32_e32 ||
1717 Opc == AMDGPU::S_XOR_B32) {
1718 if (Src1Val == 0) {
1719 // y = xor x, 0 => y = copy x
1720 MI->removeOperand(OpNo: Src1Idx);
1721 TII->mutateAndCleanupImplicit(MI&: *MI, NewDesc: TII->get(Opcode: AMDGPU::COPY));
1722 return true;
1723 }
1724 }
1725
1726 return false;
1727}
1728
1729// Try to fold an instruction into a simpler one
1730bool SIFoldOperandsImpl::tryFoldCndMask(MachineInstr &MI) const {
1731 unsigned Opc = MI.getOpcode();
1732 if (Opc != AMDGPU::V_CNDMASK_B32_e32 && Opc != AMDGPU::V_CNDMASK_B32_e64 &&
1733 Opc != AMDGPU::V_CNDMASK_B64_PSEUDO)
1734 return false;
1735
1736 MachineOperand *Src0 = TII->getNamedOperand(MI, OperandName: AMDGPU::OpName::src0);
1737 MachineOperand *Src1 = TII->getNamedOperand(MI, OperandName: AMDGPU::OpName::src1);
1738 if (!Src1->isIdenticalTo(Other: *Src0)) {
1739 std::optional<int64_t> Src1Imm = TII->getImmOrMaterializedImm(Op&: *Src1);
1740 if (!Src1Imm)
1741 return false;
1742
1743 std::optional<int64_t> Src0Imm = TII->getImmOrMaterializedImm(Op&: *Src0);
1744 if (!Src0Imm || *Src0Imm != *Src1Imm)
1745 return false;
1746 }
1747
1748 int Src1ModIdx =
1749 AMDGPU::getNamedOperandIdx(Opcode: Opc, Name: AMDGPU::OpName::src1_modifiers);
1750 int Src0ModIdx =
1751 AMDGPU::getNamedOperandIdx(Opcode: Opc, Name: AMDGPU::OpName::src0_modifiers);
1752 if ((Src1ModIdx != -1 && MI.getOperand(i: Src1ModIdx).getImm() != 0) ||
1753 (Src0ModIdx != -1 && MI.getOperand(i: Src0ModIdx).getImm() != 0))
1754 return false;
1755
1756 LLVM_DEBUG(dbgs() << "Folded " << MI << " into ");
1757 auto &NewDesc =
1758 TII->get(Opcode: Src0->isReg() ? (unsigned)AMDGPU::COPY : getMovOpc(IsScalar: false));
1759 int Src2Idx = AMDGPU::getNamedOperandIdx(Opcode: Opc, Name: AMDGPU::OpName::src2);
1760 if (Src2Idx != -1)
1761 MI.removeOperand(OpNo: Src2Idx);
1762 MI.removeOperand(OpNo: AMDGPU::getNamedOperandIdx(Opcode: Opc, Name: AMDGPU::OpName::src1));
1763 if (Src1ModIdx != -1)
1764 MI.removeOperand(OpNo: Src1ModIdx);
1765 if (Src0ModIdx != -1)
1766 MI.removeOperand(OpNo: Src0ModIdx);
1767 TII->mutateAndCleanupImplicit(MI, NewDesc);
1768 LLVM_DEBUG(dbgs() << MI);
1769 return true;
1770}
1771
1772bool SIFoldOperandsImpl::tryFoldZeroHighBits(MachineInstr &MI) const {
1773 if (MI.getOpcode() != AMDGPU::V_AND_B32_e64 &&
1774 MI.getOpcode() != AMDGPU::V_AND_B32_e32)
1775 return false;
1776
1777 std::optional<int64_t> Src0Imm =
1778 TII->getImmOrMaterializedImm(Op&: MI.getOperand(i: 1));
1779 if (!Src0Imm || *Src0Imm != 0xffff || !MI.getOperand(i: 2).isReg())
1780 return false;
1781
1782 Register Src1 = MI.getOperand(i: 2).getReg();
1783 MachineInstr *SrcDef = MRI->getVRegDef(Reg: Src1);
1784 if (!ST->zeroesHigh16BitsOfDest(Opcode: SrcDef->getOpcode()))
1785 return false;
1786
1787 Register Dst = MI.getOperand(i: 0).getReg();
1788 MRI->replaceRegWith(FromReg: Dst, ToReg: Src1);
1789 if (!MI.getOperand(i: 2).isKill())
1790 MRI->clearKillFlags(Reg: Src1);
1791 MI.eraseFromParent();
1792 return true;
1793}
1794
1795bool SIFoldOperandsImpl::foldInstOperand(MachineInstr &MI,
1796 const FoldableDef &OpToFold) const {
1797 // We need mutate the operands of new mov instructions to add implicit
1798 // uses of EXEC, but adding them invalidates the use_iterator, so defer
1799 // this.
1800 SmallVector<MachineInstr *, 4> CopiesToReplace;
1801 SmallVector<FoldCandidate, 4> FoldList;
1802 MachineOperand &Dst = MI.getOperand(i: 0);
1803 bool Changed = false;
1804
1805 if (OpToFold.isImm()) {
1806 for (auto &UseMI :
1807 make_early_inc_range(Range: MRI->use_nodbg_instructions(Reg: Dst.getReg()))) {
1808 // Folding the immediate may reveal operations that can be constant
1809 // folded or replaced with a copy. This can happen for example after
1810 // frame indices are lowered to constants or from splitting 64-bit
1811 // constants.
1812 //
1813 // We may also encounter cases where one or both operands are
1814 // immediates materialized into a register, which would ordinarily not
1815 // be folded due to multiple uses or operand constraints.
1816 if (tryConstantFoldOp(MI: &UseMI)) {
1817 LLVM_DEBUG(dbgs() << "Constant folded " << UseMI);
1818 Changed = true;
1819 }
1820 }
1821 }
1822
1823 SmallVector<MachineOperand *, 4> UsesToProcess(
1824 llvm::make_pointer_range(Range: MRI->use_nodbg_operands(Reg: Dst.getReg())));
1825 for (auto *U : UsesToProcess) {
1826 MachineInstr *UseMI = U->getParent();
1827
1828 FoldableDef SubOpToFold = OpToFold.getWithSubReg(TRI: *TRI, SubReg: U->getSubReg());
1829 foldOperand(OpToFold: SubOpToFold, UseMI, UseOpIdx: UseMI->getOperandNo(I: U), FoldList,
1830 CopiesToReplace);
1831 }
1832
1833 if (CopiesToReplace.empty() && FoldList.empty())
1834 return Changed;
1835
1836 MachineFunction *MF = MI.getMF();
1837 // Make sure we add EXEC uses to any new v_mov instructions created.
1838 for (MachineInstr *Copy : CopiesToReplace)
1839 Copy->addImplicitDefUseOperands(MF&: *MF);
1840
1841 SetVector<MachineInstr *> ConstantFoldCandidates;
1842 for (FoldCandidate &Fold : FoldList) {
1843 assert(!Fold.isReg() || Fold.Def.OpToFold);
1844 if (Fold.isReg() && Fold.getReg().isVirtual()) {
1845 Register Reg = Fold.getReg();
1846 const MachineInstr *DefMI = Fold.Def.DefMI;
1847 if (DefMI->readsRegister(Reg: AMDGPU::EXEC, TRI) &&
1848 execMayBeModifiedBeforeUse(MRI: *MRI, VReg: Reg, DefMI: *DefMI, UseMI: *Fold.UseMI))
1849 continue;
1850 }
1851 if (updateOperand(Fold)) {
1852 // Clear kill flags.
1853 if (Fold.isReg()) {
1854 assert(Fold.Def.OpToFold && Fold.isReg());
1855 // FIXME: Probably shouldn't bother trying to fold if not an
1856 // SGPR. PeepholeOptimizer can eliminate redundant VGPR->VGPR
1857 // copies.
1858 MRI->clearKillFlags(Reg: Fold.getReg());
1859 }
1860 LLVM_DEBUG(dbgs() << "Folded source from " << MI << " into OpNo "
1861 << static_cast<int>(Fold.UseOpNo) << " of "
1862 << *Fold.UseMI);
1863
1864 if (Fold.isImm())
1865 ConstantFoldCandidates.insert(X: Fold.UseMI);
1866
1867 } else if (Fold.Commuted) {
1868 // Restoring instruction's original operand order if fold has failed.
1869 TII->commuteInstruction(MI&: *Fold.UseMI, NewMI: false);
1870 }
1871 }
1872
1873 for (MachineInstr *MI : ConstantFoldCandidates) {
1874 if (tryConstantFoldOp(MI)) {
1875 LLVM_DEBUG(dbgs() << "Constant folded " << *MI);
1876 Changed = true;
1877 }
1878 }
1879 return true;
1880}
1881
1882/// Fold %agpr = COPY (REG_SEQUENCE x_MOV_B32, ...) into REG_SEQUENCE
1883/// (V_ACCVGPR_WRITE_B32_e64) ... depending on the reg_sequence input values.
1884bool SIFoldOperandsImpl::foldCopyToAGPRRegSequence(MachineInstr *CopyMI) const {
1885 // It is very tricky to store a value into an AGPR. v_accvgpr_write_b32 can
1886 // only accept VGPR or inline immediate. Recreate a reg_sequence with its
1887 // initializers right here, so we will rematerialize immediates and avoid
1888 // copies via different reg classes.
1889 const TargetRegisterClass *DefRC =
1890 MRI->getRegClass(Reg: CopyMI->getOperand(i: 0).getReg());
1891 if (!TRI->isAGPRClass(RC: DefRC))
1892 return false;
1893
1894 Register UseReg = CopyMI->getOperand(i: 1).getReg();
1895 MachineInstr *RegSeq = MRI->getVRegDef(Reg: UseReg);
1896 if (!RegSeq || !RegSeq->isRegSequence())
1897 return false;
1898
1899 const DebugLoc &DL = CopyMI->getDebugLoc();
1900 MachineBasicBlock &MBB = *CopyMI->getParent();
1901
1902 MachineInstrBuilder B(*MBB.getParent(), CopyMI);
1903 DenseMap<TargetInstrInfo::RegSubRegPair, Register> VGPRCopies;
1904
1905 const TargetRegisterClass *UseRC =
1906 MRI->getRegClass(Reg: CopyMI->getOperand(i: 1).getReg());
1907
1908 // Value, subregindex for new REG_SEQUENCE
1909 SmallVector<std::pair<MachineOperand *, unsigned>, 32> NewDefs;
1910
1911 unsigned NumRegSeqOperands = RegSeq->getNumOperands();
1912 unsigned NumFoldable = 0;
1913
1914 for (unsigned I = 1; I != NumRegSeqOperands; I += 2) {
1915 MachineOperand &RegOp = RegSeq->getOperand(i: I);
1916 unsigned SubRegIdx = RegSeq->getOperand(i: I + 1).getImm();
1917
1918 if (RegOp.getSubReg()) {
1919 // TODO: Handle subregister compose
1920 NewDefs.emplace_back(Args: &RegOp, Args&: SubRegIdx);
1921 continue;
1922 }
1923
1924 MachineOperand *Lookup = lookUpCopyChain(TII: *TII, MRI: *MRI, SrcReg: RegOp.getReg());
1925 if (!Lookup)
1926 Lookup = &RegOp;
1927
1928 if (Lookup->isImm()) {
1929 // Check if this is an agpr_32 subregister.
1930 const TargetRegisterClass *DestSuperRC = TRI->getMatchingSuperRegClass(
1931 A: DefRC, B: &AMDGPU::AGPR_32RegClass, Idx: SubRegIdx);
1932 if (DestSuperRC &&
1933 TII->isInlineConstant(MO: *Lookup, OperandType: AMDGPU::OPERAND_REG_INLINE_C_INT32)) {
1934 ++NumFoldable;
1935 NewDefs.emplace_back(Args&: Lookup, Args&: SubRegIdx);
1936 continue;
1937 }
1938 }
1939
1940 const TargetRegisterClass *InputRC =
1941 Lookup->isReg() ? MRI->getRegClass(Reg: Lookup->getReg())
1942 : MRI->getRegClass(Reg: RegOp.getReg());
1943
1944 // TODO: Account for Lookup->getSubReg()
1945
1946 // If we can't find a matching super class, this is an SGPR->AGPR or
1947 // VGPR->AGPR subreg copy (or something constant-like we have to materialize
1948 // in the AGPR). We can't directly copy from SGPR to AGPR on gfx908, so we
1949 // want to rewrite to copy to an intermediate VGPR class.
1950 const TargetRegisterClass *MatchRC =
1951 TRI->getMatchingSuperRegClass(A: DefRC, B: InputRC, Idx: SubRegIdx);
1952 if (!MatchRC) {
1953 ++NumFoldable;
1954 NewDefs.emplace_back(Args: &RegOp, Args&: SubRegIdx);
1955 continue;
1956 }
1957
1958 NewDefs.emplace_back(Args: &RegOp, Args&: SubRegIdx);
1959 }
1960
1961 // Do not clone a reg_sequence and merely change the result register class.
1962 if (NumFoldable == 0)
1963 return false;
1964
1965 CopyMI->setDesc(TII->get(Opcode: AMDGPU::REG_SEQUENCE));
1966 for (unsigned I = CopyMI->getNumOperands() - 1; I > 0; --I)
1967 CopyMI->removeOperand(OpNo: I);
1968
1969 for (auto [Def, DestSubIdx] : NewDefs) {
1970 if (!Def->isReg()) {
1971 // TODO: Should we use single write for each repeated value like in
1972 // register case?
1973 Register Tmp = MRI->createVirtualRegister(RegClass: &AMDGPU::AGPR_32RegClass);
1974 BuildMI(BB&: MBB, I: CopyMI, MIMD: DL, MCID: TII->get(Opcode: AMDGPU::V_ACCVGPR_WRITE_B32_e64), DestReg: Tmp)
1975 .add(MO: *Def);
1976 B.addReg(RegNo: Tmp);
1977 } else {
1978 TargetInstrInfo::RegSubRegPair Src = getRegSubRegPair(O: *Def);
1979 Def->setIsKill(false);
1980
1981 Register &VGPRCopy = VGPRCopies[Src];
1982 if (!VGPRCopy) {
1983 const TargetRegisterClass *VGPRUseSubRC =
1984 TRI->getSubRegisterClass(UseRC, DestSubIdx);
1985
1986 // We cannot build a reg_sequence out of the same registers, they
1987 // must be copied. Better do it here before copyPhysReg() created
1988 // several reads to do the AGPR->VGPR->AGPR copy.
1989
1990 // Direct copy from SGPR to AGPR is not possible on gfx908. To avoid
1991 // creation of exploded copies SGPR->VGPR->AGPR in the copyPhysReg()
1992 // later, create a copy here and track if we already have such a copy.
1993 const TargetRegisterClass *SubRC =
1994 TRI->getSubRegisterClass(MRI->getRegClass(Reg: Src.Reg), Src.SubReg);
1995 if (!VGPRUseSubRC->hasSubClassEq(RC: SubRC)) {
1996 // TODO: Try to reconstrain class
1997 VGPRCopy = MRI->createVirtualRegister(RegClass: VGPRUseSubRC);
1998 BuildMI(BB&: MBB, I: CopyMI, MIMD: DL, MCID: TII->get(Opcode: AMDGPU::COPY), DestReg: VGPRCopy).add(MO: *Def);
1999 B.addReg(RegNo: VGPRCopy);
2000 } else {
2001 // If it is already a VGPR, do not copy the register.
2002 B.add(MO: *Def);
2003 }
2004 } else {
2005 B.addReg(RegNo: VGPRCopy);
2006 }
2007 }
2008
2009 B.addImm(Val: DestSubIdx);
2010 }
2011
2012 LLVM_DEBUG(dbgs() << "Folded " << *CopyMI);
2013 return true;
2014}
2015
2016bool SIFoldOperandsImpl::tryFoldFoldableCopy(
2017 MachineInstr &MI, MachineOperand *&CurrentKnownM0Val) const {
2018 Register DstReg = MI.getOperand(i: 0).getReg();
2019 // Specially track simple redefs of m0 to the same value in a block, so we
2020 // can erase the later ones.
2021 if (DstReg == AMDGPU::M0) {
2022 MachineOperand &NewM0Val = MI.getOperand(i: 1);
2023 if (CurrentKnownM0Val && CurrentKnownM0Val->isIdenticalTo(Other: NewM0Val)) {
2024 MI.eraseFromParent();
2025 return true;
2026 }
2027
2028 // We aren't tracking other physical registers
2029 CurrentKnownM0Val = (NewM0Val.isReg() && NewM0Val.getReg().isPhysical())
2030 ? nullptr
2031 : &NewM0Val;
2032 return false;
2033 }
2034
2035 MachineOperand *OpToFoldPtr;
2036 if (MI.getOpcode() == AMDGPU::V_MOV_B16_t16_e64) {
2037 // Folding when any src_modifiers are non-zero is unsupported
2038 if (TII->hasAnyModifiersSet(MI))
2039 return false;
2040 OpToFoldPtr = &MI.getOperand(i: 2);
2041 } else
2042 OpToFoldPtr = &MI.getOperand(i: 1);
2043 MachineOperand &OpToFold = *OpToFoldPtr;
2044 bool FoldingImm = OpToFold.isImm() || OpToFold.isFI() || OpToFold.isGlobal();
2045
2046 // FIXME: We could also be folding things like TargetIndexes.
2047 if (!FoldingImm && !OpToFold.isReg())
2048 return false;
2049
2050 // Fold virtual registers and constant physical registers.
2051 if (OpToFold.isReg() && OpToFold.getReg().isPhysical() &&
2052 !TRI->isConstantPhysReg(PhysReg: OpToFold.getReg()))
2053 return false;
2054
2055 // Prevent folding operands backwards in the function. For example,
2056 // the COPY opcode must not be replaced by 1 in this example:
2057 //
2058 // %3 = COPY %vgpr0; VGPR_32:%3
2059 // ...
2060 // %vgpr0 = V_MOV_B32_e32 1, implicit %exec
2061 if (!DstReg.isVirtual())
2062 return false;
2063
2064 const TargetRegisterClass *DstRC =
2065 MRI->getRegClass(Reg: MI.getOperand(i: 0).getReg());
2066
2067 // True16: Fix malformed 16-bit sgpr COPY produced by peephole-opt
2068 // Can remove this code if proper 16-bit SGPRs are implemented
2069 // Example: Pre-peephole-opt
2070 // %29:sgpr_lo16 = COPY %16.lo16:sreg_32
2071 // %32:sreg_32 = COPY %29:sgpr_lo16
2072 // %30:sreg_32 = S_PACK_LL_B32_B16 killed %31:sreg_32, killed %32:sreg_32
2073 // Post-peephole-opt and DCE
2074 // %32:sreg_32 = COPY %16.lo16:sreg_32
2075 // %30:sreg_32 = S_PACK_LL_B32_B16 killed %31:sreg_32, killed %32:sreg_32
2076 // After this transform
2077 // %32:sreg_32 = COPY %16:sreg_32
2078 // %30:sreg_32 = S_PACK_LL_B32_B16 killed %31:sreg_32, killed %32:sreg_32
2079 // After the fold operands pass
2080 // %30:sreg_32 = S_PACK_LL_B32_B16 killed %31:sreg_32, killed %16:sreg_32
2081 if (MI.getOpcode() == AMDGPU::COPY && OpToFold.isReg() &&
2082 OpToFold.getSubReg()) {
2083 if (DstRC == &AMDGPU::SReg_32RegClass &&
2084 DstRC == MRI->getRegClass(Reg: OpToFold.getReg())) {
2085 assert(OpToFold.getSubReg() == AMDGPU::lo16);
2086 OpToFold.setSubReg(0);
2087 }
2088 }
2089
2090 // Fold copy to AGPR through reg_sequence
2091 // TODO: Handle with subregister extract
2092 if (OpToFold.isReg() && MI.isCopy() && !MI.getOperand(i: 1).getSubReg()) {
2093 if (foldCopyToAGPRRegSequence(CopyMI: &MI))
2094 return true;
2095 }
2096
2097 FoldableDef Def(OpToFold, DstRC);
2098 bool Changed = foldInstOperand(MI, OpToFold: Def);
2099
2100 // If we managed to fold all uses of this copy then we might as well
2101 // delete it now.
2102 // The only reason we need to follow chains of copies here is that
2103 // tryFoldRegSequence looks forward through copies before folding a
2104 // REG_SEQUENCE into its eventual users.
2105 auto *InstToErase = &MI;
2106 while (MRI->use_nodbg_empty(RegNo: InstToErase->getOperand(i: 0).getReg())) {
2107 auto &SrcOp = InstToErase->getOperand(i: 1);
2108 auto SrcReg = SrcOp.isReg() ? SrcOp.getReg() : Register();
2109 InstToErase->eraseFromParent();
2110 Changed = true;
2111 InstToErase = nullptr;
2112 if (!SrcReg || SrcReg.isPhysical())
2113 break;
2114 InstToErase = MRI->getVRegDef(Reg: SrcReg);
2115 if (!InstToErase || !TII->isFoldableCopy(MI: *InstToErase))
2116 break;
2117 }
2118
2119 if (InstToErase && InstToErase->isRegSequence() &&
2120 MRI->use_nodbg_empty(RegNo: InstToErase->getOperand(i: 0).getReg())) {
2121 InstToErase->eraseFromParent();
2122 Changed = true;
2123 }
2124
2125 if (Changed)
2126 return true;
2127
2128 // Run this after foldInstOperand to avoid turning scalar additions into
2129 // vector additions when the result scalar result could just be folded into
2130 // the user(s).
2131 return OpToFold.isReg() &&
2132 foldCopyToVGPROfScalarAddOfFrameIndex(DstReg, SrcReg: OpToFold.getReg(), MI);
2133}
2134
2135// Clamp patterns are canonically selected to v_max_* instructions, so only
2136// handle them.
2137const MachineOperand *
2138SIFoldOperandsImpl::isClamp(const MachineInstr &MI) const {
2139 unsigned Op = MI.getOpcode();
2140 switch (Op) {
2141 case AMDGPU::V_MAX_F32_e64:
2142 case AMDGPU::V_MAX_F16_e64:
2143 case AMDGPU::V_MAX_F16_t16_e64:
2144 case AMDGPU::V_MAX_F16_fake16_e64:
2145 case AMDGPU::V_MAX_F64_e64:
2146 case AMDGPU::V_MAX_NUM_F64_e64:
2147 case AMDGPU::V_PK_MAX_F16:
2148 case AMDGPU::V_MAX_BF16_PSEUDO_e64:
2149 case AMDGPU::V_PK_MAX_NUM_BF16: {
2150 if (MI.mayRaiseFPException())
2151 return nullptr;
2152
2153 if (!TII->getNamedOperand(MI, OperandName: AMDGPU::OpName::clamp)->getImm())
2154 return nullptr;
2155
2156 // Make sure sources are identical.
2157 const MachineOperand *Src0 = TII->getNamedOperand(MI, OperandName: AMDGPU::OpName::src0);
2158 const MachineOperand *Src1 = TII->getNamedOperand(MI, OperandName: AMDGPU::OpName::src1);
2159 if (!Src0->isReg() || !Src1->isReg() ||
2160 Src0->getReg() != Src1->getReg() ||
2161 Src0->getSubReg() != Src1->getSubReg() ||
2162 Src0->getSubReg() != AMDGPU::NoSubRegister)
2163 return nullptr;
2164
2165 // Can't fold up if we have modifiers.
2166 if (TII->hasModifiersSet(MI, OpName: AMDGPU::OpName::omod))
2167 return nullptr;
2168
2169 unsigned Src0Mods
2170 = TII->getNamedOperand(MI, OperandName: AMDGPU::OpName::src0_modifiers)->getImm();
2171 unsigned Src1Mods
2172 = TII->getNamedOperand(MI, OperandName: AMDGPU::OpName::src1_modifiers)->getImm();
2173
2174 // Having a 0 op_sel_hi would require swizzling the output in the source
2175 // instruction, which we can't do.
2176 unsigned UnsetMods =
2177 (Op == AMDGPU::V_PK_MAX_F16 || Op == AMDGPU::V_PK_MAX_NUM_BF16)
2178 ? SISrcMods::OP_SEL_1
2179 : 0u;
2180 if (Src0Mods != UnsetMods && Src1Mods != UnsetMods)
2181 return nullptr;
2182 return Src0;
2183 }
2184 default:
2185 return nullptr;
2186 }
2187}
2188
2189// FIXME: Clamp for v_mad_mixhi_f16 handled during isel.
2190bool SIFoldOperandsImpl::tryFoldClamp(MachineInstr &MI) {
2191 const MachineOperand *ClampSrc = isClamp(MI);
2192 if (!ClampSrc || !MRI->hasOneNonDBGUser(RegNo: ClampSrc->getReg()))
2193 return false;
2194
2195 if (!ClampSrc->getReg().isVirtual())
2196 return false;
2197
2198 // Look through COPY. COPY only observed with True16.
2199 Register DefSrcReg = TRI->lookThruCopyLike(SrcReg: ClampSrc->getReg(), MRI);
2200 MachineInstr *Def =
2201 MRI->getVRegDef(Reg: DefSrcReg.isVirtual() ? DefSrcReg : ClampSrc->getReg());
2202
2203 // The type of clamp must be compatible.
2204 if (!SIInstrInfo::hasSameClamp(A: *Def, B: MI))
2205 return false;
2206
2207 if (Def->mayRaiseFPException())
2208 return false;
2209
2210 MachineOperand *DefClamp = TII->getNamedOperand(MI&: *Def, OperandName: AMDGPU::OpName::clamp);
2211 if (!DefClamp)
2212 return false;
2213
2214 LLVM_DEBUG(dbgs() << "Folding clamp " << *DefClamp << " into " << *Def);
2215
2216 // Clamp is applied after omod, so it is OK if omod is set.
2217 DefClamp->setImm(1);
2218
2219 Register DefReg = Def->getOperand(i: 0).getReg();
2220 Register MIDstReg = MI.getOperand(i: 0).getReg();
2221 if (TRI->isSGPRReg(MRI: *MRI, Reg: DefReg)) {
2222 // Pseudo scalar instructions have a SGPR for dst and clamp is a v_max*
2223 // instruction with a VGPR dst.
2224 BuildMI(BB&: *MI.getParent(), I&: MI, MIMD: MI.getDebugLoc(), MCID: TII->get(Opcode: AMDGPU::COPY),
2225 DestReg: MIDstReg)
2226 .addReg(RegNo: DefReg);
2227 } else {
2228 MRI->replaceRegWith(FromReg: MIDstReg, ToReg: DefReg);
2229 }
2230 MI.eraseFromParent();
2231
2232 // Use of output modifiers forces VOP3 encoding for a VOP2 mac/fmac
2233 // instruction, so we might as well convert it to the more flexible VOP3-only
2234 // mad/fma form.
2235 if (TII->convertToThreeAddress(MI&: *Def, LV: nullptr, LIS: nullptr))
2236 Def->eraseFromParent();
2237
2238 return true;
2239}
2240
2241static int getOModValue(unsigned Opc, int64_t Val) {
2242 switch (Opc) {
2243 case AMDGPU::V_MUL_F64_e64:
2244 case AMDGPU::V_MUL_F64_pseudo_e64: {
2245 switch (Val) {
2246 case 0x3fe0000000000000: // 0.5
2247 return SIOutMods::DIV2;
2248 case 0x4000000000000000: // 2.0
2249 return SIOutMods::MUL2;
2250 case 0x4010000000000000: // 4.0
2251 return SIOutMods::MUL4;
2252 default:
2253 return SIOutMods::NONE;
2254 }
2255 }
2256 case AMDGPU::V_MUL_F32_e64: {
2257 switch (static_cast<uint32_t>(Val)) {
2258 case 0x3f000000: // 0.5
2259 return SIOutMods::DIV2;
2260 case 0x40000000: // 2.0
2261 return SIOutMods::MUL2;
2262 case 0x40800000: // 4.0
2263 return SIOutMods::MUL4;
2264 default:
2265 return SIOutMods::NONE;
2266 }
2267 }
2268 case AMDGPU::V_MUL_F16_e64:
2269 case AMDGPU::V_MUL_F16_t16_e64:
2270 case AMDGPU::V_MUL_F16_fake16_e64: {
2271 switch (static_cast<uint16_t>(Val)) {
2272 case 0x3800: // 0.5
2273 return SIOutMods::DIV2;
2274 case 0x4000: // 2.0
2275 return SIOutMods::MUL2;
2276 case 0x4400: // 4.0
2277 return SIOutMods::MUL4;
2278 default:
2279 return SIOutMods::NONE;
2280 }
2281 }
2282 default:
2283 llvm_unreachable("invalid mul opcode");
2284 }
2285}
2286
2287// FIXME: Does this really not support denormals with f16?
2288// FIXME: Does this need to check IEEE mode bit? SNaNs are generally not
2289// handled, so will anything other than that break?
2290std::pair<const MachineOperand *, int>
2291SIFoldOperandsImpl::isOMod(const MachineInstr &MI) const {
2292 unsigned Op = MI.getOpcode();
2293 switch (Op) {
2294 case AMDGPU::V_MUL_F64_e64:
2295 case AMDGPU::V_MUL_F64_pseudo_e64:
2296 case AMDGPU::V_MUL_F32_e64:
2297 case AMDGPU::V_MUL_F16_t16_e64:
2298 case AMDGPU::V_MUL_F16_fake16_e64:
2299 case AMDGPU::V_MUL_F16_e64: {
2300 // If output denormals are enabled, omod is ignored.
2301 if ((Op == AMDGPU::V_MUL_F32_e64 &&
2302 MFI->getMode().FP32Denormals.Output != DenormalMode::PreserveSign) ||
2303 ((Op == AMDGPU::V_MUL_F64_e64 || Op == AMDGPU::V_MUL_F64_pseudo_e64 ||
2304 Op == AMDGPU::V_MUL_F16_e64 || Op == AMDGPU::V_MUL_F16_t16_e64 ||
2305 Op == AMDGPU::V_MUL_F16_fake16_e64) &&
2306 MFI->getMode().FP64FP16Denormals.Output !=
2307 DenormalMode::PreserveSign) ||
2308 MI.mayRaiseFPException())
2309 return std::pair(nullptr, SIOutMods::NONE);
2310
2311 const MachineOperand *RegOp = nullptr;
2312 const MachineOperand *ImmOp = nullptr;
2313 const MachineOperand *Src0 = TII->getNamedOperand(MI, OperandName: AMDGPU::OpName::src0);
2314 const MachineOperand *Src1 = TII->getNamedOperand(MI, OperandName: AMDGPU::OpName::src1);
2315 if (Src0->isImm()) {
2316 ImmOp = Src0;
2317 RegOp = Src1;
2318 } else if (Src1->isImm()) {
2319 ImmOp = Src1;
2320 RegOp = Src0;
2321 } else
2322 return std::pair(nullptr, SIOutMods::NONE);
2323
2324 int OMod = getOModValue(Opc: Op, Val: ImmOp->getImm());
2325 if (OMod == SIOutMods::NONE ||
2326 TII->hasModifiersSet(MI, OpName: AMDGPU::OpName::src0_modifiers) ||
2327 TII->hasModifiersSet(MI, OpName: AMDGPU::OpName::src1_modifiers) ||
2328 TII->hasModifiersSet(MI, OpName: AMDGPU::OpName::omod) ||
2329 TII->hasModifiersSet(MI, OpName: AMDGPU::OpName::clamp))
2330 return std::pair(nullptr, SIOutMods::NONE);
2331
2332 return std::pair(RegOp, OMod);
2333 }
2334 case AMDGPU::V_ADD_F64_e64:
2335 case AMDGPU::V_ADD_F64_pseudo_e64:
2336 case AMDGPU::V_ADD_F32_e64:
2337 case AMDGPU::V_ADD_F16_e64:
2338 case AMDGPU::V_ADD_F16_t16_e64:
2339 case AMDGPU::V_ADD_F16_fake16_e64: {
2340 // If output denormals are enabled, omod is ignored.
2341 if ((Op == AMDGPU::V_ADD_F32_e64 &&
2342 MFI->getMode().FP32Denormals.Output != DenormalMode::PreserveSign) ||
2343 ((Op == AMDGPU::V_ADD_F64_e64 || Op == AMDGPU::V_ADD_F64_pseudo_e64 ||
2344 Op == AMDGPU::V_ADD_F16_e64 || Op == AMDGPU::V_ADD_F16_t16_e64 ||
2345 Op == AMDGPU::V_ADD_F16_fake16_e64) &&
2346 MFI->getMode().FP64FP16Denormals.Output != DenormalMode::PreserveSign))
2347 return std::pair(nullptr, SIOutMods::NONE);
2348
2349 // Look through the DAGCombiner canonicalization fmul x, 2 -> fadd x, x
2350 const MachineOperand *Src0 = TII->getNamedOperand(MI, OperandName: AMDGPU::OpName::src0);
2351 const MachineOperand *Src1 = TII->getNamedOperand(MI, OperandName: AMDGPU::OpName::src1);
2352
2353 if (Src0->isReg() && Src1->isReg() && Src0->getReg() == Src1->getReg() &&
2354 Src0->getSubReg() == Src1->getSubReg() &&
2355 !TII->hasModifiersSet(MI, OpName: AMDGPU::OpName::src0_modifiers) &&
2356 !TII->hasModifiersSet(MI, OpName: AMDGPU::OpName::src1_modifiers) &&
2357 !TII->hasModifiersSet(MI, OpName: AMDGPU::OpName::clamp) &&
2358 !TII->hasModifiersSet(MI, OpName: AMDGPU::OpName::omod))
2359 return std::pair(Src0, SIOutMods::MUL2);
2360
2361 return std::pair(nullptr, SIOutMods::NONE);
2362 }
2363 default:
2364 return std::pair(nullptr, SIOutMods::NONE);
2365 }
2366}
2367
2368// FIXME: Does this need to check IEEE bit on function?
2369bool SIFoldOperandsImpl::tryFoldOMod(MachineInstr &MI) {
2370 const MachineOperand *RegOp;
2371 int OMod;
2372 std::tie(args&: RegOp, args&: OMod) = isOMod(MI);
2373 if (OMod == SIOutMods::NONE || !RegOp->isReg() ||
2374 RegOp->getSubReg() != AMDGPU::NoSubRegister ||
2375 !MRI->hasOneNonDBGUser(RegNo: RegOp->getReg()))
2376 return false;
2377
2378 MachineInstr *Def = MRI->getVRegDef(Reg: RegOp->getReg());
2379 MachineOperand *DefOMod = TII->getNamedOperand(MI&: *Def, OperandName: AMDGPU::OpName::omod);
2380 if (!DefOMod || DefOMod->getImm() != SIOutMods::NONE)
2381 return false;
2382
2383 if (Def->mayRaiseFPException())
2384 return false;
2385
2386 // Clamp is applied after omod. If the source already has clamp set, don't
2387 // fold it.
2388 if (TII->hasModifiersSet(MI: *Def, OpName: AMDGPU::OpName::clamp))
2389 return false;
2390
2391 LLVM_DEBUG(dbgs() << "Folding omod " << MI << " into " << *Def);
2392
2393 DefOMod->setImm(OMod);
2394 MRI->replaceRegWith(FromReg: MI.getOperand(i: 0).getReg(), ToReg: Def->getOperand(i: 0).getReg());
2395 // Kill flags can be wrong if we replaced a def inside a loop with a def
2396 // outside the loop.
2397 MRI->clearKillFlags(Reg: Def->getOperand(i: 0).getReg());
2398 MI.eraseFromParent();
2399
2400 // Use of output modifiers forces VOP3 encoding for a VOP2 mac/fmac
2401 // instruction, so we might as well convert it to the more flexible VOP3-only
2402 // mad/fma form.
2403 if (TII->convertToThreeAddress(MI&: *Def, LV: nullptr, LIS: nullptr))
2404 Def->eraseFromParent();
2405
2406 return true;
2407}
2408
2409// Try to fold a reg_sequence with vgpr output and agpr inputs into an
2410// instruction which can take an agpr. So far that means a store.
2411bool SIFoldOperandsImpl::tryFoldRegSequence(MachineInstr &MI) {
2412 assert(MI.isRegSequence());
2413 auto Reg = MI.getOperand(i: 0).getReg();
2414
2415 if (!ST->hasGFX90AInsts() || !TRI->isVGPR(MRI: *MRI, Reg) ||
2416 !MRI->hasOneNonDBGUse(RegNo: Reg))
2417 return false;
2418
2419 SmallVector<std::pair<MachineOperand*, unsigned>, 32> Defs;
2420 if (!getRegSeqInit(Defs, UseReg: Reg))
2421 return false;
2422
2423 for (auto &[Op, SubIdx] : Defs) {
2424 if (!Op->isReg())
2425 return false;
2426 if (TRI->isAGPR(MRI: *MRI, Reg: Op->getReg()))
2427 continue;
2428 // Maybe this is a COPY from AREG
2429 const MachineInstr *SubDef = MRI->getVRegDef(Reg: Op->getReg());
2430 if (!SubDef || !SubDef->isCopy() || SubDef->getOperand(i: 1).getSubReg())
2431 return false;
2432 if (!TRI->isAGPR(MRI: *MRI, Reg: SubDef->getOperand(i: 1).getReg()))
2433 return false;
2434 }
2435
2436 MachineOperand *Op = &*MRI->use_nodbg_begin(RegNo: Reg);
2437 MachineInstr *UseMI = Op->getParent();
2438 while (UseMI->isCopy() && !Op->getSubReg()) {
2439 Reg = UseMI->getOperand(i: 0).getReg();
2440 if (!TRI->isVGPR(MRI: *MRI, Reg) || !MRI->hasOneNonDBGUse(RegNo: Reg))
2441 return false;
2442 Op = &*MRI->use_nodbg_begin(RegNo: Reg);
2443 UseMI = Op->getParent();
2444 }
2445
2446 if (Op->getSubReg())
2447 return false;
2448
2449 unsigned OpIdx = Op - &UseMI->getOperand(i: 0);
2450 const MCInstrDesc &InstDesc = UseMI->getDesc();
2451 const TargetRegisterClass *OpRC = TII->getRegClass(MCID: InstDesc, OpNum: OpIdx);
2452 if (!OpRC || !TRI->isVectorSuperClass(RC: OpRC))
2453 return false;
2454
2455 const auto *NewDstRC = TRI->getEquivalentAGPRClass(SRC: MRI->getRegClass(Reg));
2456 auto Dst = MRI->createVirtualRegister(RegClass: NewDstRC);
2457 auto RS = BuildMI(BB&: *MI.getParent(), I&: MI, MIMD: MI.getDebugLoc(),
2458 MCID: TII->get(Opcode: AMDGPU::REG_SEQUENCE), DestReg: Dst);
2459
2460 for (auto &[Def, SubIdx] : Defs) {
2461 Def->setIsKill(false);
2462 if (TRI->isAGPR(MRI: *MRI, Reg: Def->getReg())) {
2463 RS.add(MO: *Def);
2464 } else { // This is a copy
2465 MachineInstr *SubDef = MRI->getVRegDef(Reg: Def->getReg());
2466 SubDef->getOperand(i: 1).setIsKill(false);
2467 RS.addReg(RegNo: SubDef->getOperand(i: 1).getReg(), Flags: {}, SubReg: Def->getSubReg());
2468 }
2469 RS.addImm(Val: SubIdx);
2470 }
2471
2472 Op->setReg(Dst);
2473 if (!TII->isOperandLegal(MI: *UseMI, OpIdx, MO: Op)) {
2474 Op->setReg(Reg);
2475 RS->eraseFromParent();
2476 return false;
2477 }
2478
2479 LLVM_DEBUG(dbgs() << "Folded " << *RS << " into " << *UseMI);
2480
2481 // Erase the REG_SEQUENCE eagerly, unless we followed a chain of COPY users,
2482 // in which case we can erase them all later in runOnMachineFunction.
2483 if (MRI->use_nodbg_empty(RegNo: MI.getOperand(i: 0).getReg()))
2484 MI.eraseFromParent();
2485 return true;
2486}
2487
2488/// Checks whether \p Copy is a AGPR -> VGPR copy. Returns `true` on success and
2489/// stores the AGPR register in \p OutReg and the subreg in \p OutSubReg
2490static bool isAGPRCopy(const SIRegisterInfo &TRI,
2491 const MachineRegisterInfo &MRI, const MachineInstr &Copy,
2492 Register &OutReg, unsigned &OutSubReg) {
2493 assert(Copy.isCopy());
2494
2495 const MachineOperand &CopySrc = Copy.getOperand(i: 1);
2496 Register CopySrcReg = CopySrc.getReg();
2497 if (!CopySrcReg.isVirtual())
2498 return false;
2499
2500 // Common case: copy from AGPR directly, e.g.
2501 // %1:vgpr_32 = COPY %0:agpr_32
2502 if (TRI.isAGPR(MRI, Reg: CopySrcReg)) {
2503 OutReg = CopySrcReg;
2504 OutSubReg = CopySrc.getSubReg();
2505 return true;
2506 }
2507
2508 // Sometimes it can also involve two copies, e.g.
2509 // %1:vgpr_256 = COPY %0:agpr_256
2510 // %2:vgpr_32 = COPY %1:vgpr_256.sub0
2511 const MachineInstr *CopySrcDef = MRI.getVRegDef(Reg: CopySrcReg);
2512 if (!CopySrcDef || !CopySrcDef->isCopy())
2513 return false;
2514
2515 const MachineOperand &OtherCopySrc = CopySrcDef->getOperand(i: 1);
2516 Register OtherCopySrcReg = OtherCopySrc.getReg();
2517 if (!OtherCopySrcReg.isVirtual() ||
2518 CopySrcDef->getOperand(i: 0).getSubReg() != AMDGPU::NoSubRegister ||
2519 OtherCopySrc.getSubReg() != AMDGPU::NoSubRegister ||
2520 !TRI.isAGPR(MRI, Reg: OtherCopySrcReg))
2521 return false;
2522
2523 OutReg = OtherCopySrcReg;
2524 OutSubReg = CopySrc.getSubReg();
2525 return true;
2526}
2527
2528// Try to hoist an AGPR to VGPR copy across a PHI.
2529// This should allow folding of an AGPR into a consumer which may support it.
2530//
2531// Example 1: LCSSA PHI
2532// loop:
2533// %1:vreg = COPY %0:areg
2534// exit:
2535// %2:vreg = PHI %1:vreg, %loop
2536// =>
2537// loop:
2538// exit:
2539// %1:areg = PHI %0:areg, %loop
2540// %2:vreg = COPY %1:areg
2541//
2542// Example 2: PHI with multiple incoming values:
2543// entry:
2544// %1:vreg = GLOBAL_LOAD(..)
2545// loop:
2546// %2:vreg = PHI %1:vreg, %entry, %5:vreg, %loop
2547// %3:areg = COPY %2:vreg
2548// %4:areg = (instr using %3:areg)
2549// %5:vreg = COPY %4:areg
2550// =>
2551// entry:
2552// %1:vreg = GLOBAL_LOAD(..)
2553// %2:areg = COPY %1:vreg
2554// loop:
2555// %3:areg = PHI %2:areg, %entry, %X:areg,
2556// %4:areg = (instr using %3:areg)
2557bool SIFoldOperandsImpl::tryFoldPhiAGPR(MachineInstr &PHI) {
2558 assert(PHI.isPHI());
2559
2560 Register PhiOut = PHI.getOperand(i: 0).getReg();
2561 if (!TRI->isVGPR(MRI: *MRI, Reg: PhiOut))
2562 return false;
2563
2564 // Iterate once over all incoming values of the PHI to check if this PHI is
2565 // eligible, and determine the exact AGPR RC we'll target.
2566 const TargetRegisterClass *ARC = nullptr;
2567 for (unsigned K = 1; K < PHI.getNumExplicitOperands(); K += 2) {
2568 MachineOperand &MO = PHI.getOperand(i: K);
2569 MachineInstr *Copy = MRI->getVRegDef(Reg: MO.getReg());
2570 if (!Copy || !Copy->isCopy())
2571 continue;
2572
2573 Register AGPRSrc;
2574 unsigned AGPRRegMask = AMDGPU::NoSubRegister;
2575 if (!isAGPRCopy(TRI: *TRI, MRI: *MRI, Copy: *Copy, OutReg&: AGPRSrc, OutSubReg&: AGPRRegMask))
2576 continue;
2577
2578 const TargetRegisterClass *CopyInRC = MRI->getRegClass(Reg: AGPRSrc);
2579 if (const auto *SubRC = TRI->getSubRegisterClass(CopyInRC, AGPRRegMask))
2580 CopyInRC = SubRC;
2581
2582 if (ARC && !ARC->hasSubClassEq(RC: CopyInRC))
2583 return false;
2584 ARC = CopyInRC;
2585 }
2586
2587 if (!ARC)
2588 return false;
2589
2590 bool IsAGPR32 = (ARC == &AMDGPU::AGPR_32RegClass);
2591
2592 // Rewrite the PHI's incoming values to ARC.
2593 LLVM_DEBUG(dbgs() << "Folding AGPR copies into: " << PHI);
2594 for (unsigned K = 1; K < PHI.getNumExplicitOperands(); K += 2) {
2595 MachineOperand &MO = PHI.getOperand(i: K);
2596 Register Reg = MO.getReg();
2597
2598 MachineBasicBlock::iterator InsertPt;
2599 MachineBasicBlock *InsertMBB = nullptr;
2600
2601 // Look at the def of Reg, ignoring all copies.
2602 unsigned CopyOpc = AMDGPU::COPY;
2603 if (MachineInstr *Def = MRI->getVRegDef(Reg)) {
2604
2605 // Look at pre-existing COPY instructions from ARC: Steal the operand. If
2606 // the copy was single-use, it will be removed by DCE later.
2607 if (Def->isCopy()) {
2608 Register AGPRSrc;
2609 unsigned AGPRSubReg = AMDGPU::NoSubRegister;
2610 if (isAGPRCopy(TRI: *TRI, MRI: *MRI, Copy: *Def, OutReg&: AGPRSrc, OutSubReg&: AGPRSubReg)) {
2611 MO.setReg(AGPRSrc);
2612 MO.setSubReg(AGPRSubReg);
2613 continue;
2614 }
2615
2616 // If this is a multi-use SGPR -> VGPR copy, use V_ACCVGPR_WRITE on
2617 // GFX908 directly instead of a COPY. Otherwise, SIFoldOperand may try
2618 // to fold the sgpr -> vgpr -> agpr copy into a sgpr -> agpr copy which
2619 // is unlikely to be profitable.
2620 //
2621 // Note that V_ACCVGPR_WRITE is only used for AGPR_32.
2622 MachineOperand &CopyIn = Def->getOperand(i: 1);
2623 if (IsAGPR32 && !ST->hasGFX90AInsts() && !MRI->hasOneNonDBGUse(RegNo: Reg) &&
2624 TRI->isSGPRReg(MRI: *MRI, Reg: CopyIn.getReg()))
2625 CopyOpc = AMDGPU::V_ACCVGPR_WRITE_B32_e64;
2626 }
2627
2628 InsertMBB = Def->getParent();
2629 InsertPt = InsertMBB->SkipPHIsLabelsAndDebug(I: ++Def->getIterator());
2630 } else {
2631 InsertMBB = PHI.getOperand(i: MO.getOperandNo() + 1).getMBB();
2632 InsertPt = InsertMBB->getFirstTerminator();
2633 }
2634
2635 Register NewReg = MRI->createVirtualRegister(RegClass: ARC);
2636 MachineInstr *MI = BuildMI(BB&: *InsertMBB, I: InsertPt, MIMD: PHI.getDebugLoc(),
2637 MCID: TII->get(Opcode: CopyOpc), DestReg: NewReg)
2638 .addReg(RegNo: Reg);
2639 MO.setReg(NewReg);
2640
2641 (void)MI;
2642 LLVM_DEBUG(dbgs() << " Created COPY: " << *MI);
2643 }
2644
2645 // Replace the PHI's result with a new register.
2646 Register NewReg = MRI->createVirtualRegister(RegClass: ARC);
2647 PHI.getOperand(i: 0).setReg(NewReg);
2648
2649 // COPY that new register back to the original PhiOut register. This COPY will
2650 // usually be folded out later.
2651 MachineBasicBlock *MBB = PHI.getParent();
2652 BuildMI(BB&: *MBB, I: MBB->getFirstNonPHI(), MIMD: PHI.getDebugLoc(),
2653 MCID: TII->get(Opcode: AMDGPU::COPY), DestReg: PhiOut)
2654 .addReg(RegNo: NewReg);
2655
2656 LLVM_DEBUG(dbgs() << " Done: Folded " << PHI);
2657 return true;
2658}
2659
2660// Attempt to convert VGPR load to an AGPR load.
2661bool SIFoldOperandsImpl::tryFoldLoad(MachineInstr &MI) {
2662 assert(MI.mayLoad());
2663 if (!ST->hasGFX90AInsts() || MI.getNumExplicitDefs() != 1)
2664 return false;
2665
2666 MachineOperand &Def = MI.getOperand(i: 0);
2667 if (!Def.isDef())
2668 return false;
2669
2670 Register DefReg = Def.getReg();
2671
2672 if (DefReg.isPhysical() || !TRI->isVGPR(MRI: *MRI, Reg: DefReg))
2673 return false;
2674
2675 SmallVector<const MachineInstr *, 8> Users(
2676 llvm::make_pointer_range(Range: MRI->use_nodbg_instructions(Reg: DefReg)));
2677 SmallVector<Register, 8> MoveRegs;
2678
2679 if (Users.empty())
2680 return false;
2681
2682 // Check that all uses a copy to an agpr or a reg_sequence producing an agpr.
2683 while (!Users.empty()) {
2684 const MachineInstr *I = Users.pop_back_val();
2685 if (!I->isCopy() && !I->isRegSequence())
2686 return false;
2687 Register DstReg = I->getOperand(i: 0).getReg();
2688 // Physical registers may have more than one instruction definitions
2689 if (DstReg.isPhysical())
2690 return false;
2691 if (TRI->isAGPR(MRI: *MRI, Reg: DstReg))
2692 continue;
2693 MoveRegs.push_back(Elt: DstReg);
2694 for (const MachineInstr &U : MRI->use_nodbg_instructions(Reg: DstReg))
2695 Users.push_back(Elt: &U);
2696 }
2697
2698 const TargetRegisterClass *RC = MRI->getRegClass(Reg: DefReg);
2699 MRI->setRegClass(Reg: DefReg, RC: TRI->getEquivalentAGPRClass(SRC: RC));
2700 if (!TII->isOperandLegal(MI, OpIdx: 0, MO: &Def)) {
2701 MRI->setRegClass(Reg: DefReg, RC);
2702 return false;
2703 }
2704
2705 while (!MoveRegs.empty()) {
2706 Register Reg = MoveRegs.pop_back_val();
2707 MRI->setRegClass(Reg, RC: TRI->getEquivalentAGPRClass(SRC: MRI->getRegClass(Reg)));
2708 }
2709
2710 LLVM_DEBUG(dbgs() << "Folded " << MI);
2711
2712 return true;
2713}
2714
2715// tryFoldPhiAGPR will aggressively try to create AGPR PHIs.
2716// For GFX90A and later, this is pretty much always a good thing, but for GFX908
2717// there's cases where it can create a lot more AGPR-AGPR copies, which are
2718// expensive on this architecture due to the lack of V_ACCVGPR_MOV.
2719//
2720// This function looks at all AGPR PHIs in a basic block and collects their
2721// operands. Then, it checks for register that are used more than once across
2722// all PHIs and caches them in a VGPR. This prevents ExpandPostRAPseudo from
2723// having to create one VGPR temporary per use, which can get very messy if
2724// these PHIs come from a broken-up large PHI (e.g. 32 AGPR phis, one per vector
2725// element).
2726//
2727// Example
2728// a:
2729// %in:agpr_256 = COPY %foo:vgpr_256
2730// c:
2731// %x:agpr_32 = ..
2732// b:
2733// %0:areg = PHI %in.sub0:agpr_32, %a, %x, %c
2734// %1:areg = PHI %in.sub0:agpr_32, %a, %y, %c
2735// %2:areg = PHI %in.sub0:agpr_32, %a, %z, %c
2736// =>
2737// a:
2738// %in:agpr_256 = COPY %foo:vgpr_256
2739// %tmp:vgpr_32 = V_ACCVGPR_READ_B32_e64 %in.sub0:agpr_32
2740// %tmp_agpr:agpr_32 = COPY %tmp
2741// c:
2742// %x:agpr_32 = ..
2743// b:
2744// %0:areg = PHI %tmp_agpr, %a, %x, %c
2745// %1:areg = PHI %tmp_agpr, %a, %y, %c
2746// %2:areg = PHI %tmp_agpr, %a, %z, %c
2747bool SIFoldOperandsImpl::tryOptimizeAGPRPhis(MachineBasicBlock &MBB) {
2748 // This is only really needed on GFX908 where AGPR-AGPR copies are
2749 // unreasonably difficult.
2750 if (ST->hasGFX90AInsts())
2751 return false;
2752
2753 // Look at all AGPR Phis and collect the register + subregister used.
2754 DenseMap<std::pair<Register, unsigned>, std::vector<MachineOperand *>>
2755 RegToMO;
2756
2757 for (auto &MI : MBB) {
2758 if (!MI.isPHI())
2759 break;
2760
2761 if (!TRI->isAGPR(MRI: *MRI, Reg: MI.getOperand(i: 0).getReg()))
2762 continue;
2763
2764 for (unsigned K = 1; K < MI.getNumOperands(); K += 2) {
2765 MachineOperand &PhiMO = MI.getOperand(i: K);
2766 if (!PhiMO.getSubReg())
2767 continue;
2768 RegToMO[{PhiMO.getReg(), PhiMO.getSubReg()}].push_back(x: &PhiMO);
2769 }
2770 }
2771
2772 // For all (Reg, SubReg) pair that are used more than once, cache the value in
2773 // a VGPR.
2774 bool Changed = false;
2775 for (const auto &[Entry, MOs] : RegToMO) {
2776 if (MOs.size() == 1)
2777 continue;
2778
2779 const auto [Reg, SubReg] = Entry;
2780 MachineInstr *Def = MRI->getVRegDef(Reg);
2781 MachineBasicBlock *DefMBB = Def->getParent();
2782
2783 // Create a copy in a VGPR using V_ACCVGPR_READ_B32_e64 so it's not folded
2784 // out.
2785 const TargetRegisterClass *ARC = getRegOpRC(MRI: *MRI, TRI: *TRI, MO: *MOs.front());
2786 Register TempVGPR =
2787 MRI->createVirtualRegister(RegClass: TRI->getEquivalentVGPRClass(SRC: ARC));
2788 MachineInstr *VGPRCopy =
2789 BuildMI(BB&: *DefMBB, I: ++Def->getIterator(), MIMD: Def->getDebugLoc(),
2790 MCID: TII->get(Opcode: AMDGPU::V_ACCVGPR_READ_B32_e64), DestReg: TempVGPR)
2791 .addReg(RegNo: Reg, /* flags */ Flags: {}, SubReg);
2792
2793 // Copy back to an AGPR and use that instead of the AGPR subreg in all MOs.
2794 Register TempAGPR = MRI->createVirtualRegister(RegClass: ARC);
2795 BuildMI(BB&: *DefMBB, I: ++VGPRCopy->getIterator(), MIMD: Def->getDebugLoc(),
2796 MCID: TII->get(Opcode: AMDGPU::COPY), DestReg: TempAGPR)
2797 .addReg(RegNo: TempVGPR);
2798
2799 LLVM_DEBUG(dbgs() << "Caching AGPR into VGPR: " << *VGPRCopy);
2800 for (MachineOperand *MO : MOs) {
2801 MO->setReg(TempAGPR);
2802 MO->setSubReg(AMDGPU::NoSubRegister);
2803 LLVM_DEBUG(dbgs() << " Changed PHI Operand: " << *MO << "\n");
2804 }
2805
2806 Changed = true;
2807 }
2808
2809 return Changed;
2810}
2811
2812bool SIFoldOperandsImpl::run(MachineFunction &MF) {
2813 this->MF = &MF;
2814 MRI = &MF.getRegInfo();
2815 ST = &MF.getSubtarget<GCNSubtarget>();
2816 TII = ST->getInstrInfo();
2817 TRI = &TII->getRegisterInfo();
2818 MFI = MF.getInfo<SIMachineFunctionInfo>();
2819
2820 // omod is ignored by hardware if IEEE bit is enabled. omod also does not
2821 // correctly handle signed zeros.
2822 //
2823 // FIXME: Also need to check strictfp
2824 bool IsIEEEMode = MFI->getMode().IEEE;
2825
2826 bool Changed = false;
2827 for (MachineBasicBlock *MBB : depth_first(G: &MF)) {
2828 MachineOperand *CurrentKnownM0Val = nullptr;
2829 for (auto &MI : make_early_inc_range(Range&: *MBB)) {
2830 Changed |= tryFoldCndMask(MI);
2831
2832 if (tryFoldZeroHighBits(MI)) {
2833 Changed = true;
2834 continue;
2835 }
2836
2837 if (MI.isRegSequence() && tryFoldRegSequence(MI)) {
2838 Changed = true;
2839 continue;
2840 }
2841
2842 if (MI.isPHI() && tryFoldPhiAGPR(PHI&: MI)) {
2843 Changed = true;
2844 continue;
2845 }
2846
2847 if (MI.mayLoad() && tryFoldLoad(MI)) {
2848 Changed = true;
2849 continue;
2850 }
2851
2852 if (TII->isFoldableCopy(MI)) {
2853 Changed |= tryFoldFoldableCopy(MI, CurrentKnownM0Val);
2854 continue;
2855 }
2856
2857 // Saw an unknown clobber of m0, so we no longer know what it is.
2858 if (CurrentKnownM0Val && MI.modifiesRegister(Reg: AMDGPU::M0, TRI))
2859 CurrentKnownM0Val = nullptr;
2860
2861 // TODO: Omod might be OK if there is NSZ only on the source
2862 // instruction, and not the omod multiply.
2863 if (IsIEEEMode || !MI.getFlag(Flag: MachineInstr::FmNsz) || !tryFoldOMod(MI))
2864 Changed |= tryFoldClamp(MI);
2865 }
2866
2867 Changed |= tryOptimizeAGPRPhis(MBB&: *MBB);
2868 }
2869
2870 return Changed;
2871}
2872
2873PreservedAnalyses SIFoldOperandsPass::run(MachineFunction &MF,
2874 MachineFunctionAnalysisManager &) {
2875 MFPropsModifier _(*this, MF);
2876
2877 bool Changed = SIFoldOperandsImpl().run(MF);
2878 if (!Changed) {
2879 return PreservedAnalyses::all();
2880 }
2881 auto PA = getMachineFunctionPassPreservedAnalyses();
2882 PA.preserveSet<CFGAnalyses>();
2883 return PA;
2884}
2885