LLVM 22.0.0git
SIFoldOperands.cpp
Go to the documentation of this file.
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"
15#include "SIInstrInfo.h"
17#include "SIRegisterInfo.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.
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),
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(DefSubReg, 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(ImmToFold, 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) {
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(*ImmToFold);
124 return TII.isOperandLegal(MI, OpIdx, &TmpOp);
125 }
127 if (DefSubReg != AMDGPU::NoSubRegister)
128 return false;
129 MachineOperand TmpOp = MachineOperand::CreateFI(FrameIndexToFold);
130 return TII.isOperandLegal(MI, OpIdx, &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, OpToFold);
138 }
139
140 llvm_unreachable("covered MachineOperand kind switch");
141 }
142};
143
144struct FoldCandidate {
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:
177 const SIInstrInfo *TII;
178 const SIRegisterInfo *TRI;
179 const GCNSubtarget *ST;
180 const SIMachineFunctionInfo *MFI;
181
182 bool frameIndexMayFold(const MachineInstr &UseMI, int OpNo,
183 const FoldableDef &OpToFold) const;
184
185 // TODO: Just use TII::getVALUOp
186 unsigned convertToVALUOp(unsigned Opc, bool UseVOP3 = false) const {
187 switch (Opc) {
188 case AMDGPU::S_ADD_I32: {
189 if (ST->hasAddNoCarry())
190 return UseVOP3 ? AMDGPU::V_ADD_U32_e64 : AMDGPU::V_ADD_U32_e32;
191 return UseVOP3 ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_ADD_CO_U32_e32;
192 }
193 case AMDGPU::S_OR_B32:
194 return UseVOP3 ? AMDGPU::V_OR_B32_e64 : AMDGPU::V_OR_B32_e32;
195 case AMDGPU::S_AND_B32:
196 return UseVOP3 ? AMDGPU::V_AND_B32_e64 : AMDGPU::V_AND_B32_e32;
197 case AMDGPU::S_MUL_I32:
198 return AMDGPU::V_MUL_LO_U32_e64;
199 default:
200 return AMDGPU::INSTRUCTION_LIST_END;
201 }
202 }
203
204 bool foldCopyToVGPROfScalarAddOfFrameIndex(Register DstReg, Register SrcReg,
205 MachineInstr &MI) const;
206
207 bool updateOperand(FoldCandidate &Fold) const;
208
209 bool canUseImmWithOpSel(const MachineInstr *MI, unsigned UseOpNo,
210 int64_t ImmVal) const;
211
212 /// Try to fold immediate \p ImmVal into \p MI's operand at index \p UseOpNo.
213 bool tryFoldImmWithOpSel(MachineInstr *MI, unsigned UseOpNo,
214 int64_t ImmVal) const;
215
216 bool tryAddToFoldList(SmallVectorImpl<FoldCandidate> &FoldList,
217 MachineInstr *MI, unsigned OpNo,
218 const FoldableDef &OpToFold) const;
219 bool isUseSafeToFold(const MachineInstr &MI,
220 const MachineOperand &UseMO) const;
221
222 const TargetRegisterClass *getRegSeqInit(
223 MachineInstr &RegSeq,
224 SmallVectorImpl<std::pair<MachineOperand *, unsigned>> &Defs) const;
225
226 const TargetRegisterClass *
227 getRegSeqInit(SmallVectorImpl<std::pair<MachineOperand *, unsigned>> &Defs,
228 Register UseReg) const;
229
230 std::pair<int64_t, const TargetRegisterClass *>
231 isRegSeqSplat(MachineInstr &RegSeg) const;
232
233 bool tryFoldRegSeqSplat(MachineInstr *UseMI, unsigned UseOpIdx,
234 int64_t SplatVal,
235 const TargetRegisterClass *SplatRC) const;
236
237 bool tryToFoldACImm(const FoldableDef &OpToFold, MachineInstr *UseMI,
238 unsigned UseOpIdx,
239 SmallVectorImpl<FoldCandidate> &FoldList) const;
240 void foldOperand(FoldableDef OpToFold, MachineInstr *UseMI, int UseOpIdx,
242 SmallVectorImpl<MachineInstr *> &CopiesToReplace) const;
243
244 std::optional<int64_t> getImmOrMaterializedImm(MachineOperand &Op) const;
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(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();
288 }
289
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
306 const MachineOperand &MO) {
307 const TargetRegisterClass *RC = MRI.getRegClass(MO.getReg());
308 if (const TargetRegisterClass *SubRC =
309 TRI.getSubRegisterClass(RC, 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(OpNo == 1 ? 2 : 1).isImm() &&
354 MRI->hasOneNonDBGUse(UseMI.getOperand(OpNo).getReg());
355 case AMDGPU::V_ADD_U32_e64:
356 case AMDGPU::V_ADD_CO_U32_e64:
357 return UseMI.getOperand(OpNo == 2 ? 3 : 2).isImm() &&
358 MRI->hasOneNonDBGUse(UseMI.getOperand(OpNo).getReg());
359 default:
360 break;
361 }
362
363 if (TII->isMUBUF(UseMI))
364 return OpNo == AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vaddr);
365 if (!TII->isFLATScratch(UseMI))
366 return false;
367
368 int SIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::saddr);
369 if (OpNo == SIdx)
370 return true;
371
372 int VIdx = AMDGPU::getNamedOperandIdx(Opc, 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, DstReg) && TRI->isSGPRReg(*MRI, SrcReg) &&
382 MRI->hasOneNonDBGUse(SrcReg)) {
383 MachineInstr *Def = MRI->getVRegDef(SrcReg);
384 if (!Def || Def->getNumOperands() != 4)
385 return false;
386
387 MachineOperand *Src0 = &Def->getOperand(1);
388 MachineOperand *Src1 = &Def->getOperand(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(Src0, Src1);
398
399 const bool UseVOP3 = !Src0->isImm() || TII->isInlineConstant(*Src0);
400 unsigned NewOp = convertToVALUOp(Def->getOpcode(), UseVOP3);
401 if (NewOp == AMDGPU::INSTRUCTION_LIST_END ||
402 !Def->getOperand(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) {
409 BuildMI(*MBB, *Def, DL, TII->get(NewOp), DstReg);
410
411 if (Add->getDesc().getNumDefs() == 2) {
412 Register CarryOutReg = MRI->createVirtualRegister(TRI->getBoolRC());
413 Add.addDef(CarryOutReg, RegState::Dead);
414 MRI->setRegAllocationHint(CarryOutReg, 0, TRI->getVCC());
415 }
416
417 Add.add(*Src0).add(*Src1).setMIFlags(Def->getFlags());
418 if (AMDGPU::hasNamedOperand(NewOp, AMDGPU::OpName::clamp))
419 Add.addImm(0);
420
421 Def->eraseFromParent();
422 MI.eraseFromParent();
423 return true;
424 }
425
426 assert(NewOp == AMDGPU::V_ADD_CO_U32_e32);
427
429 MBB->computeRegisterLiveness(TRI, AMDGPU::VCC, *Def, 16);
430 if (Liveness == MachineBasicBlock::LQR_Dead) {
431 // TODO: If src1 satisfies operand constraints, use vop3 version.
432 BuildMI(*MBB, *Def, DL, TII->get(NewOp), DstReg)
433 .add(*Src0)
434 .add(*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
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(UseOpNo);
461 int OpNo = MI->getOperandNo(&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;
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(UseOpNo);
489 unsigned Opcode = MI->getOpcode();
490 int OpNo = MI->getOperandNo(&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(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, AMDGPU::OpName::src0)) {
506 ModName = AMDGPU::OpName::src0_modifiers;
507 SrcIdx = 0;
508 } else if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1)) {
509 ModName = AMDGPU::OpName::src1_modifiers;
510 SrcIdx = 1;
511 } else if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, 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, ModName);
517 MachineOperand &Mod = MI->getOperand(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(Imm, OpType)) {
531 Mod.setImm(NewModVal | SISrcMods::OP_SEL_1);
532 Old.ChangeToImmediate(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(Lo, OpType)) {
542 Mod.setImm(NewModVal);
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(SExt, OpType)) {
550 Mod.setImm(NewModVal);
551 Old.ChangeToImmediate(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(Lo << 16, OpType)) {
559 Mod.setImm(NewModVal | SISrcMods::OP_SEL_0 | SISrcMods::OP_SEL_1);
560 Old.ChangeToImmediate(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(Swapped, OpType)) {
567 Mod.setImm(NewModVal | SISrcMods::OP_SEL_0);
568 Old.ChangeToImmediate(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, AMDGPU::OpName::clamp);
590 bool Clamp = MI->getOperand(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(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(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(Fold.UseMI, Fold.UseOpNo, *ImmVal)) {
619 if (tryFoldImmWithOpSel(Fold.UseMI, Fold.UseOpNo, *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.
625 int OpNo = MI->getOperandNo(&Old);
626 if (!TII->isOperandLegal(*MI, OpNo, &New))
627 return false;
628 Old.ChangeToImmediate(*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, AMDGPU::VCC, MI, 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(0);
642 MachineOperand &Dst1 = MI->getOperand(1);
643 assert(Dst0.isDef() && Dst1.isDef());
644
645 bool HaveNonDbgCarryUse = !MRI->use_nodbg_empty(Dst1.getReg());
646
647 const TargetRegisterClass *Dst0RC = MRI->getRegClass(Dst0.getReg());
648 Register NewReg0 = MRI->createVirtualRegister(Dst0RC);
649
650 MachineInstr *Inst32 = TII->buildShrunkInst(*MI, Op32);
651
652 if (HaveNonDbgCarryUse) {
653 BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(AMDGPU::COPY),
654 Dst1.getReg())
655 .addReg(AMDGPU::VCC, 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(I);
667 MI->setDesc(TII->get(AMDGPU::IMPLICIT_DEF));
668
669 if (Fold.Commuted)
670 TII->commuteInstruction(*Inst32, 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(MI->getOpcode());
679 if (NewMFMAOpc == -1)
680 return false;
681 MI->setDesc(TII->get(NewMFMAOpc));
682 MI->untieRegOperand(0);
683 }
684
685 // TODO: Should we try to avoid adding this to the candidate list?
687 int OpNo = MI->getOperandNo(&Old);
688 if (!TII->isOperandLegal(*MI, OpNo, &New))
689 return false;
690
691 Old.ChangeToImmediate(*ImmVal);
692 return true;
693 }
694
695 if (Fold.isGlobal()) {
696 Old.ChangeToGA(Fold.Def.OpToFold->getGlobal(),
697 Fold.Def.OpToFold->getOffset(),
698 Fold.Def.OpToFold->getTargetFlags());
699 return true;
700 }
701
702 if (Fold.isFI()) {
703 Old.ChangeToFrameIndex(Fold.getFI());
704 return true;
705 }
706
707 MachineOperand *New = Fold.Def.OpToFold;
708 // Rework once the VS_16 register class is updated to include proper
709 // 16-bit SGPRs instead of 32-bit ones.
710 if (Old.getSubReg() == AMDGPU::lo16 && TRI->isSGPRReg(*MRI, New->getReg()))
711 Old.setSubReg(AMDGPU::NoSubRegister);
712 Old.substVirtReg(New->getReg(), New->getSubReg(), *TRI);
713 Old.setIsUndef(New->isUndef());
714 return true;
715}
716
718 FoldCandidate &&Entry) {
719 // Skip additional folding on the same operand.
720 for (FoldCandidate &Fold : FoldList)
721 if (Fold.UseMI == Entry.UseMI && Fold.UseOpNo == Entry.UseOpNo)
722 return;
723 LLVM_DEBUG(dbgs() << "Append " << (Entry.Commuted ? "commuted" : "normal")
724 << " operand " << Entry.UseOpNo << "\n " << *Entry.UseMI);
725 FoldList.push_back(Entry);
726}
727
729 MachineInstr *MI, unsigned OpNo,
730 const FoldableDef &FoldOp,
731 bool Commuted = false, int ShrinkOp = -1) {
732 appendFoldCandidate(FoldList,
733 FoldCandidate(MI, OpNo, FoldOp, Commuted, ShrinkOp));
734}
735
736bool SIFoldOperandsImpl::tryAddToFoldList(
737 SmallVectorImpl<FoldCandidate> &FoldList, MachineInstr *MI, unsigned OpNo,
738 const FoldableDef &OpToFold) const {
739 const unsigned Opc = MI->getOpcode();
740
741 auto tryToFoldAsFMAAKorMK = [&]() {
742 if (!OpToFold.isImm())
743 return false;
744
745 const bool TryAK = OpNo == 3;
746 const unsigned NewOpc = TryAK ? AMDGPU::S_FMAAK_F32 : AMDGPU::S_FMAMK_F32;
747 MI->setDesc(TII->get(NewOpc));
748
749 // We have to fold into operand which would be Imm not into OpNo.
750 bool FoldAsFMAAKorMK =
751 tryAddToFoldList(FoldList, MI, TryAK ? 3 : 2, OpToFold);
752 if (FoldAsFMAAKorMK) {
753 // Untie Src2 of fmac.
754 MI->untieRegOperand(3);
755 // For fmamk swap operands 1 and 2 if OpToFold was meant for operand 1.
756 if (OpNo == 1) {
757 MachineOperand &Op1 = MI->getOperand(1);
758 MachineOperand &Op2 = MI->getOperand(2);
759 Register OldReg = Op1.getReg();
760 // Operand 2 might be an inlinable constant
761 if (Op2.isImm()) {
762 Op1.ChangeToImmediate(Op2.getImm());
763 Op2.ChangeToRegister(OldReg, false);
764 } else {
765 Op1.setReg(Op2.getReg());
766 Op2.setReg(OldReg);
767 }
768 }
769 return true;
770 }
771 MI->setDesc(TII->get(Opc));
772 return false;
773 };
774
775 bool IsLegal = OpToFold.isOperandLegal(*TII, *MI, OpNo);
776 if (!IsLegal && OpToFold.isImm()) {
777 if (std::optional<int64_t> ImmVal = OpToFold.getEffectiveImmVal())
778 IsLegal = canUseImmWithOpSel(MI, OpNo, *ImmVal);
779 }
780
781 if (!IsLegal) {
782 // Special case for v_mac_{f16, f32}_e64 if we are trying to fold into src2
783 unsigned NewOpc = macToMad(Opc);
784 if (NewOpc != AMDGPU::INSTRUCTION_LIST_END) {
785 // Check if changing this to a v_mad_{f16, f32} instruction will allow us
786 // to fold the operand.
787 MI->setDesc(TII->get(NewOpc));
788 bool AddOpSel = !AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::op_sel) &&
789 AMDGPU::hasNamedOperand(NewOpc, AMDGPU::OpName::op_sel);
790 if (AddOpSel)
791 MI->addOperand(MachineOperand::CreateImm(0));
792 bool FoldAsMAD = tryAddToFoldList(FoldList, MI, OpNo, OpToFold);
793 if (FoldAsMAD) {
794 MI->untieRegOperand(OpNo);
795 return true;
796 }
797 if (AddOpSel)
798 MI->removeOperand(MI->getNumExplicitOperands() - 1);
799 MI->setDesc(TII->get(Opc));
800 }
801
802 // Special case for s_fmac_f32 if we are trying to fold into Src2.
803 // By transforming into fmaak we can untie Src2 and make folding legal.
804 if (Opc == AMDGPU::S_FMAC_F32 && OpNo == 3) {
805 if (tryToFoldAsFMAAKorMK())
806 return true;
807 }
808
809 // Special case for s_setreg_b32
810 if (OpToFold.isImm()) {
811 unsigned ImmOpc = 0;
812 if (Opc == AMDGPU::S_SETREG_B32)
813 ImmOpc = AMDGPU::S_SETREG_IMM32_B32;
814 else if (Opc == AMDGPU::S_SETREG_B32_mode)
815 ImmOpc = AMDGPU::S_SETREG_IMM32_B32_mode;
816 if (ImmOpc) {
817 MI->setDesc(TII->get(ImmOpc));
818 appendFoldCandidate(FoldList, MI, OpNo, OpToFold);
819 return true;
820 }
821 }
822
823 // Operand is not legal, so try to commute the instruction to
824 // see if this makes it possible to fold.
825 unsigned CommuteOpNo = TargetInstrInfo::CommuteAnyOperandIndex;
826 bool CanCommute = TII->findCommutedOpIndices(*MI, OpNo, CommuteOpNo);
827 if (!CanCommute)
828 return false;
829
830 MachineOperand &Op = MI->getOperand(OpNo);
831 MachineOperand &CommutedOp = MI->getOperand(CommuteOpNo);
832
833 // One of operands might be an Imm operand, and OpNo may refer to it after
834 // the call of commuteInstruction() below. Such situations are avoided
835 // here explicitly as OpNo must be a register operand to be a candidate
836 // for memory folding.
837 if (!Op.isReg() || !CommutedOp.isReg())
838 return false;
839
840 // The same situation with an immediate could reproduce if both inputs are
841 // the same register.
842 if (Op.isReg() && CommutedOp.isReg() &&
843 (Op.getReg() == CommutedOp.getReg() &&
844 Op.getSubReg() == CommutedOp.getSubReg()))
845 return false;
846
847 if (!TII->commuteInstruction(*MI, false, OpNo, CommuteOpNo))
848 return false;
849
850 int Op32 = -1;
851 if (!OpToFold.isOperandLegal(*TII, *MI, CommuteOpNo)) {
852 if ((Opc != AMDGPU::V_ADD_CO_U32_e64 && Opc != AMDGPU::V_SUB_CO_U32_e64 &&
853 Opc != AMDGPU::V_SUBREV_CO_U32_e64) || // FIXME
854 (!OpToFold.isImm() && !OpToFold.isFI() && !OpToFold.isGlobal())) {
855 TII->commuteInstruction(*MI, false, OpNo, CommuteOpNo);
856 return false;
857 }
858
859 // Verify the other operand is a VGPR, otherwise we would violate the
860 // constant bus restriction.
861 MachineOperand &OtherOp = MI->getOperand(OpNo);
862 if (!OtherOp.isReg() ||
863 !TII->getRegisterInfo().isVGPR(*MRI, OtherOp.getReg()))
864 return false;
865
866 assert(MI->getOperand(1).isDef());
867
868 // Make sure to get the 32-bit version of the commuted opcode.
869 unsigned MaybeCommutedOpc = MI->getOpcode();
870 Op32 = AMDGPU::getVOPe32(MaybeCommutedOpc);
871 }
872
873 appendFoldCandidate(FoldList, MI, CommuteOpNo, OpToFold, /*Commuted=*/true,
874 Op32);
875 return true;
876 }
877
878 // Special case for s_fmac_f32 if we are trying to fold into Src0 or Src1.
879 // By changing into fmamk we can untie Src2.
880 // If folding for Src0 happens first and it is identical operand to Src1 we
881 // should avoid transforming into fmamk which requires commuting as it would
882 // cause folding into Src1 to fail later on due to wrong OpNo used.
883 if (Opc == AMDGPU::S_FMAC_F32 &&
884 (OpNo != 1 || !MI->getOperand(1).isIdenticalTo(MI->getOperand(2)))) {
885 if (tryToFoldAsFMAAKorMK())
886 return true;
887 }
888
889 appendFoldCandidate(FoldList, MI, OpNo, OpToFold);
890 return true;
891}
892
893bool SIFoldOperandsImpl::isUseSafeToFold(const MachineInstr &MI,
894 const MachineOperand &UseMO) const {
895 // Operands of SDWA instructions must be registers.
896 return !TII->isSDWA(MI);
897}
898
901 Register SrcReg) {
902 MachineOperand *Sub = nullptr;
903 for (MachineInstr *SubDef = MRI.getVRegDef(SrcReg);
904 SubDef && TII.isFoldableCopy(*SubDef);
905 SubDef = MRI.getVRegDef(Sub->getReg())) {
906 MachineOperand &SrcOp = SubDef->getOperand(1);
907 if (SrcOp.isImm())
908 return &SrcOp;
909 if (!SrcOp.isReg() || SrcOp.getReg().isPhysical())
910 break;
911 Sub = &SrcOp;
912 // TODO: Support compose
913 if (SrcOp.getSubReg())
914 break;
915 }
916
917 return Sub;
918}
919
920const TargetRegisterClass *SIFoldOperandsImpl::getRegSeqInit(
921 MachineInstr &RegSeq,
922 SmallVectorImpl<std::pair<MachineOperand *, unsigned>> &Defs) const {
923
924 assert(RegSeq.isRegSequence());
925
926 const TargetRegisterClass *RC = nullptr;
927
928 for (unsigned I = 1, E = RegSeq.getNumExplicitOperands(); I != E; I += 2) {
929 MachineOperand &SrcOp = RegSeq.getOperand(I);
930 unsigned SubRegIdx = RegSeq.getOperand(I + 1).getImm();
931
932 // Only accept reg_sequence with uniform reg class inputs for simplicity.
933 const TargetRegisterClass *OpRC = getRegOpRC(*MRI, *TRI, SrcOp);
934 if (!RC)
935 RC = OpRC;
936 else if (!TRI->getCommonSubClass(RC, OpRC))
937 return nullptr;
938
939 if (SrcOp.getSubReg()) {
940 // TODO: Handle subregister compose
941 Defs.emplace_back(&SrcOp, SubRegIdx);
942 continue;
943 }
944
946 if (DefSrc && (DefSrc->isReg() || DefSrc->isImm())) {
947 Defs.emplace_back(DefSrc, SubRegIdx);
948 continue;
949 }
950
951 Defs.emplace_back(&SrcOp, SubRegIdx);
952 }
953
954 return RC;
955}
956
957// Find a def of the UseReg, check if it is a reg_sequence and find initializers
958// for each subreg, tracking it to an immediate if possible. Returns the
959// register class of the inputs on success.
960const TargetRegisterClass *SIFoldOperandsImpl::getRegSeqInit(
961 SmallVectorImpl<std::pair<MachineOperand *, unsigned>> &Defs,
962 Register UseReg) const {
963 MachineInstr *Def = MRI->getVRegDef(UseReg);
964 if (!Def || !Def->isRegSequence())
965 return nullptr;
966
967 return getRegSeqInit(*Def, Defs);
968}
969
970std::pair<int64_t, const TargetRegisterClass *>
971SIFoldOperandsImpl::isRegSeqSplat(MachineInstr &RegSeq) const {
973 const TargetRegisterClass *SrcRC = getRegSeqInit(RegSeq, Defs);
974 if (!SrcRC)
975 return {};
976
977 bool TryToMatchSplat64 = false;
978
979 int64_t Imm;
980 for (unsigned I = 0, E = Defs.size(); I != E; ++I) {
981 const MachineOperand *Op = Defs[I].first;
982 if (!Op->isImm())
983 return {};
984
985 int64_t SubImm = Op->getImm();
986 if (!I) {
987 Imm = SubImm;
988 continue;
989 }
990
991 if (Imm != SubImm) {
992 if (I == 1 && (E & 1) == 0) {
993 // If we have an even number of inputs, there's a chance this is a
994 // 64-bit element splat broken into 32-bit pieces.
995 TryToMatchSplat64 = true;
996 break;
997 }
998
999 return {}; // Can only fold splat constants
1000 }
1001 }
1002
1003 if (!TryToMatchSplat64)
1004 return {Defs[0].first->getImm(), SrcRC};
1005
1006 // Fallback to recognizing 64-bit splats broken into 32-bit pieces
1007 // (i.e. recognize every other other element is 0 for 64-bit immediates)
1008 int64_t SplatVal64;
1009 for (unsigned I = 0, E = Defs.size(); I != E; I += 2) {
1010 const MachineOperand *Op0 = Defs[I].first;
1011 const MachineOperand *Op1 = Defs[I + 1].first;
1012
1013 if (!Op0->isImm() || !Op1->isImm())
1014 return {};
1015
1016 unsigned SubReg0 = Defs[I].second;
1017 unsigned SubReg1 = Defs[I + 1].second;
1018
1019 // Assume we're going to generally encounter reg_sequences with sorted
1020 // subreg indexes, so reject any that aren't consecutive.
1021 if (TRI->getChannelFromSubReg(SubReg0) + 1 !=
1022 TRI->getChannelFromSubReg(SubReg1))
1023 return {};
1024
1025 int64_t MergedVal = Make_64(Op1->getImm(), Op0->getImm());
1026 if (I == 0)
1027 SplatVal64 = MergedVal;
1028 else if (SplatVal64 != MergedVal)
1029 return {};
1030 }
1031
1032 const TargetRegisterClass *RC64 = TRI->getSubRegisterClass(
1033 MRI->getRegClass(RegSeq.getOperand(0).getReg()), AMDGPU::sub0_sub1);
1034
1035 return {SplatVal64, RC64};
1036}
1037
1038bool SIFoldOperandsImpl::tryFoldRegSeqSplat(
1039 MachineInstr *UseMI, unsigned UseOpIdx, int64_t SplatVal,
1040 const TargetRegisterClass *SplatRC) const {
1041 const MCInstrDesc &Desc = UseMI->getDesc();
1042 if (UseOpIdx >= Desc.getNumOperands())
1043 return false;
1044
1045 // Filter out unhandled pseudos.
1046 if (!AMDGPU::isSISrcOperand(Desc, UseOpIdx))
1047 return false;
1048
1049 int16_t RCID = Desc.operands()[UseOpIdx].RegClass;
1050 if (RCID == -1)
1051 return false;
1052
1053 const TargetRegisterClass *OpRC = TRI->getRegClass(RCID);
1054
1055 // Special case 0/-1, since when interpreted as a 64-bit element both halves
1056 // have the same bits. These are the only cases where a splat has the same
1057 // interpretation for 32-bit and 64-bit splats.
1058 if (SplatVal != 0 && SplatVal != -1) {
1059 // We need to figure out the scalar type read by the operand. e.g. the MFMA
1060 // operand will be AReg_128, and we want to check if it's compatible with an
1061 // AReg_32 constant.
1062 uint8_t OpTy = Desc.operands()[UseOpIdx].OperandType;
1063 switch (OpTy) {
1068 OpRC = TRI->getSubRegisterClass(OpRC, AMDGPU::sub0);
1069 break;
1073 OpRC = TRI->getSubRegisterClass(OpRC, AMDGPU::sub0_sub1);
1074 break;
1075 default:
1076 return false;
1077 }
1078
1079 if (!TRI->getCommonSubClass(OpRC, SplatRC))
1080 return false;
1081 }
1082
1083 MachineOperand TmpOp = MachineOperand::CreateImm(SplatVal);
1084 if (!TII->isOperandLegal(*UseMI, UseOpIdx, &TmpOp))
1085 return false;
1086
1087 return true;
1088}
1089
1090bool SIFoldOperandsImpl::tryToFoldACImm(
1091 const FoldableDef &OpToFold, MachineInstr *UseMI, unsigned UseOpIdx,
1092 SmallVectorImpl<FoldCandidate> &FoldList) const {
1093 const MCInstrDesc &Desc = UseMI->getDesc();
1094 if (UseOpIdx >= Desc.getNumOperands())
1095 return false;
1096
1097 // Filter out unhandled pseudos.
1098 if (!AMDGPU::isSISrcOperand(Desc, UseOpIdx))
1099 return false;
1100
1101 MachineOperand &UseOp = UseMI->getOperand(UseOpIdx);
1102 if (OpToFold.isImm() && OpToFold.isOperandLegal(*TII, *UseMI, UseOpIdx)) {
1103 appendFoldCandidate(FoldList, UseMI, UseOpIdx, OpToFold);
1104 return true;
1105 }
1106
1107 // TODO: Verify the following code handles subregisters correctly.
1108 // TODO: Handle extract of global reference
1109 if (UseOp.getSubReg())
1110 return false;
1111
1112 if (!OpToFold.isReg())
1113 return false;
1114
1115 Register UseReg = OpToFold.getReg();
1116 if (!UseReg.isVirtual())
1117 return false;
1118
1119 // Maybe it is just a COPY of an immediate itself.
1120
1121 // FIXME: Remove this handling. There is already special case folding of
1122 // immediate into copy in foldOperand. This is looking for the def of the
1123 // value the folding started from in the first place.
1124 MachineInstr *Def = MRI->getVRegDef(UseReg);
1125 if (Def && TII->isFoldableCopy(*Def)) {
1126 MachineOperand &DefOp = Def->getOperand(1);
1127 if (DefOp.isImm() && TII->isOperandLegal(*UseMI, UseOpIdx, &DefOp)) {
1128 FoldableDef FoldableImm(DefOp.getImm(), OpToFold.DefRC,
1129 OpToFold.DefSubReg);
1130 appendFoldCandidate(FoldList, UseMI, UseOpIdx, FoldableImm);
1131 return true;
1132 }
1133 }
1134
1135 return false;
1136}
1137
1138void SIFoldOperandsImpl::foldOperand(
1139 FoldableDef OpToFold, MachineInstr *UseMI, int UseOpIdx,
1141 SmallVectorImpl<MachineInstr *> &CopiesToReplace) const {
1142 const MachineOperand *UseOp = &UseMI->getOperand(UseOpIdx);
1143
1144 if (!isUseSafeToFold(*UseMI, *UseOp))
1145 return;
1146
1147 // FIXME: Fold operands with subregs.
1148 if (UseOp->isReg() && OpToFold.isReg()) {
1149 if (UseOp->isImplicit())
1150 return;
1151 // Allow folding from SGPRs to 16-bit VGPRs.
1152 if (UseOp->getSubReg() != AMDGPU::NoSubRegister &&
1153 (UseOp->getSubReg() != AMDGPU::lo16 ||
1154 !TRI->isSGPRReg(*MRI, OpToFold.getReg())))
1155 return;
1156 }
1157
1158 // Special case for REG_SEQUENCE: We can't fold literals into
1159 // REG_SEQUENCE instructions, so we have to fold them into the
1160 // uses of REG_SEQUENCE.
1161 if (UseMI->isRegSequence()) {
1162 Register RegSeqDstReg = UseMI->getOperand(0).getReg();
1163 unsigned RegSeqDstSubReg = UseMI->getOperand(UseOpIdx + 1).getImm();
1164
1165 int64_t SplatVal;
1166 const TargetRegisterClass *SplatRC;
1167 std::tie(SplatVal, SplatRC) = isRegSeqSplat(*UseMI);
1168
1169 // Grab the use operands first
1171 llvm::make_pointer_range(MRI->use_nodbg_operands(RegSeqDstReg)));
1172 for (unsigned I = 0; I != UsesToProcess.size(); ++I) {
1173 MachineOperand *RSUse = UsesToProcess[I];
1174 MachineInstr *RSUseMI = RSUse->getParent();
1175 unsigned OpNo = RSUseMI->getOperandNo(RSUse);
1176
1177 if (SplatRC) {
1178 if (RSUseMI->isCopy()) {
1179 Register DstReg = RSUseMI->getOperand(0).getReg();
1180 append_range(UsesToProcess,
1181 make_pointer_range(MRI->use_nodbg_operands(DstReg)));
1182 continue;
1183 }
1184 if (tryFoldRegSeqSplat(RSUseMI, OpNo, SplatVal, SplatRC)) {
1185 FoldableDef SplatDef(SplatVal, SplatRC);
1186 appendFoldCandidate(FoldList, RSUseMI, OpNo, SplatDef);
1187 continue;
1188 }
1189 }
1190
1191 // TODO: Handle general compose
1192 if (RSUse->getSubReg() != RegSeqDstSubReg)
1193 continue;
1194
1195 // FIXME: We should avoid recursing here. There should be a cleaner split
1196 // between the in-place mutations and adding to the fold list.
1197 foldOperand(OpToFold, RSUseMI, RSUseMI->getOperandNo(RSUse), FoldList,
1198 CopiesToReplace);
1199 }
1200
1201 return;
1202 }
1203
1204 if (tryToFoldACImm(OpToFold, UseMI, UseOpIdx, FoldList))
1205 return;
1206
1207 if (frameIndexMayFold(*UseMI, UseOpIdx, OpToFold)) {
1208 // Verify that this is a stack access.
1209 // FIXME: Should probably use stack pseudos before frame lowering.
1210
1211 if (TII->isMUBUF(*UseMI)) {
1212 if (TII->getNamedOperand(*UseMI, AMDGPU::OpName::srsrc)->getReg() !=
1213 MFI->getScratchRSrcReg())
1214 return;
1215
1216 // Ensure this is either relative to the current frame or the current
1217 // wave.
1218 MachineOperand &SOff =
1219 *TII->getNamedOperand(*UseMI, AMDGPU::OpName::soffset);
1220 if (!SOff.isImm() || SOff.getImm() != 0)
1221 return;
1222 }
1223
1224 const unsigned Opc = UseMI->getOpcode();
1225 if (TII->isFLATScratch(*UseMI) &&
1226 AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::vaddr) &&
1227 !AMDGPU::hasNamedOperand(Opc, AMDGPU::OpName::saddr)) {
1228 unsigned NewOpc = AMDGPU::getFlatScratchInstSSfromSV(Opc);
1229 unsigned CPol =
1230 TII->getNamedOperand(*UseMI, AMDGPU::OpName::cpol)->getImm();
1231 if ((CPol & AMDGPU::CPol::SCAL) &&
1233 return;
1234
1235 UseMI->setDesc(TII->get(NewOpc));
1236 }
1237
1238 // A frame index will resolve to a positive constant, so it should always be
1239 // safe to fold the addressing mode, even pre-GFX9.
1240 UseMI->getOperand(UseOpIdx).ChangeToFrameIndex(OpToFold.getFI());
1241
1242 return;
1243 }
1244
1245 bool FoldingImmLike =
1246 OpToFold.isImm() || OpToFold.isFI() || OpToFold.isGlobal();
1247
1248 if (FoldingImmLike && UseMI->isCopy()) {
1249 Register DestReg = UseMI->getOperand(0).getReg();
1250 Register SrcReg = UseMI->getOperand(1).getReg();
1251 unsigned UseSubReg = UseMI->getOperand(1).getSubReg();
1252 assert(SrcReg.isVirtual());
1253
1254 const TargetRegisterClass *SrcRC = MRI->getRegClass(SrcReg);
1255
1256 // Don't fold into a copy to a physical register with the same class. Doing
1257 // so would interfere with the register coalescer's logic which would avoid
1258 // redundant initializations.
1259 if (DestReg.isPhysical() && SrcRC->contains(DestReg))
1260 return;
1261
1262 const TargetRegisterClass *DestRC = TRI->getRegClassForReg(*MRI, DestReg);
1263 // In order to fold immediates into copies, we need to change the copy to a
1264 // MOV. Find a compatible mov instruction with the value.
1265 for (unsigned MovOp :
1266 {AMDGPU::S_MOV_B32, AMDGPU::V_MOV_B32_e32, AMDGPU::S_MOV_B64,
1267 AMDGPU::V_MOV_B64_PSEUDO, AMDGPU::V_MOV_B16_t16_e64,
1268 AMDGPU::V_ACCVGPR_WRITE_B32_e64, AMDGPU::AV_MOV_B32_IMM_PSEUDO}) {
1269 const MCInstrDesc &MovDesc = TII->get(MovOp);
1270 assert(MovDesc.getNumDefs() > 0 && MovDesc.operands()[0].RegClass != -1);
1271
1272 const TargetRegisterClass *MovDstRC =
1273 TRI->getRegClass(MovDesc.operands()[0].RegClass);
1274
1275 // Fold if the destination register class of the MOV instruction (ResRC)
1276 // is a superclass of (or equal to) the destination register class of the
1277 // COPY (DestRC). If this condition fails, folding would be illegal.
1278 if (!DestRC->hasSuperClassEq(MovDstRC))
1279 continue;
1280
1281 const int SrcIdx = MovOp == AMDGPU::V_MOV_B16_t16_e64 ? 2 : 1;
1282 const TargetRegisterClass *MovSrcRC =
1283 TRI->getRegClass(MovDesc.operands()[SrcIdx].RegClass);
1284
1285 if (UseSubReg)
1286 MovSrcRC = TRI->getMatchingSuperRegClass(SrcRC, MovSrcRC, UseSubReg);
1287 if (!MRI->constrainRegClass(SrcReg, MovSrcRC))
1288 break;
1289
1292 while (ImpOpI != ImpOpE) {
1293 MachineInstr::mop_iterator Tmp = ImpOpI;
1294 ImpOpI++;
1296 }
1297 UseMI->setDesc(MovDesc);
1298
1299 if (MovOp == AMDGPU::V_MOV_B16_t16_e64) {
1300 const auto &SrcOp = UseMI->getOperand(UseOpIdx);
1301 MachineOperand NewSrcOp(SrcOp);
1303 UseMI->removeOperand(1);
1304 UseMI->addOperand(*MF, MachineOperand::CreateImm(0)); // src0_modifiers
1305 UseMI->addOperand(NewSrcOp); // src0
1306 UseMI->addOperand(*MF, MachineOperand::CreateImm(0)); // op_sel
1307 UseOpIdx = SrcIdx;
1308 UseOp = &UseMI->getOperand(UseOpIdx);
1309 }
1310 CopiesToReplace.push_back(UseMI);
1311 break;
1312 }
1313
1314 // We failed to replace the copy, so give up.
1315 if (UseMI->getOpcode() == AMDGPU::COPY)
1316 return;
1317
1318 } else {
1319 if (UseMI->isCopy() && OpToFold.isReg() &&
1320 UseMI->getOperand(0).getReg().isVirtual() &&
1321 !UseMI->getOperand(1).getSubReg() &&
1322 OpToFold.DefMI->implicit_operands().empty()) {
1323 LLVM_DEBUG(dbgs() << "Folding " << OpToFold.OpToFold << "\n into "
1324 << *UseMI);
1325 unsigned Size = TII->getOpSize(*UseMI, 1);
1326 Register UseReg = OpToFold.getReg();
1328 unsigned SubRegIdx = OpToFold.getSubReg();
1329 // Hack to allow 32-bit SGPRs to be folded into True16 instructions
1330 // Remove this if 16-bit SGPRs (i.e. SGPR_LO16) are added to the
1331 // VS_16RegClass
1332 //
1333 // Excerpt from AMDGPUGenRegisterInfo.inc
1334 // NoSubRegister, //0
1335 // hi16, // 1
1336 // lo16, // 2
1337 // sub0, // 3
1338 // ...
1339 // sub1, // 11
1340 // sub1_hi16, // 12
1341 // sub1_lo16, // 13
1342 static_assert(AMDGPU::sub1_hi16 == 12, "Subregister layout has changed");
1343 if (Size == 2 && TRI->isVGPR(*MRI, UseMI->getOperand(0).getReg()) &&
1344 TRI->isSGPRReg(*MRI, UseReg)) {
1345 // Produce the 32 bit subregister index to which the 16-bit subregister
1346 // is aligned.
1347 if (SubRegIdx > AMDGPU::sub1) {
1348 LaneBitmask M = TRI->getSubRegIndexLaneMask(SubRegIdx);
1349 M |= M.getLane(M.getHighestLane() - 1);
1351 TRI->getCoveringSubRegIndexes(TRI->getRegClassForReg(*MRI, UseReg), M,
1352 Indexes);
1353 assert(Indexes.size() == 1 && "Expected one 32-bit subreg to cover");
1354 SubRegIdx = Indexes[0];
1355 // 32-bit registers do not have a sub0 index
1356 } else if (TII->getOpSize(*UseMI, 1) == 4)
1357 SubRegIdx = 0;
1358 else
1359 SubRegIdx = AMDGPU::sub0;
1360 }
1361 UseMI->getOperand(1).setSubReg(SubRegIdx);
1362 UseMI->getOperand(1).setIsKill(false);
1363 CopiesToReplace.push_back(UseMI);
1364 OpToFold.OpToFold->setIsKill(false);
1365
1366 // Remove kill flags as kills may now be out of order with uses.
1367 MRI->clearKillFlags(UseReg);
1368 if (foldCopyToAGPRRegSequence(UseMI))
1369 return;
1370 }
1371
1372 unsigned UseOpc = UseMI->getOpcode();
1373 if (UseOpc == AMDGPU::V_READFIRSTLANE_B32 ||
1374 (UseOpc == AMDGPU::V_READLANE_B32 &&
1375 (int)UseOpIdx ==
1376 AMDGPU::getNamedOperandIdx(UseOpc, AMDGPU::OpName::src0))) {
1377 // %vgpr = V_MOV_B32 imm
1378 // %sgpr = V_READFIRSTLANE_B32 %vgpr
1379 // =>
1380 // %sgpr = S_MOV_B32 imm
1381 if (FoldingImmLike) {
1383 UseMI->getOperand(UseOpIdx).getReg(),
1384 *OpToFold.DefMI, *UseMI))
1385 return;
1386
1387 UseMI->setDesc(TII->get(AMDGPU::S_MOV_B32));
1388
1389 if (OpToFold.isImm()) {
1391 *OpToFold.getEffectiveImmVal());
1392 } else if (OpToFold.isFI())
1393 UseMI->getOperand(1).ChangeToFrameIndex(OpToFold.getFI());
1394 else {
1395 assert(OpToFold.isGlobal());
1396 UseMI->getOperand(1).ChangeToGA(OpToFold.OpToFold->getGlobal(),
1397 OpToFold.OpToFold->getOffset(),
1398 OpToFold.OpToFold->getTargetFlags());
1399 }
1400 UseMI->removeOperand(2); // Remove exec read (or src1 for readlane)
1401 return;
1402 }
1403
1404 if (OpToFold.isReg() && TRI->isSGPRReg(*MRI, OpToFold.getReg())) {
1406 UseMI->getOperand(UseOpIdx).getReg(),
1407 *OpToFold.DefMI, *UseMI))
1408 return;
1409
1410 // %vgpr = COPY %sgpr0
1411 // %sgpr1 = V_READFIRSTLANE_B32 %vgpr
1412 // =>
1413 // %sgpr1 = COPY %sgpr0
1414 UseMI->setDesc(TII->get(AMDGPU::COPY));
1415 UseMI->getOperand(1).setReg(OpToFold.getReg());
1416 UseMI->getOperand(1).setSubReg(OpToFold.getSubReg());
1417 UseMI->getOperand(1).setIsKill(false);
1418 UseMI->removeOperand(2); // Remove exec read (or src1 for readlane)
1419 return;
1420 }
1421 }
1422
1423 const MCInstrDesc &UseDesc = UseMI->getDesc();
1424
1425 // Don't fold into target independent nodes. Target independent opcodes
1426 // don't have defined register classes.
1427 if (UseDesc.isVariadic() || UseOp->isImplicit() ||
1428 UseDesc.operands()[UseOpIdx].RegClass == -1)
1429 return;
1430 }
1431
1432 if (!FoldingImmLike) {
1433 if (OpToFold.isReg() && ST->needsAlignedVGPRs()) {
1434 // Don't fold if OpToFold doesn't hold an aligned register.
1435 const TargetRegisterClass *RC =
1436 TRI->getRegClassForReg(*MRI, OpToFold.getReg());
1437 assert(RC);
1438 if (TRI->hasVectorRegisters(RC) && OpToFold.getSubReg()) {
1439 unsigned SubReg = OpToFold.getSubReg();
1440 if (const TargetRegisterClass *SubRC =
1441 TRI->getSubRegisterClass(RC, SubReg))
1442 RC = SubRC;
1443 }
1444
1445 if (!RC || !TRI->isProperlyAlignedRC(*RC))
1446 return;
1447 }
1448
1449 tryAddToFoldList(FoldList, UseMI, UseOpIdx, OpToFold);
1450
1451 // FIXME: We could try to change the instruction from 64-bit to 32-bit
1452 // to enable more folding opportunities. The shrink operands pass
1453 // already does this.
1454 return;
1455 }
1456
1457 tryAddToFoldList(FoldList, UseMI, UseOpIdx, OpToFold);
1458}
1459
1460static bool evalBinaryInstruction(unsigned Opcode, int32_t &Result,
1461 uint32_t LHS, uint32_t RHS) {
1462 switch (Opcode) {
1463 case AMDGPU::V_AND_B32_e64:
1464 case AMDGPU::V_AND_B32_e32:
1465 case AMDGPU::S_AND_B32:
1466 Result = LHS & RHS;
1467 return true;
1468 case AMDGPU::V_OR_B32_e64:
1469 case AMDGPU::V_OR_B32_e32:
1470 case AMDGPU::S_OR_B32:
1471 Result = LHS | RHS;
1472 return true;
1473 case AMDGPU::V_XOR_B32_e64:
1474 case AMDGPU::V_XOR_B32_e32:
1475 case AMDGPU::S_XOR_B32:
1476 Result = LHS ^ RHS;
1477 return true;
1478 case AMDGPU::S_XNOR_B32:
1479 Result = ~(LHS ^ RHS);
1480 return true;
1481 case AMDGPU::S_NAND_B32:
1482 Result = ~(LHS & RHS);
1483 return true;
1484 case AMDGPU::S_NOR_B32:
1485 Result = ~(LHS | RHS);
1486 return true;
1487 case AMDGPU::S_ANDN2_B32:
1488 Result = LHS & ~RHS;
1489 return true;
1490 case AMDGPU::S_ORN2_B32:
1491 Result = LHS | ~RHS;
1492 return true;
1493 case AMDGPU::V_LSHL_B32_e64:
1494 case AMDGPU::V_LSHL_B32_e32:
1495 case AMDGPU::S_LSHL_B32:
1496 // The instruction ignores the high bits for out of bounds shifts.
1497 Result = LHS << (RHS & 31);
1498 return true;
1499 case AMDGPU::V_LSHLREV_B32_e64:
1500 case AMDGPU::V_LSHLREV_B32_e32:
1501 Result = RHS << (LHS & 31);
1502 return true;
1503 case AMDGPU::V_LSHR_B32_e64:
1504 case AMDGPU::V_LSHR_B32_e32:
1505 case AMDGPU::S_LSHR_B32:
1506 Result = LHS >> (RHS & 31);
1507 return true;
1508 case AMDGPU::V_LSHRREV_B32_e64:
1509 case AMDGPU::V_LSHRREV_B32_e32:
1510 Result = RHS >> (LHS & 31);
1511 return true;
1512 case AMDGPU::V_ASHR_I32_e64:
1513 case AMDGPU::V_ASHR_I32_e32:
1514 case AMDGPU::S_ASHR_I32:
1515 Result = static_cast<int32_t>(LHS) >> (RHS & 31);
1516 return true;
1517 case AMDGPU::V_ASHRREV_I32_e64:
1518 case AMDGPU::V_ASHRREV_I32_e32:
1519 Result = static_cast<int32_t>(RHS) >> (LHS & 31);
1520 return true;
1521 default:
1522 return false;
1523 }
1524}
1525
1526static unsigned getMovOpc(bool IsScalar) {
1527 return IsScalar ? AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32;
1528}
1529
1530static void mutateCopyOp(MachineInstr &MI, const MCInstrDesc &NewDesc) {
1531 MI.setDesc(NewDesc);
1532
1533 // Remove any leftover implicit operands from mutating the instruction. e.g.
1534 // if we replace an s_and_b32 with a copy, we don't need the implicit scc def
1535 // anymore.
1536 const MCInstrDesc &Desc = MI.getDesc();
1537 unsigned NumOps = Desc.getNumOperands() + Desc.implicit_uses().size() +
1538 Desc.implicit_defs().size();
1539
1540 for (unsigned I = MI.getNumOperands() - 1; I >= NumOps; --I)
1541 MI.removeOperand(I);
1542}
1543
1544std::optional<int64_t>
1545SIFoldOperandsImpl::getImmOrMaterializedImm(MachineOperand &Op) const {
1546 if (Op.isImm())
1547 return Op.getImm();
1548
1549 if (!Op.isReg() || !Op.getReg().isVirtual())
1550 return std::nullopt;
1551
1552 const MachineInstr *Def = MRI->getVRegDef(Op.getReg());
1553 if (Def && Def->isMoveImmediate()) {
1554 const MachineOperand &ImmSrc = Def->getOperand(1);
1555 if (ImmSrc.isImm())
1556 return TII->extractSubregFromImm(ImmSrc.getImm(), Op.getSubReg());
1557 }
1558
1559 return std::nullopt;
1560}
1561
1562// Try to simplify operations with a constant that may appear after instruction
1563// selection.
1564// TODO: See if a frame index with a fixed offset can fold.
1565bool SIFoldOperandsImpl::tryConstantFoldOp(MachineInstr *MI) const {
1566 if (!MI->allImplicitDefsAreDead())
1567 return false;
1568
1569 unsigned Opc = MI->getOpcode();
1570
1571 int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0);
1572 if (Src0Idx == -1)
1573 return false;
1574
1575 MachineOperand *Src0 = &MI->getOperand(Src0Idx);
1576 std::optional<int64_t> Src0Imm = getImmOrMaterializedImm(*Src0);
1577
1578 if ((Opc == AMDGPU::V_NOT_B32_e64 || Opc == AMDGPU::V_NOT_B32_e32 ||
1579 Opc == AMDGPU::S_NOT_B32) &&
1580 Src0Imm) {
1581 MI->getOperand(1).ChangeToImmediate(~*Src0Imm);
1582 mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_NOT_B32)));
1583 return true;
1584 }
1585
1586 int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1);
1587 if (Src1Idx == -1)
1588 return false;
1589
1590 MachineOperand *Src1 = &MI->getOperand(Src1Idx);
1591 std::optional<int64_t> Src1Imm = getImmOrMaterializedImm(*Src1);
1592
1593 if (!Src0Imm && !Src1Imm)
1594 return false;
1595
1596 // and k0, k1 -> v_mov_b32 (k0 & k1)
1597 // or k0, k1 -> v_mov_b32 (k0 | k1)
1598 // xor k0, k1 -> v_mov_b32 (k0 ^ k1)
1599 if (Src0Imm && Src1Imm) {
1600 int32_t NewImm;
1601 if (!evalBinaryInstruction(Opc, NewImm, *Src0Imm, *Src1Imm))
1602 return false;
1603
1604 bool IsSGPR = TRI->isSGPRReg(*MRI, MI->getOperand(0).getReg());
1605
1606 // Be careful to change the right operand, src0 may belong to a different
1607 // instruction.
1608 MI->getOperand(Src0Idx).ChangeToImmediate(NewImm);
1609 MI->removeOperand(Src1Idx);
1610 mutateCopyOp(*MI, TII->get(getMovOpc(IsSGPR)));
1611 return true;
1612 }
1613
1614 if (!MI->isCommutable())
1615 return false;
1616
1617 if (Src0Imm && !Src1Imm) {
1618 std::swap(Src0, Src1);
1619 std::swap(Src0Idx, Src1Idx);
1620 std::swap(Src0Imm, Src1Imm);
1621 }
1622
1623 int32_t Src1Val = static_cast<int32_t>(*Src1Imm);
1624 if (Opc == AMDGPU::V_OR_B32_e64 ||
1625 Opc == AMDGPU::V_OR_B32_e32 ||
1626 Opc == AMDGPU::S_OR_B32) {
1627 if (Src1Val == 0) {
1628 // y = or x, 0 => y = copy x
1629 MI->removeOperand(Src1Idx);
1630 mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
1631 } else if (Src1Val == -1) {
1632 // y = or x, -1 => y = v_mov_b32 -1
1633 MI->removeOperand(Src1Idx);
1634 mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_OR_B32)));
1635 } else
1636 return false;
1637
1638 return true;
1639 }
1640
1641 if (Opc == AMDGPU::V_AND_B32_e64 || Opc == AMDGPU::V_AND_B32_e32 ||
1642 Opc == AMDGPU::S_AND_B32) {
1643 if (Src1Val == 0) {
1644 // y = and x, 0 => y = v_mov_b32 0
1645 MI->removeOperand(Src0Idx);
1646 mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_AND_B32)));
1647 } else if (Src1Val == -1) {
1648 // y = and x, -1 => y = copy x
1649 MI->removeOperand(Src1Idx);
1650 mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
1651 } else
1652 return false;
1653
1654 return true;
1655 }
1656
1657 if (Opc == AMDGPU::V_XOR_B32_e64 || Opc == AMDGPU::V_XOR_B32_e32 ||
1658 Opc == AMDGPU::S_XOR_B32) {
1659 if (Src1Val == 0) {
1660 // y = xor x, 0 => y = copy x
1661 MI->removeOperand(Src1Idx);
1662 mutateCopyOp(*MI, TII->get(AMDGPU::COPY));
1663 return true;
1664 }
1665 }
1666
1667 return false;
1668}
1669
1670// Try to fold an instruction into a simpler one
1671bool SIFoldOperandsImpl::tryFoldCndMask(MachineInstr &MI) const {
1672 unsigned Opc = MI.getOpcode();
1673 if (Opc != AMDGPU::V_CNDMASK_B32_e32 && Opc != AMDGPU::V_CNDMASK_B32_e64 &&
1674 Opc != AMDGPU::V_CNDMASK_B64_PSEUDO)
1675 return false;
1676
1677 MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1678 MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1679 if (!Src1->isIdenticalTo(*Src0)) {
1680 std::optional<int64_t> Src1Imm = getImmOrMaterializedImm(*Src1);
1681 if (!Src1Imm)
1682 return false;
1683
1684 std::optional<int64_t> Src0Imm = getImmOrMaterializedImm(*Src0);
1685 if (!Src0Imm || *Src0Imm != *Src1Imm)
1686 return false;
1687 }
1688
1689 int Src1ModIdx =
1690 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1_modifiers);
1691 int Src0ModIdx =
1692 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0_modifiers);
1693 if ((Src1ModIdx != -1 && MI.getOperand(Src1ModIdx).getImm() != 0) ||
1694 (Src0ModIdx != -1 && MI.getOperand(Src0ModIdx).getImm() != 0))
1695 return false;
1696
1697 LLVM_DEBUG(dbgs() << "Folded " << MI << " into ");
1698 auto &NewDesc =
1699 TII->get(Src0->isReg() ? (unsigned)AMDGPU::COPY : getMovOpc(false));
1700 int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
1701 if (Src2Idx != -1)
1702 MI.removeOperand(Src2Idx);
1703 MI.removeOperand(AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1));
1704 if (Src1ModIdx != -1)
1705 MI.removeOperand(Src1ModIdx);
1706 if (Src0ModIdx != -1)
1707 MI.removeOperand(Src0ModIdx);
1708 mutateCopyOp(MI, NewDesc);
1709 LLVM_DEBUG(dbgs() << MI);
1710 return true;
1711}
1712
1713bool SIFoldOperandsImpl::tryFoldZeroHighBits(MachineInstr &MI) const {
1714 if (MI.getOpcode() != AMDGPU::V_AND_B32_e64 &&
1715 MI.getOpcode() != AMDGPU::V_AND_B32_e32)
1716 return false;
1717
1718 std::optional<int64_t> Src0Imm = getImmOrMaterializedImm(MI.getOperand(1));
1719 if (!Src0Imm || *Src0Imm != 0xffff || !MI.getOperand(2).isReg())
1720 return false;
1721
1722 Register Src1 = MI.getOperand(2).getReg();
1723 MachineInstr *SrcDef = MRI->getVRegDef(Src1);
1724 if (!ST->zeroesHigh16BitsOfDest(SrcDef->getOpcode()))
1725 return false;
1726
1727 Register Dst = MI.getOperand(0).getReg();
1728 MRI->replaceRegWith(Dst, Src1);
1729 if (!MI.getOperand(2).isKill())
1730 MRI->clearKillFlags(Src1);
1731 MI.eraseFromParent();
1732 return true;
1733}
1734
1735bool SIFoldOperandsImpl::foldInstOperand(MachineInstr &MI,
1736 const FoldableDef &OpToFold) const {
1737 // We need mutate the operands of new mov instructions to add implicit
1738 // uses of EXEC, but adding them invalidates the use_iterator, so defer
1739 // this.
1740 SmallVector<MachineInstr *, 4> CopiesToReplace;
1742 MachineOperand &Dst = MI.getOperand(0);
1743 bool Changed = false;
1744
1745 if (OpToFold.isImm()) {
1746 for (auto &UseMI :
1747 make_early_inc_range(MRI->use_nodbg_instructions(Dst.getReg()))) {
1748 // Folding the immediate may reveal operations that can be constant
1749 // folded or replaced with a copy. This can happen for example after
1750 // frame indices are lowered to constants or from splitting 64-bit
1751 // constants.
1752 //
1753 // We may also encounter cases where one or both operands are
1754 // immediates materialized into a register, which would ordinarily not
1755 // be folded due to multiple uses or operand constraints.
1756 if (tryConstantFoldOp(&UseMI)) {
1757 LLVM_DEBUG(dbgs() << "Constant folded " << UseMI);
1758 Changed = true;
1759 }
1760 }
1761 }
1762
1764 llvm::make_pointer_range(MRI->use_nodbg_operands(Dst.getReg())));
1765 for (auto *U : UsesToProcess) {
1766 MachineInstr *UseMI = U->getParent();
1767
1768 FoldableDef SubOpToFold = OpToFold.getWithSubReg(*TRI, U->getSubReg());
1769 foldOperand(SubOpToFold, UseMI, UseMI->getOperandNo(U), FoldList,
1770 CopiesToReplace);
1771 }
1772
1773 if (CopiesToReplace.empty() && FoldList.empty())
1774 return Changed;
1775
1776 MachineFunction *MF = MI.getParent()->getParent();
1777 // Make sure we add EXEC uses to any new v_mov instructions created.
1778 for (MachineInstr *Copy : CopiesToReplace)
1779 Copy->addImplicitDefUseOperands(*MF);
1780
1781 SetVector<MachineInstr *> ConstantFoldCandidates;
1782 for (FoldCandidate &Fold : FoldList) {
1783 assert(!Fold.isReg() || Fold.Def.OpToFold);
1784 if (Fold.isReg() && Fold.getReg().isVirtual()) {
1785 Register Reg = Fold.getReg();
1786 const MachineInstr *DefMI = Fold.Def.DefMI;
1787 if (DefMI->readsRegister(AMDGPU::EXEC, TRI) &&
1788 execMayBeModifiedBeforeUse(*MRI, Reg, *DefMI, *Fold.UseMI))
1789 continue;
1790 }
1791 if (updateOperand(Fold)) {
1792 // Clear kill flags.
1793 if (Fold.isReg()) {
1794 assert(Fold.Def.OpToFold && Fold.isReg());
1795 // FIXME: Probably shouldn't bother trying to fold if not an
1796 // SGPR. PeepholeOptimizer can eliminate redundant VGPR->VGPR
1797 // copies.
1798 MRI->clearKillFlags(Fold.getReg());
1799 }
1800 LLVM_DEBUG(dbgs() << "Folded source from " << MI << " into OpNo "
1801 << static_cast<int>(Fold.UseOpNo) << " of "
1802 << *Fold.UseMI);
1803
1804 if (Fold.isImm())
1805 ConstantFoldCandidates.insert(Fold.UseMI);
1806
1807 } else if (Fold.Commuted) {
1808 // Restoring instruction's original operand order if fold has failed.
1809 TII->commuteInstruction(*Fold.UseMI, false);
1810 }
1811 }
1812
1813 for (MachineInstr *MI : ConstantFoldCandidates) {
1814 if (tryConstantFoldOp(MI)) {
1815 LLVM_DEBUG(dbgs() << "Constant folded " << *MI);
1816 Changed = true;
1817 }
1818 }
1819 return true;
1820}
1821
1822/// Fold %agpr = COPY (REG_SEQUENCE x_MOV_B32, ...) into REG_SEQUENCE
1823/// (V_ACCVGPR_WRITE_B32_e64) ... depending on the reg_sequence input values.
1824bool SIFoldOperandsImpl::foldCopyToAGPRRegSequence(MachineInstr *CopyMI) const {
1825 // It is very tricky to store a value into an AGPR. v_accvgpr_write_b32 can
1826 // only accept VGPR or inline immediate. Recreate a reg_sequence with its
1827 // initializers right here, so we will rematerialize immediates and avoid
1828 // copies via different reg classes.
1829 const TargetRegisterClass *DefRC =
1830 MRI->getRegClass(CopyMI->getOperand(0).getReg());
1831 if (!TRI->isAGPRClass(DefRC))
1832 return false;
1833
1834 Register UseReg = CopyMI->getOperand(1).getReg();
1835 MachineInstr *RegSeq = MRI->getVRegDef(UseReg);
1836 if (!RegSeq || !RegSeq->isRegSequence())
1837 return false;
1838
1839 const DebugLoc &DL = CopyMI->getDebugLoc();
1840 MachineBasicBlock &MBB = *CopyMI->getParent();
1841
1842 MachineInstrBuilder B(*MBB.getParent(), CopyMI);
1844
1845 const TargetRegisterClass *UseRC =
1846 MRI->getRegClass(CopyMI->getOperand(1).getReg());
1847
1848 // Value, subregindex for new REG_SEQUENCE
1850
1851 unsigned NumRegSeqOperands = RegSeq->getNumOperands();
1852 unsigned NumFoldable = 0;
1853
1854 for (unsigned I = 1; I != NumRegSeqOperands; I += 2) {
1855 MachineOperand &RegOp = RegSeq->getOperand(I);
1856 unsigned SubRegIdx = RegSeq->getOperand(I + 1).getImm();
1857
1858 if (RegOp.getSubReg()) {
1859 // TODO: Handle subregister compose
1860 NewDefs.emplace_back(&RegOp, SubRegIdx);
1861 continue;
1862 }
1863
1865 if (!Lookup)
1866 Lookup = &RegOp;
1867
1868 if (Lookup->isImm()) {
1869 // Check if this is an agpr_32 subregister.
1870 const TargetRegisterClass *DestSuperRC = TRI->getMatchingSuperRegClass(
1871 DefRC, &AMDGPU::AGPR_32RegClass, SubRegIdx);
1872 if (DestSuperRC &&
1873 TII->isInlineConstant(*Lookup, AMDGPU::OPERAND_REG_INLINE_C_INT32)) {
1874 ++NumFoldable;
1875 NewDefs.emplace_back(Lookup, SubRegIdx);
1876 continue;
1877 }
1878 }
1879
1880 const TargetRegisterClass *InputRC =
1881 Lookup->isReg() ? MRI->getRegClass(Lookup->getReg())
1882 : MRI->getRegClass(RegOp.getReg());
1883
1884 // TODO: Account for Lookup->getSubReg()
1885
1886 // If we can't find a matching super class, this is an SGPR->AGPR or
1887 // VGPR->AGPR subreg copy (or something constant-like we have to materialize
1888 // in the AGPR). We can't directly copy from SGPR to AGPR on gfx908, so we
1889 // want to rewrite to copy to an intermediate VGPR class.
1890 const TargetRegisterClass *MatchRC =
1891 TRI->getMatchingSuperRegClass(DefRC, InputRC, SubRegIdx);
1892 if (!MatchRC) {
1893 ++NumFoldable;
1894 NewDefs.emplace_back(&RegOp, SubRegIdx);
1895 continue;
1896 }
1897
1898 NewDefs.emplace_back(&RegOp, SubRegIdx);
1899 }
1900
1901 // Do not clone a reg_sequence and merely change the result register class.
1902 if (NumFoldable == 0)
1903 return false;
1904
1905 CopyMI->setDesc(TII->get(AMDGPU::REG_SEQUENCE));
1906 for (unsigned I = CopyMI->getNumOperands() - 1; I > 0; --I)
1907 CopyMI->removeOperand(I);
1908
1909 for (auto [Def, DestSubIdx] : NewDefs) {
1910 if (!Def->isReg()) {
1911 // TODO: Should we use single write for each repeated value like in
1912 // register case?
1913 Register Tmp = MRI->createVirtualRegister(&AMDGPU::AGPR_32RegClass);
1914 BuildMI(MBB, CopyMI, DL, TII->get(AMDGPU::V_ACCVGPR_WRITE_B32_e64), Tmp)
1915 .add(*Def);
1916 B.addReg(Tmp);
1917 } else {
1919 Def->setIsKill(false);
1920
1921 Register &VGPRCopy = VGPRCopies[Src];
1922 if (!VGPRCopy) {
1923 const TargetRegisterClass *VGPRUseSubRC =
1924 TRI->getSubRegisterClass(UseRC, DestSubIdx);
1925
1926 // We cannot build a reg_sequence out of the same registers, they
1927 // must be copied. Better do it here before copyPhysReg() created
1928 // several reads to do the AGPR->VGPR->AGPR copy.
1929
1930 // Direct copy from SGPR to AGPR is not possible on gfx908. To avoid
1931 // creation of exploded copies SGPR->VGPR->AGPR in the copyPhysReg()
1932 // later, create a copy here and track if we already have such a copy.
1933 if (TRI->getSubRegisterClass(MRI->getRegClass(Src.Reg), Src.SubReg) !=
1934 VGPRUseSubRC) {
1935 VGPRCopy = MRI->createVirtualRegister(VGPRUseSubRC);
1936 BuildMI(MBB, CopyMI, DL, TII->get(AMDGPU::COPY), VGPRCopy).add(*Def);
1937 B.addReg(VGPRCopy);
1938 } else {
1939 // If it is already a VGPR, do not copy the register.
1940 B.add(*Def);
1941 }
1942 } else {
1943 B.addReg(VGPRCopy);
1944 }
1945 }
1946
1947 B.addImm(DestSubIdx);
1948 }
1949
1950 LLVM_DEBUG(dbgs() << "Folded " << *CopyMI);
1951 return true;
1952}
1953
1954bool SIFoldOperandsImpl::tryFoldFoldableCopy(
1955 MachineInstr &MI, MachineOperand *&CurrentKnownM0Val) const {
1956 Register DstReg = MI.getOperand(0).getReg();
1957 // Specially track simple redefs of m0 to the same value in a block, so we
1958 // can erase the later ones.
1959 if (DstReg == AMDGPU::M0) {
1960 MachineOperand &NewM0Val = MI.getOperand(1);
1961 if (CurrentKnownM0Val && CurrentKnownM0Val->isIdenticalTo(NewM0Val)) {
1962 MI.eraseFromParent();
1963 return true;
1964 }
1965
1966 // We aren't tracking other physical registers
1967 CurrentKnownM0Val = (NewM0Val.isReg() && NewM0Val.getReg().isPhysical())
1968 ? nullptr
1969 : &NewM0Val;
1970 return false;
1971 }
1972
1973 MachineOperand *OpToFoldPtr;
1974 if (MI.getOpcode() == AMDGPU::V_MOV_B16_t16_e64) {
1975 // Folding when any src_modifiers are non-zero is unsupported
1976 if (TII->hasAnyModifiersSet(MI))
1977 return false;
1978 OpToFoldPtr = &MI.getOperand(2);
1979 } else
1980 OpToFoldPtr = &MI.getOperand(1);
1981 MachineOperand &OpToFold = *OpToFoldPtr;
1982 bool FoldingImm = OpToFold.isImm() || OpToFold.isFI() || OpToFold.isGlobal();
1983
1984 // FIXME: We could also be folding things like TargetIndexes.
1985 if (!FoldingImm && !OpToFold.isReg())
1986 return false;
1987
1988 if (OpToFold.isReg() && !OpToFold.getReg().isVirtual())
1989 return false;
1990
1991 // Prevent folding operands backwards in the function. For example,
1992 // the COPY opcode must not be replaced by 1 in this example:
1993 //
1994 // %3 = COPY %vgpr0; VGPR_32:%3
1995 // ...
1996 // %vgpr0 = V_MOV_B32_e32 1, implicit %exec
1997 if (!DstReg.isVirtual())
1998 return false;
1999
2000 const TargetRegisterClass *DstRC =
2001 MRI->getRegClass(MI.getOperand(0).getReg());
2002
2003 // True16: Fix malformed 16-bit sgpr COPY produced by peephole-opt
2004 // Can remove this code if proper 16-bit SGPRs are implemented
2005 // Example: Pre-peephole-opt
2006 // %29:sgpr_lo16 = COPY %16.lo16:sreg_32
2007 // %32:sreg_32 = COPY %29:sgpr_lo16
2008 // %30:sreg_32 = S_PACK_LL_B32_B16 killed %31:sreg_32, killed %32:sreg_32
2009 // Post-peephole-opt and DCE
2010 // %32:sreg_32 = COPY %16.lo16:sreg_32
2011 // %30:sreg_32 = S_PACK_LL_B32_B16 killed %31:sreg_32, killed %32:sreg_32
2012 // After this transform
2013 // %32:sreg_32 = COPY %16:sreg_32
2014 // %30:sreg_32 = S_PACK_LL_B32_B16 killed %31:sreg_32, killed %32:sreg_32
2015 // After the fold operands pass
2016 // %30:sreg_32 = S_PACK_LL_B32_B16 killed %31:sreg_32, killed %16:sreg_32
2017 if (MI.getOpcode() == AMDGPU::COPY && OpToFold.isReg() &&
2018 OpToFold.getSubReg()) {
2019 if (DstRC == &AMDGPU::SReg_32RegClass &&
2020 DstRC == MRI->getRegClass(OpToFold.getReg())) {
2021 assert(OpToFold.getSubReg() == AMDGPU::lo16);
2022 OpToFold.setSubReg(0);
2023 }
2024 }
2025
2026 // Fold copy to AGPR through reg_sequence
2027 // TODO: Handle with subregister extract
2028 if (OpToFold.isReg() && MI.isCopy() && !MI.getOperand(1).getSubReg()) {
2029 if (foldCopyToAGPRRegSequence(&MI))
2030 return true;
2031 }
2032
2033 FoldableDef Def(OpToFold, DstRC);
2034 bool Changed = foldInstOperand(MI, Def);
2035
2036 // If we managed to fold all uses of this copy then we might as well
2037 // delete it now.
2038 // The only reason we need to follow chains of copies here is that
2039 // tryFoldRegSequence looks forward through copies before folding a
2040 // REG_SEQUENCE into its eventual users.
2041 auto *InstToErase = &MI;
2042 while (MRI->use_nodbg_empty(InstToErase->getOperand(0).getReg())) {
2043 auto &SrcOp = InstToErase->getOperand(1);
2044 auto SrcReg = SrcOp.isReg() ? SrcOp.getReg() : Register();
2045 InstToErase->eraseFromParent();
2046 Changed = true;
2047 InstToErase = nullptr;
2048 if (!SrcReg || SrcReg.isPhysical())
2049 break;
2050 InstToErase = MRI->getVRegDef(SrcReg);
2051 if (!InstToErase || !TII->isFoldableCopy(*InstToErase))
2052 break;
2053 }
2054
2055 if (InstToErase && InstToErase->isRegSequence() &&
2056 MRI->use_nodbg_empty(InstToErase->getOperand(0).getReg())) {
2057 InstToErase->eraseFromParent();
2058 Changed = true;
2059 }
2060
2061 if (Changed)
2062 return true;
2063
2064 // Run this after foldInstOperand to avoid turning scalar additions into
2065 // vector additions when the result scalar result could just be folded into
2066 // the user(s).
2067 return OpToFold.isReg() &&
2068 foldCopyToVGPROfScalarAddOfFrameIndex(DstReg, OpToFold.getReg(), MI);
2069}
2070
2071// Clamp patterns are canonically selected to v_max_* instructions, so only
2072// handle them.
2073const MachineOperand *
2074SIFoldOperandsImpl::isClamp(const MachineInstr &MI) const {
2075 unsigned Op = MI.getOpcode();
2076 switch (Op) {
2077 case AMDGPU::V_MAX_F32_e64:
2078 case AMDGPU::V_MAX_F16_e64:
2079 case AMDGPU::V_MAX_F16_t16_e64:
2080 case AMDGPU::V_MAX_F16_fake16_e64:
2081 case AMDGPU::V_MAX_F64_e64:
2082 case AMDGPU::V_MAX_NUM_F64_e64:
2083 case AMDGPU::V_PK_MAX_F16:
2084 case AMDGPU::V_MAX_BF16_PSEUDO_e64:
2085 case AMDGPU::V_PK_MAX_NUM_BF16: {
2086 if (MI.mayRaiseFPException())
2087 return nullptr;
2088
2089 if (!TII->getNamedOperand(MI, AMDGPU::OpName::clamp)->getImm())
2090 return nullptr;
2091
2092 // Make sure sources are identical.
2093 const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
2094 const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
2095 if (!Src0->isReg() || !Src1->isReg() ||
2096 Src0->getReg() != Src1->getReg() ||
2097 Src0->getSubReg() != Src1->getSubReg() ||
2098 Src0->getSubReg() != AMDGPU::NoSubRegister)
2099 return nullptr;
2100
2101 // Can't fold up if we have modifiers.
2102 if (TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
2103 return nullptr;
2104
2105 unsigned Src0Mods
2106 = TII->getNamedOperand(MI, AMDGPU::OpName::src0_modifiers)->getImm();
2107 unsigned Src1Mods
2108 = TII->getNamedOperand(MI, AMDGPU::OpName::src1_modifiers)->getImm();
2109
2110 // Having a 0 op_sel_hi would require swizzling the output in the source
2111 // instruction, which we can't do.
2112 unsigned UnsetMods =
2113 (Op == AMDGPU::V_PK_MAX_F16 || Op == AMDGPU::V_PK_MAX_NUM_BF16)
2115 : 0u;
2116 if (Src0Mods != UnsetMods && Src1Mods != UnsetMods)
2117 return nullptr;
2118 return Src0;
2119 }
2120 default:
2121 return nullptr;
2122 }
2123}
2124
2125// FIXME: Clamp for v_mad_mixhi_f16 handled during isel.
2126bool SIFoldOperandsImpl::tryFoldClamp(MachineInstr &MI) {
2127 const MachineOperand *ClampSrc = isClamp(MI);
2128 if (!ClampSrc || !MRI->hasOneNonDBGUser(ClampSrc->getReg()))
2129 return false;
2130
2131 if (!ClampSrc->getReg().isVirtual())
2132 return false;
2133
2134 // Look through COPY. COPY only observed with True16.
2135 Register DefSrcReg = TRI->lookThruCopyLike(ClampSrc->getReg(), MRI);
2136 MachineInstr *Def =
2137 MRI->getVRegDef(DefSrcReg.isVirtual() ? DefSrcReg : ClampSrc->getReg());
2138
2139 // The type of clamp must be compatible.
2140 if (TII->getClampMask(*Def) != TII->getClampMask(MI))
2141 return false;
2142
2143 if (Def->mayRaiseFPException())
2144 return false;
2145
2146 MachineOperand *DefClamp = TII->getNamedOperand(*Def, AMDGPU::OpName::clamp);
2147 if (!DefClamp)
2148 return false;
2149
2150 LLVM_DEBUG(dbgs() << "Folding clamp " << *DefClamp << " into " << *Def);
2151
2152 // Clamp is applied after omod, so it is OK if omod is set.
2153 DefClamp->setImm(1);
2154
2155 Register DefReg = Def->getOperand(0).getReg();
2156 Register MIDstReg = MI.getOperand(0).getReg();
2157 if (TRI->isSGPRReg(*MRI, DefReg)) {
2158 // Pseudo scalar instructions have a SGPR for dst and clamp is a v_max*
2159 // instruction with a VGPR dst.
2160 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), TII->get(AMDGPU::COPY),
2161 MIDstReg)
2162 .addReg(DefReg);
2163 } else {
2164 MRI->replaceRegWith(MIDstReg, DefReg);
2165 }
2166 MI.eraseFromParent();
2167
2168 // Use of output modifiers forces VOP3 encoding for a VOP2 mac/fmac
2169 // instruction, so we might as well convert it to the more flexible VOP3-only
2170 // mad/fma form.
2171 if (TII->convertToThreeAddress(*Def, nullptr, nullptr))
2172 Def->eraseFromParent();
2173
2174 return true;
2175}
2176
2177static int getOModValue(unsigned Opc, int64_t Val) {
2178 switch (Opc) {
2179 case AMDGPU::V_MUL_F64_e64:
2180 case AMDGPU::V_MUL_F64_pseudo_e64: {
2181 switch (Val) {
2182 case 0x3fe0000000000000: // 0.5
2183 return SIOutMods::DIV2;
2184 case 0x4000000000000000: // 2.0
2185 return SIOutMods::MUL2;
2186 case 0x4010000000000000: // 4.0
2187 return SIOutMods::MUL4;
2188 default:
2189 return SIOutMods::NONE;
2190 }
2191 }
2192 case AMDGPU::V_MUL_F32_e64: {
2193 switch (static_cast<uint32_t>(Val)) {
2194 case 0x3f000000: // 0.5
2195 return SIOutMods::DIV2;
2196 case 0x40000000: // 2.0
2197 return SIOutMods::MUL2;
2198 case 0x40800000: // 4.0
2199 return SIOutMods::MUL4;
2200 default:
2201 return SIOutMods::NONE;
2202 }
2203 }
2204 case AMDGPU::V_MUL_F16_e64:
2205 case AMDGPU::V_MUL_F16_t16_e64:
2206 case AMDGPU::V_MUL_F16_fake16_e64: {
2207 switch (static_cast<uint16_t>(Val)) {
2208 case 0x3800: // 0.5
2209 return SIOutMods::DIV2;
2210 case 0x4000: // 2.0
2211 return SIOutMods::MUL2;
2212 case 0x4400: // 4.0
2213 return SIOutMods::MUL4;
2214 default:
2215 return SIOutMods::NONE;
2216 }
2217 }
2218 default:
2219 llvm_unreachable("invalid mul opcode");
2220 }
2221}
2222
2223// FIXME: Does this really not support denormals with f16?
2224// FIXME: Does this need to check IEEE mode bit? SNaNs are generally not
2225// handled, so will anything other than that break?
2226std::pair<const MachineOperand *, int>
2227SIFoldOperandsImpl::isOMod(const MachineInstr &MI) const {
2228 unsigned Op = MI.getOpcode();
2229 switch (Op) {
2230 case AMDGPU::V_MUL_F64_e64:
2231 case AMDGPU::V_MUL_F64_pseudo_e64:
2232 case AMDGPU::V_MUL_F32_e64:
2233 case AMDGPU::V_MUL_F16_t16_e64:
2234 case AMDGPU::V_MUL_F16_fake16_e64:
2235 case AMDGPU::V_MUL_F16_e64: {
2236 // If output denormals are enabled, omod is ignored.
2237 if ((Op == AMDGPU::V_MUL_F32_e64 &&
2238 MFI->getMode().FP32Denormals.Output != DenormalMode::PreserveSign) ||
2239 ((Op == AMDGPU::V_MUL_F64_e64 || Op == AMDGPU::V_MUL_F64_pseudo_e64 ||
2240 Op == AMDGPU::V_MUL_F16_e64 || Op == AMDGPU::V_MUL_F16_t16_e64 ||
2241 Op == AMDGPU::V_MUL_F16_fake16_e64) &&
2242 MFI->getMode().FP64FP16Denormals.Output !=
2244 MI.mayRaiseFPException())
2245 return std::pair(nullptr, SIOutMods::NONE);
2246
2247 const MachineOperand *RegOp = nullptr;
2248 const MachineOperand *ImmOp = nullptr;
2249 const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
2250 const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
2251 if (Src0->isImm()) {
2252 ImmOp = Src0;
2253 RegOp = Src1;
2254 } else if (Src1->isImm()) {
2255 ImmOp = Src1;
2256 RegOp = Src0;
2257 } else
2258 return std::pair(nullptr, SIOutMods::NONE);
2259
2260 int OMod = getOModValue(Op, ImmOp->getImm());
2261 if (OMod == SIOutMods::NONE ||
2262 TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) ||
2263 TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) ||
2264 TII->hasModifiersSet(MI, AMDGPU::OpName::omod) ||
2265 TII->hasModifiersSet(MI, AMDGPU::OpName::clamp))
2266 return std::pair(nullptr, SIOutMods::NONE);
2267
2268 return std::pair(RegOp, OMod);
2269 }
2270 case AMDGPU::V_ADD_F64_e64:
2271 case AMDGPU::V_ADD_F64_pseudo_e64:
2272 case AMDGPU::V_ADD_F32_e64:
2273 case AMDGPU::V_ADD_F16_e64:
2274 case AMDGPU::V_ADD_F16_t16_e64:
2275 case AMDGPU::V_ADD_F16_fake16_e64: {
2276 // If output denormals are enabled, omod is ignored.
2277 if ((Op == AMDGPU::V_ADD_F32_e64 &&
2278 MFI->getMode().FP32Denormals.Output != DenormalMode::PreserveSign) ||
2279 ((Op == AMDGPU::V_ADD_F64_e64 || Op == AMDGPU::V_ADD_F64_pseudo_e64 ||
2280 Op == AMDGPU::V_ADD_F16_e64 || Op == AMDGPU::V_ADD_F16_t16_e64 ||
2281 Op == AMDGPU::V_ADD_F16_fake16_e64) &&
2282 MFI->getMode().FP64FP16Denormals.Output != DenormalMode::PreserveSign))
2283 return std::pair(nullptr, SIOutMods::NONE);
2284
2285 // Look through the DAGCombiner canonicalization fmul x, 2 -> fadd x, x
2286 const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
2287 const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
2288
2289 if (Src0->isReg() && Src1->isReg() && Src0->getReg() == Src1->getReg() &&
2290 Src0->getSubReg() == Src1->getSubReg() &&
2291 !TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) &&
2292 !TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) &&
2293 !TII->hasModifiersSet(MI, AMDGPU::OpName::clamp) &&
2294 !TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
2295 return std::pair(Src0, SIOutMods::MUL2);
2296
2297 return std::pair(nullptr, SIOutMods::NONE);
2298 }
2299 default:
2300 return std::pair(nullptr, SIOutMods::NONE);
2301 }
2302}
2303
2304// FIXME: Does this need to check IEEE bit on function?
2305bool SIFoldOperandsImpl::tryFoldOMod(MachineInstr &MI) {
2306 const MachineOperand *RegOp;
2307 int OMod;
2308 std::tie(RegOp, OMod) = isOMod(MI);
2309 if (OMod == SIOutMods::NONE || !RegOp->isReg() ||
2310 RegOp->getSubReg() != AMDGPU::NoSubRegister ||
2311 !MRI->hasOneNonDBGUser(RegOp->getReg()))
2312 return false;
2313
2314 MachineInstr *Def = MRI->getVRegDef(RegOp->getReg());
2315 MachineOperand *DefOMod = TII->getNamedOperand(*Def, AMDGPU::OpName::omod);
2316 if (!DefOMod || DefOMod->getImm() != SIOutMods::NONE)
2317 return false;
2318
2319 if (Def->mayRaiseFPException())
2320 return false;
2321
2322 // Clamp is applied after omod. If the source already has clamp set, don't
2323 // fold it.
2324 if (TII->hasModifiersSet(*Def, AMDGPU::OpName::clamp))
2325 return false;
2326
2327 LLVM_DEBUG(dbgs() << "Folding omod " << MI << " into " << *Def);
2328
2329 DefOMod->setImm(OMod);
2330 MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg());
2331 // Kill flags can be wrong if we replaced a def inside a loop with a def
2332 // outside the loop.
2333 MRI->clearKillFlags(Def->getOperand(0).getReg());
2334 MI.eraseFromParent();
2335
2336 // Use of output modifiers forces VOP3 encoding for a VOP2 mac/fmac
2337 // instruction, so we might as well convert it to the more flexible VOP3-only
2338 // mad/fma form.
2339 if (TII->convertToThreeAddress(*Def, nullptr, nullptr))
2340 Def->eraseFromParent();
2341
2342 return true;
2343}
2344
2345// Try to fold a reg_sequence with vgpr output and agpr inputs into an
2346// instruction which can take an agpr. So far that means a store.
2347bool SIFoldOperandsImpl::tryFoldRegSequence(MachineInstr &MI) {
2348 assert(MI.isRegSequence());
2349 auto Reg = MI.getOperand(0).getReg();
2350
2351 if (!ST->hasGFX90AInsts() || !TRI->isVGPR(*MRI, Reg) ||
2352 !MRI->hasOneNonDBGUse(Reg))
2353 return false;
2354
2356 if (!getRegSeqInit(Defs, Reg))
2357 return false;
2358
2359 for (auto &[Op, SubIdx] : Defs) {
2360 if (!Op->isReg())
2361 return false;
2362 if (TRI->isAGPR(*MRI, Op->getReg()))
2363 continue;
2364 // Maybe this is a COPY from AREG
2365 const MachineInstr *SubDef = MRI->getVRegDef(Op->getReg());
2366 if (!SubDef || !SubDef->isCopy() || SubDef->getOperand(1).getSubReg())
2367 return false;
2368 if (!TRI->isAGPR(*MRI, SubDef->getOperand(1).getReg()))
2369 return false;
2370 }
2371
2372 MachineOperand *Op = &*MRI->use_nodbg_begin(Reg);
2373 MachineInstr *UseMI = Op->getParent();
2374 while (UseMI->isCopy() && !Op->getSubReg()) {
2375 Reg = UseMI->getOperand(0).getReg();
2376 if (!TRI->isVGPR(*MRI, Reg) || !MRI->hasOneNonDBGUse(Reg))
2377 return false;
2378 Op = &*MRI->use_nodbg_begin(Reg);
2379 UseMI = Op->getParent();
2380 }
2381
2382 if (Op->getSubReg())
2383 return false;
2384
2385 unsigned OpIdx = Op - &UseMI->getOperand(0);
2386 const MCInstrDesc &InstDesc = UseMI->getDesc();
2387 const TargetRegisterClass *OpRC =
2388 TII->getRegClass(InstDesc, OpIdx, TRI, *MI.getMF());
2389 if (!OpRC || !TRI->isVectorSuperClass(OpRC))
2390 return false;
2391
2392 const auto *NewDstRC = TRI->getEquivalentAGPRClass(MRI->getRegClass(Reg));
2393 auto Dst = MRI->createVirtualRegister(NewDstRC);
2394 auto RS = BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
2395 TII->get(AMDGPU::REG_SEQUENCE), Dst);
2396
2397 for (auto &[Def, SubIdx] : Defs) {
2398 Def->setIsKill(false);
2399 if (TRI->isAGPR(*MRI, Def->getReg())) {
2400 RS.add(*Def);
2401 } else { // This is a copy
2402 MachineInstr *SubDef = MRI->getVRegDef(Def->getReg());
2403 SubDef->getOperand(1).setIsKill(false);
2404 RS.addReg(SubDef->getOperand(1).getReg(), 0, Def->getSubReg());
2405 }
2406 RS.addImm(SubIdx);
2407 }
2408
2409 Op->setReg(Dst);
2410 if (!TII->isOperandLegal(*UseMI, OpIdx, Op)) {
2411 Op->setReg(Reg);
2412 RS->eraseFromParent();
2413 return false;
2414 }
2415
2416 LLVM_DEBUG(dbgs() << "Folded " << *RS << " into " << *UseMI);
2417
2418 // Erase the REG_SEQUENCE eagerly, unless we followed a chain of COPY users,
2419 // in which case we can erase them all later in runOnMachineFunction.
2420 if (MRI->use_nodbg_empty(MI.getOperand(0).getReg()))
2421 MI.eraseFromParent();
2422 return true;
2423}
2424
2425/// Checks whether \p Copy is a AGPR -> VGPR copy. Returns `true` on success and
2426/// stores the AGPR register in \p OutReg and the subreg in \p OutSubReg
2427static bool isAGPRCopy(const SIRegisterInfo &TRI,
2428 const MachineRegisterInfo &MRI, const MachineInstr &Copy,
2429 Register &OutReg, unsigned &OutSubReg) {
2430 assert(Copy.isCopy());
2431
2432 const MachineOperand &CopySrc = Copy.getOperand(1);
2433 Register CopySrcReg = CopySrc.getReg();
2434 if (!CopySrcReg.isVirtual())
2435 return false;
2436
2437 // Common case: copy from AGPR directly, e.g.
2438 // %1:vgpr_32 = COPY %0:agpr_32
2439 if (TRI.isAGPR(MRI, CopySrcReg)) {
2440 OutReg = CopySrcReg;
2441 OutSubReg = CopySrc.getSubReg();
2442 return true;
2443 }
2444
2445 // Sometimes it can also involve two copies, e.g.
2446 // %1:vgpr_256 = COPY %0:agpr_256
2447 // %2:vgpr_32 = COPY %1:vgpr_256.sub0
2448 const MachineInstr *CopySrcDef = MRI.getVRegDef(CopySrcReg);
2449 if (!CopySrcDef || !CopySrcDef->isCopy())
2450 return false;
2451
2452 const MachineOperand &OtherCopySrc = CopySrcDef->getOperand(1);
2453 Register OtherCopySrcReg = OtherCopySrc.getReg();
2454 if (!OtherCopySrcReg.isVirtual() ||
2455 CopySrcDef->getOperand(0).getSubReg() != AMDGPU::NoSubRegister ||
2456 OtherCopySrc.getSubReg() != AMDGPU::NoSubRegister ||
2457 !TRI.isAGPR(MRI, OtherCopySrcReg))
2458 return false;
2459
2460 OutReg = OtherCopySrcReg;
2461 OutSubReg = CopySrc.getSubReg();
2462 return true;
2463}
2464
2465// Try to hoist an AGPR to VGPR copy across a PHI.
2466// This should allow folding of an AGPR into a consumer which may support it.
2467//
2468// Example 1: LCSSA PHI
2469// loop:
2470// %1:vreg = COPY %0:areg
2471// exit:
2472// %2:vreg = PHI %1:vreg, %loop
2473// =>
2474// loop:
2475// exit:
2476// %1:areg = PHI %0:areg, %loop
2477// %2:vreg = COPY %1:areg
2478//
2479// Example 2: PHI with multiple incoming values:
2480// entry:
2481// %1:vreg = GLOBAL_LOAD(..)
2482// loop:
2483// %2:vreg = PHI %1:vreg, %entry, %5:vreg, %loop
2484// %3:areg = COPY %2:vreg
2485// %4:areg = (instr using %3:areg)
2486// %5:vreg = COPY %4:areg
2487// =>
2488// entry:
2489// %1:vreg = GLOBAL_LOAD(..)
2490// %2:areg = COPY %1:vreg
2491// loop:
2492// %3:areg = PHI %2:areg, %entry, %X:areg,
2493// %4:areg = (instr using %3:areg)
2494bool SIFoldOperandsImpl::tryFoldPhiAGPR(MachineInstr &PHI) {
2495 assert(PHI.isPHI());
2496
2497 Register PhiOut = PHI.getOperand(0).getReg();
2498 if (!TRI->isVGPR(*MRI, PhiOut))
2499 return false;
2500
2501 // Iterate once over all incoming values of the PHI to check if this PHI is
2502 // eligible, and determine the exact AGPR RC we'll target.
2503 const TargetRegisterClass *ARC = nullptr;
2504 for (unsigned K = 1; K < PHI.getNumExplicitOperands(); K += 2) {
2505 MachineOperand &MO = PHI.getOperand(K);
2506 MachineInstr *Copy = MRI->getVRegDef(MO.getReg());
2507 if (!Copy || !Copy->isCopy())
2508 continue;
2509
2510 Register AGPRSrc;
2511 unsigned AGPRRegMask = AMDGPU::NoSubRegister;
2512 if (!isAGPRCopy(*TRI, *MRI, *Copy, AGPRSrc, AGPRRegMask))
2513 continue;
2514
2515 const TargetRegisterClass *CopyInRC = MRI->getRegClass(AGPRSrc);
2516 if (const auto *SubRC = TRI->getSubRegisterClass(CopyInRC, AGPRRegMask))
2517 CopyInRC = SubRC;
2518
2519 if (ARC && !ARC->hasSubClassEq(CopyInRC))
2520 return false;
2521 ARC = CopyInRC;
2522 }
2523
2524 if (!ARC)
2525 return false;
2526
2527 bool IsAGPR32 = (ARC == &AMDGPU::AGPR_32RegClass);
2528
2529 // Rewrite the PHI's incoming values to ARC.
2530 LLVM_DEBUG(dbgs() << "Folding AGPR copies into: " << PHI);
2531 for (unsigned K = 1; K < PHI.getNumExplicitOperands(); K += 2) {
2532 MachineOperand &MO = PHI.getOperand(K);
2533 Register Reg = MO.getReg();
2534
2536 MachineBasicBlock *InsertMBB = nullptr;
2537
2538 // Look at the def of Reg, ignoring all copies.
2539 unsigned CopyOpc = AMDGPU::COPY;
2540 if (MachineInstr *Def = MRI->getVRegDef(Reg)) {
2541
2542 // Look at pre-existing COPY instructions from ARC: Steal the operand. If
2543 // the copy was single-use, it will be removed by DCE later.
2544 if (Def->isCopy()) {
2545 Register AGPRSrc;
2546 unsigned AGPRSubReg = AMDGPU::NoSubRegister;
2547 if (isAGPRCopy(*TRI, *MRI, *Def, AGPRSrc, AGPRSubReg)) {
2548 MO.setReg(AGPRSrc);
2549 MO.setSubReg(AGPRSubReg);
2550 continue;
2551 }
2552
2553 // If this is a multi-use SGPR -> VGPR copy, use V_ACCVGPR_WRITE on
2554 // GFX908 directly instead of a COPY. Otherwise, SIFoldOperand may try
2555 // to fold the sgpr -> vgpr -> agpr copy into a sgpr -> agpr copy which
2556 // is unlikely to be profitable.
2557 //
2558 // Note that V_ACCVGPR_WRITE is only used for AGPR_32.
2559 MachineOperand &CopyIn = Def->getOperand(1);
2560 if (IsAGPR32 && !ST->hasGFX90AInsts() && !MRI->hasOneNonDBGUse(Reg) &&
2561 TRI->isSGPRReg(*MRI, CopyIn.getReg()))
2562 CopyOpc = AMDGPU::V_ACCVGPR_WRITE_B32_e64;
2563 }
2564
2565 InsertMBB = Def->getParent();
2566 InsertPt = InsertMBB->SkipPHIsLabelsAndDebug(++Def->getIterator());
2567 } else {
2568 InsertMBB = PHI.getOperand(MO.getOperandNo() + 1).getMBB();
2569 InsertPt = InsertMBB->getFirstTerminator();
2570 }
2571
2572 Register NewReg = MRI->createVirtualRegister(ARC);
2573 MachineInstr *MI = BuildMI(*InsertMBB, InsertPt, PHI.getDebugLoc(),
2574 TII->get(CopyOpc), NewReg)
2575 .addReg(Reg);
2576 MO.setReg(NewReg);
2577
2578 (void)MI;
2579 LLVM_DEBUG(dbgs() << " Created COPY: " << *MI);
2580 }
2581
2582 // Replace the PHI's result with a new register.
2583 Register NewReg = MRI->createVirtualRegister(ARC);
2584 PHI.getOperand(0).setReg(NewReg);
2585
2586 // COPY that new register back to the original PhiOut register. This COPY will
2587 // usually be folded out later.
2588 MachineBasicBlock *MBB = PHI.getParent();
2589 BuildMI(*MBB, MBB->getFirstNonPHI(), PHI.getDebugLoc(),
2590 TII->get(AMDGPU::COPY), PhiOut)
2591 .addReg(NewReg);
2592
2593 LLVM_DEBUG(dbgs() << " Done: Folded " << PHI);
2594 return true;
2595}
2596
2597// Attempt to convert VGPR load to an AGPR load.
2598bool SIFoldOperandsImpl::tryFoldLoad(MachineInstr &MI) {
2599 assert(MI.mayLoad());
2600 if (!ST->hasGFX90AInsts() || MI.getNumExplicitDefs() != 1)
2601 return false;
2602
2603 MachineOperand &Def = MI.getOperand(0);
2604 if (!Def.isDef())
2605 return false;
2606
2607 Register DefReg = Def.getReg();
2608
2609 if (DefReg.isPhysical() || !TRI->isVGPR(*MRI, DefReg))
2610 return false;
2611
2613 llvm::make_pointer_range(MRI->use_nodbg_instructions(DefReg)));
2614 SmallVector<Register, 8> MoveRegs;
2615
2616 if (Users.empty())
2617 return false;
2618
2619 // Check that all uses a copy to an agpr or a reg_sequence producing an agpr.
2620 while (!Users.empty()) {
2621 const MachineInstr *I = Users.pop_back_val();
2622 if (!I->isCopy() && !I->isRegSequence())
2623 return false;
2624 Register DstReg = I->getOperand(0).getReg();
2625 // Physical registers may have more than one instruction definitions
2626 if (DstReg.isPhysical())
2627 return false;
2628 if (TRI->isAGPR(*MRI, DstReg))
2629 continue;
2630 MoveRegs.push_back(DstReg);
2631 for (const MachineInstr &U : MRI->use_nodbg_instructions(DstReg))
2632 Users.push_back(&U);
2633 }
2634
2635 const TargetRegisterClass *RC = MRI->getRegClass(DefReg);
2636 MRI->setRegClass(DefReg, TRI->getEquivalentAGPRClass(RC));
2637 if (!TII->isOperandLegal(MI, 0, &Def)) {
2638 MRI->setRegClass(DefReg, RC);
2639 return false;
2640 }
2641
2642 while (!MoveRegs.empty()) {
2643 Register Reg = MoveRegs.pop_back_val();
2644 MRI->setRegClass(Reg, TRI->getEquivalentAGPRClass(MRI->getRegClass(Reg)));
2645 }
2646
2647 LLVM_DEBUG(dbgs() << "Folded " << MI);
2648
2649 return true;
2650}
2651
2652// tryFoldPhiAGPR will aggressively try to create AGPR PHIs.
2653// For GFX90A and later, this is pretty much always a good thing, but for GFX908
2654// there's cases where it can create a lot more AGPR-AGPR copies, which are
2655// expensive on this architecture due to the lack of V_ACCVGPR_MOV.
2656//
2657// This function looks at all AGPR PHIs in a basic block and collects their
2658// operands. Then, it checks for register that are used more than once across
2659// all PHIs and caches them in a VGPR. This prevents ExpandPostRAPseudo from
2660// having to create one VGPR temporary per use, which can get very messy if
2661// these PHIs come from a broken-up large PHI (e.g. 32 AGPR phis, one per vector
2662// element).
2663//
2664// Example
2665// a:
2666// %in:agpr_256 = COPY %foo:vgpr_256
2667// c:
2668// %x:agpr_32 = ..
2669// b:
2670// %0:areg = PHI %in.sub0:agpr_32, %a, %x, %c
2671// %1:areg = PHI %in.sub0:agpr_32, %a, %y, %c
2672// %2:areg = PHI %in.sub0:agpr_32, %a, %z, %c
2673// =>
2674// a:
2675// %in:agpr_256 = COPY %foo:vgpr_256
2676// %tmp:vgpr_32 = V_ACCVGPR_READ_B32_e64 %in.sub0:agpr_32
2677// %tmp_agpr:agpr_32 = COPY %tmp
2678// c:
2679// %x:agpr_32 = ..
2680// b:
2681// %0:areg = PHI %tmp_agpr, %a, %x, %c
2682// %1:areg = PHI %tmp_agpr, %a, %y, %c
2683// %2:areg = PHI %tmp_agpr, %a, %z, %c
2684bool SIFoldOperandsImpl::tryOptimizeAGPRPhis(MachineBasicBlock &MBB) {
2685 // This is only really needed on GFX908 where AGPR-AGPR copies are
2686 // unreasonably difficult.
2687 if (ST->hasGFX90AInsts())
2688 return false;
2689
2690 // Look at all AGPR Phis and collect the register + subregister used.
2691 DenseMap<std::pair<Register, unsigned>, std::vector<MachineOperand *>>
2692 RegToMO;
2693
2694 for (auto &MI : MBB) {
2695 if (!MI.isPHI())
2696 break;
2697
2698 if (!TRI->isAGPR(*MRI, MI.getOperand(0).getReg()))
2699 continue;
2700
2701 for (unsigned K = 1; K < MI.getNumOperands(); K += 2) {
2702 MachineOperand &PhiMO = MI.getOperand(K);
2703 if (!PhiMO.getSubReg())
2704 continue;
2705 RegToMO[{PhiMO.getReg(), PhiMO.getSubReg()}].push_back(&PhiMO);
2706 }
2707 }
2708
2709 // For all (Reg, SubReg) pair that are used more than once, cache the value in
2710 // a VGPR.
2711 bool Changed = false;
2712 for (const auto &[Entry, MOs] : RegToMO) {
2713 if (MOs.size() == 1)
2714 continue;
2715
2716 const auto [Reg, SubReg] = Entry;
2717 MachineInstr *Def = MRI->getVRegDef(Reg);
2718 MachineBasicBlock *DefMBB = Def->getParent();
2719
2720 // Create a copy in a VGPR using V_ACCVGPR_READ_B32_e64 so it's not folded
2721 // out.
2722 const TargetRegisterClass *ARC = getRegOpRC(*MRI, *TRI, *MOs.front());
2723 Register TempVGPR =
2724 MRI->createVirtualRegister(TRI->getEquivalentVGPRClass(ARC));
2725 MachineInstr *VGPRCopy =
2726 BuildMI(*DefMBB, ++Def->getIterator(), Def->getDebugLoc(),
2727 TII->get(AMDGPU::V_ACCVGPR_READ_B32_e64), TempVGPR)
2728 .addReg(Reg, /* flags */ 0, SubReg);
2729
2730 // Copy back to an AGPR and use that instead of the AGPR subreg in all MOs.
2731 Register TempAGPR = MRI->createVirtualRegister(ARC);
2732 BuildMI(*DefMBB, ++VGPRCopy->getIterator(), Def->getDebugLoc(),
2733 TII->get(AMDGPU::COPY), TempAGPR)
2734 .addReg(TempVGPR);
2735
2736 LLVM_DEBUG(dbgs() << "Caching AGPR into VGPR: " << *VGPRCopy);
2737 for (MachineOperand *MO : MOs) {
2738 MO->setReg(TempAGPR);
2739 MO->setSubReg(AMDGPU::NoSubRegister);
2740 LLVM_DEBUG(dbgs() << " Changed PHI Operand: " << *MO << "\n");
2741 }
2742
2743 Changed = true;
2744 }
2745
2746 return Changed;
2747}
2748
2749bool SIFoldOperandsImpl::run(MachineFunction &MF) {
2750 MRI = &MF.getRegInfo();
2751 ST = &MF.getSubtarget<GCNSubtarget>();
2752 TII = ST->getInstrInfo();
2753 TRI = &TII->getRegisterInfo();
2754 MFI = MF.getInfo<SIMachineFunctionInfo>();
2755
2756 // omod is ignored by hardware if IEEE bit is enabled. omod also does not
2757 // correctly handle signed zeros.
2758 //
2759 // FIXME: Also need to check strictfp
2760 bool IsIEEEMode = MFI->getMode().IEEE;
2761 bool HasNSZ = MFI->hasNoSignedZerosFPMath();
2762
2763 bool Changed = false;
2764 for (MachineBasicBlock *MBB : depth_first(&MF)) {
2765 MachineOperand *CurrentKnownM0Val = nullptr;
2766 for (auto &MI : make_early_inc_range(*MBB)) {
2767 Changed |= tryFoldCndMask(MI);
2768
2769 if (tryFoldZeroHighBits(MI)) {
2770 Changed = true;
2771 continue;
2772 }
2773
2774 if (MI.isRegSequence() && tryFoldRegSequence(MI)) {
2775 Changed = true;
2776 continue;
2777 }
2778
2779 if (MI.isPHI() && tryFoldPhiAGPR(MI)) {
2780 Changed = true;
2781 continue;
2782 }
2783
2784 if (MI.mayLoad() && tryFoldLoad(MI)) {
2785 Changed = true;
2786 continue;
2787 }
2788
2789 if (TII->isFoldableCopy(MI)) {
2790 Changed |= tryFoldFoldableCopy(MI, CurrentKnownM0Val);
2791 continue;
2792 }
2793
2794 // Saw an unknown clobber of m0, so we no longer know what it is.
2795 if (CurrentKnownM0Val && MI.modifiesRegister(AMDGPU::M0, TRI))
2796 CurrentKnownM0Val = nullptr;
2797
2798 // TODO: Omod might be OK if there is NSZ only on the source
2799 // instruction, and not the omod multiply.
2800 if (IsIEEEMode || (!HasNSZ && !MI.getFlag(MachineInstr::FmNsz)) ||
2801 !tryFoldOMod(MI))
2802 Changed |= tryFoldClamp(MI);
2803 }
2804
2805 Changed |= tryOptimizeAGPRPhis(*MBB);
2806 }
2807
2808 return Changed;
2809}
2810
2813 MFPropsModifier _(*this, MF);
2814
2815 bool Changed = SIFoldOperandsImpl().run(MF);
2816 if (!Changed) {
2817 return PreservedAnalyses::all();
2818 }
2820 PA.preserveSet<CFGAnalyses>();
2821 return PA;
2822}
unsigned SubReg
unsigned const MachineRegisterInfo * MRI
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
Provides AMDGPU specific target descriptions.
Rewrite undef for PHI
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat)
Updates the operand at Idx in instruction Inst with the result of instruction Mat.
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
uint64_t Size
AMD GCN specific subclass of TargetSubtarget.
static Register UseReg(const MachineOperand &MO)
const HexagonInstrInfo * TII
#define _
IRTranslator LLVM IR MI
iv Induction Variable Users
Definition: IVUsers.cpp:48
#define I(x, y, z)
Definition: MD5.cpp:58
Register const TargetRegisterInfo * TRI
static unsigned getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
static bool isReg(const MCInst &MI, unsigned OpNo)
MachineInstr unsigned OpIdx
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:56
static unsigned macToMad(unsigned Opc)
static bool isAGPRCopy(const SIRegisterInfo &TRI, const MachineRegisterInfo &MRI, const MachineInstr &Copy, Register &OutReg, unsigned &OutSubReg)
Checks whether Copy is a AGPR -> VGPR copy.
static void appendFoldCandidate(SmallVectorImpl< FoldCandidate > &FoldList, FoldCandidate &&Entry)
static const TargetRegisterClass * getRegOpRC(const MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI, const MachineOperand &MO)
static bool evalBinaryInstruction(unsigned Opcode, int32_t &Result, uint32_t LHS, uint32_t RHS)
static int getOModValue(unsigned Opc, int64_t Val)
static unsigned getMovOpc(bool IsScalar)
static void mutateCopyOp(MachineInstr &MI, const MCInstrDesc &NewDesc)
static MachineOperand * lookUpCopyChain(const SIInstrInfo &TII, const MachineRegisterInfo &MRI, Register SrcReg)
#define DEBUG_TYPE
Interface definition for SIInstrInfo.
Interface definition for SIRegisterInfo.
#define LLVM_DEBUG(...)
Definition: Debug.h:119
static int Lookup(ArrayRef< TableEntry > Table, unsigned Opcode)
Value * RHS
Value * LHS
support::ulittle16_t & Lo
Definition: aarch32.cpp:205
support::ulittle16_t & Hi
Definition: aarch32.cpp:204
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:255
Represent the analysis usage information of a pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:270
Represents analyses that only rely on functions' control flow.
Definition: Analysis.h:73
This class represents an Operation in the Expression.
A debug info location.
Definition: DebugLoc.h:124
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:314
bool skipFunction(const Function &F) const
Optional passes call this function to check whether the pass should be skipped.
Definition: Pass.cpp:188
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:199
ArrayRef< MCOperandInfo > operands() const
Definition: MCInstrDesc.h:240
unsigned getNumDefs() const
Return the number of MachineOperands that are register definitions.
Definition: MCInstrDesc.h:249
bool isVariadic() const
Return true if this instruction can have a variable number of operands.
Definition: MCInstrDesc.h:262
An RAII based helper class to modify MachineFunctionProperties when running pass.
LLVM_ABI iterator SkipPHIsLabelsAndDebug(iterator I, Register Reg=Register(), bool SkipPseudoOp=true)
Return the first instruction in MBB after I that is not a PHI, label or debug.
LLVM_ABI LivenessQueryResult computeRegisterLiveness(const TargetRegisterInfo *TRI, MCRegister Reg, const_iterator Before, unsigned Neighborhood=10) const
Return whether (physical) register Reg has been defined and not killed as of just before Before.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
LLVM_ABI iterator getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LivenessQueryResult
Possible outcome of a register liveness query to computeRegisterLiveness()
@ LQR_Dead
Register is known to be fully dead.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
virtual bool runOnMachineFunction(MachineFunction &MF)=0
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
virtual MachineFunctionProperties getRequiredProperties() const
Properties which a MachineFunction may have at a given point in time.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
Register getReg(unsigned Idx) const
Get the register for the operand index.
const MachineInstrBuilder & setOperandDead(unsigned OpIdx) const
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & setMIFlags(unsigned Flags) const
Representation of each machine instruction.
Definition: MachineInstr.h:72
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:587
bool isCopy() const
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:359
bool readsRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr reads the specified register.
unsigned getNumOperands() const
Retuns the total number of operands.
Definition: MachineInstr.h:590
LLVM_ABI void addOperand(MachineFunction &MF, const MachineOperand &Op)
Add the specified operand to the instruction.
unsigned getOperandNo(const_mop_iterator I) const
Returns the number of the operand iterator I points to.
Definition: MachineInstr.h:773
LLVM_ABI unsigned getNumExplicitOperands() const
Returns the number of non-implicit operands.
mop_range implicit_operands()
Definition: MachineInstr.h:702
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
Definition: MachineInstr.h:584
bool isRegSequence() const
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
Definition: MachineInstr.h:511
LLVM_ABI void removeOperand(unsigned OpNo)
Erase an operand from an instruction, leaving it with one fewer operand than it started with.
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:595
MachineOperand class - Representation of each machine instruction operand.
void setSubReg(unsigned subReg)
unsigned getSubReg() const
LLVM_ABI unsigned getOperandNo() const
Returns the index of this operand in the instruction that it belongs to.
LLVM_ABI void substVirtReg(Register Reg, unsigned SubIdx, const TargetRegisterInfo &)
substVirtReg - Substitute the current register with the virtual subregister Reg:SubReg.
LLVM_ABI void ChangeToFrameIndex(int Idx, unsigned TargetFlags=0)
Replace this operand with a frame index.
void setImm(int64_t immVal)
int64_t getImm() const
bool isImplicit() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
LLVM_ABI void ChangeToImmediate(int64_t ImmVal, unsigned TargetFlags=0)
ChangeToImmediate - Replace this operand with a new immediate operand of the specified value.
LLVM_ABI void ChangeToGA(const GlobalValue *GV, int64_t Offset, unsigned TargetFlags=0)
ChangeToGA - Replace this operand with a new global address operand.
void setIsKill(bool Val=true)
LLVM_ABI void ChangeToRegister(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isDebug=false)
ChangeToRegister - Replace this operand with a new register operand of the specified value.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
static MachineOperand CreateImm(int64_t Val)
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
void setIsUndef(bool Val=true)
Register getReg() const
getReg - Returns the register number.
bool isFI() const
isFI - Tests if this is a MO_FrameIndex operand.
LLVM_ABI bool isIdenticalTo(const MachineOperand &Other) const
Returns true if this operand is identical to the specified operand except for liveness related flags ...
@ MO_Immediate
Immediate operand.
@ MO_GlobalAddress
Address of a global value.
@ MO_FrameIndex
Abstract Stack Frame Index.
@ MO_Register
Register operand.
static MachineOperand CreateFI(int Idx)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:85
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:118
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition: Register.h:74
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition: Register.h:78
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
static std::optional< int64_t > extractSubregFromImm(int64_t ImmVal, unsigned SubRegIndex)
Return the extracted immediate value in a subregister use from a constant materialized in a super reg...
This class keeps track of the SPI_SP_INPUT_ADDR config register, which tells the hardware which inter...
SIModeRegisterDefaults getMode() const
A vector that has set insertion semantics.
Definition: SetVector.h:59
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:168
bool empty() const
Definition: SmallVector.h:82
size_t size() const
Definition: SmallVector.h:79
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:574
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:938
void push_back(const T &Elt)
Definition: SmallVector.h:414
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
Register getReg() const
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
static const unsigned CommuteAnyOperandIndex
bool contains(Register Reg) const
Return true if the specified register is included in this register class.
bool hasSubClassEq(const TargetRegisterClass *RC) const
Returns true if RC is a sub-class of or equal to this class.
bool hasSuperClassEq(const TargetRegisterClass *RC) const
Returns true if RC is a super-class of or equal to this class.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
self_iterator getIterator()
Definition: ilist_node.h:134
IteratorT end() const
IteratorT begin() const
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool isInlinableLiteralV216(uint32_t Literal, uint8_t OpType)
LLVM_READONLY int getVOPe32(uint16_t Opcode)
LLVM_READONLY int getMFMAEarlyClobberOp(uint16_t Opcode)
LLVM_READONLY bool hasNamedOperand(uint64_t Opcode, OpName NamedIdx)
bool isSISrcOperand(const MCInstrDesc &Desc, unsigned OpNo)
Is this an AMDGPU specific source operand? These include registers, inline constants,...
@ OPERAND_REG_IMM_V2FP16
Definition: SIDefines.h:209
@ OPERAND_REG_INLINE_C_FP64
Definition: SIDefines.h:222
@ OPERAND_REG_INLINE_C_V2BF16
Definition: SIDefines.h:224
@ OPERAND_REG_IMM_V2INT16
Definition: SIDefines.h:210
@ OPERAND_REG_IMM_V2BF16
Definition: SIDefines.h:208
@ OPERAND_REG_INLINE_C_INT64
Definition: SIDefines.h:218
@ OPERAND_REG_IMM_NOINLINE_V2FP16
Definition: SIDefines.h:211
@ OPERAND_REG_INLINE_C_V2FP16
Definition: SIDefines.h:225
@ OPERAND_REG_INLINE_AC_INT32
Operands with an AccVGPR register or inline constant.
Definition: SIDefines.h:236
@ OPERAND_REG_INLINE_AC_FP32
Definition: SIDefines.h:237
@ OPERAND_REG_INLINE_C_FP32
Definition: SIDefines.h:221
@ OPERAND_REG_INLINE_C_INT32
Definition: SIDefines.h:217
@ OPERAND_REG_INLINE_C_V2INT16
Definition: SIDefines.h:223
@ OPERAND_REG_INLINE_AC_FP64
Definition: SIDefines.h:238
bool supportsScaleOffset(const MCInstrInfo &MII, unsigned Opcode)
LLVM_READONLY int getFlatScratchInstSSfromSV(uint16_t Opcode)
@ Entry
Definition: COFF.h:862
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ Dead
Unused definition.
@ Kill
The last use of a register.
Reg
All possible values of the reg field in the ModR/M byte.
NodeAddr< DefNode * > Def
Definition: RDFGraph.h:384
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
TargetInstrInfo::RegSubRegPair getRegSubRegPair(const MachineOperand &O)
Create RegSubRegPair from a register MachineOperand.
Definition: SIInstrInfo.h:1563
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
bool execMayBeModifiedBeforeUse(const MachineRegisterInfo &MRI, Register VReg, const MachineInstr &DefMI, const MachineInstr &UseMI)
Return false if EXEC is not changed between the def of VReg at DefMI and the use at UseMI.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition: STLExtras.h:2155
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition: STLExtras.h:663
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
FunctionPass * createSIFoldOperandsLegacyPass()
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:207
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
char & SIFoldOperandsLegacyID
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition: iterator.h:363
iterator_range< df_iterator< T > > depth_first(const T &G)
constexpr uint64_t Make_64(uint32_t High, uint32_t Low)
Make a 64-bit integer from a high / low pair of 32-bit integers.
Definition: MathExtras.h:169
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:858
Description of the encoding of one expression Op.
@ PreserveSign
The sign of a flushed-to-zero number is preserved in the sign of 0.
bool IEEE
Floating point opcodes that support exception flag gathering quiet and propagate signaling NaN inputs...
A pair composed of a register and a sub-register index.