LLVM 19.0.0git
SIPeepholeSDWA.cpp
Go to the documentation of this file.
1//===- SIPeepholeSDWA.cpp - Peephole optimization for SDWA instructions ---===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file This pass tries to apply several peephole SDWA patterns.
10///
11/// E.g. original:
12/// V_LSHRREV_B32_e32 %0, 16, %1
13/// V_ADD_CO_U32_e32 %2, %0, %3
14/// V_LSHLREV_B32_e32 %4, 16, %2
15///
16/// Replace:
17/// V_ADD_CO_U32_sdwa %4, %1, %3
18/// dst_sel:WORD_1 dst_unused:UNUSED_PAD src0_sel:WORD_1 src1_sel:DWORD
19///
20//===----------------------------------------------------------------------===//
21
22#include "AMDGPU.h"
23#include "GCNSubtarget.h"
25#include "llvm/ADT/MapVector.h"
26#include "llvm/ADT/Statistic.h"
28#include <optional>
29
30using namespace llvm;
31
32#define DEBUG_TYPE "si-peephole-sdwa"
33
34STATISTIC(NumSDWAPatternsFound, "Number of SDWA patterns found.");
35STATISTIC(NumSDWAInstructionsPeepholed,
36 "Number of instruction converted to SDWA.");
37
38namespace {
39
40class SDWAOperand;
41class SDWADstOperand;
42
43class SIPeepholeSDWA : public MachineFunctionPass {
44public:
45 using SDWAOperandsVector = SmallVector<SDWAOperand *, 4>;
46
47private:
49 const SIRegisterInfo *TRI;
50 const SIInstrInfo *TII;
51
54 SmallVector<MachineInstr *, 8> ConvertedInstructions;
55
56 std::optional<int64_t> foldToImm(const MachineOperand &Op) const;
57
58public:
59 static char ID;
60
61 SIPeepholeSDWA() : MachineFunctionPass(ID) {
63 }
64
65 bool runOnMachineFunction(MachineFunction &MF) override;
66 void matchSDWAOperands(MachineBasicBlock &MBB);
67 std::unique_ptr<SDWAOperand> matchSDWAOperand(MachineInstr &MI);
68 bool isConvertibleToSDWA(MachineInstr &MI, const GCNSubtarget &ST) const;
69 void pseudoOpConvertToVOP2(MachineInstr &MI,
70 const GCNSubtarget &ST) const;
71 bool convertToSDWA(MachineInstr &MI, const SDWAOperandsVector &SDWAOperands);
72 void legalizeScalarOperands(MachineInstr &MI, const GCNSubtarget &ST) const;
73
74 StringRef getPassName() const override { return "SI Peephole SDWA"; }
75
76 void getAnalysisUsage(AnalysisUsage &AU) const override {
77 AU.setPreservesCFG();
79 }
80};
81
82class SDWAOperand {
83private:
84 MachineOperand *Target; // Operand that would be used in converted instruction
85 MachineOperand *Replaced; // Operand that would be replace by Target
86
87public:
88 SDWAOperand(MachineOperand *TargetOp, MachineOperand *ReplacedOp)
89 : Target(TargetOp), Replaced(ReplacedOp) {
90 assert(Target->isReg());
91 assert(Replaced->isReg());
92 }
93
94 virtual ~SDWAOperand() = default;
95
96 virtual MachineInstr *potentialToConvert(const SIInstrInfo *TII) = 0;
97 virtual bool convertToSDWA(MachineInstr &MI, const SIInstrInfo *TII) = 0;
98
99 MachineOperand *getTargetOperand() const { return Target; }
100 MachineOperand *getReplacedOperand() const { return Replaced; }
101 MachineInstr *getParentInst() const { return Target->getParent(); }
102
103 MachineRegisterInfo *getMRI() const {
104 return &getParentInst()->getParent()->getParent()->getRegInfo();
105 }
106
107#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
108 virtual void print(raw_ostream& OS) const = 0;
109 void dump() const { print(dbgs()); }
110#endif
111};
112
113using namespace AMDGPU::SDWA;
114
115class SDWASrcOperand : public SDWAOperand {
116private:
117 SdwaSel SrcSel;
118 bool Abs;
119 bool Neg;
120 bool Sext;
121
122public:
123 SDWASrcOperand(MachineOperand *TargetOp, MachineOperand *ReplacedOp,
124 SdwaSel SrcSel_ = DWORD, bool Abs_ = false, bool Neg_ = false,
125 bool Sext_ = false)
126 : SDWAOperand(TargetOp, ReplacedOp),
127 SrcSel(SrcSel_), Abs(Abs_), Neg(Neg_), Sext(Sext_) {}
128
129 MachineInstr *potentialToConvert(const SIInstrInfo *TII) override;
130 bool convertToSDWA(MachineInstr &MI, const SIInstrInfo *TII) override;
131
132 SdwaSel getSrcSel() const { return SrcSel; }
133 bool getAbs() const { return Abs; }
134 bool getNeg() const { return Neg; }
135 bool getSext() const { return Sext; }
136
137 uint64_t getSrcMods(const SIInstrInfo *TII,
138 const MachineOperand *SrcOp) const;
139
140#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
141 void print(raw_ostream& OS) const override;
142#endif
143};
144
145class SDWADstOperand : public SDWAOperand {
146private:
147 SdwaSel DstSel;
148 DstUnused DstUn;
149
150public:
151
152 SDWADstOperand(MachineOperand *TargetOp, MachineOperand *ReplacedOp,
153 SdwaSel DstSel_ = DWORD, DstUnused DstUn_ = UNUSED_PAD)
154 : SDWAOperand(TargetOp, ReplacedOp), DstSel(DstSel_), DstUn(DstUn_) {}
155
156 MachineInstr *potentialToConvert(const SIInstrInfo *TII) override;
157 bool convertToSDWA(MachineInstr &MI, const SIInstrInfo *TII) override;
158
159 SdwaSel getDstSel() const { return DstSel; }
160 DstUnused getDstUnused() const { return DstUn; }
161
162#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
163 void print(raw_ostream& OS) const override;
164#endif
165};
166
167class SDWADstPreserveOperand : public SDWADstOperand {
168private:
169 MachineOperand *Preserve;
170
171public:
172 SDWADstPreserveOperand(MachineOperand *TargetOp, MachineOperand *ReplacedOp,
173 MachineOperand *PreserveOp, SdwaSel DstSel_ = DWORD)
174 : SDWADstOperand(TargetOp, ReplacedOp, DstSel_, UNUSED_PRESERVE),
175 Preserve(PreserveOp) {}
176
177 bool convertToSDWA(MachineInstr &MI, const SIInstrInfo *TII) override;
178
179 MachineOperand *getPreservedOperand() const { return Preserve; }
180
181#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
182 void print(raw_ostream& OS) const override;
183#endif
184};
185
186} // end anonymous namespace
187
188INITIALIZE_PASS(SIPeepholeSDWA, DEBUG_TYPE, "SI Peephole SDWA", false, false)
189
190char SIPeepholeSDWA::ID = 0;
191
192char &llvm::SIPeepholeSDWAID = SIPeepholeSDWA::ID;
193
195 return new SIPeepholeSDWA();
196}
197
198
199#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
201 switch(Sel) {
202 case BYTE_0: OS << "BYTE_0"; break;
203 case BYTE_1: OS << "BYTE_1"; break;
204 case BYTE_2: OS << "BYTE_2"; break;
205 case BYTE_3: OS << "BYTE_3"; break;
206 case WORD_0: OS << "WORD_0"; break;
207 case WORD_1: OS << "WORD_1"; break;
208 case DWORD: OS << "DWORD"; break;
209 }
210 return OS;
211}
212
214 switch(Un) {
215 case UNUSED_PAD: OS << "UNUSED_PAD"; break;
216 case UNUSED_SEXT: OS << "UNUSED_SEXT"; break;
217 case UNUSED_PRESERVE: OS << "UNUSED_PRESERVE"; break;
218 }
219 return OS;
220}
221
223void SDWASrcOperand::print(raw_ostream& OS) const {
224 OS << "SDWA src: " << *getTargetOperand()
225 << " src_sel:" << getSrcSel()
226 << " abs:" << getAbs() << " neg:" << getNeg()
227 << " sext:" << getSext() << '\n';
228}
229
231void SDWADstOperand::print(raw_ostream& OS) const {
232 OS << "SDWA dst: " << *getTargetOperand()
233 << " dst_sel:" << getDstSel()
234 << " dst_unused:" << getDstUnused() << '\n';
235}
236
238void SDWADstPreserveOperand::print(raw_ostream& OS) const {
239 OS << "SDWA preserve dst: " << *getTargetOperand()
240 << " dst_sel:" << getDstSel()
241 << " preserve:" << *getPreservedOperand() << '\n';
242}
243
244#endif
245
247 assert(To.isReg() && From.isReg());
248 To.setReg(From.getReg());
249 To.setSubReg(From.getSubReg());
250 To.setIsUndef(From.isUndef());
251 if (To.isUse()) {
252 To.setIsKill(From.isKill());
253 } else {
254 To.setIsDead(From.isDead());
255 }
256}
257
258static bool isSameReg(const MachineOperand &LHS, const MachineOperand &RHS) {
259 return LHS.isReg() &&
260 RHS.isReg() &&
261 LHS.getReg() == RHS.getReg() &&
262 LHS.getSubReg() == RHS.getSubReg();
263}
264
266 const MachineRegisterInfo *MRI) {
267 if (!Reg->isReg() || !Reg->isDef())
268 return nullptr;
269
270 MachineOperand *ResMO = nullptr;
271 for (MachineOperand &UseMO : MRI->use_nodbg_operands(Reg->getReg())) {
272 // If there exist use of subreg of Reg then return nullptr
273 if (!isSameReg(UseMO, *Reg))
274 return nullptr;
275
276 // Check that there is only one instruction that uses Reg
277 if (!ResMO) {
278 ResMO = &UseMO;
279 } else if (ResMO->getParent() != UseMO.getParent()) {
280 return nullptr;
281 }
282 }
283
284 return ResMO;
285}
286
288 const MachineRegisterInfo *MRI) {
289 if (!Reg->isReg())
290 return nullptr;
291
292 MachineInstr *DefInstr = MRI->getUniqueVRegDef(Reg->getReg());
293 if (!DefInstr)
294 return nullptr;
295
296 for (auto &DefMO : DefInstr->defs()) {
297 if (DefMO.isReg() && DefMO.getReg() == Reg->getReg())
298 return &DefMO;
299 }
300
301 // Ignore implicit defs.
302 return nullptr;
303}
304
305uint64_t SDWASrcOperand::getSrcMods(const SIInstrInfo *TII,
306 const MachineOperand *SrcOp) const {
307 uint64_t Mods = 0;
308 const auto *MI = SrcOp->getParent();
309 if (TII->getNamedOperand(*MI, AMDGPU::OpName::src0) == SrcOp) {
310 if (auto *Mod = TII->getNamedOperand(*MI, AMDGPU::OpName::src0_modifiers)) {
311 Mods = Mod->getImm();
312 }
313 } else if (TII->getNamedOperand(*MI, AMDGPU::OpName::src1) == SrcOp) {
314 if (auto *Mod = TII->getNamedOperand(*MI, AMDGPU::OpName::src1_modifiers)) {
315 Mods = Mod->getImm();
316 }
317 }
318 if (Abs || Neg) {
319 assert(!Sext &&
320 "Float and integer src modifiers can't be set simultaneously");
321 Mods |= Abs ? SISrcMods::ABS : 0u;
322 Mods ^= Neg ? SISrcMods::NEG : 0u;
323 } else if (Sext) {
324 Mods |= SISrcMods::SEXT;
325 }
326
327 return Mods;
328}
329
330MachineInstr *SDWASrcOperand::potentialToConvert(const SIInstrInfo *TII) {
331 // For SDWA src operand potential instruction is one that use register
332 // defined by parent instruction
333 MachineOperand *PotentialMO = findSingleRegUse(getReplacedOperand(), getMRI());
334 if (!PotentialMO)
335 return nullptr;
336
337 return PotentialMO->getParent();
338}
339
340bool SDWASrcOperand::convertToSDWA(MachineInstr &MI, const SIInstrInfo *TII) {
341 // Find operand in instruction that matches source operand and replace it with
342 // target operand. Set corresponding src_sel
343 bool IsPreserveSrc = false;
344 MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
345 MachineOperand *SrcSel = TII->getNamedOperand(MI, AMDGPU::OpName::src0_sel);
346 MachineOperand *SrcMods =
347 TII->getNamedOperand(MI, AMDGPU::OpName::src0_modifiers);
348 assert(Src && (Src->isReg() || Src->isImm()));
349 if (!isSameReg(*Src, *getReplacedOperand())) {
350 // If this is not src0 then it could be src1
351 Src = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
352 SrcSel = TII->getNamedOperand(MI, AMDGPU::OpName::src1_sel);
353 SrcMods = TII->getNamedOperand(MI, AMDGPU::OpName::src1_modifiers);
354
355 if (!Src ||
356 !isSameReg(*Src, *getReplacedOperand())) {
357 // It's possible this Src is a tied operand for
358 // UNUSED_PRESERVE, in which case we can either
359 // abandon the peephole attempt, or if legal we can
360 // copy the target operand into the tied slot
361 // if the preserve operation will effectively cause the same
362 // result by overwriting the rest of the dst.
363 MachineOperand *Dst = TII->getNamedOperand(MI, AMDGPU::OpName::vdst);
365 TII->getNamedOperand(MI, AMDGPU::OpName::dst_unused);
366
367 if (Dst &&
368 DstUnused->getImm() == AMDGPU::SDWA::DstUnused::UNUSED_PRESERVE) {
369 // This will work if the tied src is accessing WORD_0, and the dst is
370 // writing WORD_1. Modifiers don't matter because all the bits that
371 // would be impacted are being overwritten by the dst.
372 // Any other case will not work.
373 SdwaSel DstSel = static_cast<SdwaSel>(
374 TII->getNamedImmOperand(MI, AMDGPU::OpName::dst_sel));
375 if (DstSel == AMDGPU::SDWA::SdwaSel::WORD_1 &&
376 getSrcSel() == AMDGPU::SDWA::SdwaSel::WORD_0) {
377 IsPreserveSrc = true;
378 auto DstIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
379 AMDGPU::OpName::vdst);
380 auto TiedIdx = MI.findTiedOperandIdx(DstIdx);
381 Src = &MI.getOperand(TiedIdx);
382 SrcSel = nullptr;
383 SrcMods = nullptr;
384 } else {
385 // Not legal to convert this src
386 return false;
387 }
388 }
389 }
390 assert(Src && Src->isReg());
391
392 if ((MI.getOpcode() == AMDGPU::V_FMAC_F16_sdwa ||
393 MI.getOpcode() == AMDGPU::V_FMAC_F32_sdwa ||
394 MI.getOpcode() == AMDGPU::V_MAC_F16_sdwa ||
395 MI.getOpcode() == AMDGPU::V_MAC_F32_sdwa) &&
396 !isSameReg(*Src, *getReplacedOperand())) {
397 // In case of v_mac_f16/32_sdwa this pass can try to apply src operand to
398 // src2. This is not allowed.
399 return false;
400 }
401
402 assert(isSameReg(*Src, *getReplacedOperand()) &&
403 (IsPreserveSrc || (SrcSel && SrcMods)));
404 }
405 copyRegOperand(*Src, *getTargetOperand());
406 if (!IsPreserveSrc) {
407 SrcSel->setImm(getSrcSel());
408 SrcMods->setImm(getSrcMods(TII, Src));
409 }
410 getTargetOperand()->setIsKill(false);
411 return true;
412}
413
414MachineInstr *SDWADstOperand::potentialToConvert(const SIInstrInfo *TII) {
415 // For SDWA dst operand potential instruction is one that defines register
416 // that this operand uses
417 MachineRegisterInfo *MRI = getMRI();
418 MachineInstr *ParentMI = getParentInst();
419
420 MachineOperand *PotentialMO = findSingleRegDef(getReplacedOperand(), MRI);
421 if (!PotentialMO)
422 return nullptr;
423
424 // Check that ParentMI is the only instruction that uses replaced register
425 for (MachineInstr &UseInst : MRI->use_nodbg_instructions(PotentialMO->getReg())) {
426 if (&UseInst != ParentMI)
427 return nullptr;
428 }
429
430 return PotentialMO->getParent();
431}
432
433bool SDWADstOperand::convertToSDWA(MachineInstr &MI, const SIInstrInfo *TII) {
434 // Replace vdst operand in MI with target operand. Set dst_sel and dst_unused
435
436 if ((MI.getOpcode() == AMDGPU::V_FMAC_F16_sdwa ||
437 MI.getOpcode() == AMDGPU::V_FMAC_F32_sdwa ||
438 MI.getOpcode() == AMDGPU::V_MAC_F16_sdwa ||
439 MI.getOpcode() == AMDGPU::V_MAC_F32_sdwa) &&
440 getDstSel() != AMDGPU::SDWA::DWORD) {
441 // v_mac_f16/32_sdwa allow dst_sel to be equal only to DWORD
442 return false;
443 }
444
445 MachineOperand *Operand = TII->getNamedOperand(MI, AMDGPU::OpName::vdst);
446 assert(Operand &&
447 Operand->isReg() &&
448 isSameReg(*Operand, *getReplacedOperand()));
449 copyRegOperand(*Operand, *getTargetOperand());
450 MachineOperand *DstSel= TII->getNamedOperand(MI, AMDGPU::OpName::dst_sel);
451 assert(DstSel);
452 DstSel->setImm(getDstSel());
453 MachineOperand *DstUnused= TII->getNamedOperand(MI, AMDGPU::OpName::dst_unused);
455 DstUnused->setImm(getDstUnused());
456
457 // Remove original instruction because it would conflict with our new
458 // instruction by register definition
459 getParentInst()->eraseFromParent();
460 return true;
461}
462
463bool SDWADstPreserveOperand::convertToSDWA(MachineInstr &MI,
464 const SIInstrInfo *TII) {
465 // MI should be moved right before v_or_b32.
466 // For this we should clear all kill flags on uses of MI src-operands or else
467 // we can encounter problem with use of killed operand.
468 for (MachineOperand &MO : MI.uses()) {
469 if (!MO.isReg())
470 continue;
471 getMRI()->clearKillFlags(MO.getReg());
472 }
473
474 // Move MI before v_or_b32
475 MI.getParent()->remove(&MI);
476 getParentInst()->getParent()->insert(getParentInst(), &MI);
477
478 // Add Implicit use of preserved register
479 MachineInstrBuilder MIB(*MI.getMF(), MI);
480 MIB.addReg(getPreservedOperand()->getReg(),
482 getPreservedOperand()->getSubReg());
483
484 // Tie dst to implicit use
485 MI.tieOperands(AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdst),
486 MI.getNumOperands() - 1);
487
488 // Convert MI as any other SDWADstOperand and remove v_or_b32
489 return SDWADstOperand::convertToSDWA(MI, TII);
490}
491
492std::optional<int64_t>
493SIPeepholeSDWA::foldToImm(const MachineOperand &Op) const {
494 if (Op.isImm()) {
495 return Op.getImm();
496 }
497
498 // If this is not immediate then it can be copy of immediate value, e.g.:
499 // %1 = S_MOV_B32 255;
500 if (Op.isReg()) {
501 for (const MachineOperand &Def : MRI->def_operands(Op.getReg())) {
502 if (!isSameReg(Op, Def))
503 continue;
504
505 const MachineInstr *DefInst = Def.getParent();
506 if (!TII->isFoldableCopy(*DefInst))
507 return std::nullopt;
508
509 const MachineOperand &Copied = DefInst->getOperand(1);
510 if (!Copied.isImm())
511 return std::nullopt;
512
513 return Copied.getImm();
514 }
515 }
516
517 return std::nullopt;
518}
519
520std::unique_ptr<SDWAOperand>
521SIPeepholeSDWA::matchSDWAOperand(MachineInstr &MI) {
522 unsigned Opcode = MI.getOpcode();
523 switch (Opcode) {
524 case AMDGPU::V_LSHRREV_B32_e32:
525 case AMDGPU::V_ASHRREV_I32_e32:
526 case AMDGPU::V_LSHLREV_B32_e32:
527 case AMDGPU::V_LSHRREV_B32_e64:
528 case AMDGPU::V_ASHRREV_I32_e64:
529 case AMDGPU::V_LSHLREV_B32_e64: {
530 // from: v_lshrrev_b32_e32 v1, 16/24, v0
531 // to SDWA src:v0 src_sel:WORD_1/BYTE_3
532
533 // from: v_ashrrev_i32_e32 v1, 16/24, v0
534 // to SDWA src:v0 src_sel:WORD_1/BYTE_3 sext:1
535
536 // from: v_lshlrev_b32_e32 v1, 16/24, v0
537 // to SDWA dst:v1 dst_sel:WORD_1/BYTE_3 dst_unused:UNUSED_PAD
538 MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
539 auto Imm = foldToImm(*Src0);
540 if (!Imm)
541 break;
542
543 if (*Imm != 16 && *Imm != 24)
544 break;
545
546 MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
547 MachineOperand *Dst = TII->getNamedOperand(MI, AMDGPU::OpName::vdst);
548 if (!Src1->isReg() || Src1->getReg().isPhysical() ||
549 Dst->getReg().isPhysical())
550 break;
551
552 if (Opcode == AMDGPU::V_LSHLREV_B32_e32 ||
553 Opcode == AMDGPU::V_LSHLREV_B32_e64) {
554 return std::make_unique<SDWADstOperand>(
555 Dst, Src1, *Imm == 16 ? WORD_1 : BYTE_3, UNUSED_PAD);
556 } else {
557 return std::make_unique<SDWASrcOperand>(
558 Src1, Dst, *Imm == 16 ? WORD_1 : BYTE_3, false, false,
559 Opcode != AMDGPU::V_LSHRREV_B32_e32 &&
560 Opcode != AMDGPU::V_LSHRREV_B32_e64);
561 }
562 break;
563 }
564
565 case AMDGPU::V_LSHRREV_B16_e32:
566 case AMDGPU::V_ASHRREV_I16_e32:
567 case AMDGPU::V_LSHLREV_B16_e32:
568 case AMDGPU::V_LSHRREV_B16_e64:
569 case AMDGPU::V_ASHRREV_I16_e64:
570 case AMDGPU::V_LSHLREV_B16_e64: {
571 // from: v_lshrrev_b16_e32 v1, 8, v0
572 // to SDWA src:v0 src_sel:BYTE_1
573
574 // from: v_ashrrev_i16_e32 v1, 8, v0
575 // to SDWA src:v0 src_sel:BYTE_1 sext:1
576
577 // from: v_lshlrev_b16_e32 v1, 8, v0
578 // to SDWA dst:v1 dst_sel:BYTE_1 dst_unused:UNUSED_PAD
579 MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
580 auto Imm = foldToImm(*Src0);
581 if (!Imm || *Imm != 8)
582 break;
583
584 MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
585 MachineOperand *Dst = TII->getNamedOperand(MI, AMDGPU::OpName::vdst);
586
587 if (!Src1->isReg() || Src1->getReg().isPhysical() ||
588 Dst->getReg().isPhysical())
589 break;
590
591 if (Opcode == AMDGPU::V_LSHLREV_B16_e32 ||
592 Opcode == AMDGPU::V_LSHLREV_B16_e64) {
593 return std::make_unique<SDWADstOperand>(Dst, Src1, BYTE_1, UNUSED_PAD);
594 } else {
595 return std::make_unique<SDWASrcOperand>(
596 Src1, Dst, BYTE_1, false, false,
597 Opcode != AMDGPU::V_LSHRREV_B16_e32 &&
598 Opcode != AMDGPU::V_LSHRREV_B16_e64);
599 }
600 break;
601 }
602
603 case AMDGPU::V_BFE_I32_e64:
604 case AMDGPU::V_BFE_U32_e64: {
605 // e.g.:
606 // from: v_bfe_u32 v1, v0, 8, 8
607 // to SDWA src:v0 src_sel:BYTE_1
608
609 // offset | width | src_sel
610 // ------------------------
611 // 0 | 8 | BYTE_0
612 // 0 | 16 | WORD_0
613 // 0 | 32 | DWORD ?
614 // 8 | 8 | BYTE_1
615 // 16 | 8 | BYTE_2
616 // 16 | 16 | WORD_1
617 // 24 | 8 | BYTE_3
618
619 MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
620 auto Offset = foldToImm(*Src1);
621 if (!Offset)
622 break;
623
624 MachineOperand *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2);
625 auto Width = foldToImm(*Src2);
626 if (!Width)
627 break;
628
629 SdwaSel SrcSel = DWORD;
630
631 if (*Offset == 0 && *Width == 8)
632 SrcSel = BYTE_0;
633 else if (*Offset == 0 && *Width == 16)
634 SrcSel = WORD_0;
635 else if (*Offset == 0 && *Width == 32)
636 SrcSel = DWORD;
637 else if (*Offset == 8 && *Width == 8)
638 SrcSel = BYTE_1;
639 else if (*Offset == 16 && *Width == 8)
640 SrcSel = BYTE_2;
641 else if (*Offset == 16 && *Width == 16)
642 SrcSel = WORD_1;
643 else if (*Offset == 24 && *Width == 8)
644 SrcSel = BYTE_3;
645 else
646 break;
647
648 MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
649 MachineOperand *Dst = TII->getNamedOperand(MI, AMDGPU::OpName::vdst);
650
651 if (!Src0->isReg() || Src0->getReg().isPhysical() ||
652 Dst->getReg().isPhysical())
653 break;
654
655 return std::make_unique<SDWASrcOperand>(
656 Src0, Dst, SrcSel, false, false, Opcode != AMDGPU::V_BFE_U32_e64);
657 }
658
659 case AMDGPU::V_AND_B32_e32:
660 case AMDGPU::V_AND_B32_e64: {
661 // e.g.:
662 // from: v_and_b32_e32 v1, 0x0000ffff/0x000000ff, v0
663 // to SDWA src:v0 src_sel:WORD_0/BYTE_0
664
665 MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
666 MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
667 auto ValSrc = Src1;
668 auto Imm = foldToImm(*Src0);
669
670 if (!Imm) {
671 Imm = foldToImm(*Src1);
672 ValSrc = Src0;
673 }
674
675 if (!Imm || (*Imm != 0x0000ffff && *Imm != 0x000000ff))
676 break;
677
678 MachineOperand *Dst = TII->getNamedOperand(MI, AMDGPU::OpName::vdst);
679
680 if (!ValSrc->isReg() || ValSrc->getReg().isPhysical() ||
681 Dst->getReg().isPhysical())
682 break;
683
684 return std::make_unique<SDWASrcOperand>(
685 ValSrc, Dst, *Imm == 0x0000ffff ? WORD_0 : BYTE_0);
686 }
687
688 case AMDGPU::V_OR_B32_e32:
689 case AMDGPU::V_OR_B32_e64: {
690 // Patterns for dst_unused:UNUSED_PRESERVE.
691 // e.g., from:
692 // v_add_f16_sdwa v0, v1, v2 dst_sel:WORD_1 dst_unused:UNUSED_PAD
693 // src1_sel:WORD_1 src2_sel:WORD1
694 // v_add_f16_e32 v3, v1, v2
695 // v_or_b32_e32 v4, v0, v3
696 // to SDWA preserve dst:v4 dst_sel:WORD_1 dst_unused:UNUSED_PRESERVE preserve:v3
697
698 // Check if one of operands of v_or_b32 is SDWA instruction
699 using CheckRetType =
700 std::optional<std::pair<MachineOperand *, MachineOperand *>>;
701 auto CheckOROperandsForSDWA =
702 [&](const MachineOperand *Op1, const MachineOperand *Op2) -> CheckRetType {
703 if (!Op1 || !Op1->isReg() || !Op2 || !Op2->isReg())
704 return CheckRetType(std::nullopt);
705
706 MachineOperand *Op1Def = findSingleRegDef(Op1, MRI);
707 if (!Op1Def)
708 return CheckRetType(std::nullopt);
709
710 MachineInstr *Op1Inst = Op1Def->getParent();
711 if (!TII->isSDWA(*Op1Inst))
712 return CheckRetType(std::nullopt);
713
714 MachineOperand *Op2Def = findSingleRegDef(Op2, MRI);
715 if (!Op2Def)
716 return CheckRetType(std::nullopt);
717
718 return CheckRetType(std::pair(Op1Def, Op2Def));
719 };
720
721 MachineOperand *OrSDWA = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
722 MachineOperand *OrOther = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
723 assert(OrSDWA && OrOther);
724 auto Res = CheckOROperandsForSDWA(OrSDWA, OrOther);
725 if (!Res) {
726 OrSDWA = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
727 OrOther = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
728 assert(OrSDWA && OrOther);
729 Res = CheckOROperandsForSDWA(OrSDWA, OrOther);
730 if (!Res)
731 break;
732 }
733
734 MachineOperand *OrSDWADef = Res->first;
735 MachineOperand *OrOtherDef = Res->second;
736 assert(OrSDWADef && OrOtherDef);
737
738 MachineInstr *SDWAInst = OrSDWADef->getParent();
739 MachineInstr *OtherInst = OrOtherDef->getParent();
740
741 // Check that OtherInstr is actually bitwise compatible with SDWAInst = their
742 // destination patterns don't overlap. Compatible instruction can be either
743 // regular instruction with compatible bitness or SDWA instruction with
744 // correct dst_sel
745 // SDWAInst | OtherInst bitness / OtherInst dst_sel
746 // -----------------------------------------------------
747 // DWORD | no / no
748 // WORD_0 | no / BYTE_2/3, WORD_1
749 // WORD_1 | 8/16-bit instructions / BYTE_0/1, WORD_0
750 // BYTE_0 | no / BYTE_1/2/3, WORD_1
751 // BYTE_1 | 8-bit / BYTE_0/2/3, WORD_1
752 // BYTE_2 | 8/16-bit / BYTE_0/1/3. WORD_0
753 // BYTE_3 | 8/16/24-bit / BYTE_0/1/2, WORD_0
754 // E.g. if SDWAInst is v_add_f16_sdwa dst_sel:WORD_1 then v_add_f16 is OK
755 // but v_add_f32 is not.
756
757 // TODO: add support for non-SDWA instructions as OtherInst.
758 // For now this only works with SDWA instructions. For regular instructions
759 // there is no way to determine if the instruction writes only 8/16/24-bit
760 // out of full register size and all registers are at min 32-bit wide.
761 if (!TII->isSDWA(*OtherInst))
762 break;
763
764 SdwaSel DstSel = static_cast<SdwaSel>(
765 TII->getNamedImmOperand(*SDWAInst, AMDGPU::OpName::dst_sel));
766 SdwaSel OtherDstSel = static_cast<SdwaSel>(
767 TII->getNamedImmOperand(*OtherInst, AMDGPU::OpName::dst_sel));
768
769 bool DstSelAgree = false;
770 switch (DstSel) {
771 case WORD_0: DstSelAgree = ((OtherDstSel == BYTE_2) ||
772 (OtherDstSel == BYTE_3) ||
773 (OtherDstSel == WORD_1));
774 break;
775 case WORD_1: DstSelAgree = ((OtherDstSel == BYTE_0) ||
776 (OtherDstSel == BYTE_1) ||
777 (OtherDstSel == WORD_0));
778 break;
779 case BYTE_0: DstSelAgree = ((OtherDstSel == BYTE_1) ||
780 (OtherDstSel == BYTE_2) ||
781 (OtherDstSel == BYTE_3) ||
782 (OtherDstSel == WORD_1));
783 break;
784 case BYTE_1: DstSelAgree = ((OtherDstSel == BYTE_0) ||
785 (OtherDstSel == BYTE_2) ||
786 (OtherDstSel == BYTE_3) ||
787 (OtherDstSel == WORD_1));
788 break;
789 case BYTE_2: DstSelAgree = ((OtherDstSel == BYTE_0) ||
790 (OtherDstSel == BYTE_1) ||
791 (OtherDstSel == BYTE_3) ||
792 (OtherDstSel == WORD_0));
793 break;
794 case BYTE_3: DstSelAgree = ((OtherDstSel == BYTE_0) ||
795 (OtherDstSel == BYTE_1) ||
796 (OtherDstSel == BYTE_2) ||
797 (OtherDstSel == WORD_0));
798 break;
799 default: DstSelAgree = false;
800 }
801
802 if (!DstSelAgree)
803 break;
804
805 // Also OtherInst dst_unused should be UNUSED_PAD
806 DstUnused OtherDstUnused = static_cast<DstUnused>(
807 TII->getNamedImmOperand(*OtherInst, AMDGPU::OpName::dst_unused));
808 if (OtherDstUnused != DstUnused::UNUSED_PAD)
809 break;
810
811 // Create DstPreserveOperand
812 MachineOperand *OrDst = TII->getNamedOperand(MI, AMDGPU::OpName::vdst);
813 assert(OrDst && OrDst->isReg());
814
815 return std::make_unique<SDWADstPreserveOperand>(
816 OrDst, OrSDWADef, OrOtherDef, DstSel);
817
818 }
819 }
820
821 return std::unique_ptr<SDWAOperand>(nullptr);
822}
823
824#if !defined(NDEBUG)
825static raw_ostream& operator<<(raw_ostream &OS, const SDWAOperand &Operand) {
826 Operand.print(OS);
827 return OS;
828}
829#endif
830
831void SIPeepholeSDWA::matchSDWAOperands(MachineBasicBlock &MBB) {
832 for (MachineInstr &MI : MBB) {
833 if (auto Operand = matchSDWAOperand(MI)) {
834 LLVM_DEBUG(dbgs() << "Match: " << MI << "To: " << *Operand << '\n');
835 SDWAOperands[&MI] = std::move(Operand);
836 ++NumSDWAPatternsFound;
837 }
838 }
839}
840
841// Convert the V_ADD_CO_U32_e64 into V_ADD_CO_U32_e32. This allows
842// isConvertibleToSDWA to perform its transformation on V_ADD_CO_U32_e32 into
843// V_ADD_CO_U32_sdwa.
844//
845// We are transforming from a VOP3 into a VOP2 form of the instruction.
846// %19:vgpr_32 = V_AND_B32_e32 255,
847// killed %16:vgpr_32, implicit $exec
848// %47:vgpr_32, %49:sreg_64_xexec = V_ADD_CO_U32_e64
849// %26.sub0:vreg_64, %19:vgpr_32, implicit $exec
850// %48:vgpr_32, dead %50:sreg_64_xexec = V_ADDC_U32_e64
851// %26.sub1:vreg_64, %54:vgpr_32, killed %49:sreg_64_xexec, implicit $exec
852//
853// becomes
854// %47:vgpr_32 = V_ADD_CO_U32_sdwa
855// 0, %26.sub0:vreg_64, 0, killed %16:vgpr_32, 0, 6, 0, 6, 0,
856// implicit-def $vcc, implicit $exec
857// %48:vgpr_32, dead %50:sreg_64_xexec = V_ADDC_U32_e64
858// %26.sub1:vreg_64, %54:vgpr_32, killed $vcc, implicit $exec
859void SIPeepholeSDWA::pseudoOpConvertToVOP2(MachineInstr &MI,
860 const GCNSubtarget &ST) const {
861 int Opc = MI.getOpcode();
862 assert((Opc == AMDGPU::V_ADD_CO_U32_e64 || Opc == AMDGPU::V_SUB_CO_U32_e64) &&
863 "Currently only handles V_ADD_CO_U32_e64 or V_SUB_CO_U32_e64");
864
865 // Can the candidate MI be shrunk?
866 if (!TII->canShrink(MI, *MRI))
867 return;
868 Opc = AMDGPU::getVOPe32(Opc);
869 // Find the related ADD instruction.
870 const MachineOperand *Sdst = TII->getNamedOperand(MI, AMDGPU::OpName::sdst);
871 if (!Sdst)
872 return;
873 MachineOperand *NextOp = findSingleRegUse(Sdst, MRI);
874 if (!NextOp)
875 return;
876 MachineInstr &MISucc = *NextOp->getParent();
877
878 // Make sure the carry in/out are subsequently unused.
879 MachineOperand *CarryIn = TII->getNamedOperand(MISucc, AMDGPU::OpName::src2);
880 if (!CarryIn)
881 return;
882 MachineOperand *CarryOut = TII->getNamedOperand(MISucc, AMDGPU::OpName::sdst);
883 if (!CarryOut)
884 return;
885 if (!MRI->hasOneUse(CarryIn->getReg()) || !MRI->use_empty(CarryOut->getReg()))
886 return;
887 // Make sure VCC or its subregs are dead before MI.
888 MachineBasicBlock &MBB = *MI.getParent();
889 auto Liveness = MBB.computeRegisterLiveness(TRI, AMDGPU::VCC, MI, 25);
890 if (Liveness != MachineBasicBlock::LQR_Dead)
891 return;
892 // Check if VCC is referenced in range of (MI,MISucc].
893 for (auto I = std::next(MI.getIterator()), E = MISucc.getIterator();
894 I != E; ++I) {
895 if (I->modifiesRegister(AMDGPU::VCC, TRI))
896 return;
897 }
898
899 // Replace MI with V_{SUB|ADD}_I32_e32
900 BuildMI(MBB, MI, MI.getDebugLoc(), TII->get(Opc))
901 .add(*TII->getNamedOperand(MI, AMDGPU::OpName::vdst))
902 .add(*TII->getNamedOperand(MI, AMDGPU::OpName::src0))
903 .add(*TII->getNamedOperand(MI, AMDGPU::OpName::src1))
904 .setMIFlags(MI.getFlags());
905
906 MI.eraseFromParent();
907
908 // Since the carry output of MI is now VCC, update its use in MISucc.
909
910 MISucc.substituteRegister(CarryIn->getReg(), TRI->getVCC(), 0, *TRI);
911}
912
913bool SIPeepholeSDWA::isConvertibleToSDWA(MachineInstr &MI,
914 const GCNSubtarget &ST) const {
915 // Check if this is already an SDWA instruction
916 unsigned Opc = MI.getOpcode();
917 if (TII->isSDWA(Opc))
918 return true;
919
920 // Check if this instruction has opcode that supports SDWA
921 if (AMDGPU::getSDWAOp(Opc) == -1)
922 Opc = AMDGPU::getVOPe32(Opc);
923
924 if (AMDGPU::getSDWAOp(Opc) == -1)
925 return false;
926
927 if (!ST.hasSDWAOmod() && TII->hasModifiersSet(MI, AMDGPU::OpName::omod))
928 return false;
929
930 if (TII->isVOPC(Opc)) {
931 if (!ST.hasSDWASdst()) {
932 const MachineOperand *SDst = TII->getNamedOperand(MI, AMDGPU::OpName::sdst);
933 if (SDst && (SDst->getReg() != AMDGPU::VCC &&
934 SDst->getReg() != AMDGPU::VCC_LO))
935 return false;
936 }
937
938 if (!ST.hasSDWAOutModsVOPC() &&
939 (TII->hasModifiersSet(MI, AMDGPU::OpName::clamp) ||
940 TII->hasModifiersSet(MI, AMDGPU::OpName::omod)))
941 return false;
942
943 } else if (TII->getNamedOperand(MI, AMDGPU::OpName::sdst) ||
944 !TII->getNamedOperand(MI, AMDGPU::OpName::vdst)) {
945 return false;
946 }
947
948 if (!ST.hasSDWAMac() && (Opc == AMDGPU::V_FMAC_F16_e32 ||
949 Opc == AMDGPU::V_FMAC_F32_e32 ||
950 Opc == AMDGPU::V_MAC_F16_e32 ||
951 Opc == AMDGPU::V_MAC_F32_e32))
952 return false;
953
954 // Check if target supports this SDWA opcode
955 if (TII->pseudoToMCOpcode(Opc) == -1)
956 return false;
957
958 // FIXME: has SDWA but require handling of implicit VCC use
959 if (Opc == AMDGPU::V_CNDMASK_B32_e32)
960 return false;
961
962 if (MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0)) {
963 if (!Src0->isReg() && !Src0->isImm())
964 return false;
965 }
966
967 if (MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1)) {
968 if (!Src1->isReg() && !Src1->isImm())
969 return false;
970 }
971
972 return true;
973}
974
975bool SIPeepholeSDWA::convertToSDWA(MachineInstr &MI,
976 const SDWAOperandsVector &SDWAOperands) {
977
978 LLVM_DEBUG(dbgs() << "Convert instruction:" << MI);
979
980 // Convert to sdwa
981 int SDWAOpcode;
982 unsigned Opcode = MI.getOpcode();
983 if (TII->isSDWA(Opcode)) {
984 SDWAOpcode = Opcode;
985 } else {
986 SDWAOpcode = AMDGPU::getSDWAOp(Opcode);
987 if (SDWAOpcode == -1)
988 SDWAOpcode = AMDGPU::getSDWAOp(AMDGPU::getVOPe32(Opcode));
989 }
990 assert(SDWAOpcode != -1);
991
992 const MCInstrDesc &SDWADesc = TII->get(SDWAOpcode);
993
994 // Create SDWA version of instruction MI and initialize its operands
995 MachineInstrBuilder SDWAInst =
996 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), SDWADesc)
997 .setMIFlags(MI.getFlags());
998
999 // Copy dst, if it is present in original then should also be present in SDWA
1000 MachineOperand *Dst = TII->getNamedOperand(MI, AMDGPU::OpName::vdst);
1001 if (Dst) {
1002 assert(AMDGPU::hasNamedOperand(SDWAOpcode, AMDGPU::OpName::vdst));
1003 SDWAInst.add(*Dst);
1004 } else if ((Dst = TII->getNamedOperand(MI, AMDGPU::OpName::sdst))) {
1005 assert(Dst && AMDGPU::hasNamedOperand(SDWAOpcode, AMDGPU::OpName::sdst));
1006 SDWAInst.add(*Dst);
1007 } else {
1008 assert(AMDGPU::hasNamedOperand(SDWAOpcode, AMDGPU::OpName::sdst));
1009 SDWAInst.addReg(TRI->getVCC(), RegState::Define);
1010 }
1011
1012 // Copy src0, initialize src0_modifiers. All sdwa instructions has src0 and
1013 // src0_modifiers (except for v_nop_sdwa, but it can't get here)
1014 MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0);
1015 assert(Src0 && AMDGPU::hasNamedOperand(SDWAOpcode, AMDGPU::OpName::src0) &&
1016 AMDGPU::hasNamedOperand(SDWAOpcode, AMDGPU::OpName::src0_modifiers));
1017 if (auto *Mod = TII->getNamedOperand(MI, AMDGPU::OpName::src0_modifiers))
1018 SDWAInst.addImm(Mod->getImm());
1019 else
1020 SDWAInst.addImm(0);
1021 SDWAInst.add(*Src0);
1022
1023 // Copy src1 if present, initialize src1_modifiers.
1024 MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1);
1025 if (Src1) {
1026 assert(AMDGPU::hasNamedOperand(SDWAOpcode, AMDGPU::OpName::src1) &&
1027 AMDGPU::hasNamedOperand(SDWAOpcode, AMDGPU::OpName::src1_modifiers));
1028 if (auto *Mod = TII->getNamedOperand(MI, AMDGPU::OpName::src1_modifiers))
1029 SDWAInst.addImm(Mod->getImm());
1030 else
1031 SDWAInst.addImm(0);
1032 SDWAInst.add(*Src1);
1033 }
1034
1035 if (SDWAOpcode == AMDGPU::V_FMAC_F16_sdwa ||
1036 SDWAOpcode == AMDGPU::V_FMAC_F32_sdwa ||
1037 SDWAOpcode == AMDGPU::V_MAC_F16_sdwa ||
1038 SDWAOpcode == AMDGPU::V_MAC_F32_sdwa) {
1039 // v_mac_f16/32 has additional src2 operand tied to vdst
1040 MachineOperand *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2);
1041 assert(Src2);
1042 SDWAInst.add(*Src2);
1043 }
1044
1045 // Copy clamp if present, initialize otherwise
1046 assert(AMDGPU::hasNamedOperand(SDWAOpcode, AMDGPU::OpName::clamp));
1047 MachineOperand *Clamp = TII->getNamedOperand(MI, AMDGPU::OpName::clamp);
1048 if (Clamp) {
1049 SDWAInst.add(*Clamp);
1050 } else {
1051 SDWAInst.addImm(0);
1052 }
1053
1054 // Copy omod if present, initialize otherwise if needed
1055 if (AMDGPU::hasNamedOperand(SDWAOpcode, AMDGPU::OpName::omod)) {
1056 MachineOperand *OMod = TII->getNamedOperand(MI, AMDGPU::OpName::omod);
1057 if (OMod) {
1058 SDWAInst.add(*OMod);
1059 } else {
1060 SDWAInst.addImm(0);
1061 }
1062 }
1063
1064 // Copy dst_sel if present, initialize otherwise if needed
1065 if (AMDGPU::hasNamedOperand(SDWAOpcode, AMDGPU::OpName::dst_sel)) {
1066 MachineOperand *DstSel = TII->getNamedOperand(MI, AMDGPU::OpName::dst_sel);
1067 if (DstSel) {
1068 SDWAInst.add(*DstSel);
1069 } else {
1070 SDWAInst.addImm(AMDGPU::SDWA::SdwaSel::DWORD);
1071 }
1072 }
1073
1074 // Copy dst_unused if present, initialize otherwise if needed
1075 if (AMDGPU::hasNamedOperand(SDWAOpcode, AMDGPU::OpName::dst_unused)) {
1076 MachineOperand *DstUnused = TII->getNamedOperand(MI, AMDGPU::OpName::dst_unused);
1077 if (DstUnused) {
1078 SDWAInst.add(*DstUnused);
1079 } else {
1080 SDWAInst.addImm(AMDGPU::SDWA::DstUnused::UNUSED_PAD);
1081 }
1082 }
1083
1084 // Copy src0_sel if present, initialize otherwise
1085 assert(AMDGPU::hasNamedOperand(SDWAOpcode, AMDGPU::OpName::src0_sel));
1086 MachineOperand *Src0Sel = TII->getNamedOperand(MI, AMDGPU::OpName::src0_sel);
1087 if (Src0Sel) {
1088 SDWAInst.add(*Src0Sel);
1089 } else {
1090 SDWAInst.addImm(AMDGPU::SDWA::SdwaSel::DWORD);
1091 }
1092
1093 // Copy src1_sel if present, initialize otherwise if needed
1094 if (Src1) {
1095 assert(AMDGPU::hasNamedOperand(SDWAOpcode, AMDGPU::OpName::src1_sel));
1096 MachineOperand *Src1Sel = TII->getNamedOperand(MI, AMDGPU::OpName::src1_sel);
1097 if (Src1Sel) {
1098 SDWAInst.add(*Src1Sel);
1099 } else {
1100 SDWAInst.addImm(AMDGPU::SDWA::SdwaSel::DWORD);
1101 }
1102 }
1103
1104 // Check for a preserved register that needs to be copied.
1105 auto DstUnused = TII->getNamedOperand(MI, AMDGPU::OpName::dst_unused);
1106 if (DstUnused &&
1107 DstUnused->getImm() == AMDGPU::SDWA::DstUnused::UNUSED_PRESERVE) {
1108 // We expect, if we are here, that the instruction was already in it's SDWA form,
1109 // with a tied operand.
1110 assert(Dst && Dst->isTied());
1111 assert(Opcode == static_cast<unsigned int>(SDWAOpcode));
1112 // We also expect a vdst, since sdst can't preserve.
1113 auto PreserveDstIdx = AMDGPU::getNamedOperandIdx(SDWAOpcode, AMDGPU::OpName::vdst);
1114 assert(PreserveDstIdx != -1);
1115
1116 auto TiedIdx = MI.findTiedOperandIdx(PreserveDstIdx);
1117 auto Tied = MI.getOperand(TiedIdx);
1118
1119 SDWAInst.add(Tied);
1120 SDWAInst->tieOperands(PreserveDstIdx, SDWAInst->getNumOperands() - 1);
1121 }
1122
1123 // Apply all sdwa operand patterns.
1124 bool Converted = false;
1125 for (auto &Operand : SDWAOperands) {
1126 LLVM_DEBUG(dbgs() << *SDWAInst << "\nOperand: " << *Operand);
1127 // There should be no intersection between SDWA operands and potential MIs
1128 // e.g.:
1129 // v_and_b32 v0, 0xff, v1 -> src:v1 sel:BYTE_0
1130 // v_and_b32 v2, 0xff, v0 -> src:v0 sel:BYTE_0
1131 // v_add_u32 v3, v4, v2
1132 //
1133 // In that example it is possible that we would fold 2nd instruction into
1134 // 3rd (v_add_u32_sdwa) and then try to fold 1st instruction into 2nd (that
1135 // was already destroyed). So if SDWAOperand is also a potential MI then do
1136 // not apply it.
1137 if (PotentialMatches.count(Operand->getParentInst()) == 0)
1138 Converted |= Operand->convertToSDWA(*SDWAInst, TII);
1139 }
1140 if (Converted) {
1141 ConvertedInstructions.push_back(SDWAInst);
1142 } else {
1143 SDWAInst->eraseFromParent();
1144 return false;
1145 }
1146
1147 LLVM_DEBUG(dbgs() << "\nInto:" << *SDWAInst << '\n');
1148 ++NumSDWAInstructionsPeepholed;
1149
1150 MI.eraseFromParent();
1151 return true;
1152}
1153
1154// If an instruction was converted to SDWA it should not have immediates or SGPR
1155// operands (allowed one SGPR on GFX9). Copy its scalar operands into VGPRs.
1156void SIPeepholeSDWA::legalizeScalarOperands(MachineInstr &MI,
1157 const GCNSubtarget &ST) const {
1158 const MCInstrDesc &Desc = TII->get(MI.getOpcode());
1159 unsigned ConstantBusCount = 0;
1160 for (MachineOperand &Op : MI.explicit_uses()) {
1161 if (!Op.isImm() && !(Op.isReg() && !TRI->isVGPR(*MRI, Op.getReg())))
1162 continue;
1163
1164 unsigned I = Op.getOperandNo();
1165 if (Desc.operands()[I].RegClass == -1 ||
1166 !TRI->isVSSuperClass(TRI->getRegClass(Desc.operands()[I].RegClass)))
1167 continue;
1168
1169 if (ST.hasSDWAScalar() && ConstantBusCount == 0 && Op.isReg() &&
1170 TRI->isSGPRReg(*MRI, Op.getReg())) {
1171 ++ConstantBusCount;
1172 continue;
1173 }
1174
1175 Register VGPR = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1176 auto Copy = BuildMI(*MI.getParent(), MI.getIterator(), MI.getDebugLoc(),
1177 TII->get(AMDGPU::V_MOV_B32_e32), VGPR);
1178 if (Op.isImm())
1179 Copy.addImm(Op.getImm());
1180 else if (Op.isReg())
1181 Copy.addReg(Op.getReg(), Op.isKill() ? RegState::Kill : 0,
1182 Op.getSubReg());
1183 Op.ChangeToRegister(VGPR, false);
1184 }
1185}
1186
1187bool SIPeepholeSDWA::runOnMachineFunction(MachineFunction &MF) {
1189
1190 if (!ST.hasSDWA() || skipFunction(MF.getFunction()))
1191 return false;
1192
1193 MRI = &MF.getRegInfo();
1194 TRI = ST.getRegisterInfo();
1195 TII = ST.getInstrInfo();
1196
1197 // Find all SDWA operands in MF.
1198 bool Ret = false;
1199 for (MachineBasicBlock &MBB : MF) {
1200 bool Changed = false;
1201 do {
1202 // Preprocess the ADD/SUB pairs so they could be SDWA'ed.
1203 // Look for a possible ADD or SUB that resulted from a previously lowered
1204 // V_{ADD|SUB}_U64_PSEUDO. The function pseudoOpConvertToVOP2
1205 // lowers the pair of instructions into e32 form.
1206 matchSDWAOperands(MBB);
1207 for (const auto &OperandPair : SDWAOperands) {
1208 const auto &Operand = OperandPair.second;
1209 MachineInstr *PotentialMI = Operand->potentialToConvert(TII);
1210 if (PotentialMI &&
1211 (PotentialMI->getOpcode() == AMDGPU::V_ADD_CO_U32_e64 ||
1212 PotentialMI->getOpcode() == AMDGPU::V_SUB_CO_U32_e64))
1213 pseudoOpConvertToVOP2(*PotentialMI, ST);
1214 }
1215 SDWAOperands.clear();
1216
1217 // Generate potential match list.
1218 matchSDWAOperands(MBB);
1219
1220 for (const auto &OperandPair : SDWAOperands) {
1221 const auto &Operand = OperandPair.second;
1222 MachineInstr *PotentialMI = Operand->potentialToConvert(TII);
1223 if (PotentialMI && isConvertibleToSDWA(*PotentialMI, ST)) {
1224 PotentialMatches[PotentialMI].push_back(Operand.get());
1225 }
1226 }
1227
1228 for (auto &PotentialPair : PotentialMatches) {
1229 MachineInstr &PotentialMI = *PotentialPair.first;
1230 convertToSDWA(PotentialMI, PotentialPair.second);
1231 }
1232
1233 PotentialMatches.clear();
1234 SDWAOperands.clear();
1235
1236 Changed = !ConvertedInstructions.empty();
1237
1238 if (Changed)
1239 Ret = true;
1240 while (!ConvertedInstructions.empty())
1241 legalizeScalarOperands(*ConvertedInstructions.pop_back_val(), ST);
1242 } while (Changed);
1243 }
1244
1245 return Ret;
1246}
unsigned const MachineRegisterInfo * MRI
MachineBasicBlock & MBB
Provides AMDGPU specific target descriptions.
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
BlockVerifier::State From
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition: Compiler.h:529
#define LLVM_DEBUG(X)
Definition: Debug.h:101
AMD GCN specific subclass of TargetSubtarget.
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition: MD5.cpp:58
unsigned const TargetRegisterInfo * TRI
This file implements a map that provides insertion order iteration.
static unsigned getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
Module * Mod
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:38
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static MachineOperand * findSingleRegDef(const MachineOperand *Reg, const MachineRegisterInfo *MRI)
static void copyRegOperand(MachineOperand &To, const MachineOperand &From)
static MachineOperand * findSingleRegUse(const MachineOperand *Reg, const MachineRegisterInfo *MRI)
static bool isSameReg(const MachineOperand &LHS, const MachineOperand &RHS)
static raw_ostream & operator<<(raw_ostream &OS, SdwaSel Sel)
#define DEBUG_TYPE
raw_pwrite_stream & OS
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
Value * RHS
Value * LHS
Represent the analysis usage information of a pass.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:269
This class represents an Operation in the Expression.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:311
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:198
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.
@ 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...
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.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
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:69
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:544
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:327
unsigned getNumOperands() const
Retuns the total number of operands.
Definition: MachineInstr.h:547
void substituteRegister(Register FromReg, Register ToReg, unsigned SubIdx, const TargetRegisterInfo &RegInfo)
Replace all occurrences of FromReg with ToReg:SubIdx, properly composing subreg indices where necessa...
void tieOperands(unsigned DefIdx, unsigned UseIdx)
Add a tie between the register operands at DefIdx and UseIdx.
iterator_range< mop_iterator > defs()
Returns a range over all explicit operands that are register definitions.
Definition: MachineInstr.h:697
void eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:554
MachineOperand class - Representation of each machine instruction operand.
void setSubReg(unsigned subReg)
void setImm(int64_t immVal)
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
void setIsDead(bool Val=true)
void setReg(Register Reg)
Change the register this operand corresponds to.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
void setIsKill(bool Val=true)
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
void setIsUndef(bool Val=true)
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
This class implements a map that also provides access to all stored values in a deterministic order.
Definition: MapVector.h:36
size_type count(const KeyT &Key) const
Definition: MapVector.h:165
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:81
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition: Register.h:95
bool empty() const
Definition: SmallVector.h:94
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Target - Wrapper for Target specific information.
self_iterator getIterator()
Definition: ilist_node.h:109
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
LLVM_READONLY int getVOPe32(uint16_t Opcode)
LLVM_READONLY int16_t getNamedOperandIdx(uint16_t Opcode, uint16_t NamedIdx)
LLVM_READONLY int getSDWAOp(uint16_t Opcode)
LLVM_READONLY bool hasNamedOperand(uint64_t Opcode, uint64_t NamedIdx)
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ Define
Register definition.
@ Kill
The last use of a register.
NodeAddr< DefNode * > Def
Definition: RDFGraph.h:384
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
@ Offset
Definition: DWP.cpp:456
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
FunctionPass * createSIPeepholeSDWAPass()
void initializeSIPeepholeSDWAPass(PassRegistry &)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
char & SIPeepholeSDWAID
Description of the encoding of one expression Op.