LLVM 24.0.0git
AMDGPUInstructionSelector.cpp
Go to the documentation of this file.
1//===- AMDGPUInstructionSelector.cpp ----------------------------*- C++ -*-==//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8/// \file
9/// This file implements the targeting of the InstructionSelector class for
10/// AMDGPU.
11/// \todo This should be generated by TableGen.
12//===----------------------------------------------------------------------===//
13
15#include "AMDGPU.h"
17#include "AMDGPUInstrInfo.h"
28#include "llvm/IR/IntrinsicsAMDGPU.h"
29#include <optional>
30
31#define DEBUG_TYPE "amdgpu-isel"
32
33using namespace llvm;
34using namespace MIPatternMatch;
35
36#define GET_GLOBALISEL_IMPL
37#define AMDGPUSubtarget GCNSubtarget
38#include "AMDGPUGenGlobalISel.inc"
39#undef GET_GLOBALISEL_IMPL
40#undef AMDGPUSubtarget
41
43 const GCNSubtarget &STI, const AMDGPURegisterBankInfo &RBI)
44 : TII(*STI.getInstrInfo()), TRI(*STI.getRegisterInfo()), RBI(RBI), STI(STI),
46#include "AMDGPUGenGlobalISel.inc"
49#include "AMDGPUGenGlobalISel.inc"
51{
52}
53
54const char *AMDGPUInstructionSelector::getName() { return DEBUG_TYPE; }
55
66
67// Return the wave level SGPR base address if this is a wave address.
69 return Def->getOpcode() == AMDGPU::G_AMDGPU_WAVE_ADDRESS
70 ? Def->getOperand(1).getReg()
71 : Register();
72}
73
74bool AMDGPUInstructionSelector::isVCC(Register Reg,
75 const MachineRegisterInfo &MRI) const {
76 // The verifier is oblivious to s1 being a valid value for wavesize registers.
77 if (Reg.isPhysical())
78 return false;
79
80 auto &RegClassOrBank = MRI.getRegClassOrRegBank(Reg);
81 const TargetRegisterClass *RC =
83 if (RC) {
84 const LLT Ty = MRI.getType(Reg);
85 if (!Ty.isValid() || Ty.getSizeInBits() != 1)
86 return false;
87 // G_TRUNC s1 result is never vcc.
88 return !mi_match(Reg, MRI, m_GTrunc(m_Reg())) &&
89 RC->hasSuperClassEq(TRI.getBoolRC());
90 }
91
92 const RegisterBank *RB = cast<const RegisterBank *>(RegClassOrBank);
93 return RB->getID() == AMDGPU::VCCRegBankID;
94}
95
96bool AMDGPUInstructionSelector::constrainCopyLikeIntrin(MachineInstr &MI,
97 unsigned NewOpc) const {
98 MI.setDesc(TII.get(NewOpc));
99 MI.removeOperand(1); // Remove intrinsic ID.
100 MI.addOperand(*MF, MachineOperand::CreateReg(AMDGPU::EXEC, false, true));
101
102 Register DstReg = MI.getOperand(0).getReg();
103 Register SrcReg = MI.getOperand(1).getReg();
104
105 // TODO: This should be legalized to s32 if needed
106 if (MRI->getType(DstReg) == LLT::scalar(1))
107 return false;
108
109 const TargetRegisterClass *DstRC =
110 TRI.getConstrainedRegClassForReg(DstReg, *MRI);
111 const TargetRegisterClass *SrcRC =
112 TRI.getConstrainedRegClassForReg(SrcReg, *MRI);
113 if (!DstRC || DstRC != SrcRC)
114 return false;
115
116 if (!RBI.constrainGenericRegister(DstReg, *DstRC, *MRI) ||
117 !RBI.constrainGenericRegister(SrcReg, *SrcRC, *MRI))
118 return false;
119 const MCInstrDesc &MCID = MI.getDesc();
120 if (MCID.getOperandConstraint(0, MCOI::EARLY_CLOBBER) != -1) {
121 MI.getOperand(0).setIsEarlyClobber(true);
122 }
123 return true;
124}
125
126bool AMDGPUInstructionSelector::selectCOPY(MachineInstr &I) const {
127 const DebugLoc &DL = I.getDebugLoc();
128 MachineBasicBlock *BB = I.getParent();
129 I.setDesc(TII.get(TargetOpcode::COPY));
130
131 Register DstReg = I.getOperand(0).getReg();
132 Register SrcReg = I.getOperand(1).getReg();
133
134 if (isVCC(DstReg, *MRI)) {
135 if (SrcReg == AMDGPU::SCC) {
136 const TargetRegisterClass *RC =
137 TRI.getConstrainedRegClassForReg(DstReg, *MRI);
138 if (!RC)
139 return true;
140 return RBI.constrainGenericRegister(DstReg, *RC, *MRI);
141 }
142
143 if (!isVCC(SrcReg, *MRI)) {
144 // TODO: Should probably leave the copy and let copyPhysReg expand it.
145 if (!RBI.constrainGenericRegister(DstReg, *TRI.getBoolRC(), *MRI))
146 return false;
147
148 const TargetRegisterClass *SrcRC =
149 TRI.getConstrainedRegClassForReg(SrcReg, *MRI);
150
151 std::optional<ValueAndVReg> ConstVal =
152 getIConstantVRegValWithLookThrough(SrcReg, *MRI, true);
153 if (ConstVal) {
154 unsigned MovOpc =
155 STI.isWave64() ? AMDGPU::S_MOV_B64 : AMDGPU::S_MOV_B32;
156 BuildMI(*BB, &I, DL, TII.get(MovOpc), DstReg)
157 .addImm(ConstVal->Value.getBoolValue() ? -1 : 0);
158 } else {
159 Register MaskedReg = MRI->createVirtualRegister(SrcRC);
160
161 // We can't trust the high bits at this point, so clear them.
162
163 // TODO: Skip masking high bits if def is known boolean.
164
165 if (AMDGPU::getRegBitWidth(SrcRC->getID()) == 16) {
166 assert(Subtarget->useRealTrue16Insts());
167 const int64_t NoMods = 0;
168 BuildMI(*BB, &I, DL, TII.get(AMDGPU::V_AND_B16_t16_e64), MaskedReg)
169 .addImm(NoMods)
170 .addImm(1)
171 .addImm(NoMods)
172 .addReg(SrcReg)
173 .addImm(NoMods);
174 BuildMI(*BB, &I, DL, TII.get(AMDGPU::V_CMP_NE_U16_t16_e64), DstReg)
175 .addImm(NoMods)
176 .addImm(0)
177 .addImm(NoMods)
178 .addReg(MaskedReg)
179 .addImm(NoMods);
180 } else {
181 bool IsSGPR = TRI.isSGPRClass(SrcRC);
182 unsigned AndOpc = IsSGPR ? AMDGPU::S_AND_B32 : AMDGPU::V_AND_B32_e32;
183 auto And = BuildMI(*BB, &I, DL, TII.get(AndOpc), MaskedReg)
184 .addImm(1)
185 .addReg(SrcReg);
186 if (IsSGPR)
187 And.setOperandDead(3); // Dead scc
188
189 BuildMI(*BB, &I, DL, TII.get(AMDGPU::V_CMP_NE_U32_e64), DstReg)
190 .addImm(0)
191 .addReg(MaskedReg);
192 }
193 }
194
195 if (!MRI->getRegClassOrNull(SrcReg))
196 MRI->setRegClass(SrcReg, SrcRC);
197 I.eraseFromParent();
198 return true;
199 }
200
201 const TargetRegisterClass *RC =
202 TRI.getConstrainedRegClassForReg(DstReg, *MRI);
203 if (RC && !RBI.constrainGenericRegister(DstReg, *RC, *MRI))
204 return false;
205
206 return true;
207 }
208
209 for (const MachineOperand &MO : I.operands()) {
210 if (MO.getReg().isPhysical())
211 continue;
212
213 const TargetRegisterClass *RC =
214 TRI.getConstrainedRegClassForReg(MO.getReg(), *MRI);
215 if (!RC)
216 continue;
217 RBI.constrainGenericRegister(MO.getReg(), *RC, *MRI);
218 }
219 return true;
220}
221
222bool AMDGPUInstructionSelector::selectCOPY_SCC_VCC(MachineInstr &I) const {
223 const DebugLoc &DL = I.getDebugLoc();
224 MachineBasicBlock *BB = I.getParent();
225 Register VCCReg = I.getOperand(1).getReg();
226 MachineInstr *Cmp;
227
228 // Set SCC as a side effect with S_CMP or S_OR.
229 if (STI.hasScalarCompareEq64()) {
230 unsigned CmpOpc =
231 STI.isWave64() ? AMDGPU::S_CMP_LG_U64 : AMDGPU::S_CMP_LG_U32;
232 Cmp = BuildMI(*BB, &I, DL, TII.get(CmpOpc)).addReg(VCCReg).addImm(0);
233 } else {
234 Register DeadDst = MRI->createVirtualRegister(&AMDGPU::SReg_64RegClass);
235 Cmp = BuildMI(*BB, &I, DL, TII.get(AMDGPU::S_OR_B64), DeadDst)
236 .addReg(VCCReg)
237 .addReg(VCCReg);
238 }
239
240 constrainSelectedInstRegOperands(*Cmp, TII, TRI, RBI);
241
242 Register DstReg = I.getOperand(0).getReg();
243 BuildMI(*BB, &I, DL, TII.get(AMDGPU::COPY), DstReg).addReg(AMDGPU::SCC);
244
245 I.eraseFromParent();
246 return RBI.constrainGenericRegister(DstReg, AMDGPU::SReg_32RegClass, *MRI);
247}
248
249bool AMDGPUInstructionSelector::selectCOPY_VCC_SCC(MachineInstr &I) const {
250 const DebugLoc &DL = I.getDebugLoc();
251 MachineBasicBlock *BB = I.getParent();
252
253 Register DstReg = I.getOperand(0).getReg();
254 Register SrcReg = I.getOperand(1).getReg();
255 std::optional<ValueAndVReg> Arg =
256 getIConstantVRegValWithLookThrough(I.getOperand(1).getReg(), *MRI);
257
258 if (Arg) {
259 const int64_t Value = Arg->Value.getZExtValue();
260 if (Value == 0) {
261 unsigned Opcode = STI.isWave64() ? AMDGPU::S_MOV_B64 : AMDGPU::S_MOV_B32;
262 BuildMI(*BB, &I, DL, TII.get(Opcode), DstReg).addImm(0);
263 } else {
264 assert(Value == 1);
265 BuildMI(*BB, &I, DL, TII.get(AMDGPU::COPY), DstReg).addReg(TRI.getExec());
266 }
267 I.eraseFromParent();
268 return RBI.constrainGenericRegister(DstReg, *TRI.getBoolRC(), *MRI);
269 }
270
271 // RegBankLegalize ensures that SrcReg is bool in reg (high bits are 0).
272 BuildMI(*BB, &I, DL, TII.get(AMDGPU::COPY), AMDGPU::SCC).addReg(SrcReg);
273
274 unsigned SelectOpcode =
275 STI.isWave64() ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
276 MachineInstr *Select = BuildMI(*BB, &I, DL, TII.get(SelectOpcode), DstReg)
277 .addReg(TRI.getExec())
278 .addImm(0);
279
280 I.eraseFromParent();
282 return true;
283}
284
285bool AMDGPUInstructionSelector::selectReadAnyLane(MachineInstr &I) const {
286 Register DstReg = I.getOperand(0).getReg();
287 Register SrcReg = I.getOperand(1).getReg();
288
289 const DebugLoc &DL = I.getDebugLoc();
290 MachineBasicBlock *BB = I.getParent();
291
292 auto RFL = BuildMI(*BB, &I, DL, TII.get(AMDGPU::V_READFIRSTLANE_B32), DstReg)
293 .addReg(SrcReg);
294
295 I.eraseFromParent();
296 constrainSelectedInstRegOperands(*RFL, TII, TRI, RBI);
297 return true;
298}
299
300bool AMDGPUInstructionSelector::selectPHI(MachineInstr &I) const {
301 const Register DefReg = I.getOperand(0).getReg();
302 const LLT DefTy = MRI->getType(DefReg);
303
304 // S1 G_PHIs should not be selected in instruction-select, instead:
305 // - divergent S1 G_PHI should go through lane mask merging algorithm
306 // and be fully inst-selected in AMDGPUGlobalISelDivergenceLowering
307 // - uniform S1 G_PHI should be lowered into S32 G_PHI in AMDGPURegBankSelect
308 if (DefTy == LLT::scalar(1))
309 return false;
310
311 // TODO: Verify this doesn't have insane operands (i.e. VGPR to SGPR copy)
312
313 const RegClassOrRegBank &RegClassOrBank =
314 MRI->getRegClassOrRegBank(DefReg);
315
316 const TargetRegisterClass *DefRC =
318 if (!DefRC) {
319 if (!DefTy.isValid()) {
320 LLVM_DEBUG(dbgs() << "PHI operand has no type, not a gvreg?\n");
321 return false;
322 }
323
324 const RegisterBank &RB = *cast<const RegisterBank *>(RegClassOrBank);
325 DefRC = TRI.getRegClassForTypeOnBank(DefTy, RB);
326 if (!DefRC) {
327 LLVM_DEBUG(dbgs() << "PHI operand has unexpected size/bank\n");
328 return false;
329 }
330 }
331
332 // If inputs have register bank, assign corresponding reg class.
333 // Note: registers don't need to have the same reg bank.
334 for (unsigned i = 1; i != I.getNumOperands(); i += 2) {
335 const Register SrcReg = I.getOperand(i).getReg();
336
337 const RegisterBank *RB = MRI->getRegBankOrNull(SrcReg);
338 if (RB) {
339 const LLT SrcTy = MRI->getType(SrcReg);
340 const TargetRegisterClass *SrcRC =
341 TRI.getRegClassForTypeOnBank(SrcTy, *RB);
342 if (!RBI.constrainGenericRegister(SrcReg, *SrcRC, *MRI))
343 return false;
344 }
345 }
346
347 I.setDesc(TII.get(TargetOpcode::PHI));
348 return RBI.constrainGenericRegister(DefReg, *DefRC, *MRI);
349}
350
352AMDGPUInstructionSelector::getSubOperand64(MachineOperand &MO,
353 const TargetRegisterClass &SubRC,
354 unsigned SubIdx) const {
355
356 MachineInstr *MI = MO.getParent();
357 MachineBasicBlock *BB = MO.getParent()->getParent();
358 Register DstReg = MRI->createVirtualRegister(&SubRC);
359
360 if (MO.isReg()) {
361 unsigned ComposedSubIdx = TRI.composeSubRegIndices(MO.getSubReg(), SubIdx);
362 Register Reg = MO.getReg();
363 BuildMI(*BB, MI, MI->getDebugLoc(), TII.get(AMDGPU::COPY), DstReg)
364 .addReg(Reg, {}, ComposedSubIdx);
365
366 return MachineOperand::CreateReg(DstReg, MO.isDef(), MO.isImplicit(),
367 MO.isKill(), MO.isDead(), MO.isUndef(),
368 MO.isEarlyClobber(), 0, MO.isDebug(),
369 MO.isInternalRead());
370 }
371
372 assert(MO.isImm());
373
374 APInt Imm(64, MO.getImm());
375
376 switch (SubIdx) {
377 default:
378 llvm_unreachable("do not know to split immediate with this sub index.");
379 case AMDGPU::sub0:
380 return MachineOperand::CreateImm(Imm.getLoBits(32).getSExtValue());
381 case AMDGPU::sub1:
382 return MachineOperand::CreateImm(Imm.getHiBits(32).getSExtValue());
383 }
384}
385
386static unsigned getLogicalBitOpcode(unsigned Opc, bool Is64) {
387 switch (Opc) {
388 case AMDGPU::G_AND:
389 return Is64 ? AMDGPU::S_AND_B64 : AMDGPU::S_AND_B32;
390 case AMDGPU::G_OR:
391 return Is64 ? AMDGPU::S_OR_B64 : AMDGPU::S_OR_B32;
392 case AMDGPU::G_XOR:
393 return Is64 ? AMDGPU::S_XOR_B64 : AMDGPU::S_XOR_B32;
394 default:
395 llvm_unreachable("not a bit op");
396 }
397}
398
399bool AMDGPUInstructionSelector::selectG_AND_OR_XOR(MachineInstr &I) const {
400 Register DstReg = I.getOperand(0).getReg();
401 uint64_t Size = TRI.getRegSizeInBits(DstReg, *MRI);
402
403 const RegisterBank *DstRB = RBI.getRegBank(DstReg, *MRI, TRI);
404 if (DstRB->getID() != AMDGPU::SGPRRegBankID &&
405 DstRB->getID() != AMDGPU::VCCRegBankID)
406 return false;
407
408 bool Is64 = Size > 32 || (DstRB->getID() == AMDGPU::VCCRegBankID &&
409 STI.isWave64());
410 I.setDesc(TII.get(getLogicalBitOpcode(I.getOpcode(), Is64)));
411
412 // Dead implicit-def of scc
413 I.addOperand(MachineOperand::CreateReg(AMDGPU::SCC, true, // isDef
414 true, // isImp
415 false, // isKill
416 true)); // isDead
417 constrainSelectedInstRegOperands(I, TII, TRI, RBI);
418 return true;
419}
420
421bool AMDGPUInstructionSelector::selectG_ADD_SUB(MachineInstr &I) const {
422 MachineBasicBlock *BB = I.getParent();
424 Register DstReg = I.getOperand(0).getReg();
425 const DebugLoc &DL = I.getDebugLoc();
426 LLT Ty = MRI->getType(DstReg);
427 if (Ty.isVector())
428 return false;
429
431 const RegisterBank *DstRB = RBI.getRegBank(DstReg, *MRI, TRI);
432 const bool IsSALU = DstRB->getID() == AMDGPU::SGPRRegBankID;
433 const bool Sub = I.getOpcode() == TargetOpcode::G_SUB;
434
435 if (Size == 32) {
436 if (IsSALU) {
437 const unsigned Opc = Sub ? AMDGPU::S_SUB_U32 : AMDGPU::S_ADD_U32;
438 MachineInstr *Add =
439 BuildMI(*BB, &I, DL, TII.get(Opc), DstReg)
440 .add(I.getOperand(1))
441 .add(I.getOperand(2))
442 .setOperandDead(3); // Dead scc
443 I.eraseFromParent();
444 constrainSelectedInstRegOperands(*Add, TII, TRI, RBI);
445 return true;
446 }
447
448 if (STI.hasAddNoCarryInsts()) {
449 const unsigned Opc = Sub ? AMDGPU::V_SUB_U32_e64 : AMDGPU::V_ADD_U32_e64;
450 I.setDesc(TII.get(Opc));
451 I.addOperand(*MF, MachineOperand::CreateImm(0));
452 I.addOperand(*MF, MachineOperand::CreateReg(AMDGPU::EXEC, false, true));
453 constrainSelectedInstRegOperands(I, TII, TRI, RBI);
454 return true;
455 }
456
457 const unsigned Opc = Sub ? AMDGPU::V_SUB_CO_U32_e64 : AMDGPU::V_ADD_CO_U32_e64;
458
459 Register UnusedCarry = MRI->createVirtualRegister(TRI.getWaveMaskRegClass());
460 MachineInstr *Add
461 = BuildMI(*BB, &I, DL, TII.get(Opc), DstReg)
462 .addDef(UnusedCarry, RegState::Dead)
463 .add(I.getOperand(1))
464 .add(I.getOperand(2))
465 .addImm(0);
466 I.eraseFromParent();
467 constrainSelectedInstRegOperands(*Add, TII, TRI, RBI);
468 return true;
469 }
470
471 assert(!Sub && "illegal sub should not reach here");
472
473 const TargetRegisterClass &RC
474 = IsSALU ? AMDGPU::SReg_64_XEXECRegClass : AMDGPU::VReg_64RegClass;
475 const TargetRegisterClass &HalfRC
476 = IsSALU ? AMDGPU::SReg_32RegClass : AMDGPU::VGPR_32RegClass;
477
478 MachineOperand Lo1(getSubOperand64(I.getOperand(1), HalfRC, AMDGPU::sub0));
479 MachineOperand Lo2(getSubOperand64(I.getOperand(2), HalfRC, AMDGPU::sub0));
480 MachineOperand Hi1(getSubOperand64(I.getOperand(1), HalfRC, AMDGPU::sub1));
481 MachineOperand Hi2(getSubOperand64(I.getOperand(2), HalfRC, AMDGPU::sub1));
482
483 Register DstLo = MRI->createVirtualRegister(&HalfRC);
484 Register DstHi = MRI->createVirtualRegister(&HalfRC);
485
486 if (IsSALU) {
487 BuildMI(*BB, &I, DL, TII.get(AMDGPU::S_ADD_U32), DstLo)
488 .add(Lo1)
489 .add(Lo2);
490 BuildMI(*BB, &I, DL, TII.get(AMDGPU::S_ADDC_U32), DstHi)
491 .add(Hi1)
492 .add(Hi2)
493 .setOperandDead(3); // Dead scc
494 } else {
495 const TargetRegisterClass *CarryRC = TRI.getWaveMaskRegClass();
496 Register CarryReg = MRI->createVirtualRegister(CarryRC);
497 BuildMI(*BB, &I, DL, TII.get(AMDGPU::V_ADD_CO_U32_e64), DstLo)
498 .addDef(CarryReg)
499 .add(Lo1)
500 .add(Lo2)
501 .addImm(0);
502 MachineInstr *Addc =
503 BuildMI(*BB, &I, DL, TII.get(AMDGPU::V_ADDC_U32_e64), DstHi)
504 .addDef(MRI->createVirtualRegister(CarryRC), RegState::Dead)
505 .add(Hi1)
506 .add(Hi2)
507 .addReg(CarryReg)
508 .addImm(0);
509
510 constrainSelectedInstRegOperands(*Addc, TII, TRI, RBI);
511 }
512
513 BuildMI(*BB, &I, DL, TII.get(AMDGPU::REG_SEQUENCE), DstReg)
514 .addReg(DstLo)
515 .addImm(AMDGPU::sub0)
516 .addReg(DstHi)
517 .addImm(AMDGPU::sub1);
518
519
520 if (!RBI.constrainGenericRegister(DstReg, RC, *MRI))
521 return false;
522
523 I.eraseFromParent();
524 return true;
525}
526
527bool AMDGPUInstructionSelector::selectG_UADDO_USUBO_UADDE_USUBE(
528 MachineInstr &I) const {
529 MachineBasicBlock *BB = I.getParent();
531 const DebugLoc &DL = I.getDebugLoc();
532 Register Dst0Reg = I.getOperand(0).getReg();
533 Register Dst1Reg = I.getOperand(1).getReg();
534 const bool IsAdd = I.getOpcode() == AMDGPU::G_UADDO ||
535 I.getOpcode() == AMDGPU::G_UADDE;
536 const bool HasCarryIn = I.getOpcode() == AMDGPU::G_UADDE ||
537 I.getOpcode() == AMDGPU::G_USUBE;
538
539 if (isVCC(Dst1Reg, *MRI)) {
540 unsigned NoCarryOpc =
541 IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
542 unsigned CarryOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
543 I.setDesc(TII.get(HasCarryIn ? CarryOpc : NoCarryOpc));
544 I.addOperand(*MF, MachineOperand::CreateReg(AMDGPU::EXEC, false, true));
545 I.addOperand(*MF, MachineOperand::CreateImm(0));
546 constrainSelectedInstRegOperands(I, TII, TRI, RBI);
547 return true;
548 }
549
550 Register Src0Reg = I.getOperand(2).getReg();
551 Register Src1Reg = I.getOperand(3).getReg();
552
553 if (HasCarryIn) {
554 BuildMI(*BB, &I, DL, TII.get(AMDGPU::COPY), AMDGPU::SCC)
555 .addReg(I.getOperand(4).getReg());
556 }
557
558 unsigned NoCarryOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
559 unsigned CarryOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
560
561 auto CarryInst = BuildMI(*BB, &I, DL, TII.get(HasCarryIn ? CarryOpc : NoCarryOpc), Dst0Reg)
562 .add(I.getOperand(2))
563 .add(I.getOperand(3));
564
565 if (MRI->use_nodbg_empty(Dst1Reg)) {
566 CarryInst.setOperandDead(3); // Dead scc
567 } else {
568 BuildMI(*BB, &I, DL, TII.get(AMDGPU::COPY), Dst1Reg)
569 .addReg(AMDGPU::SCC);
570 if (!MRI->getRegClassOrNull(Dst1Reg))
571 MRI->setRegClass(Dst1Reg, &AMDGPU::SReg_32RegClass);
572 }
573
574 if (!RBI.constrainGenericRegister(Dst0Reg, AMDGPU::SReg_32RegClass, *MRI) ||
575 !RBI.constrainGenericRegister(Src0Reg, AMDGPU::SReg_32RegClass, *MRI) ||
576 !RBI.constrainGenericRegister(Src1Reg, AMDGPU::SReg_32RegClass, *MRI))
577 return false;
578
579 if (HasCarryIn &&
580 !RBI.constrainGenericRegister(I.getOperand(4).getReg(),
581 AMDGPU::SReg_32RegClass, *MRI))
582 return false;
583
584 I.eraseFromParent();
585 return true;
586}
587
588bool AMDGPUInstructionSelector::selectG_AMDGPU_MAD_64_32(
589 MachineInstr &I) const {
590 MachineBasicBlock *BB = I.getParent();
592 const bool IsUnsigned = I.getOpcode() == AMDGPU::G_AMDGPU_MAD_U64_U32;
593 bool UseNoCarry = Subtarget->hasMadNC64_32Insts() &&
594 MRI->use_nodbg_empty(I.getOperand(1).getReg());
595
596 unsigned Opc;
597 if (Subtarget->hasMADIntraFwdBug())
598 Opc = IsUnsigned ? AMDGPU::V_MAD_U64_U32_gfx11_e64
599 : AMDGPU::V_MAD_I64_I32_gfx11_e64;
600 else if (UseNoCarry)
601 Opc = IsUnsigned ? AMDGPU::V_MAD_NC_U64_U32_e64
602 : AMDGPU::V_MAD_NC_I64_I32_e64;
603 else
604 Opc = IsUnsigned ? AMDGPU::V_MAD_U64_U32_e64 : AMDGPU::V_MAD_I64_I32_e64;
605
606 if (UseNoCarry)
607 I.removeOperand(1);
608
609 I.setDesc(TII.get(Opc));
610 I.addOperand(*MF, MachineOperand::CreateImm(0));
611 I.addImplicitDefUseOperands(*MF);
612 I.getOperand(0).setIsEarlyClobber(true);
613 constrainSelectedInstRegOperands(I, TII, TRI, RBI);
614 return true;
615}
616
617// TODO: We should probably legalize these to only using 32-bit results.
618bool AMDGPUInstructionSelector::selectG_EXTRACT(MachineInstr &I) const {
619 MachineBasicBlock *BB = I.getParent();
620 Register DstReg = I.getOperand(0).getReg();
621 Register SrcReg = I.getOperand(1).getReg();
622 LLT DstTy = MRI->getType(DstReg);
623 LLT SrcTy = MRI->getType(SrcReg);
624 const uint64_t SrcSize = SrcTy.getSizeInBits();
625 uint64_t DstSize = DstTy.getSizeInBits();
626
627 // TODO: Should handle any multiple of 32 offset.
628 int64_t Offset = I.getOperand(2).getImm();
629 if (Offset % 32 != 0 || DstSize > 128)
630 return false;
631
632 // 16-bit operations really use 32-bit registers.
633 // FIXME: Probably should not allow 16-bit G_EXTRACT results.
634 if (DstSize == 16)
635 DstSize = 32;
636
637 const TargetRegisterClass *DstRC =
638 TRI.getConstrainedRegClassForReg(DstReg, *MRI);
639 if (!DstRC || !RBI.constrainGenericRegister(DstReg, *DstRC, *MRI))
640 return false;
641
642 const RegisterBank *SrcBank = RBI.getRegBank(SrcReg, *MRI, TRI);
643 const TargetRegisterClass *SrcRC =
644 TRI.getRegClassForSizeOnBank(SrcSize, *SrcBank);
645 if (!SrcRC)
646 return false;
647 unsigned SubReg = SIRegisterInfo::getSubRegFromChannel(Offset / 32,
648 DstSize / 32);
649 SrcRC = TRI.getSubClassWithSubReg(SrcRC, SubReg);
650 if (!SrcRC)
651 return false;
652
653 SrcReg = constrainOperandRegClass(*MF, TRI, *MRI, TII, RBI, I,
654 *SrcRC, I.getOperand(1));
655 const DebugLoc &DL = I.getDebugLoc();
656 BuildMI(*BB, &I, DL, TII.get(TargetOpcode::COPY), DstReg)
657 .addReg(SrcReg, {}, SubReg);
658
659 I.eraseFromParent();
660 return true;
661}
662
663bool AMDGPUInstructionSelector::selectS16MergeToS32(MachineInstr &MI) const {
664 Register Dst = MI.getOperand(0).getReg();
665 Register Src0 = MI.getOperand(1).getReg();
666 Register Src1 = MI.getOperand(2).getReg();
667
668 LLT Src0Ty = MRI->getType(Src0);
669 LLT Src1Ty = MRI->getType(Src1);
670
671 const RegisterBank *DstBank = RBI.getRegBank(Dst, *MRI, TRI);
672 const RegisterBank *Src0Bank = RBI.getRegBank(Src0, *MRI, TRI);
673 const RegisterBank *Src1Bank = RBI.getRegBank(Src1, *MRI, TRI);
674 const bool IsVector = DstBank->getID() == AMDGPU::VGPRRegBankID;
675
676 Register ShiftSrc0;
677 Register ShiftSrc1;
678
679 const DebugLoc &DL = MI.getDebugLoc();
680 MachineBasicBlock *BB = MI.getParent();
681
682 // VGPR case
683 if (IsVector) {
684 // If source are both VGPR16, use REG_SEQUENCE with lo16/hi16 subregisters
685 if (Src0Bank->getID() == AMDGPU::VGPRRegBankID &&
686 Src1Bank->getID() == AMDGPU::VGPRRegBankID &&
687 Src0Ty == LLT::scalar(16) && Src1Ty == LLT::scalar(16)) {
688 BuildMI(*BB, MI, DL, TII.get(TargetOpcode::REG_SEQUENCE), Dst)
689 .addReg(Src0)
690 .addImm(AMDGPU::lo16)
691 .addReg(Src1)
692 .addImm(AMDGPU::hi16);
693
694 if (!RBI.constrainGenericRegister(Dst, AMDGPU::VGPR_32RegClass, *MRI))
695 return false;
696
697 MI.eraseFromParent();
698 return true;
699 }
700
701 // Otherwise, use V_LSHL_OR_B32_e64
702 Register TmpReg = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
703 auto MIB = BuildMI(*BB, MI, DL, TII.get(AMDGPU::V_AND_B32_e32), TmpReg)
704 .addImm(0xFFFF)
705 .addReg(Src0);
706 constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
707
708 MIB = BuildMI(*BB, MI, DL, TII.get(AMDGPU::V_LSHL_OR_B32_e64), Dst)
709 .addReg(Src1)
710 .addImm(16)
711 .addReg(TmpReg);
712 constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
713
714 MI.eraseFromParent();
715 return true;
716 }
717
718 // SGPR case -> S_PACK_*_B32_B16
719 // With multiple uses of the shift, this will duplicate the shift and
720 // increase register pressure.
721 //
722 // (merge (lshr_oneuse $src0, 16), (lshr_oneuse $src1, 16)
723 // => (S_PACK_HH_B32_B16 $src0, $src1)
724 // (merge (lshr_oneuse SReg_32:$src0, 16), $src1)
725 // => (S_PACK_HL_B32_B16 $src0, $src1)
726 // (merge $src0, (lshr_oneuse SReg_32:$src1, 16))
727 // => (S_PACK_LH_B32_B16 $src0, $src1)
728 // (merge $src0, $src1)
729 // => (S_PACK_LL_B32_B16 $src0, $src1)
730
731 bool Shift0 = mi_match(
732 Src0, *MRI, m_OneUse(m_GLShr(m_Reg(ShiftSrc0), m_SpecificICst(16))));
733
734 bool Shift1 = mi_match(
735 Src1, *MRI, m_OneUse(m_GLShr(m_Reg(ShiftSrc1), m_SpecificICst(16))));
736
737 unsigned Opc = AMDGPU::S_PACK_LL_B32_B16;
738 if (Shift0 && Shift1) {
739 Opc = AMDGPU::S_PACK_HH_B32_B16;
740 MI.getOperand(1).setReg(ShiftSrc0);
741 MI.getOperand(2).setReg(ShiftSrc1);
742 } else if (Shift1) {
743 Opc = AMDGPU::S_PACK_LH_B32_B16;
744 MI.getOperand(2).setReg(ShiftSrc1);
745 } else if (Shift0) {
746 auto ConstSrc1 =
747 getAnyConstantVRegValWithLookThrough(Src1, *MRI, true, true);
748 if (ConstSrc1 && ConstSrc1->Value == 0) {
749 // build_vector_trunc (lshr $src0, 16), 0 -> s_lshr_b32 $src0, 16
750 auto MIB = BuildMI(*BB, &MI, DL, TII.get(AMDGPU::S_LSHR_B32), Dst)
751 .addReg(ShiftSrc0)
752 .addImm(16)
753 .setOperandDead(3); // Dead scc
754
755 MI.eraseFromParent();
756 constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
757 return true;
758 }
759 if (STI.hasSPackHL()) {
760 Opc = AMDGPU::S_PACK_HL_B32_B16;
761 MI.getOperand(1).setReg(ShiftSrc0);
762 }
763 }
764
765 MI.setDesc(TII.get(Opc));
766 constrainSelectedInstRegOperands(MI, TII, TRI, RBI);
767 return true;
768}
769
770// Pack each pair of s16 into an s32 with S_PACK_LL_B32_B16, then combine the
771// s32 pieces into the destination with a REG_SEQUENCE.
772bool AMDGPUInstructionSelector::selectS16MergeToWide(MachineInstr &MI) const {
773 MachineBasicBlock *BB = MI.getParent();
774 const DebugLoc &DL = MI.getDebugLoc();
775 Register DstReg = MI.getOperand(0).getReg();
776 const uint64_t DstSize = MRI->getType(DstReg).getSizeInBits();
777 const RegisterBank *DstBank = RBI.getRegBank(DstReg, *MRI, TRI);
778 const unsigned NumSrc = MI.getNumOperands() - 1;
779
780 // Pack each pair of s16 sources into an s32.
782 for (unsigned I = 0; I != NumSrc; I += 2) {
783 Register S32 = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
784 auto Pack = BuildMI(*BB, MI, DL, TII.get(AMDGPU::S_PACK_LL_B32_B16), S32)
785 .addReg(MI.getOperand(I + 1).getReg())
786 .addReg(MI.getOperand(I + 2).getReg());
787 constrainSelectedInstRegOperands(*Pack, TII, TRI, RBI);
788 S32Regs.push_back(S32);
789 }
790
791 // Combine the s32 pieces into the destination with a REG_SEQUENCE.
792 const TargetRegisterClass *DstRC =
793 TRI.getRegClassForSizeOnBank(DstSize, *DstBank);
794 if (!DstRC || !RBI.constrainGenericRegister(DstReg, *DstRC, *MRI))
795 return false;
796 ArrayRef<int16_t> SubRegs = TRI.getRegSplitParts(DstRC, /*EltSize=*/4);
797 auto MIB = BuildMI(*BB, MI, DL, TII.get(TargetOpcode::REG_SEQUENCE), DstReg);
798 for (size_t I = 0, E = S32Regs.size(); I != E; ++I)
799 MIB.addReg(S32Regs[I]).addImm(SubRegs[I]);
800
801 MI.eraseFromParent();
802 return true;
803}
804
805bool AMDGPUInstructionSelector::selectG_MERGE_VALUES(MachineInstr &MI) const {
806 MachineBasicBlock *BB = MI.getParent();
807 Register DstReg = MI.getOperand(0).getReg();
808 LLT DstTy = MRI->getType(DstReg);
809 LLT SrcTy = MRI->getType(MI.getOperand(1).getReg());
810
811 const uint64_t SrcSize = SrcTy.getSizeInBits();
812 if (SrcSize < 32) {
813 // Handle s32 <- G_MERGE_VALUES s16, s16
814 if (SrcSize == 16 && DstTy.getSizeInBits() == 32 &&
815 MI.getNumOperands() == 3) {
816 return selectS16MergeToS32(MI);
817 }
818 // With true16 a scalar s16 is a register type, so a scalar wider than 32
819 // bits can be built from s16 pieces.
820 bool IsWideS16Merge = SrcSize == 16 && DstTy.getSizeInBits() > 32 &&
821 DstTy.getSizeInBits() % 32 == 0;
822
823 // SGPRs have no 16-bit subregisters, so pack pairs of s16 with S_PACK.
824 if (IsWideS16Merge &&
825 RBI.getRegBank(DstReg, *MRI, TRI)->getID() != AMDGPU::VGPRRegBankID)
826 return selectS16MergeToWide(MI);
827
828 // A VGPR wide s16 merge falls through to the generic path below.
829 if (!IsWideS16Merge)
830 return selectImpl(MI, *CoverageInfo);
831 }
832
833 const DebugLoc &DL = MI.getDebugLoc();
834 const RegisterBank *DstBank = RBI.getRegBank(DstReg, *MRI, TRI);
835 const uint64_t DstSize = DstTy.getSizeInBits();
836 const TargetRegisterClass *DstRC =
837 TRI.getRegClassForSizeOnBank(DstSize, *DstBank);
838 if (!DstRC)
839 return false;
840
841 unsigned SrcSizeEnc = static_cast<unsigned>(SrcSize);
842 ArrayRef<int16_t> SubRegs = TRI.getRegSplitParts(DstRC, SrcSizeEnc / 8);
843 MachineInstrBuilder MIB =
844 BuildMI(*BB, &MI, DL, TII.get(TargetOpcode::REG_SEQUENCE), DstReg);
845 for (int I = 0, E = MI.getNumOperands() - 1; I != E; ++I) {
846 MachineOperand &Src = MI.getOperand(I + 1);
847 Register SrcReg = Src.getReg();
848 MIB.addReg(SrcReg, getUndefRegState(Src.isUndef()));
849 MIB.addImm(SubRegs[I]);
850
851 const TargetRegisterClass *SrcRC =
852 TRI.getConstrainedRegClassForReg(SrcReg, *MRI);
853 if (SrcRC && !RBI.constrainGenericRegister(SrcReg, *SrcRC, *MRI))
854 return false;
855 }
856
857 if (!RBI.constrainGenericRegister(DstReg, *DstRC, *MRI))
858 return false;
859
860 MI.eraseFromParent();
861 return true;
862}
863
864bool AMDGPUInstructionSelector::selectG_UNMERGE_VALUES(MachineInstr &MI) const {
865 MachineBasicBlock *BB = MI.getParent();
866 const int NumDst = MI.getNumOperands() - 1;
867
868 MachineOperand &Src = MI.getOperand(NumDst);
869
870 Register SrcReg = Src.getReg();
871 Register DstReg0 = MI.getOperand(0).getReg();
872 LLT DstTy = MRI->getType(DstReg0);
873 LLT SrcTy = MRI->getType(SrcReg);
874
875 const uint64_t DstSize = DstTy.getSizeInBits();
876 const uint64_t SrcSize = SrcTy.getSizeInBits();
877 const DebugLoc &DL = MI.getDebugLoc();
878 const RegisterBank *SrcBank = RBI.getRegBank(SrcReg, *MRI, TRI);
879
880 const TargetRegisterClass *SrcRC =
881 TRI.getRegClassForSizeOnBank(SrcSize, *SrcBank);
882
883 // Note we could have mixed SGPR and VGPR destination banks for an SGPR
884 // source, and this relies on the fact that the same subregister indices are
885 // used for both.
886 unsigned DstSizeEnc = static_cast<unsigned>(DstSize);
887 ArrayRef<int16_t> SubRegs = TRI.getRegSplitParts(SrcRC, DstSizeEnc / 8);
888 for (int I = 0, E = NumDst; I != E; ++I) {
889 Register DstReg = MI.getOperand(I).getReg();
890 // hi16:sreg_32 is not allowed so explicitly shift upper 16-bits.
891 if (SrcBank->getID() == AMDGPU::SGPRRegBankID &&
892 SubRegs[I] == AMDGPU::hi16) {
893 BuildMI(*BB, &MI, DL, TII.get(AMDGPU::S_LSHR_B32), DstReg)
894 .addReg(SrcReg)
895 .addImm(16);
896 } else {
897 BuildMI(*BB, &MI, DL, TII.get(TargetOpcode::COPY), DstReg)
898 .addReg(SrcReg, {}, SubRegs[I]);
899
900 // Make sure the subregister index is valid for the source register.
901 SrcRC = TRI.getSubClassWithSubReg(SrcRC, SubRegs[I]);
902 }
903
904 if (!SrcRC || !RBI.constrainGenericRegister(SrcReg, *SrcRC, *MRI))
905 return false;
906
907 const TargetRegisterClass *DstRC =
908 TRI.getConstrainedRegClassForReg(DstReg, *MRI);
909 if (DstRC && !RBI.constrainGenericRegister(DstReg, *DstRC, *MRI))
910 return false;
911 }
912
913 MI.eraseFromParent();
914 return true;
915}
916
917bool AMDGPUInstructionSelector::selectG_BUILD_VECTOR(MachineInstr &MI) const {
918 assert(MI.getOpcode() == AMDGPU::G_BUILD_VECTOR_TRUNC ||
919 MI.getOpcode() == AMDGPU::G_BUILD_VECTOR);
920
921 Register Src0 = MI.getOperand(1).getReg();
922 Register Src1 = MI.getOperand(2).getReg();
923 LLT SrcTy = MRI->getType(Src0);
924 const uint64_t SrcSize = SrcTy.getSizeInBits();
925
926 // BUILD_VECTOR with >=32 bits source is handled by MERGE_VALUE.
927 if (MI.getOpcode() == AMDGPU::G_BUILD_VECTOR && SrcSize >= 32) {
928 return selectG_MERGE_VALUES(MI);
929 }
930
931 // Selection logic below is for V2S16 only.
932 // For G_BUILD_VECTOR_TRUNC, additionally check that the operands are s32.
933 Register Dst = MI.getOperand(0).getReg();
934 if (MRI->getType(Dst) != LLT::fixed_vector(2, 16) ||
935 (MI.getOpcode() == AMDGPU::G_BUILD_VECTOR_TRUNC &&
936 SrcTy != LLT::scalar(32)))
937 return selectImpl(MI, *CoverageInfo);
938
939 const RegisterBank *DstBank = RBI.getRegBank(Dst, *MRI, TRI);
940 if (DstBank->getID() == AMDGPU::AGPRRegBankID)
941 return false;
942
943 assert(DstBank->getID() == AMDGPU::SGPRRegBankID ||
944 DstBank->getID() == AMDGPU::VGPRRegBankID);
945 const bool IsVector = DstBank->getID() == AMDGPU::VGPRRegBankID;
946
947 const DebugLoc &DL = MI.getDebugLoc();
948 MachineBasicBlock *BB = MI.getParent();
949
950 // First, before trying TableGen patterns, check if both sources are
951 // constants. In those cases, we can trivially compute the final constant
952 // and emit a simple move.
953 auto ConstSrc1 = getAnyConstantVRegValWithLookThrough(Src1, *MRI, true, true);
954 if (ConstSrc1) {
955 auto ConstSrc0 =
956 getAnyConstantVRegValWithLookThrough(Src0, *MRI, true, true);
957 if (ConstSrc0) {
958 const int64_t K0 = ConstSrc0->Value.getSExtValue();
959 const int64_t K1 = ConstSrc1->Value.getSExtValue();
960 uint32_t Lo16 = static_cast<uint32_t>(K0) & 0xffff;
961 uint32_t Hi16 = static_cast<uint32_t>(K1) & 0xffff;
962 uint32_t Imm = Lo16 | (Hi16 << 16);
963
964 // VALU
965 if (IsVector) {
966 BuildMI(*BB, &MI, DL, TII.get(AMDGPU::V_MOV_B32_e32), Dst).addImm(Imm);
967 MI.eraseFromParent();
968 return RBI.constrainGenericRegister(Dst, AMDGPU::VGPR_32RegClass, *MRI);
969 }
970
971 // SALU
972 BuildMI(*BB, &MI, DL, TII.get(AMDGPU::S_MOV_B32), Dst).addImm(Imm);
973 MI.eraseFromParent();
974 return RBI.constrainGenericRegister(Dst, AMDGPU::SReg_32RegClass, *MRI);
975 }
976 }
977
978 // Now try TableGen patterns.
979 if (selectImpl(MI, *CoverageInfo))
980 return true;
981
982 // TODO: This should probably be a combine somewhere
983 // (build_vector $src0, undef) -> copy $src0
984 MachineInstr *Src1Def = getDefIgnoringCopies(Src1, *MRI);
985 if (Src1Def->getOpcode() == AMDGPU::G_IMPLICIT_DEF) {
986 MI.setDesc(TII.get(AMDGPU::COPY));
987 MI.removeOperand(2);
988 const auto &RC =
989 IsVector ? AMDGPU::VGPR_32RegClass : AMDGPU::SReg_32RegClass;
990 return RBI.constrainGenericRegister(Dst, RC, *MRI) &&
991 RBI.constrainGenericRegister(Src0, RC, *MRI);
992 }
993
994 return selectS16MergeToS32(MI);
995}
996
997bool AMDGPUInstructionSelector::selectG_IMPLICIT_DEF(MachineInstr &I) const {
998 const MachineOperand &MO = I.getOperand(0);
999
1000 // FIXME: Interface for getConstrainedRegClassForReg needs work. The
1001 // regbank check here is to know why getConstrainedRegClassForReg failed.
1002 const TargetRegisterClass *RC =
1003 TRI.getConstrainedRegClassForReg(MO.getReg(), *MRI);
1004 if ((!RC && !MRI->getRegBankOrNull(MO.getReg())) ||
1005 (RC && RBI.constrainGenericRegister(MO.getReg(), *RC, *MRI))) {
1006 I.setDesc(TII.get(TargetOpcode::IMPLICIT_DEF));
1007 return true;
1008 }
1009
1010 return false;
1011}
1012
1013bool AMDGPUInstructionSelector::selectG_INSERT(MachineInstr &I) const {
1014 MachineBasicBlock *BB = I.getParent();
1015
1016 Register DstReg = I.getOperand(0).getReg();
1017 Register Src0Reg = I.getOperand(1).getReg();
1018 Register Src1Reg = I.getOperand(2).getReg();
1019 LLT Src1Ty = MRI->getType(Src1Reg);
1020
1021 uint64_t DstSize = MRI->getType(DstReg).getSizeInBits();
1022 uint64_t InsSize = Src1Ty.getSizeInBits();
1023
1024 int64_t Offset = I.getOperand(3).getImm();
1025
1026 // FIXME: These cases should have been illegal and unnecessary to check here.
1027 if (Offset % 32 != 0 || InsSize % 32 != 0)
1028 return false;
1029
1030 // Currently not handled by getSubRegFromChannel.
1031 if (InsSize > 128)
1032 return false;
1033
1034 unsigned SubReg = TRI.getSubRegFromChannel(Offset / 32, InsSize / 32);
1035 if (SubReg == AMDGPU::NoSubRegister)
1036 return false;
1037
1038 const RegisterBank *DstBank = RBI.getRegBank(DstReg, *MRI, TRI);
1039 const TargetRegisterClass *DstRC =
1040 TRI.getRegClassForSizeOnBank(DstSize, *DstBank);
1041 if (!DstRC)
1042 return false;
1043
1044 const RegisterBank *Src0Bank = RBI.getRegBank(Src0Reg, *MRI, TRI);
1045 const RegisterBank *Src1Bank = RBI.getRegBank(Src1Reg, *MRI, TRI);
1046 const TargetRegisterClass *Src0RC =
1047 TRI.getRegClassForSizeOnBank(DstSize, *Src0Bank);
1048 const TargetRegisterClass *Src1RC =
1049 TRI.getRegClassForSizeOnBank(InsSize, *Src1Bank);
1050
1051 // Deal with weird cases where the class only partially supports the subreg
1052 // index.
1053 Src0RC = TRI.getSubClassWithSubReg(Src0RC, SubReg);
1054 if (!Src0RC || !Src1RC)
1055 return false;
1056
1057 if (!RBI.constrainGenericRegister(DstReg, *DstRC, *MRI) ||
1058 !RBI.constrainGenericRegister(Src0Reg, *Src0RC, *MRI) ||
1059 !RBI.constrainGenericRegister(Src1Reg, *Src1RC, *MRI))
1060 return false;
1061
1062 const DebugLoc &DL = I.getDebugLoc();
1063 BuildMI(*BB, &I, DL, TII.get(TargetOpcode::INSERT_SUBREG), DstReg)
1064 .addReg(Src0Reg)
1065 .addReg(Src1Reg)
1066 .addImm(SubReg);
1067
1068 I.eraseFromParent();
1069 return true;
1070}
1071
1072bool AMDGPUInstructionSelector::selectG_SBFX_UBFX(MachineInstr &MI) const {
1073 Register DstReg = MI.getOperand(0).getReg();
1074 Register SrcReg = MI.getOperand(1).getReg();
1075 Register OffsetReg = MI.getOperand(2).getReg();
1076 Register WidthReg = MI.getOperand(3).getReg();
1077
1078 assert(RBI.getRegBank(DstReg, *MRI, TRI)->getID() == AMDGPU::VGPRRegBankID &&
1079 "scalar BFX instructions are expanded in regbankselect");
1080 assert(MRI->getType(MI.getOperand(0).getReg()).getSizeInBits() == 32 &&
1081 "64-bit vector BFX instructions are expanded in regbankselect");
1082
1083 const DebugLoc &DL = MI.getDebugLoc();
1084 MachineBasicBlock *MBB = MI.getParent();
1085
1086 bool IsSigned = MI.getOpcode() == TargetOpcode::G_SBFX;
1087 unsigned Opc = IsSigned ? AMDGPU::V_BFE_I32_e64 : AMDGPU::V_BFE_U32_e64;
1088 auto MIB = BuildMI(*MBB, &MI, DL, TII.get(Opc), DstReg)
1089 .addReg(SrcReg)
1090 .addReg(OffsetReg)
1091 .addReg(WidthReg);
1092 MI.eraseFromParent();
1093 constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
1094 return true;
1095}
1096
1097bool AMDGPUInstructionSelector::selectInterpP1F16(MachineInstr &MI) const {
1098 if (STI.getLDSBankCount() != 16)
1099 return selectImpl(MI, *CoverageInfo);
1100
1101 Register Dst = MI.getOperand(0).getReg();
1102 Register Src0 = MI.getOperand(2).getReg();
1103 Register M0Val = MI.getOperand(6).getReg();
1104 if (!RBI.constrainGenericRegister(M0Val, AMDGPU::SReg_32RegClass, *MRI) ||
1105 !RBI.constrainGenericRegister(Dst, AMDGPU::VGPR_32RegClass, *MRI) ||
1106 !RBI.constrainGenericRegister(Src0, AMDGPU::VGPR_32RegClass, *MRI))
1107 return false;
1108
1109 // This requires 2 instructions. It is possible to write a pattern to support
1110 // this, but the generated isel emitter doesn't correctly deal with multiple
1111 // output instructions using the same physical register input. The copy to m0
1112 // is incorrectly placed before the second instruction.
1113 //
1114 // TODO: Match source modifiers.
1115
1116 Register InterpMov = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
1117 const DebugLoc &DL = MI.getDebugLoc();
1118 MachineBasicBlock *MBB = MI.getParent();
1119
1120 BuildMI(*MBB, &MI, DL, TII.get(AMDGPU::COPY), AMDGPU::M0)
1121 .addReg(M0Val);
1122 BuildMI(*MBB, &MI, DL, TII.get(AMDGPU::V_INTERP_MOV_F32), InterpMov)
1123 .addImm(2)
1124 .addImm(MI.getOperand(4).getImm()) // $attr
1125 .addImm(MI.getOperand(3).getImm()); // $attrchan
1126
1127 BuildMI(*MBB, &MI, DL, TII.get(AMDGPU::V_INTERP_P1LV_F16), Dst)
1128 .addImm(0) // $src0_modifiers
1129 .addReg(Src0) // $src0
1130 .addImm(MI.getOperand(4).getImm()) // $attr
1131 .addImm(MI.getOperand(3).getImm()) // $attrchan
1132 .addImm(0) // $src2_modifiers
1133 .addReg(InterpMov) // $src2 - 2 f16 values selected by high
1134 .addImm(MI.getOperand(5).getImm()) // $high
1135 .addImm(0) // $clamp
1136 .addImm(0); // $omod
1137
1138 MI.eraseFromParent();
1139 return true;
1140}
1141
1142// Writelane is special in that it can use SGPR and M0 (which would normally
1143// count as using the constant bus twice - but in this case it is allowed since
1144// the lane selector doesn't count as a use of the constant bus). However, it is
1145// still required to abide by the 1 SGPR rule. Fix this up if we might have
1146// multiple SGPRs.
1147bool AMDGPUInstructionSelector::selectWritelane(MachineInstr &MI) const {
1148 // With a constant bus limit of at least 2, there's no issue.
1149 if (STI.getConstantBusLimit(AMDGPU::V_WRITELANE_B32) > 1)
1150 return selectImpl(MI, *CoverageInfo);
1151
1152 MachineBasicBlock *MBB = MI.getParent();
1153 const DebugLoc &DL = MI.getDebugLoc();
1154 Register VDst = MI.getOperand(0).getReg();
1155 Register Val = MI.getOperand(2).getReg();
1156 Register LaneSelect = MI.getOperand(3).getReg();
1157 Register VDstIn = MI.getOperand(4).getReg();
1158
1159 auto MIB = BuildMI(*MBB, &MI, DL, TII.get(AMDGPU::V_WRITELANE_B32), VDst);
1160
1161 std::optional<ValueAndVReg> ConstSelect =
1162 getIConstantVRegValWithLookThrough(LaneSelect, *MRI);
1163 if (ConstSelect) {
1164 // The selector has to be an inline immediate, so we can use whatever for
1165 // the other operands.
1166 MIB.addReg(Val);
1167 MIB.addImm(ConstSelect->Value.getSExtValue() &
1168 maskTrailingOnes<uint64_t>(STI.getWavefrontSizeLog2()));
1169 } else {
1170 std::optional<ValueAndVReg> ConstVal =
1172
1173 // If the value written is an inline immediate, we can get away without a
1174 // copy to m0.
1175 if (ConstVal && AMDGPU::isInlinableLiteral32(
1176 static_cast<int32_t>(ConstVal->Value.getSExtValue()),
1177 STI.hasInv2PiInlineImm())) {
1178 MIB.addImm(ConstVal->Value.getSExtValue());
1179 MIB.addReg(LaneSelect);
1180 } else {
1181 MIB.addReg(Val);
1182
1183 // If the lane selector was originally in a VGPR and copied with
1184 // readfirstlane, there's a hazard to read the same SGPR from the
1185 // VALU. Constrain to a different SGPR to help avoid needing a nop later.
1186 RBI.constrainGenericRegister(LaneSelect, AMDGPU::SReg_32_XM0RegClass, *MRI);
1187
1188 BuildMI(*MBB, *MIB, DL, TII.get(AMDGPU::COPY), AMDGPU::M0)
1189 .addReg(LaneSelect);
1190 MIB.addReg(AMDGPU::M0);
1191 }
1192 }
1193
1194 MIB.addReg(VDstIn);
1195
1196 MI.eraseFromParent();
1197 constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
1198 return true;
1199}
1200
1201// We need to handle this here because tablegen doesn't support matching
1202// instructions with multiple outputs.
1203bool AMDGPUInstructionSelector::selectDivScale(MachineInstr &MI) const {
1204 Register Dst0 = MI.getOperand(0).getReg();
1205 Register Dst1 = MI.getOperand(1).getReg();
1206
1207 LLT Ty = MRI->getType(Dst0);
1208 unsigned Opc;
1209 if (Ty == LLT::scalar(32))
1210 Opc = AMDGPU::V_DIV_SCALE_F32_e64;
1211 else if (Ty == LLT::scalar(64))
1212 Opc = AMDGPU::V_DIV_SCALE_F64_e64;
1213 else
1214 return false;
1215
1216 // TODO: Match source modifiers.
1217
1218 const DebugLoc &DL = MI.getDebugLoc();
1219 MachineBasicBlock *MBB = MI.getParent();
1220
1221 Register Numer = MI.getOperand(3).getReg();
1222 Register Denom = MI.getOperand(4).getReg();
1223 unsigned ChooseDenom = static_cast<unsigned>(MI.getOperand(5).getImm());
1224
1225 Register Src0 = ChooseDenom != 0 ? Numer : Denom;
1226
1227 auto MIB = BuildMI(*MBB, &MI, DL, TII.get(Opc), Dst0)
1228 .addDef(Dst1)
1229 .addImm(0) // $src0_modifiers
1230 .addUse(Src0) // $src0
1231 .addImm(0) // $src1_modifiers
1232 .addUse(Denom) // $src1
1233 .addImm(0) // $src2_modifiers
1234 .addUse(Numer) // $src2
1235 .addImm(0) // $clamp
1236 .addImm(0); // $omod
1237
1238 MI.eraseFromParent();
1239 constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
1240 return true;
1241}
1242
1243bool AMDGPUInstructionSelector::selectG_INTRINSIC(MachineInstr &I) const {
1244 Intrinsic::ID IntrinsicID = cast<GIntrinsic>(I).getIntrinsicID();
1245 switch (IntrinsicID) {
1246 case Intrinsic::amdgcn_if_break: {
1247 MachineBasicBlock *BB = I.getParent();
1248
1249 // FIXME: Manually selecting to avoid dealing with the SReg_1 trick
1250 // SelectionDAG uses for wave32 vs wave64.
1251 BuildMI(*BB, &I, I.getDebugLoc(), TII.get(AMDGPU::SI_IF_BREAK))
1252 .add(I.getOperand(0))
1253 .add(I.getOperand(2))
1254 .add(I.getOperand(3))
1255 .setOperandDead(3); // implicit-def $scc
1256
1257 Register DstReg = I.getOperand(0).getReg();
1258 Register Src0Reg = I.getOperand(2).getReg();
1259 Register Src1Reg = I.getOperand(3).getReg();
1260
1261 I.eraseFromParent();
1262
1263 for (Register Reg : { DstReg, Src0Reg, Src1Reg })
1264 MRI->setRegClass(Reg, TRI.getWaveMaskRegClass());
1265
1266 return true;
1267 }
1268 case Intrinsic::amdgcn_interp_p1_f16:
1269 return selectInterpP1F16(I);
1270 case Intrinsic::amdgcn_wqm:
1271 return constrainCopyLikeIntrin(I, AMDGPU::WQM);
1272 case Intrinsic::amdgcn_softwqm:
1273 return constrainCopyLikeIntrin(I, AMDGPU::SOFT_WQM);
1274 case Intrinsic::amdgcn_strict_wwm:
1275 case Intrinsic::amdgcn_wwm:
1276 return constrainCopyLikeIntrin(I, AMDGPU::STRICT_WWM);
1277 case Intrinsic::amdgcn_strict_wqm:
1278 return constrainCopyLikeIntrin(I, AMDGPU::STRICT_WQM);
1279 case Intrinsic::amdgcn_writelane:
1280 return selectWritelane(I);
1281 case Intrinsic::amdgcn_div_scale:
1282 return selectDivScale(I);
1283 case Intrinsic::amdgcn_ballot:
1284 return selectBallot(I);
1285 case Intrinsic::amdgcn_reloc_constant:
1286 return selectRelocConstant(I);
1287 case Intrinsic::amdgcn_groupstaticsize:
1288 return selectGroupStaticSize(I);
1289 case Intrinsic::returnaddress:
1290 return selectReturnAddress(I);
1291 case Intrinsic::amdgcn_smfmac_f32_16x16x32_f16:
1292 case Intrinsic::amdgcn_smfmac_f32_32x32x16_f16:
1293 case Intrinsic::amdgcn_smfmac_f32_16x16x32_bf16:
1294 case Intrinsic::amdgcn_smfmac_f32_32x32x16_bf16:
1295 case Intrinsic::amdgcn_smfmac_i32_16x16x64_i8:
1296 case Intrinsic::amdgcn_smfmac_i32_32x32x32_i8:
1297 case Intrinsic::amdgcn_smfmac_f32_16x16x64_bf8_bf8:
1298 case Intrinsic::amdgcn_smfmac_f32_16x16x64_bf8_fp8:
1299 case Intrinsic::amdgcn_smfmac_f32_16x16x64_fp8_bf8:
1300 case Intrinsic::amdgcn_smfmac_f32_16x16x64_fp8_fp8:
1301 case Intrinsic::amdgcn_smfmac_f32_32x32x32_bf8_bf8:
1302 case Intrinsic::amdgcn_smfmac_f32_32x32x32_bf8_fp8:
1303 case Intrinsic::amdgcn_smfmac_f32_32x32x32_fp8_bf8:
1304 case Intrinsic::amdgcn_smfmac_f32_32x32x32_fp8_fp8:
1305 case Intrinsic::amdgcn_smfmac_f32_16x16x64_f16:
1306 case Intrinsic::amdgcn_smfmac_f32_32x32x32_f16:
1307 case Intrinsic::amdgcn_smfmac_f32_16x16x64_bf16:
1308 case Intrinsic::amdgcn_smfmac_f32_32x32x32_bf16:
1309 case Intrinsic::amdgcn_smfmac_i32_16x16x128_i8:
1310 case Intrinsic::amdgcn_smfmac_i32_32x32x64_i8:
1311 case Intrinsic::amdgcn_smfmac_f32_16x16x128_bf8_bf8:
1312 case Intrinsic::amdgcn_smfmac_f32_16x16x128_bf8_fp8:
1313 case Intrinsic::amdgcn_smfmac_f32_16x16x128_fp8_bf8:
1314 case Intrinsic::amdgcn_smfmac_f32_16x16x128_fp8_fp8:
1315 case Intrinsic::amdgcn_smfmac_f32_32x32x64_bf8_bf8:
1316 case Intrinsic::amdgcn_smfmac_f32_32x32x64_bf8_fp8:
1317 case Intrinsic::amdgcn_smfmac_f32_32x32x64_fp8_bf8:
1318 case Intrinsic::amdgcn_smfmac_f32_32x32x64_fp8_fp8:
1319 return selectSMFMACIntrin(I);
1320 case Intrinsic::amdgcn_permlane16_swap:
1321 case Intrinsic::amdgcn_permlane32_swap:
1322 return selectPermlaneSwapIntrin(I, IntrinsicID);
1323 case Intrinsic::amdgcn_wave_shuffle:
1324 return selectWaveShuffleIntrin(I);
1325 default:
1326 return selectImpl(I, *CoverageInfo);
1327 }
1328}
1329
1331 const GCNSubtarget &ST) {
1332 if (Size != 16 && Size != 32 && Size != 64)
1333 return -1;
1334
1335 if (Size == 16 && !ST.has16BitInsts())
1336 return -1;
1337
1338 const auto Select = [&](unsigned S16Opc, unsigned TrueS16Opc,
1339 unsigned FakeS16Opc, unsigned S32Opc,
1340 unsigned S64Opc) {
1341 if (Size == 16)
1342 return ST.hasTrue16BitInsts()
1343 ? ST.useRealTrue16Insts() ? TrueS16Opc : FakeS16Opc
1344 : S16Opc;
1345 if (Size == 32)
1346 return S32Opc;
1347 return S64Opc;
1348 };
1349
1350 switch (P) {
1351 default:
1352 llvm_unreachable("Unknown condition code!");
1353 case CmpInst::ICMP_NE:
1354 return Select(AMDGPU::V_CMP_NE_U16_e64, AMDGPU::V_CMP_NE_U16_t16_e64,
1355 AMDGPU::V_CMP_NE_U16_fake16_e64, AMDGPU::V_CMP_NE_U32_e64,
1356 AMDGPU::V_CMP_NE_U64_e64);
1357 case CmpInst::ICMP_EQ:
1358 return Select(AMDGPU::V_CMP_EQ_U16_e64, AMDGPU::V_CMP_EQ_U16_t16_e64,
1359 AMDGPU::V_CMP_EQ_U16_fake16_e64, AMDGPU::V_CMP_EQ_U32_e64,
1360 AMDGPU::V_CMP_EQ_U64_e64);
1361 case CmpInst::ICMP_SGT:
1362 return Select(AMDGPU::V_CMP_GT_I16_e64, AMDGPU::V_CMP_GT_I16_t16_e64,
1363 AMDGPU::V_CMP_GT_I16_fake16_e64, AMDGPU::V_CMP_GT_I32_e64,
1364 AMDGPU::V_CMP_GT_I64_e64);
1365 case CmpInst::ICMP_SGE:
1366 return Select(AMDGPU::V_CMP_GE_I16_e64, AMDGPU::V_CMP_GE_I16_t16_e64,
1367 AMDGPU::V_CMP_GE_I16_fake16_e64, AMDGPU::V_CMP_GE_I32_e64,
1368 AMDGPU::V_CMP_GE_I64_e64);
1369 case CmpInst::ICMP_SLT:
1370 return Select(AMDGPU::V_CMP_LT_I16_e64, AMDGPU::V_CMP_LT_I16_t16_e64,
1371 AMDGPU::V_CMP_LT_I16_fake16_e64, AMDGPU::V_CMP_LT_I32_e64,
1372 AMDGPU::V_CMP_LT_I64_e64);
1373 case CmpInst::ICMP_SLE:
1374 return Select(AMDGPU::V_CMP_LE_I16_e64, AMDGPU::V_CMP_LE_I16_t16_e64,
1375 AMDGPU::V_CMP_LE_I16_fake16_e64, AMDGPU::V_CMP_LE_I32_e64,
1376 AMDGPU::V_CMP_LE_I64_e64);
1377 case CmpInst::ICMP_UGT:
1378 return Select(AMDGPU::V_CMP_GT_U16_e64, AMDGPU::V_CMP_GT_U16_t16_e64,
1379 AMDGPU::V_CMP_GT_U16_fake16_e64, AMDGPU::V_CMP_GT_U32_e64,
1380 AMDGPU::V_CMP_GT_U64_e64);
1381 case CmpInst::ICMP_UGE:
1382 return Select(AMDGPU::V_CMP_GE_U16_e64, AMDGPU::V_CMP_GE_U16_t16_e64,
1383 AMDGPU::V_CMP_GE_U16_fake16_e64, AMDGPU::V_CMP_GE_U32_e64,
1384 AMDGPU::V_CMP_GE_U64_e64);
1385 case CmpInst::ICMP_ULT:
1386 return Select(AMDGPU::V_CMP_LT_U16_e64, AMDGPU::V_CMP_LT_U16_t16_e64,
1387 AMDGPU::V_CMP_LT_U16_fake16_e64, AMDGPU::V_CMP_LT_U32_e64,
1388 AMDGPU::V_CMP_LT_U64_e64);
1389 case CmpInst::ICMP_ULE:
1390 return Select(AMDGPU::V_CMP_LE_U16_e64, AMDGPU::V_CMP_LE_U16_t16_e64,
1391 AMDGPU::V_CMP_LE_U16_fake16_e64, AMDGPU::V_CMP_LE_U32_e64,
1392 AMDGPU::V_CMP_LE_U64_e64);
1393
1394 case CmpInst::FCMP_OEQ:
1395 return Select(AMDGPU::V_CMP_EQ_F16_e64, AMDGPU::V_CMP_EQ_F16_t16_e64,
1396 AMDGPU::V_CMP_EQ_F16_fake16_e64, AMDGPU::V_CMP_EQ_F32_e64,
1397 AMDGPU::V_CMP_EQ_F64_e64);
1398 case CmpInst::FCMP_OGT:
1399 return Select(AMDGPU::V_CMP_GT_F16_e64, AMDGPU::V_CMP_GT_F16_t16_e64,
1400 AMDGPU::V_CMP_GT_F16_fake16_e64, AMDGPU::V_CMP_GT_F32_e64,
1401 AMDGPU::V_CMP_GT_F64_e64);
1402 case CmpInst::FCMP_OGE:
1403 return Select(AMDGPU::V_CMP_GE_F16_e64, AMDGPU::V_CMP_GE_F16_t16_e64,
1404 AMDGPU::V_CMP_GE_F16_fake16_e64, AMDGPU::V_CMP_GE_F32_e64,
1405 AMDGPU::V_CMP_GE_F64_e64);
1406 case CmpInst::FCMP_OLT:
1407 return Select(AMDGPU::V_CMP_LT_F16_e64, AMDGPU::V_CMP_LT_F16_t16_e64,
1408 AMDGPU::V_CMP_LT_F16_fake16_e64, AMDGPU::V_CMP_LT_F32_e64,
1409 AMDGPU::V_CMP_LT_F64_e64);
1410 case CmpInst::FCMP_OLE:
1411 return Select(AMDGPU::V_CMP_LE_F16_e64, AMDGPU::V_CMP_LE_F16_t16_e64,
1412 AMDGPU::V_CMP_LE_F16_fake16_e64, AMDGPU::V_CMP_LE_F32_e64,
1413 AMDGPU::V_CMP_LE_F64_e64);
1414 case CmpInst::FCMP_ONE:
1415 return Select(AMDGPU::V_CMP_NEQ_F16_e64, AMDGPU::V_CMP_NEQ_F16_t16_e64,
1416 AMDGPU::V_CMP_NEQ_F16_fake16_e64, AMDGPU::V_CMP_NEQ_F32_e64,
1417 AMDGPU::V_CMP_NEQ_F64_e64);
1418 case CmpInst::FCMP_ORD:
1419 return Select(AMDGPU::V_CMP_O_F16_e64, AMDGPU::V_CMP_O_F16_t16_e64,
1420 AMDGPU::V_CMP_O_F16_fake16_e64, AMDGPU::V_CMP_O_F32_e64,
1421 AMDGPU::V_CMP_O_F64_e64);
1422 case CmpInst::FCMP_UNO:
1423 return Select(AMDGPU::V_CMP_U_F16_e64, AMDGPU::V_CMP_U_F16_t16_e64,
1424 AMDGPU::V_CMP_U_F16_fake16_e64, AMDGPU::V_CMP_U_F32_e64,
1425 AMDGPU::V_CMP_U_F64_e64);
1426 case CmpInst::FCMP_UEQ:
1427 return Select(AMDGPU::V_CMP_NLG_F16_e64, AMDGPU::V_CMP_NLG_F16_t16_e64,
1428 AMDGPU::V_CMP_NLG_F16_fake16_e64, AMDGPU::V_CMP_NLG_F32_e64,
1429 AMDGPU::V_CMP_NLG_F64_e64);
1430 case CmpInst::FCMP_UGT:
1431 return Select(AMDGPU::V_CMP_NLE_F16_e64, AMDGPU::V_CMP_NLE_F16_t16_e64,
1432 AMDGPU::V_CMP_NLE_F16_fake16_e64, AMDGPU::V_CMP_NLE_F32_e64,
1433 AMDGPU::V_CMP_NLE_F64_e64);
1434 case CmpInst::FCMP_UGE:
1435 return Select(AMDGPU::V_CMP_NLT_F16_e64, AMDGPU::V_CMP_NLT_F16_t16_e64,
1436 AMDGPU::V_CMP_NLT_F16_fake16_e64, AMDGPU::V_CMP_NLT_F32_e64,
1437 AMDGPU::V_CMP_NLT_F64_e64);
1438 case CmpInst::FCMP_ULT:
1439 return Select(AMDGPU::V_CMP_NGE_F16_e64, AMDGPU::V_CMP_NGE_F16_t16_e64,
1440 AMDGPU::V_CMP_NGE_F16_fake16_e64, AMDGPU::V_CMP_NGE_F32_e64,
1441 AMDGPU::V_CMP_NGE_F64_e64);
1442 case CmpInst::FCMP_ULE:
1443 return Select(AMDGPU::V_CMP_NGT_F16_e64, AMDGPU::V_CMP_NGT_F16_t16_e64,
1444 AMDGPU::V_CMP_NGT_F16_fake16_e64, AMDGPU::V_CMP_NGT_F32_e64,
1445 AMDGPU::V_CMP_NGT_F64_e64);
1446 case CmpInst::FCMP_UNE:
1447 return Select(AMDGPU::V_CMP_NEQ_F16_e64, AMDGPU::V_CMP_NEQ_F16_t16_e64,
1448 AMDGPU::V_CMP_NEQ_F16_fake16_e64, AMDGPU::V_CMP_NEQ_F32_e64,
1449 AMDGPU::V_CMP_NEQ_F64_e64);
1450 case CmpInst::FCMP_TRUE:
1451 return Select(AMDGPU::V_CMP_TRU_F16_e64, AMDGPU::V_CMP_TRU_F16_t16_e64,
1452 AMDGPU::V_CMP_TRU_F16_fake16_e64, AMDGPU::V_CMP_TRU_F32_e64,
1453 AMDGPU::V_CMP_TRU_F64_e64);
1455 return Select(AMDGPU::V_CMP_F_F16_e64, AMDGPU::V_CMP_F_F16_t16_e64,
1456 AMDGPU::V_CMP_F_F16_fake16_e64, AMDGPU::V_CMP_F_F32_e64,
1457 AMDGPU::V_CMP_F_F64_e64);
1458 }
1459}
1460
1461int AMDGPUInstructionSelector::getS_CMPOpcode(CmpInst::Predicate P,
1462 uint64_t Size) const {
1463 if (Size == 64) {
1464 if (!STI.hasScalarCompareEq64())
1465 return -1;
1466
1467 switch (P) {
1468 case CmpInst::ICMP_NE:
1469 return AMDGPU::S_CMP_LG_U64;
1470 case CmpInst::ICMP_EQ:
1471 return AMDGPU::S_CMP_EQ_U64;
1472 default:
1473 return -1;
1474 }
1475 }
1476
1477 if (Size == 32) {
1478 switch (P) {
1479 case CmpInst::ICMP_NE:
1480 return AMDGPU::S_CMP_LG_U32;
1481 case CmpInst::ICMP_EQ:
1482 return AMDGPU::S_CMP_EQ_U32;
1483 case CmpInst::ICMP_SGT:
1484 return AMDGPU::S_CMP_GT_I32;
1485 case CmpInst::ICMP_SGE:
1486 return AMDGPU::S_CMP_GE_I32;
1487 case CmpInst::ICMP_SLT:
1488 return AMDGPU::S_CMP_LT_I32;
1489 case CmpInst::ICMP_SLE:
1490 return AMDGPU::S_CMP_LE_I32;
1491 case CmpInst::ICMP_UGT:
1492 return AMDGPU::S_CMP_GT_U32;
1493 case CmpInst::ICMP_UGE:
1494 return AMDGPU::S_CMP_GE_U32;
1495 case CmpInst::ICMP_ULT:
1496 return AMDGPU::S_CMP_LT_U32;
1497 case CmpInst::ICMP_ULE:
1498 return AMDGPU::S_CMP_LE_U32;
1499 case CmpInst::FCMP_OEQ:
1500 return AMDGPU::S_CMP_EQ_F32;
1501 case CmpInst::FCMP_OGT:
1502 return AMDGPU::S_CMP_GT_F32;
1503 case CmpInst::FCMP_OGE:
1504 return AMDGPU::S_CMP_GE_F32;
1505 case CmpInst::FCMP_OLT:
1506 return AMDGPU::S_CMP_LT_F32;
1507 case CmpInst::FCMP_OLE:
1508 return AMDGPU::S_CMP_LE_F32;
1509 case CmpInst::FCMP_ONE:
1510 return AMDGPU::S_CMP_LG_F32;
1511 case CmpInst::FCMP_ORD:
1512 return AMDGPU::S_CMP_O_F32;
1513 case CmpInst::FCMP_UNO:
1514 return AMDGPU::S_CMP_U_F32;
1515 case CmpInst::FCMP_UEQ:
1516 return AMDGPU::S_CMP_NLG_F32;
1517 case CmpInst::FCMP_UGT:
1518 return AMDGPU::S_CMP_NLE_F32;
1519 case CmpInst::FCMP_UGE:
1520 return AMDGPU::S_CMP_NLT_F32;
1521 case CmpInst::FCMP_ULT:
1522 return AMDGPU::S_CMP_NGE_F32;
1523 case CmpInst::FCMP_ULE:
1524 return AMDGPU::S_CMP_NGT_F32;
1525 case CmpInst::FCMP_UNE:
1526 return AMDGPU::S_CMP_NEQ_F32;
1527 default:
1528 llvm_unreachable("Unknown condition code!");
1529 }
1530 }
1531
1532 if (Size == 16) {
1533 if (!STI.hasSALUFloatInsts())
1534 return -1;
1535
1536 switch (P) {
1537 case CmpInst::FCMP_OEQ:
1538 return AMDGPU::S_CMP_EQ_F16;
1539 case CmpInst::FCMP_OGT:
1540 return AMDGPU::S_CMP_GT_F16;
1541 case CmpInst::FCMP_OGE:
1542 return AMDGPU::S_CMP_GE_F16;
1543 case CmpInst::FCMP_OLT:
1544 return AMDGPU::S_CMP_LT_F16;
1545 case CmpInst::FCMP_OLE:
1546 return AMDGPU::S_CMP_LE_F16;
1547 case CmpInst::FCMP_ONE:
1548 return AMDGPU::S_CMP_LG_F16;
1549 case CmpInst::FCMP_ORD:
1550 return AMDGPU::S_CMP_O_F16;
1551 case CmpInst::FCMP_UNO:
1552 return AMDGPU::S_CMP_U_F16;
1553 case CmpInst::FCMP_UEQ:
1554 return AMDGPU::S_CMP_NLG_F16;
1555 case CmpInst::FCMP_UGT:
1556 return AMDGPU::S_CMP_NLE_F16;
1557 case CmpInst::FCMP_UGE:
1558 return AMDGPU::S_CMP_NLT_F16;
1559 case CmpInst::FCMP_ULT:
1560 return AMDGPU::S_CMP_NGE_F16;
1561 case CmpInst::FCMP_ULE:
1562 return AMDGPU::S_CMP_NGT_F16;
1563 case CmpInst::FCMP_UNE:
1564 return AMDGPU::S_CMP_NEQ_F16;
1565 default:
1566 llvm_unreachable("Unknown condition code!");
1567 }
1568 }
1569
1570 return -1;
1571}
1572
1573bool AMDGPUInstructionSelector::selectG_ICMP_or_FCMP(MachineInstr &I) const {
1574
1575 MachineBasicBlock *BB = I.getParent();
1576 const DebugLoc &DL = I.getDebugLoc();
1577
1578 Register SrcReg = I.getOperand(2).getReg();
1579 uint64_t Size = TRI.getRegSizeInBits(SrcReg, *MRI);
1580
1581 auto Pred = (CmpInst::Predicate)I.getOperand(1).getPredicate();
1582
1583 Register CCReg = I.getOperand(0).getReg();
1584 if (!isVCC(CCReg, *MRI)) {
1585 int Opcode = getS_CMPOpcode(Pred, Size);
1586 if (Opcode == -1)
1587 return false;
1588 MachineInstr *ICmp = BuildMI(*BB, &I, DL, TII.get(Opcode))
1589 .add(I.getOperand(2))
1590 .add(I.getOperand(3));
1591 BuildMI(*BB, &I, DL, TII.get(AMDGPU::COPY), CCReg)
1592 .addReg(AMDGPU::SCC);
1593 constrainSelectedInstRegOperands(*ICmp, TII, TRI, RBI);
1594 bool Ret =
1595 RBI.constrainGenericRegister(CCReg, AMDGPU::SReg_32RegClass, *MRI);
1596 I.eraseFromParent();
1597 return Ret;
1598 }
1599
1600 if (I.getOpcode() == AMDGPU::G_FCMP)
1601 return false;
1602
1603 int Opcode = getV_CMPOpcode(Pred, Size, *Subtarget);
1604 if (Opcode == -1)
1605 return false;
1606
1607 MachineInstrBuilder ICmp;
1608 // t16 instructions
1609 if (AMDGPU::hasNamedOperand(Opcode, AMDGPU::OpName::src0_modifiers)) {
1610 ICmp = BuildMI(*BB, &I, DL, TII.get(Opcode), I.getOperand(0).getReg())
1611 .addImm(0)
1612 .add(I.getOperand(2))
1613 .addImm(0)
1614 .add(I.getOperand(3))
1615 .addImm(0); // op_sel
1616 } else {
1617 ICmp = BuildMI(*BB, &I, DL, TII.get(Opcode), I.getOperand(0).getReg())
1618 .add(I.getOperand(2))
1619 .add(I.getOperand(3));
1620 }
1621
1622 RBI.constrainGenericRegister(ICmp->getOperand(0).getReg(),
1623 *TRI.getBoolRC(), *MRI);
1624 constrainSelectedInstRegOperands(*ICmp, TII, TRI, RBI);
1625 I.eraseFromParent();
1626 return true;
1627}
1628
1629// Ballot has to zero bits in input lane-mask that are zero in current exec,
1630// Done as AND with exec. For inputs that are results of instruction that
1631// implicitly use same exec, for example compares in same basic block or SCC to
1632// VCC copy, use copy.
1635 MachineInstr *MI = MRI.getVRegDef(Reg);
1636 if (MI->getParent() != MBB)
1637 return false;
1638
1639 // Lane mask generated by SCC to VCC copy.
1640 if (MI->getOpcode() == AMDGPU::COPY) {
1641 auto DstRB = MRI.getRegBankOrNull(MI->getOperand(0).getReg());
1642 auto SrcRB = MRI.getRegBankOrNull(MI->getOperand(1).getReg());
1643 if (DstRB && SrcRB && DstRB->getID() == AMDGPU::VCCRegBankID &&
1644 SrcRB->getID() == AMDGPU::SGPRRegBankID)
1645 return true;
1646 }
1647
1648 // Lane mask generated by SCC to VCC copy
1649 if (MI->getOpcode() == AMDGPU::G_AMDGPU_COPY_VCC_SCC)
1650 return true;
1651
1652 // Lane mask generated using compare with same exec.
1653 if (isa<GAnyCmp>(MI))
1654 return true;
1655
1656 Register LHS, RHS;
1657 // Look through AND.
1658 if (mi_match(Reg, MRI, m_GAnd(m_Reg(LHS), m_Reg(RHS))))
1659 return isLaneMaskFromSameBlock(LHS, MRI, MBB) ||
1661
1662 return false;
1663}
1664
1665bool AMDGPUInstructionSelector::selectBallot(MachineInstr &I) const {
1666 MachineBasicBlock *BB = I.getParent();
1667 const DebugLoc &DL = I.getDebugLoc();
1668 Register DstReg = I.getOperand(0).getReg();
1669 Register SrcReg = I.getOperand(2).getReg();
1670 const uint64_t BallotSize = MRI->getType(DstReg).getSizeInBits();
1671 const unsigned WaveSize = STI.getWavefrontSize();
1672
1673 // In the common case, the return type matches the wave size.
1674 // However we also support emitting i64 ballots in wave32 mode.
1675 if (BallotSize != WaveSize && (BallotSize != 64 || WaveSize != 32))
1676 return false;
1677
1678 std::optional<ValueAndVReg> Arg =
1680
1681 Register Dst = DstReg;
1682 // i64 ballot on Wave32: new Dst(i32) for WaveSize ballot.
1683 if (BallotSize != WaveSize) {
1684 Dst = MRI->createVirtualRegister(TRI.getBoolRC());
1685 }
1686
1687 if (Arg) {
1688 const int64_t Value = Arg->Value.getZExtValue();
1689 if (Value == 0) {
1690 // Dst = S_MOV 0
1691 unsigned Opcode = WaveSize == 64 ? AMDGPU::S_MOV_B64 : AMDGPU::S_MOV_B32;
1692 BuildMI(*BB, &I, DL, TII.get(Opcode), Dst).addImm(0);
1693 } else {
1694 // Dst = COPY EXEC
1695 assert(Value == 1);
1696 BuildMI(*BB, &I, DL, TII.get(AMDGPU::COPY), Dst).addReg(TRI.getExec());
1697 }
1698 if (!RBI.constrainGenericRegister(Dst, *TRI.getBoolRC(), *MRI))
1699 return false;
1700 } else {
1701 if (isLaneMaskFromSameBlock(SrcReg, *MRI, BB)) {
1702 // Dst = COPY SrcReg
1703 BuildMI(*BB, &I, DL, TII.get(AMDGPU::COPY), Dst).addReg(SrcReg);
1704 if (!RBI.constrainGenericRegister(Dst, *TRI.getBoolRC(), *MRI))
1705 return false;
1706 } else {
1707 // Dst = S_AND SrcReg, EXEC
1708 unsigned AndOpc = WaveSize == 64 ? AMDGPU::S_AND_B64 : AMDGPU::S_AND_B32;
1709 auto And = BuildMI(*BB, &I, DL, TII.get(AndOpc), Dst)
1710 .addReg(SrcReg)
1711 .addReg(TRI.getExec())
1712 .setOperandDead(3); // Dead scc
1713 constrainSelectedInstRegOperands(*And, TII, TRI, RBI);
1714 }
1715 }
1716
1717 // i64 ballot on Wave32: zero-extend i32 ballot to i64.
1718 if (BallotSize != WaveSize) {
1719 Register HiReg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
1720 BuildMI(*BB, &I, DL, TII.get(AMDGPU::S_MOV_B32), HiReg).addImm(0);
1721 BuildMI(*BB, &I, DL, TII.get(AMDGPU::REG_SEQUENCE), DstReg)
1722 .addReg(Dst)
1723 .addImm(AMDGPU::sub0)
1724 .addReg(HiReg)
1725 .addImm(AMDGPU::sub1);
1726 }
1727
1728 I.eraseFromParent();
1729 return true;
1730}
1731
1732bool AMDGPUInstructionSelector::selectRelocConstant(MachineInstr &I) const {
1733 Register DstReg = I.getOperand(0).getReg();
1734 const RegisterBank *DstBank = RBI.getRegBank(DstReg, *MRI, TRI);
1735 const TargetRegisterClass *DstRC = TRI.getRegClassForSizeOnBank(32, *DstBank);
1736 if (!DstRC || !RBI.constrainGenericRegister(DstReg, *DstRC, *MRI))
1737 return false;
1738
1739 const bool IsVALU = DstBank->getID() == AMDGPU::VGPRRegBankID;
1740
1741 Module *M = MF->getFunction().getParent();
1742 const MDNode *Metadata = I.getOperand(2).getMetadata();
1743 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
1744 auto *RelocSymbol = cast<GlobalVariable>(
1745 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
1746
1747 MachineBasicBlock *BB = I.getParent();
1748 BuildMI(*BB, &I, I.getDebugLoc(),
1749 TII.get(IsVALU ? AMDGPU::V_MOV_B32_e32 : AMDGPU::S_MOV_B32), DstReg)
1751
1752 I.eraseFromParent();
1753 return true;
1754}
1755
1756bool AMDGPUInstructionSelector::selectGroupStaticSize(MachineInstr &I) const {
1757 Triple::OSType OS = MF->getTarget().getTargetTriple().getOS();
1758
1759 Register DstReg = I.getOperand(0).getReg();
1760 const RegisterBank *DstRB = RBI.getRegBank(DstReg, *MRI, TRI);
1761 unsigned Mov = DstRB->getID() == AMDGPU::SGPRRegBankID ?
1762 AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32;
1763
1764 MachineBasicBlock *MBB = I.getParent();
1765 const DebugLoc &DL = I.getDebugLoc();
1766
1767 auto MIB = BuildMI(*MBB, &I, DL, TII.get(Mov), DstReg);
1768
1769 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) {
1770 const SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
1771 MIB.addImm(MFI->getLDSSize());
1772 } else {
1773 Module *M = MF->getFunction().getParent();
1774 const GlobalValue *GV =
1775 Intrinsic::getOrInsertDeclaration(M, Intrinsic::amdgcn_groupstaticsize);
1777 }
1778
1779 I.eraseFromParent();
1780 constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
1781 return true;
1782}
1783
1784bool AMDGPUInstructionSelector::selectReturnAddress(MachineInstr &I) const {
1785 MachineBasicBlock *MBB = I.getParent();
1787 const DebugLoc &DL = I.getDebugLoc();
1788
1789 Register DstReg = I.getOperand(0).getReg();
1790 unsigned Depth = static_cast<unsigned>(I.getOperand(2).getImm());
1791
1792 const TargetRegisterClass *RC =
1793 TRI.getConstrainedRegClassForReg(DstReg, *MRI);
1794 if (!RC->hasSubClassEq(&AMDGPU::SGPR_64RegClass) ||
1795 !RBI.constrainGenericRegister(DstReg, *RC, *MRI))
1796 return false;
1797
1798 // Check for kernel and shader functions
1799 if (Depth != 0 ||
1800 MF.getInfo<SIMachineFunctionInfo>()->isEntryFunction()) {
1801 BuildMI(*MBB, &I, DL, TII.get(AMDGPU::S_MOV_B64), DstReg)
1802 .addImm(0);
1803 I.eraseFromParent();
1804 return true;
1805 }
1806
1807 MachineFrameInfo &MFI = MF.getFrameInfo();
1808 // There is a call to @llvm.returnaddress in this function
1809 MFI.setReturnAddressIsTaken(true);
1810
1811 // Get the return address reg and mark it as an implicit live-in
1812 Register ReturnAddrReg = TRI.getReturnAddressReg(MF);
1813 Register LiveIn = getFunctionLiveInPhysReg(MF, TII, ReturnAddrReg,
1814 AMDGPU::SReg_64RegClass, DL);
1815 BuildMI(*MBB, &I, DL, TII.get(AMDGPU::COPY), DstReg)
1816 .addReg(LiveIn);
1817 I.eraseFromParent();
1818 return true;
1819}
1820
1821bool AMDGPUInstructionSelector::selectEndCfIntrinsic(MachineInstr &MI) const {
1822 // FIXME: Manually selecting to avoid dealing with the SReg_1 trick
1823 // SelectionDAG uses for wave32 vs wave64.
1824 MachineBasicBlock *BB = MI.getParent();
1825 BuildMI(*BB, &MI, MI.getDebugLoc(), TII.get(AMDGPU::SI_END_CF))
1826 .add(MI.getOperand(1))
1827 .setOperandDead(2); // implicit-def $scc
1828
1829 Register Reg = MI.getOperand(1).getReg();
1830 MI.eraseFromParent();
1831
1832 if (!MRI->getRegClassOrNull(Reg))
1833 MRI->setRegClass(Reg, TRI.getWaveMaskRegClass());
1834 return true;
1835}
1836
1837bool AMDGPUInstructionSelector::selectDSOrderedIntrinsic(
1838 MachineInstr &MI, Intrinsic::ID IntrID) const {
1839 MachineBasicBlock *MBB = MI.getParent();
1841 const DebugLoc &DL = MI.getDebugLoc();
1842
1843 unsigned IndexOperand = static_cast<unsigned>(MI.getOperand(7).getImm());
1844 bool WaveRelease = MI.getOperand(8).getImm() != 0;
1845 bool WaveDone = MI.getOperand(9).getImm() != 0;
1846
1847 if (WaveDone && !WaveRelease) {
1848 // TODO: Move this to IR verifier
1849 const Function &Fn = MF->getFunction();
1850 Fn.getContext().diagnose(DiagnosticInfoUnsupported(
1851 Fn, "ds_ordered_count: wave_done requires wave_release", DL));
1852 }
1853
1854 unsigned OrderedCountIndex = IndexOperand & 0x3f;
1855 IndexOperand &= ~0x3f;
1856 unsigned CountDw = 0;
1857
1858 if (STI.getGeneration() >= AMDGPUSubtarget::GFX10) {
1859 CountDw = (IndexOperand >> 24) & 0xf;
1860 IndexOperand &= ~(0xf << 24);
1861
1862 if (CountDw < 1 || CountDw > 4) {
1863 const Function &Fn = MF->getFunction();
1864 Fn.getContext().diagnose(DiagnosticInfoUnsupported(
1865 Fn, "ds_ordered_count: dword count must be between 1 and 4", DL));
1866 CountDw = 1;
1867 }
1868 }
1869
1870 if (IndexOperand) {
1871 const Function &Fn = MF->getFunction();
1872 Fn.getContext().diagnose(DiagnosticInfoUnsupported(
1873 Fn, "ds_ordered_count: bad index operand", DL));
1874 }
1875
1876 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
1877 unsigned ShaderType = SIInstrInfo::getDSShaderTypeValue(*MF);
1878
1879 unsigned Offset0 = OrderedCountIndex << 2;
1880 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (Instruction << 4);
1881
1882 if (STI.getGeneration() >= AMDGPUSubtarget::GFX10)
1883 Offset1 |= (CountDw - 1) << 6;
1884
1885 if (STI.getGeneration() < AMDGPUSubtarget::GFX11)
1886 Offset1 |= ShaderType << 2;
1887
1888 unsigned Offset = Offset0 | (Offset1 << 8);
1889
1890 Register M0Val = MI.getOperand(2).getReg();
1891 BuildMI(*MBB, &MI, DL, TII.get(AMDGPU::COPY), AMDGPU::M0)
1892 .addReg(M0Val);
1893
1894 Register DstReg = MI.getOperand(0).getReg();
1895 Register ValReg = MI.getOperand(3).getReg();
1896 MachineInstrBuilder DS =
1897 BuildMI(*MBB, &MI, DL, TII.get(AMDGPU::DS_ORDERED_COUNT), DstReg)
1898 .addReg(ValReg)
1899 .addImm(Offset)
1900 .cloneMemRefs(MI);
1901
1902 if (!RBI.constrainGenericRegister(M0Val, AMDGPU::SReg_32RegClass, *MRI))
1903 return false;
1904
1905 constrainSelectedInstRegOperands(*DS, TII, TRI, RBI);
1906 MI.eraseFromParent();
1907 return true;
1908}
1909
1910static unsigned gwsIntrinToOpcode(unsigned IntrID) {
1911 switch (IntrID) {
1912 case Intrinsic::amdgcn_ds_gws_init:
1913 return AMDGPU::DS_GWS_INIT;
1914 case Intrinsic::amdgcn_ds_gws_barrier:
1915 return AMDGPU::DS_GWS_BARRIER;
1916 case Intrinsic::amdgcn_ds_gws_sema_v:
1917 return AMDGPU::DS_GWS_SEMA_V;
1918 case Intrinsic::amdgcn_ds_gws_sema_br:
1919 return AMDGPU::DS_GWS_SEMA_BR;
1920 case Intrinsic::amdgcn_ds_gws_sema_p:
1921 return AMDGPU::DS_GWS_SEMA_P;
1922 case Intrinsic::amdgcn_ds_gws_sema_release_all:
1923 return AMDGPU::DS_GWS_SEMA_RELEASE_ALL;
1924 default:
1925 llvm_unreachable("not a gws intrinsic");
1926 }
1927}
1928
1929bool AMDGPUInstructionSelector::selectDSGWSIntrinsic(MachineInstr &MI,
1930 Intrinsic::ID IID) const {
1931 if (!STI.hasGWS() || (IID == Intrinsic::amdgcn_ds_gws_sema_release_all &&
1932 !STI.hasGWSSemaReleaseAll()))
1933 return false;
1934
1935 // intrinsic ID, vsrc, offset
1936 const bool HasVSrc = MI.getNumOperands() == 3;
1937 assert(HasVSrc || MI.getNumOperands() == 2);
1938
1939 Register BaseOffset = MI.getOperand(HasVSrc ? 2 : 1).getReg();
1940 const RegisterBank *OffsetRB = RBI.getRegBank(BaseOffset, *MRI, TRI);
1941 if (OffsetRB->getID() != AMDGPU::SGPRRegBankID)
1942 return false;
1943
1944 MachineInstr *OffsetDef = getDefIgnoringCopies(BaseOffset, *MRI);
1945 unsigned ImmOffset;
1946
1947 MachineBasicBlock *MBB = MI.getParent();
1948 const DebugLoc &DL = MI.getDebugLoc();
1949
1950 MachineInstr *Readfirstlane = nullptr;
1951
1952 // If we legalized the VGPR input, strip out the readfirstlane to analyze the
1953 // incoming offset, in case there's an add of a constant. We'll have to put it
1954 // back later.
1955 if (OffsetDef->getOpcode() == AMDGPU::V_READFIRSTLANE_B32) {
1956 Readfirstlane = OffsetDef;
1957 BaseOffset = OffsetDef->getOperand(1).getReg();
1958 OffsetDef = getDefIgnoringCopies(BaseOffset, *MRI);
1959 }
1960
1961 if (OffsetDef->getOpcode() == AMDGPU::G_CONSTANT) {
1962 // If we have a constant offset, try to use the 0 in m0 as the base.
1963 // TODO: Look into changing the default m0 initialization value. If the
1964 // default -1 only set the low 16-bits, we could leave it as-is and add 1 to
1965 // the immediate offset.
1966
1967 ImmOffset = static_cast<unsigned>(
1968 OffsetDef->getOperand(1).getCImm()->getZExtValue());
1969 BuildMI(*MBB, &MI, DL, TII.get(AMDGPU::S_MOV_B32), AMDGPU::M0)
1970 .addImm(0);
1971 } else {
1972 std::tie(BaseOffset, ImmOffset) =
1973 AMDGPU::getBaseWithConstantOffset(*MRI, BaseOffset, VT);
1974
1975 if (Readfirstlane) {
1976 // We have the constant offset now, so put the readfirstlane back on the
1977 // variable component.
1978 if (!RBI.constrainGenericRegister(BaseOffset, AMDGPU::VGPR_32RegClass, *MRI))
1979 return false;
1980
1981 Readfirstlane->getOperand(1).setReg(BaseOffset);
1982 BaseOffset = Readfirstlane->getOperand(0).getReg();
1983 } else {
1984 if (!RBI.constrainGenericRegister(BaseOffset,
1985 AMDGPU::SReg_32RegClass, *MRI))
1986 return false;
1987 }
1988
1989 Register M0Base = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
1990 BuildMI(*MBB, &MI, DL, TII.get(AMDGPU::S_LSHL_B32), M0Base)
1991 .addReg(BaseOffset)
1992 .addImm(16)
1993 .setOperandDead(3); // Dead scc
1994
1995 BuildMI(*MBB, &MI, DL, TII.get(AMDGPU::COPY), AMDGPU::M0)
1996 .addReg(M0Base);
1997 }
1998
1999 // The resource id offset is computed as (<isa opaque base> + M0[21:16] +
2000 // offset field) % 64. Some versions of the programming guide omit the m0
2001 // part, or claim it's from offset 0.
2002
2003 unsigned Opc = gwsIntrinToOpcode(IID);
2004 const MCInstrDesc &InstrDesc = TII.get(Opc);
2005
2006 if (HasVSrc) {
2007 Register VSrc = MI.getOperand(1).getReg();
2008
2009 int Data0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::data0);
2010 const TargetRegisterClass *DataRC = TII.getRegClass(InstrDesc, Data0Idx);
2011 const TargetRegisterClass *SubRC =
2012 TRI.getSubRegisterClass(DataRC, AMDGPU::sub0);
2013
2014 if (!SubRC) {
2015 // 32-bit normal case.
2016 if (!RBI.constrainGenericRegister(VSrc, *DataRC, *MRI))
2017 return false;
2018
2019 BuildMI(*MBB, &MI, DL, InstrDesc)
2020 .addReg(VSrc)
2021 .addImm(ImmOffset)
2022 .cloneMemRefs(MI);
2023 } else {
2024 // Requires even register alignment, so create 64-bit value and pad the
2025 // top half with undef.
2026 Register DataReg = MRI->createVirtualRegister(DataRC);
2027 if (!RBI.constrainGenericRegister(VSrc, *SubRC, *MRI))
2028 return false;
2029
2030 Register UndefReg = MRI->createVirtualRegister(SubRC);
2031 BuildMI(*MBB, &MI, DL, TII.get(AMDGPU::IMPLICIT_DEF), UndefReg);
2032 BuildMI(*MBB, &MI, DL, TII.get(AMDGPU::REG_SEQUENCE), DataReg)
2033 .addReg(VSrc)
2034 .addImm(AMDGPU::sub0)
2035 .addReg(UndefReg)
2036 .addImm(AMDGPU::sub1);
2037
2038 BuildMI(*MBB, &MI, DL, InstrDesc)
2039 .addReg(DataReg)
2040 .addImm(ImmOffset)
2041 .cloneMemRefs(MI);
2042 }
2043 } else {
2044 BuildMI(*MBB, &MI, DL, InstrDesc)
2045 .addImm(ImmOffset)
2046 .cloneMemRefs(MI);
2047 }
2048
2049 MI.eraseFromParent();
2050 return true;
2051}
2052
2053bool AMDGPUInstructionSelector::selectDSAppendConsume(MachineInstr &MI,
2054 bool IsAppend) const {
2055 Register PtrBase = MI.getOperand(2).getReg();
2056 LLT PtrTy = MRI->getType(PtrBase);
2057 bool IsGDS = PtrTy.getAddressSpace() == AMDGPUAS::REGION_ADDRESS;
2058
2059 int64_t Offset;
2060 std::tie(PtrBase, Offset) = selectDS1Addr1OffsetImpl(MI.getOperand(2));
2061
2062 // TODO: Should this try to look through readfirstlane like GWS?
2063 if (!isDSOffsetLegal(PtrBase, Offset)) {
2064 PtrBase = MI.getOperand(2).getReg();
2065 Offset = 0;
2066 }
2067
2068 MachineBasicBlock *MBB = MI.getParent();
2069 const DebugLoc &DL = MI.getDebugLoc();
2070 const unsigned Opc = IsAppend ? AMDGPU::DS_APPEND : AMDGPU::DS_CONSUME;
2071
2072 BuildMI(*MBB, &MI, DL, TII.get(AMDGPU::COPY), AMDGPU::M0)
2073 .addReg(PtrBase);
2074 if (!RBI.constrainGenericRegister(PtrBase, AMDGPU::SReg_32RegClass, *MRI))
2075 return false;
2076
2077 auto MIB = BuildMI(*MBB, &MI, DL, TII.get(Opc), MI.getOperand(0).getReg())
2078 .addImm(Offset)
2079 .addImm(IsGDS ? -1 : 0)
2080 .cloneMemRefs(MI);
2081 MI.eraseFromParent();
2082 constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
2083 return true;
2084}
2085
2086bool AMDGPUInstructionSelector::selectInitWholeWave(MachineInstr &MI) const {
2087 MachineFunction *MF = MI.getMF();
2088 SIMachineFunctionInfo *MFInfo = MF->getInfo<SIMachineFunctionInfo>();
2089
2090 MFInfo->setInitWholeWave();
2091 return selectImpl(MI, *CoverageInfo);
2092}
2093
2094static bool parseTexFail(uint64_t TexFailCtrl, bool &TFE, bool &LWE,
2095 bool &IsTexFail) {
2096 if (TexFailCtrl)
2097 IsTexFail = true;
2098
2099 TFE = TexFailCtrl & 0x1;
2100 TexFailCtrl &= ~(uint64_t)0x1;
2101 LWE = TexFailCtrl & 0x2;
2102 TexFailCtrl &= ~(uint64_t)0x2;
2103
2104 return TexFailCtrl == 0;
2105}
2106
2107bool AMDGPUInstructionSelector::selectImageIntrinsic(
2108 MachineInstr &MI, const AMDGPU::ImageDimIntrinsicInfo *Intr) const {
2109 MachineBasicBlock *MBB = MI.getParent();
2110 const DebugLoc &DL = MI.getDebugLoc();
2111 unsigned IntrOpcode = Intr->BaseOpcode;
2112
2113 // For image atomic: use no-return opcode if result is unused.
2114 if (Intr->AtomicNoRetBaseOpcode != Intr->BaseOpcode) {
2115 Register ResultDef = MI.getOperand(0).getReg();
2116 if (MRI->use_nodbg_empty(ResultDef))
2117 IntrOpcode = Intr->AtomicNoRetBaseOpcode;
2118 }
2119
2120 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
2122
2123 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
2124 const bool IsGFX10Plus = AMDGPU::isGFX10Plus(STI);
2125 const bool IsGFX11Plus = AMDGPU::isGFX11Plus(STI);
2126 const bool IsGFX12Plus = AMDGPU::isGFX12Plus(STI);
2127 const bool IsGFX13Plus = AMDGPU::isGFX13Plus(STI);
2128
2129 const unsigned ArgOffset = MI.getNumExplicitDefs() + 1;
2130
2131 Register VDataIn = AMDGPU::NoRegister;
2132 Register VDataOut = AMDGPU::NoRegister;
2133 LLT VDataTy;
2134 int NumVDataDwords = -1;
2135 bool IsD16 = MI.getOpcode() == AMDGPU::G_AMDGPU_INTRIN_IMAGE_LOAD_D16 ||
2136 MI.getOpcode() == AMDGPU::G_AMDGPU_INTRIN_IMAGE_STORE_D16;
2137
2138 bool Unorm;
2139 if (!BaseOpcode->Sampler)
2140 Unorm = true;
2141 else
2142 Unorm = MI.getOperand(ArgOffset + Intr->UnormIndex).getImm() != 0;
2143
2144 bool TFE;
2145 bool LWE;
2146 bool IsTexFail = false;
2147 if (!parseTexFail(MI.getOperand(ArgOffset + Intr->TexFailCtrlIndex).getImm(),
2148 TFE, LWE, IsTexFail))
2149 return false;
2150
2151 const int64_t Flags = MI.getOperand(ArgOffset + Intr->NumArgs).getImm();
2152 const bool IsA16 = (Flags & 1) != 0;
2153 const bool IsG16 = (Flags & 2) != 0;
2154
2155 // A16 implies 16 bit gradients if subtarget doesn't support G16
2156 if (IsA16 && !STI.hasG16() && !IsG16)
2157 return false;
2158
2159 unsigned DMask = 0;
2160 unsigned DMaskLanes = 0;
2161
2162 if (BaseOpcode->Atomic) {
2163 if (!BaseOpcode->NoReturn)
2164 VDataOut = MI.getOperand(0).getReg();
2165 VDataIn = MI.getOperand(2).getReg();
2166 LLT Ty = MRI->getType(VDataIn);
2167
2168 // Be careful to allow atomic swap on 16-bit element vectors.
2169 const bool Is64Bit = BaseOpcode->AtomicX2 ?
2170 Ty.getSizeInBits() == 128 :
2171 Ty.getSizeInBits() == 64;
2172
2173 if (BaseOpcode->AtomicX2) {
2174 assert(MI.getOperand(3).getReg() == AMDGPU::NoRegister);
2175
2176 DMask = Is64Bit ? 0xf : 0x3;
2177 NumVDataDwords = Is64Bit ? 4 : 2;
2178 } else {
2179 DMask = Is64Bit ? 0x3 : 0x1;
2180 NumVDataDwords = Is64Bit ? 2 : 1;
2181 }
2182 } else {
2183 DMask = static_cast<unsigned>(
2184 MI.getOperand(ArgOffset + Intr->DMaskIndex).getImm());
2185 DMaskLanes = BaseOpcode->Gather4 ? 4 : llvm::popcount(DMask);
2186
2187 if (BaseOpcode->Store) {
2188 VDataIn = MI.getOperand(1).getReg();
2189 VDataTy = MRI->getType(VDataIn);
2190 NumVDataDwords = static_cast<int>((VDataTy.getSizeInBits() + 31) / 32);
2191 } else if (BaseOpcode->NoReturn) {
2192 NumVDataDwords = 0;
2193 } else {
2194 VDataOut = MI.getOperand(0).getReg();
2195 VDataTy = MRI->getType(VDataOut);
2196 NumVDataDwords = DMaskLanes;
2197
2198 if (IsD16 && !STI.hasUnpackedD16VMem())
2199 NumVDataDwords = (DMaskLanes + 1) / 2;
2200 }
2201 }
2202
2203 // Set G16 opcode
2204 if (Subtarget->hasG16() && IsG16) {
2205 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
2207 assert(G16MappingInfo);
2208 IntrOpcode = G16MappingInfo->G16; // set opcode to variant with _g16
2209 }
2210
2211 // TODO: Check this in verifier.
2212 assert((!IsTexFail || DMaskLanes >= 1) && "should have legalized this");
2213
2214 unsigned CPol = static_cast<unsigned>(
2215 MI.getOperand(ArgOffset + Intr->CachePolicyIndex).getImm());
2216 // Keep GLC only when the atomic's result is actually used.
2217 if (BaseOpcode->Atomic && !BaseOpcode->NoReturn)
2219 if (CPol & ~((IsGFX12Plus ? AMDGPU::CPol::ALL : AMDGPU::CPol::ALL_pregfx12) |
2221 return false;
2222
2223 int NumVAddrRegs = 0;
2224 int NumVAddrDwords = 0;
2225 for (unsigned I = Intr->VAddrStart; I < Intr->VAddrEnd; I++) {
2226 // Skip the $noregs and 0s inserted during legalization.
2227 MachineOperand &AddrOp = MI.getOperand(ArgOffset + I);
2228 if (!AddrOp.isReg())
2229 continue; // XXX - Break?
2230
2231 Register Addr = AddrOp.getReg();
2232 if (!Addr)
2233 break;
2234
2235 ++NumVAddrRegs;
2236 NumVAddrDwords +=
2237 static_cast<int>((MRI->getType(Addr).getSizeInBits() + 31) / 32);
2238 }
2239
2240 // The legalizer preprocessed the intrinsic arguments. If we aren't using
2241 // NSA, these should have been packed into a single value in the first
2242 // address register
2243 const bool UseNSA =
2244 NumVAddrRegs != 1 &&
2245 (STI.hasPartialNSAEncoding() ? NumVAddrDwords >= NumVAddrRegs
2246 : NumVAddrDwords == NumVAddrRegs);
2247 if (UseNSA && !STI.hasFeature(AMDGPU::FeatureNSAEncoding)) {
2248 LLVM_DEBUG(dbgs() << "Trying to use NSA on non-NSA target\n");
2249 return false;
2250 }
2251
2252 if (IsTexFail)
2253 ++NumVDataDwords;
2254
2255 int Opcode = -1;
2256 if (IsGFX13Plus) {
2257 Register RsrcReg = MI.getOperand(ArgOffset + Intr->RsrcIndex).getReg();
2258 const LLT I32 = LLT::integer(32);
2259 bool IndexedRsrc = MRI->getType(RsrcReg) == I32;
2260 bool IndexedSamp = false;
2261 if (BaseOpcode->Sampler) {
2262 Register SampReg = MI.getOperand(ArgOffset + Intr->SampIndex).getReg();
2263 IndexedSamp = MRI->getType(SampReg) == I32;
2264 }
2265 Opcode =
2266 AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx13, NumVDataDwords,
2267 NumVAddrDwords, IndexedRsrc, IndexedSamp);
2268 } else if (IsGFX12Plus) {
2269 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx12,
2270 NumVDataDwords, NumVAddrDwords);
2271 } else if (IsGFX11Plus) {
2272 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
2273 UseNSA ? AMDGPU::MIMGEncGfx11NSA
2274 : AMDGPU::MIMGEncGfx11Default,
2275 NumVDataDwords, NumVAddrDwords);
2276 } else if (IsGFX10Plus) {
2277 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
2278 UseNSA ? AMDGPU::MIMGEncGfx10NSA
2279 : AMDGPU::MIMGEncGfx10Default,
2280 NumVDataDwords, NumVAddrDwords);
2281 } else {
2282 if (Subtarget->hasGFX90AInsts()) {
2283 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
2284 NumVDataDwords, NumVAddrDwords);
2285 if (Opcode == -1) {
2286 LLVM_DEBUG(
2287 dbgs()
2288 << "requested image instruction is not supported on this GPU\n");
2289 return false;
2290 }
2291 }
2292 if (Opcode == -1 &&
2293 STI.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
2294 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
2295 NumVDataDwords, NumVAddrDwords);
2296 if (Opcode == -1)
2297 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
2298 NumVDataDwords, NumVAddrDwords);
2299 }
2300 if (Opcode == -1)
2301 return false;
2302
2303 auto MIB = BuildMI(*MBB, &MI, DL, TII.get(Opcode))
2304 .cloneMemRefs(MI);
2305
2306 if (VDataOut) {
2307 if (BaseOpcode->AtomicX2) {
2308 const bool Is64 = MRI->getType(VDataOut).getSizeInBits() == 64;
2309
2310 Register TmpReg = MRI->createVirtualRegister(
2311 Is64 ? &AMDGPU::VReg_128RegClass : &AMDGPU::VReg_64RegClass);
2312 unsigned SubReg = Is64 ? AMDGPU::sub0_sub1 : AMDGPU::sub0;
2313
2314 MIB.addDef(TmpReg);
2315 if (!MRI->use_empty(VDataOut)) {
2316 BuildMI(*MBB, &MI, DL, TII.get(AMDGPU::COPY), VDataOut)
2317 .addReg(TmpReg, {}, SubReg);
2318 }
2319
2320 } else {
2321 MIB.addDef(VDataOut); // vdata output
2322 }
2323 }
2324
2325 if (VDataIn)
2326 MIB.addReg(VDataIn); // vdata input
2327
2328 for (int I = 0; I != NumVAddrRegs; ++I) {
2329 MachineOperand &SrcOp = MI.getOperand(ArgOffset + Intr->VAddrStart + I);
2330 if (SrcOp.isReg()) {
2331 assert(SrcOp.getReg() != 0);
2332 MIB.addReg(SrcOp.getReg());
2333 }
2334 }
2335
2336 MIB.addReg(MI.getOperand(ArgOffset + Intr->RsrcIndex).getReg());
2337 if (BaseOpcode->Sampler)
2338 MIB.addReg(MI.getOperand(ArgOffset + Intr->SampIndex).getReg());
2339
2340 MIB.addImm(DMask); // dmask
2341
2342 if (IsGFX10Plus)
2343 MIB.addImm(DimInfo->Encoding);
2344 if (AMDGPU::hasNamedOperand(Opcode, AMDGPU::OpName::unorm))
2345 MIB.addImm(Unorm);
2346
2347 MIB.addImm(CPol);
2348 MIB.addImm(IsA16 && // a16 or r128
2349 STI.hasFeature(AMDGPU::FeatureR128A16) ? -1 : 0);
2350 if (IsGFX10Plus)
2351 MIB.addImm(IsA16 ? -1 : 0);
2352
2353 if (!Subtarget->hasGFX90AInsts()) {
2354 MIB.addImm(TFE); // tfe
2355 } else if (TFE) {
2356 LLVM_DEBUG(dbgs() << "TFE is not supported on this GPU\n");
2357 return false;
2358 }
2359
2360 if (AMDGPU::hasNamedOperand(Opcode, AMDGPU::OpName::lwe))
2361 MIB.addImm(LWE); // lwe
2362 if (!IsGFX10Plus)
2363 MIB.addImm(DimInfo->DA ? -1 : 0);
2364 if (BaseOpcode->HasD16)
2365 MIB.addImm(IsD16 ? -1 : 0);
2366
2367 MI.eraseFromParent();
2368 constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
2369 TII.enforceOperandRCAlignment(*MIB, AMDGPU::OpName::vaddr);
2370 return true;
2371}
2372
2373// We need to handle this here because tablegen doesn't support matching
2374// instructions with multiple outputs.
2375bool AMDGPUInstructionSelector::selectDSBvhStackIntrinsic(
2376 MachineInstr &MI) const {
2377 Register Dst0 = MI.getOperand(0).getReg();
2378 Register Dst1 = MI.getOperand(1).getReg();
2379
2380 const DebugLoc &DL = MI.getDebugLoc();
2381 MachineBasicBlock *MBB = MI.getParent();
2382
2383 Register Addr = MI.getOperand(3).getReg();
2384 Register Data0 = MI.getOperand(4).getReg();
2385 Register Data1 = MI.getOperand(5).getReg();
2386 unsigned Offset = static_cast<unsigned>(MI.getOperand(6).getImm());
2387
2388 unsigned Opc;
2389 switch (cast<GIntrinsic>(MI).getIntrinsicID()) {
2390 case Intrinsic::amdgcn_ds_bvh_stack_rtn:
2391 case Intrinsic::amdgcn_ds_bvh_stack_push4_pop1_rtn:
2392 Opc = AMDGPU::DS_BVH_STACK_RTN_B32;
2393 break;
2394 case Intrinsic::amdgcn_ds_bvh_stack_push8_pop1_rtn:
2395 Opc = AMDGPU::DS_BVH_STACK_PUSH8_POP1_RTN_B32;
2396 break;
2397 case Intrinsic::amdgcn_ds_bvh_stack_push8_pop2_rtn:
2398 Opc = AMDGPU::DS_BVH_STACK_PUSH8_POP2_RTN_B64;
2399 break;
2400 }
2401
2402 auto MIB = BuildMI(*MBB, &MI, DL, TII.get(Opc), Dst0)
2403 .addDef(Dst1)
2404 .addUse(Addr)
2405 .addUse(Data0)
2406 .addUse(Data1)
2407 .addImm(Offset)
2408 .cloneMemRefs(MI);
2409
2410 MI.eraseFromParent();
2411 constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
2412 return true;
2413}
2414
2415bool AMDGPUInstructionSelector::selectG_INTRINSIC_W_SIDE_EFFECTS(
2416 MachineInstr &I) const {
2417 Intrinsic::ID IntrinsicID = cast<GIntrinsic>(I).getIntrinsicID();
2418 if (const AMDGPU::BufferIntrinsicInfo *BufInfo =
2419 AMDGPU::lookupBufferIntrinsic(IntrinsicID);
2420 BufInfo && BufInfo->Kind == AMDGPU::BufferKindLoadToLDS)
2421 return selectBufferLoadLds(I, *BufInfo);
2422
2423 switch (IntrinsicID) {
2424 case Intrinsic::amdgcn_end_cf:
2425 return selectEndCfIntrinsic(I);
2426 case Intrinsic::amdgcn_ds_ordered_add:
2427 case Intrinsic::amdgcn_ds_ordered_swap:
2428 return selectDSOrderedIntrinsic(I, IntrinsicID);
2429 case Intrinsic::amdgcn_ds_gws_init:
2430 case Intrinsic::amdgcn_ds_gws_barrier:
2431 case Intrinsic::amdgcn_ds_gws_sema_v:
2432 case Intrinsic::amdgcn_ds_gws_sema_br:
2433 case Intrinsic::amdgcn_ds_gws_sema_p:
2434 case Intrinsic::amdgcn_ds_gws_sema_release_all:
2435 return selectDSGWSIntrinsic(I, IntrinsicID);
2436 case Intrinsic::amdgcn_ds_append:
2437 return selectDSAppendConsume(I, true);
2438 case Intrinsic::amdgcn_ds_consume:
2439 return selectDSAppendConsume(I, false);
2440 case Intrinsic::amdgcn_init_whole_wave:
2441 return selectInitWholeWave(I);
2442 // Buffer sources are lowered in IR. Generic sources must point into global
2443 // memory.
2444 case Intrinsic::amdgcn_load_to_lds:
2445 case Intrinsic::amdgcn_load_async_to_lds:
2446 case Intrinsic::amdgcn_global_load_lds:
2447 case Intrinsic::amdgcn_global_load_async_lds:
2448 return selectGlobalLoadLds(I);
2449 case Intrinsic::amdgcn_tensor_load_to_lds:
2450 case Intrinsic::amdgcn_tensor_store_from_lds:
2451 return selectTensorLoadStore(I, IntrinsicID);
2452 case Intrinsic::amdgcn_asyncmark:
2453 case Intrinsic::amdgcn_wait_asyncmark:
2454 if (!Subtarget->hasAsyncMark())
2455 return false;
2456 break;
2457 case Intrinsic::amdgcn_ds_bvh_stack_rtn:
2458 case Intrinsic::amdgcn_ds_bvh_stack_push4_pop1_rtn:
2459 case Intrinsic::amdgcn_ds_bvh_stack_push8_pop1_rtn:
2460 case Intrinsic::amdgcn_ds_bvh_stack_push8_pop2_rtn:
2461 return selectDSBvhStackIntrinsic(I);
2462 case Intrinsic::amdgcn_s_alloc_vgpr: {
2463 // S_ALLOC_VGPR doesn't have a destination register, it just implicitly sets
2464 // SCC. We then need to COPY it into the result vreg.
2465 MachineBasicBlock *MBB = I.getParent();
2466 const DebugLoc &DL = I.getDebugLoc();
2467
2468 Register ResReg = I.getOperand(0).getReg();
2469
2470 MachineInstr *AllocMI = BuildMI(*MBB, &I, DL, TII.get(AMDGPU::S_ALLOC_VGPR))
2471 .add(I.getOperand(2));
2472 (void)BuildMI(*MBB, &I, DL, TII.get(AMDGPU::COPY), ResReg)
2473 .addReg(AMDGPU::SCC);
2474 I.eraseFromParent();
2475 constrainSelectedInstRegOperands(*AllocMI, TII, TRI, RBI);
2476 return RBI.constrainGenericRegister(ResReg, AMDGPU::SReg_32RegClass, *MRI);
2477 }
2478 case Intrinsic::amdgcn_s_barrier_init:
2479 case Intrinsic::amdgcn_s_barrier_signal_var:
2480 return selectNamedBarrierInit(I, IntrinsicID);
2481 case Intrinsic::amdgcn_s_wakeup_barrier:
2482 case Intrinsic::amdgcn_s_barrier_join:
2483 case Intrinsic::amdgcn_s_get_named_barrier_state:
2484 return selectNamedBarrierInst(I, IntrinsicID);
2485 case Intrinsic::amdgcn_s_get_barrier_state:
2486 return selectSGetBarrierState(I, IntrinsicID);
2487 case Intrinsic::amdgcn_s_barrier_signal_isfirst:
2488 return selectSBarrierSignalIsfirst(I, IntrinsicID);
2489 }
2490 return selectImpl(I, *CoverageInfo);
2491}
2492
2493bool AMDGPUInstructionSelector::selectG_SELECT(MachineInstr &I) const {
2494 if (selectImpl(I, *CoverageInfo))
2495 return true;
2496
2497 MachineBasicBlock *BB = I.getParent();
2498 const DebugLoc &DL = I.getDebugLoc();
2499
2500 Register DstReg = I.getOperand(0).getReg();
2501 uint64_t Size = TRI.getRegSizeInBits(DstReg, *MRI);
2502 assert(Size <= 32 || Size == 64);
2503 const MachineOperand &CCOp = I.getOperand(1);
2504 Register CCReg = CCOp.getReg();
2505 if (!isVCC(CCReg, *MRI)) {
2506 unsigned SelectOpcode = Size == 64 ? AMDGPU::S_CSELECT_B64 :
2507 AMDGPU::S_CSELECT_B32;
2508 MachineInstr *CopySCC = BuildMI(*BB, &I, DL, TII.get(AMDGPU::COPY), AMDGPU::SCC)
2509 .addReg(CCReg);
2510
2511 // The generic constrainSelectedInstRegOperands doesn't work for the scc register
2512 // bank, because it does not cover the register class that we used to represent
2513 // for it. So we need to manually set the register class here.
2514 if (!MRI->getRegClassOrNull(CCReg))
2515 MRI->setRegClass(CCReg, TRI.getConstrainedRegClassForReg(CCReg, *MRI));
2516 MachineInstr *Select = BuildMI(*BB, &I, DL, TII.get(SelectOpcode), DstReg)
2517 .add(I.getOperand(2))
2518 .add(I.getOperand(3));
2519
2521 constrainSelectedInstRegOperands(*CopySCC, TII, TRI, RBI);
2522 I.eraseFromParent();
2523 return true;
2524 }
2525
2526 // Wide VGPR select should have been split in RegBankSelect.
2527 if (Size > 32)
2528 return false;
2529
2530 MachineInstr *Select =
2531 BuildMI(*BB, &I, DL, TII.get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
2532 .addImm(0)
2533 .add(I.getOperand(3))
2534 .addImm(0)
2535 .add(I.getOperand(2))
2536 .add(I.getOperand(1));
2537
2539 I.eraseFromParent();
2540 return true;
2541}
2542
2543bool AMDGPUInstructionSelector::selectG_TRUNC(MachineInstr &I) const {
2544 Register DstReg = I.getOperand(0).getReg();
2545 Register SrcReg = I.getOperand(1).getReg();
2546 const LLT DstTy = MRI->getType(DstReg);
2547 const LLT SrcTy = MRI->getType(SrcReg);
2548 const LLT S1 = LLT::scalar(1);
2549
2550 const RegisterBank *SrcRB = RBI.getRegBank(SrcReg, *MRI, TRI);
2551 const RegisterBank *DstRB;
2552 if (DstTy == S1) {
2553 // This is a special case. We don't treat s1 for legalization artifacts as
2554 // vcc booleans.
2555 DstRB = SrcRB;
2556 } else {
2557 DstRB = RBI.getRegBank(DstReg, *MRI, TRI);
2558 if (SrcRB != DstRB)
2559 return false;
2560 }
2561
2562 const bool IsVALU = DstRB->getID() == AMDGPU::VGPRRegBankID;
2563
2564 uint64_t DstSize = DstTy.getSizeInBits();
2565 uint64_t SrcSize = SrcTy.getSizeInBits();
2566
2567 const TargetRegisterClass *SrcRC =
2568 TRI.getRegClassForSizeOnBank(SrcSize, *SrcRB);
2569 const TargetRegisterClass *DstRC =
2570 TRI.getRegClassForSizeOnBank(DstSize, *DstRB);
2571 if (!SrcRC || !DstRC)
2572 return false;
2573
2574 if (!RBI.constrainGenericRegister(SrcReg, *SrcRC, *MRI) ||
2575 !RBI.constrainGenericRegister(DstReg, *DstRC, *MRI)) {
2576 LLVM_DEBUG(dbgs() << "Failed to constrain G_TRUNC\n");
2577 return false;
2578 }
2579
2580 if (DstRC == &AMDGPU::VGPR_16RegClass && SrcSize == 32) {
2581 assert(STI.useRealTrue16Insts());
2582 const DebugLoc &DL = I.getDebugLoc();
2583 MachineBasicBlock *MBB = I.getParent();
2584 BuildMI(*MBB, I, DL, TII.get(AMDGPU::COPY), DstReg)
2585 .addReg(SrcReg, {}, AMDGPU::lo16);
2586 I.eraseFromParent();
2587 return true;
2588 }
2589
2590 if (DstTy == LLT::fixed_vector(2, 16) && SrcTy == LLT::fixed_vector(2, 32)) {
2591 MachineBasicBlock *MBB = I.getParent();
2592 const DebugLoc &DL = I.getDebugLoc();
2593
2594 Register LoReg = MRI->createVirtualRegister(DstRC);
2595 Register HiReg = MRI->createVirtualRegister(DstRC);
2596 BuildMI(*MBB, I, DL, TII.get(AMDGPU::COPY), LoReg)
2597 .addReg(SrcReg, {}, AMDGPU::sub0);
2598 BuildMI(*MBB, I, DL, TII.get(AMDGPU::COPY), HiReg)
2599 .addReg(SrcReg, {}, AMDGPU::sub1);
2600
2601 if (IsVALU && STI.hasSDWA()) {
2602 // Write the low 16-bits of the high element into the high 16-bits of the
2603 // low element.
2604 MachineInstr *MovSDWA =
2605 BuildMI(*MBB, I, DL, TII.get(AMDGPU::V_MOV_B32_sdwa), DstReg)
2606 .addImm(0) // $src0_modifiers
2607 .addReg(HiReg) // $src0
2608 .addImm(0) // $clamp
2609 .addImm(AMDGPU::SDWA::WORD_1) // $dst_sel
2610 .addImm(AMDGPU::SDWA::UNUSED_PRESERVE) // $dst_unused
2611 .addImm(AMDGPU::SDWA::WORD_0) // $src0_sel
2612 .addReg(LoReg, RegState::Implicit);
2613 MovSDWA->tieOperands(0, MovSDWA->getNumOperands() - 1);
2614 } else {
2615 Register TmpReg0 = MRI->createVirtualRegister(DstRC);
2616 Register TmpReg1 = MRI->createVirtualRegister(DstRC);
2617 Register ImmReg = MRI->createVirtualRegister(DstRC);
2618 if (IsVALU) {
2619 BuildMI(*MBB, I, DL, TII.get(AMDGPU::V_LSHLREV_B32_e64), TmpReg0)
2620 .addImm(16)
2621 .addReg(HiReg);
2622 } else {
2623 BuildMI(*MBB, I, DL, TII.get(AMDGPU::S_LSHL_B32), TmpReg0)
2624 .addReg(HiReg)
2625 .addImm(16)
2626 .setOperandDead(3); // Dead scc
2627 }
2628
2629 unsigned MovOpc = IsVALU ? AMDGPU::V_MOV_B32_e32 : AMDGPU::S_MOV_B32;
2630 unsigned AndOpc = IsVALU ? AMDGPU::V_AND_B32_e64 : AMDGPU::S_AND_B32;
2631 unsigned OrOpc = IsVALU ? AMDGPU::V_OR_B32_e64 : AMDGPU::S_OR_B32;
2632
2633 BuildMI(*MBB, I, DL, TII.get(MovOpc), ImmReg)
2634 .addImm(0xffff);
2635 auto And = BuildMI(*MBB, I, DL, TII.get(AndOpc), TmpReg1)
2636 .addReg(LoReg)
2637 .addReg(ImmReg);
2638 auto Or = BuildMI(*MBB, I, DL, TII.get(OrOpc), DstReg)
2639 .addReg(TmpReg0)
2640 .addReg(TmpReg1);
2641
2642 if (!IsVALU) {
2643 And.setOperandDead(3); // Dead scc
2644 Or.setOperandDead(3); // Dead scc
2645 }
2646 }
2647
2648 I.eraseFromParent();
2649 return true;
2650 }
2651
2652 if (!DstTy.isScalar())
2653 return false;
2654
2655 if (SrcSize > 32) {
2656 unsigned SubRegIdx = DstSize < 32
2657 ? static_cast<unsigned>(AMDGPU::sub0)
2658 : TRI.getSubRegFromChannel(0, DstSize / 32);
2659 if (SubRegIdx == AMDGPU::NoSubRegister)
2660 return false;
2661
2662 // Deal with weird cases where the class only partially supports the subreg
2663 // index.
2664 const TargetRegisterClass *SrcWithSubRC
2665 = TRI.getSubClassWithSubReg(SrcRC, SubRegIdx);
2666 if (!SrcWithSubRC)
2667 return false;
2668
2669 if (SrcWithSubRC != SrcRC) {
2670 if (!RBI.constrainGenericRegister(SrcReg, *SrcWithSubRC, *MRI))
2671 return false;
2672 }
2673
2674 I.getOperand(1).setSubReg(SubRegIdx);
2675 }
2676
2677 I.setDesc(TII.get(TargetOpcode::COPY));
2678 return true;
2679}
2680
2681/// \returns true if a bitmask for \p Size bits will be an inline immediate.
2682static bool shouldUseAndMask(uint64_t Size, unsigned &Mask) {
2683 Mask = maskTrailingOnes<unsigned>(static_cast<unsigned>(Size));
2684 int SignedMask = static_cast<int>(Mask);
2685 return SignedMask >= -16 && SignedMask <= 64;
2686}
2687
2688// Like RegisterBankInfo::getRegBank, but don't assume vcc for s1.
2689const RegisterBank *AMDGPUInstructionSelector::getArtifactRegBank(
2691 const TargetRegisterInfo &TRI) const {
2692 const RegClassOrRegBank &RegClassOrBank = MRI.getRegClassOrRegBank(Reg);
2693 if (auto *RB = dyn_cast<const RegisterBank *>(RegClassOrBank))
2694 return RB;
2695
2696 // Ignore the type, since we don't use vcc in artifacts.
2697 if (auto *RC = dyn_cast<const TargetRegisterClass *>(RegClassOrBank))
2698 return &RBI.getRegBankFromRegClass(*RC, LLT());
2699 return nullptr;
2700}
2701
2702bool AMDGPUInstructionSelector::selectG_SZA_EXT(MachineInstr &I) const {
2703 bool InReg = I.getOpcode() == AMDGPU::G_SEXT_INREG;
2704 bool Signed = I.getOpcode() == AMDGPU::G_SEXT || InReg;
2705 const DebugLoc &DL = I.getDebugLoc();
2706 MachineBasicBlock &MBB = *I.getParent();
2707 const Register DstReg = I.getOperand(0).getReg();
2708 const Register SrcReg = I.getOperand(1).getReg();
2709
2710 const LLT DstTy = MRI->getType(DstReg);
2711 const LLT SrcTy = MRI->getType(SrcReg);
2712 const uint64_t SrcSize = I.getOpcode() == AMDGPU::G_SEXT_INREG
2713 ? I.getOperand(2).getImm()
2714 : SrcTy.getSizeInBits();
2715 const uint64_t DstSize = DstTy.getSizeInBits();
2716 if (!DstTy.isScalar())
2717 return false;
2718
2719 // Artifact casts should never use vcc.
2720 const RegisterBank *SrcBank = getArtifactRegBank(SrcReg, *MRI, TRI);
2721
2722 // FIXME: This should probably be illegal and split earlier.
2723 if (I.getOpcode() == AMDGPU::G_ANYEXT) {
2724 if (DstSize <= 32)
2725 return selectCOPY(I);
2726
2727 const TargetRegisterClass *SrcRC =
2728 TRI.getRegClassForTypeOnBank(SrcTy, *SrcBank);
2729 const RegisterBank *DstBank = RBI.getRegBank(DstReg, *MRI, TRI);
2730 const TargetRegisterClass *DstRC =
2731 TRI.getRegClassForSizeOnBank(DstSize, *DstBank);
2732
2733 Register UndefReg = MRI->createVirtualRegister(SrcRC);
2734 BuildMI(MBB, I, DL, TII.get(AMDGPU::IMPLICIT_DEF), UndefReg);
2735 BuildMI(MBB, I, DL, TII.get(AMDGPU::REG_SEQUENCE), DstReg)
2736 .addReg(SrcReg)
2737 .addImm(AMDGPU::sub0)
2738 .addReg(UndefReg)
2739 .addImm(AMDGPU::sub1);
2740 I.eraseFromParent();
2741
2742 return RBI.constrainGenericRegister(DstReg, *DstRC, *MRI) &&
2743 RBI.constrainGenericRegister(SrcReg, *SrcRC, *MRI);
2744 }
2745
2746 if (SrcBank->getID() == AMDGPU::VGPRRegBankID && DstSize <= 32) {
2747 // 64-bit should have been split up in RegBankSelect
2748
2749 // Try to use an and with a mask if it will save code size.
2750 unsigned Mask;
2751 if (!Signed && shouldUseAndMask(SrcSize, Mask)) {
2752 MachineInstr *ExtI =
2753 BuildMI(MBB, I, DL, TII.get(AMDGPU::V_AND_B32_e32), DstReg)
2754 .addImm(Mask)
2755 .addReg(SrcReg);
2756 I.eraseFromParent();
2757 constrainSelectedInstRegOperands(*ExtI, TII, TRI, RBI);
2758 return true;
2759 }
2760
2761 const unsigned BFE = Signed ? AMDGPU::V_BFE_I32_e64 : AMDGPU::V_BFE_U32_e64;
2762 MachineInstr *ExtI =
2763 BuildMI(MBB, I, DL, TII.get(BFE), DstReg)
2764 .addReg(SrcReg)
2765 .addImm(0) // Offset
2766 .addImm(SrcSize); // Width
2767 I.eraseFromParent();
2768 constrainSelectedInstRegOperands(*ExtI, TII, TRI, RBI);
2769 return true;
2770 }
2771
2772 if (SrcBank->getID() == AMDGPU::SGPRRegBankID && DstSize <= 64) {
2773 const TargetRegisterClass &SrcRC = InReg && DstSize > 32 ?
2774 AMDGPU::SReg_64RegClass : AMDGPU::SReg_32RegClass;
2775 if (!RBI.constrainGenericRegister(SrcReg, SrcRC, *MRI))
2776 return false;
2777
2778 if (Signed && DstSize == 32 && (SrcSize == 8 || SrcSize == 16)) {
2779 const unsigned SextOpc = SrcSize == 8 ?
2780 AMDGPU::S_SEXT_I32_I8 : AMDGPU::S_SEXT_I32_I16;
2781 BuildMI(MBB, I, DL, TII.get(SextOpc), DstReg)
2782 .addReg(SrcReg);
2783 I.eraseFromParent();
2784 return RBI.constrainGenericRegister(DstReg, AMDGPU::SReg_32RegClass, *MRI);
2785 }
2786
2787 // Using a single 32-bit SALU to calculate the high half is smaller than
2788 // S_BFE with a literal constant operand.
2789 if (DstSize > 32 && SrcSize == 32) {
2790 Register HiReg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
2791 unsigned SubReg = InReg ? AMDGPU::sub0 : AMDGPU::NoSubRegister;
2792 if (Signed) {
2793 BuildMI(MBB, I, DL, TII.get(AMDGPU::S_ASHR_I32), HiReg)
2794 .addReg(SrcReg, {}, SubReg)
2795 .addImm(31)
2796 .setOperandDead(3); // Dead scc
2797 } else {
2798 BuildMI(MBB, I, DL, TII.get(AMDGPU::S_MOV_B32), HiReg)
2799 .addImm(0);
2800 }
2801 BuildMI(MBB, I, DL, TII.get(AMDGPU::REG_SEQUENCE), DstReg)
2802 .addReg(SrcReg, {}, SubReg)
2803 .addImm(AMDGPU::sub0)
2804 .addReg(HiReg)
2805 .addImm(AMDGPU::sub1);
2806 I.eraseFromParent();
2807 return RBI.constrainGenericRegister(DstReg, AMDGPU::SReg_64RegClass,
2808 *MRI);
2809 }
2810
2811 const unsigned BFE64 = Signed ? AMDGPU::S_BFE_I64 : AMDGPU::S_BFE_U64;
2812 const unsigned BFE32 = Signed ? AMDGPU::S_BFE_I32 : AMDGPU::S_BFE_U32;
2813
2814 // Scalar BFE is encoded as S1[5:0] = offset, S1[22:16]= width.
2815 if (DstSize > 32 && (SrcSize <= 32 || InReg)) {
2816 // We need a 64-bit register source, but the high bits don't matter.
2817 Register ExtReg = MRI->createVirtualRegister(&AMDGPU::SReg_64RegClass);
2818 Register UndefReg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
2819 unsigned SubReg = InReg ? AMDGPU::sub0 : AMDGPU::NoSubRegister;
2820
2821 BuildMI(MBB, I, DL, TII.get(AMDGPU::IMPLICIT_DEF), UndefReg);
2822 BuildMI(MBB, I, DL, TII.get(AMDGPU::REG_SEQUENCE), ExtReg)
2823 .addReg(SrcReg, {}, SubReg)
2824 .addImm(AMDGPU::sub0)
2825 .addReg(UndefReg)
2826 .addImm(AMDGPU::sub1);
2827
2828 BuildMI(MBB, I, DL, TII.get(BFE64), DstReg)
2829 .addReg(ExtReg)
2830 .addImm(SrcSize << 16);
2831
2832 I.eraseFromParent();
2833 return RBI.constrainGenericRegister(DstReg, AMDGPU::SReg_64RegClass, *MRI);
2834 }
2835
2836 unsigned Mask;
2837 if (!Signed && shouldUseAndMask(SrcSize, Mask)) {
2838 BuildMI(MBB, I, DL, TII.get(AMDGPU::S_AND_B32), DstReg)
2839 .addReg(SrcReg)
2840 .addImm(Mask)
2841 .setOperandDead(3); // Dead scc
2842 } else {
2843 BuildMI(MBB, I, DL, TII.get(BFE32), DstReg)
2844 .addReg(SrcReg)
2845 .addImm(SrcSize << 16);
2846 }
2847
2848 I.eraseFromParent();
2849 return RBI.constrainGenericRegister(DstReg, AMDGPU::SReg_32RegClass, *MRI);
2850 }
2851
2852 return false;
2853}
2854
2858
2860 Register BitcastSrc;
2861 if (mi_match(Reg, MRI, m_GBitcast(m_Reg(BitcastSrc))))
2862 Reg = BitcastSrc;
2863 return Reg;
2864}
2865
2867 Register &Out) {
2868 // When unmerging a register that is composed of 2 x 16-bit values allow to
2869 // use an extract hi instruction for the upper 16 bits. We only need to check
2870 // the size of `In` as all defs are guaranteed to be the same type for
2871 // GUnmerge.
2872 GUnmerge *Unmerge;
2873 if (mi_match(In, MRI, m_GUnmerge(Unmerge))) {
2874 if (Unmerge->getNumDefs() == 2 && Unmerge->getOperand(1).getReg() == In &&
2875 MRI.getType(In).getSizeInBits() == 16) {
2876 Out = stripBitCast(Unmerge->getSourceReg(), MRI);
2877 return true;
2878 }
2879 }
2880
2882 if (!mi_match(In, MRI, m_GTrunc(m_Reg(Trunc))))
2883 return false;
2884
2885 Register LShlSrc;
2886 Register Cst;
2887 if (mi_match(Trunc, MRI, m_GLShr(m_Reg(LShlSrc), m_Reg(Cst)))) {
2888 Cst = stripCopy(Cst, MRI);
2889 if (mi_match(Cst, MRI, m_SpecificICst(16))) {
2890 Register Result = stripBitCast(LShlSrc, MRI);
2891 // op_sel can only select the high half of a 32-bit source. If the
2892 // shift source is wider (e.g. a 64-bit D16 image sample result), we
2893 // cannot fold it directly. Do not assign Out before this check since
2894 // the caller may pass the same register for both In and Out.
2895 if (MRI.getType(Result).getSizeInBits() != 32)
2896 return false;
2897 Out = Result;
2898 return true;
2899 }
2900 }
2901
2902 ArrayRef<int> Mask;
2903 Register Src1;
2904 if (!mi_match(Trunc, MRI, m_GShuffleVector(m_Reg(Src1), m_Reg(), Mask)))
2905 return false;
2906
2907 assert(MRI.getType(Src1) == LLT::fixed_vector(2, 16));
2908 assert(Mask.size() == 2);
2909
2910 if (Mask[0] == 1 && Mask[1] <= 1) {
2911 Out = Trunc;
2912 return true;
2913 }
2914
2915 return false;
2916}
2917
2919 Register &Out) {
2920 // There could be a bitcast between the extraction and its use.
2921 In = stripBitCast(In, MRI);
2922
2923 // The first def of a 2 x 16-bit unmerge is the low half of its source.
2924 if (auto *Unmerge = dyn_cast<GUnmerge>(MRI.getVRegDef(In))) {
2925 if (Unmerge->getNumDefs() == 2 && Unmerge->getOperand(0).getReg() == In &&
2926 MRI.getType(In).getSizeInBits() == 16) {
2927 Out = stripBitCast(Unmerge->getSourceReg(), MRI);
2928 return true;
2929 }
2930 }
2931
2932 // A truncation from 32 to 16 bits keeps the low half in place.
2934 if (mi_match(In, MRI, m_GTrunc(m_Reg(Trunc))) &&
2935 MRI.getType(Trunc).getSizeInBits() == 32) {
2936 Out = stripBitCast(Trunc, MRI);
2937 return true;
2938 }
2939
2940 return false;
2941}
2942
2943bool AMDGPUInstructionSelector::selectG_FPEXT(MachineInstr &I) const {
2944 if (!Subtarget->hasSALUFloatInsts())
2945 return false;
2946
2947 Register Dst = I.getOperand(0).getReg();
2948 const RegisterBank *DstRB = RBI.getRegBank(Dst, *MRI, TRI);
2949 if (DstRB->getID() != AMDGPU::SGPRRegBankID)
2950 return false;
2951
2952 Register Src = I.getOperand(1).getReg();
2953
2954 if (MRI->getType(Dst) == LLT::scalar(32) &&
2955 MRI->getType(Src) == LLT::scalar(16)) {
2956 if (isExtractHiElt(*MRI, Src, Src)) {
2957 MachineBasicBlock *BB = I.getParent();
2958 BuildMI(*BB, &I, I.getDebugLoc(), TII.get(AMDGPU::S_CVT_HI_F32_F16), Dst)
2959 .addUse(Src);
2960 I.eraseFromParent();
2961 return RBI.constrainGenericRegister(Dst, AMDGPU::SReg_32RegClass, *MRI);
2962 }
2963 }
2964
2965 return false;
2966}
2967
2968bool AMDGPUInstructionSelector::selectG_FNEG(MachineInstr &MI) const {
2969 // Only manually handle the f64 SGPR case.
2970 //
2971 // FIXME: This is a workaround for 2.5 different tablegen problems. Because
2972 // the bit ops theoretically have a second result due to the implicit def of
2973 // SCC, the GlobalISelEmitter is overly conservative and rejects it. Fixing
2974 // that is easy by disabling the check. The result works, but uses a
2975 // nonsensical sreg32orlds_and_sreg_1 regclass.
2976 //
2977 // The DAG emitter is more problematic, and incorrectly adds both S_XOR_B32 to
2978 // the variadic REG_SEQUENCE operands.
2979
2980 Register Dst = MI.getOperand(0).getReg();
2981 const RegisterBank *DstRB = RBI.getRegBank(Dst, *MRI, TRI);
2982 if (DstRB->getID() != AMDGPU::SGPRRegBankID ||
2983 MRI->getType(Dst) != LLT::scalar(64))
2984 return false;
2985
2986 Register Src = MI.getOperand(1).getReg();
2987 MachineInstr *Fabs = getOpcodeDef(TargetOpcode::G_FABS, Src, *MRI);
2988 if (Fabs)
2989 Src = Fabs->getOperand(1).getReg();
2990
2991 if (!RBI.constrainGenericRegister(Src, AMDGPU::SReg_64RegClass, *MRI) ||
2992 !RBI.constrainGenericRegister(Dst, AMDGPU::SReg_64RegClass, *MRI))
2993 return false;
2994
2995 MachineBasicBlock *BB = MI.getParent();
2996 const DebugLoc &DL = MI.getDebugLoc();
2997 Register LoReg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
2998 Register HiReg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
2999 Register ConstReg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
3000 Register OpReg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
3001
3002 BuildMI(*BB, &MI, DL, TII.get(AMDGPU::COPY), LoReg)
3003 .addReg(Src, {}, AMDGPU::sub0);
3004 BuildMI(*BB, &MI, DL, TII.get(AMDGPU::COPY), HiReg)
3005 .addReg(Src, {}, AMDGPU::sub1);
3006 BuildMI(*BB, &MI, DL, TII.get(AMDGPU::S_MOV_B32), ConstReg)
3007 .addImm(0x80000000);
3008
3009 // Set or toggle sign bit.
3010 unsigned Opc = Fabs ? AMDGPU::S_OR_B32 : AMDGPU::S_XOR_B32;
3011 BuildMI(*BB, &MI, DL, TII.get(Opc), OpReg)
3012 .addReg(HiReg)
3013 .addReg(ConstReg)
3014 .setOperandDead(3); // Dead scc
3015 BuildMI(*BB, &MI, DL, TII.get(AMDGPU::REG_SEQUENCE), Dst)
3016 .addReg(LoReg)
3017 .addImm(AMDGPU::sub0)
3018 .addReg(OpReg)
3019 .addImm(AMDGPU::sub1);
3020 MI.eraseFromParent();
3021 return true;
3022}
3023
3024// FIXME: This is a workaround for the same tablegen problems as G_FNEG
3025bool AMDGPUInstructionSelector::selectG_FABS(MachineInstr &MI) const {
3026 Register Dst = MI.getOperand(0).getReg();
3027 const RegisterBank *DstRB = RBI.getRegBank(Dst, *MRI, TRI);
3028 if (DstRB->getID() != AMDGPU::SGPRRegBankID ||
3029 MRI->getType(Dst) != LLT::scalar(64))
3030 return false;
3031
3032 Register Src = MI.getOperand(1).getReg();
3033 MachineBasicBlock *BB = MI.getParent();
3034 const DebugLoc &DL = MI.getDebugLoc();
3035 Register LoReg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
3036 Register HiReg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
3037 Register ConstReg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
3038 Register OpReg = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
3039
3040 if (!RBI.constrainGenericRegister(Src, AMDGPU::SReg_64RegClass, *MRI) ||
3041 !RBI.constrainGenericRegister(Dst, AMDGPU::SReg_64RegClass, *MRI))
3042 return false;
3043
3044 BuildMI(*BB, &MI, DL, TII.get(AMDGPU::COPY), LoReg)
3045 .addReg(Src, {}, AMDGPU::sub0);
3046 BuildMI(*BB, &MI, DL, TII.get(AMDGPU::COPY), HiReg)
3047 .addReg(Src, {}, AMDGPU::sub1);
3048 BuildMI(*BB, &MI, DL, TII.get(AMDGPU::S_MOV_B32), ConstReg)
3049 .addImm(0x7fffffff);
3050
3051 // Clear sign bit.
3052 // TODO: Should this used S_BITSET0_*?
3053 BuildMI(*BB, &MI, DL, TII.get(AMDGPU::S_AND_B32), OpReg)
3054 .addReg(HiReg)
3055 .addReg(ConstReg)
3056 .setOperandDead(3); // Dead scc
3057 BuildMI(*BB, &MI, DL, TII.get(AMDGPU::REG_SEQUENCE), Dst)
3058 .addReg(LoReg)
3059 .addImm(AMDGPU::sub0)
3060 .addReg(OpReg)
3061 .addImm(AMDGPU::sub1);
3062
3063 MI.eraseFromParent();
3064 return true;
3065}
3066
3067static bool isConstant(const MachineInstr &MI) {
3068 return MI.getOpcode() == TargetOpcode::G_CONSTANT;
3069}
3070
3071void AMDGPUInstructionSelector::getAddrModeInfo(const MachineInstr &Load,
3072 const MachineRegisterInfo &MRI, SmallVectorImpl<GEPInfo> &AddrInfo) const {
3073
3074 unsigned OpNo = Load.getOpcode() == AMDGPU::G_PREFETCH ? 0 : 1;
3075 const MachineInstr *PtrMI = MRI.getVRegDef(Load.getOperand(OpNo).getReg());
3076
3077 assert(PtrMI);
3078
3079 if (PtrMI->getOpcode() != TargetOpcode::G_PTR_ADD)
3080 return;
3081
3082 GEPInfo GEPInfo;
3083
3084 for (unsigned i = 1; i != 3; ++i) {
3085 const MachineOperand &GEPOp = PtrMI->getOperand(i);
3086 const MachineInstr *OpDef = MRI.getVRegDef(GEPOp.getReg());
3087 assert(OpDef);
3088 if (i == 2 && isConstant(*OpDef)) {
3089 // TODO: Could handle constant base + variable offset, but a combine
3090 // probably should have commuted it.
3091 assert(GEPInfo.Imm == 0);
3092 GEPInfo.Imm = OpDef->getOperand(1).getCImm()->getSExtValue();
3093 continue;
3094 }
3095 const RegisterBank *OpBank = RBI.getRegBank(GEPOp.getReg(), MRI, TRI);
3096 if (OpBank->getID() == AMDGPU::SGPRRegBankID)
3097 GEPInfo.SgprParts.push_back(GEPOp.getReg());
3098 else
3099 GEPInfo.VgprParts.push_back(GEPOp.getReg());
3100 }
3101
3102 AddrInfo.push_back(GEPInfo);
3103 getAddrModeInfo(*PtrMI, MRI, AddrInfo);
3104}
3105
3106bool AMDGPUInstructionSelector::isSGPR(Register Reg) const {
3107 return RBI.getRegBank(Reg, *MRI, TRI)->getID() == AMDGPU::SGPRRegBankID;
3108}
3109
3110bool AMDGPUInstructionSelector::isInstrUniform(const MachineInstr &MI) const {
3111 if (!MI.hasOneMemOperand())
3112 return false;
3113
3114 const MachineMemOperand *MMO = *MI.memoperands_begin();
3115 const Value *Ptr = MMO->getValue();
3116
3117 // UndefValue means this is a load of a kernel input. These are uniform.
3118 // Sometimes LDS instructions have constant pointers.
3119 // If Ptr is null, then that means this mem operand contains a
3120 // PseudoSourceValue like GOT.
3122 return true;
3123
3125 return true;
3126
3127 if (MI.getOpcode() == AMDGPU::G_PREFETCH)
3128 return RBI.getRegBank(MI.getOperand(0).getReg(), *MRI, TRI)->getID() ==
3129 AMDGPU::SGPRRegBankID;
3130
3131 const Instruction *I = dyn_cast<Instruction>(Ptr);
3132 return I && I->getMetadata("amdgpu.uniform");
3133}
3134
3135bool AMDGPUInstructionSelector::hasVgprParts(ArrayRef<GEPInfo> AddrInfo) const {
3136 for (const GEPInfo &GEPInfo : AddrInfo) {
3137 if (!GEPInfo.VgprParts.empty())
3138 return true;
3139 }
3140 return false;
3141}
3142
3143void AMDGPUInstructionSelector::initM0(MachineInstr &I) const {
3144 const LLT PtrTy = MRI->getType(I.getOperand(1).getReg());
3145 unsigned AS = PtrTy.getAddressSpace();
3147 STI.ldsRequiresM0Init()) {
3148 MachineBasicBlock *BB = I.getParent();
3149
3150 // If DS instructions require M0 initialization, insert it before selecting.
3151 BuildMI(*BB, &I, I.getDebugLoc(), TII.get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3152 .addImm(-1);
3153 }
3154}
3155
3156bool AMDGPUInstructionSelector::selectG_LOAD_STORE_ATOMICRMW(
3157 MachineInstr &I) const {
3158 initM0(I);
3159 return selectImpl(I, *CoverageInfo);
3160}
3161
3163 if (Reg.isPhysical())
3164 return false;
3165
3166 MachineInstr &MI = *MRI.getVRegDef(Reg);
3167 const unsigned Opcode = MI.getOpcode();
3168
3169 if (Opcode == AMDGPU::COPY)
3170 return isVCmpResult(MI.getOperand(1).getReg(), MRI);
3171
3172 if (Opcode == AMDGPU::G_AND || Opcode == AMDGPU::G_OR ||
3173 Opcode == AMDGPU::G_XOR)
3174 return isVCmpResult(MI.getOperand(1).getReg(), MRI) &&
3175 isVCmpResult(MI.getOperand(2).getReg(), MRI);
3176
3177 if (auto *GI = dyn_cast<GIntrinsic>(&MI))
3178 return GI->is(Intrinsic::amdgcn_class);
3179
3180 return Opcode == AMDGPU::G_ICMP || Opcode == AMDGPU::G_FCMP;
3181}
3182
3183bool AMDGPUInstructionSelector::selectG_BRCOND(MachineInstr &I) const {
3184 MachineBasicBlock *BB = I.getParent();
3185 MachineOperand &CondOp = I.getOperand(0);
3186 Register CondReg = CondOp.getReg();
3187 const DebugLoc &DL = I.getDebugLoc();
3188
3189 unsigned BrOpcode;
3190 Register CondPhysReg;
3191 const TargetRegisterClass *ConstrainRC;
3192
3193 // In SelectionDAG, we inspect the IR block for uniformity metadata to decide
3194 // whether the branch is uniform when selecting the instruction. In
3195 // GlobalISel, we should push that decision into RegBankSelect. Assume for now
3196 // RegBankSelect knows what it's doing if the branch condition is scc, even
3197 // though it currently does not.
3198 if (!isVCC(CondReg, *MRI)) {
3199 if (MRI->getType(CondReg) != LLT::scalar(32))
3200 return false;
3201
3202 CondPhysReg = AMDGPU::SCC;
3203 BrOpcode = AMDGPU::S_CBRANCH_SCC1;
3204 ConstrainRC = &AMDGPU::SReg_32RegClass;
3205 } else {
3206 // FIXME: Should scc->vcc copies and with exec?
3207
3208 // Unless the value of CondReg is a result of a V_CMP* instruction then we
3209 // need to insert an and with exec.
3210 if (!isVCmpResult(CondReg, *MRI)) {
3211 const bool Is64 = STI.isWave64();
3212 const unsigned Opcode = Is64 ? AMDGPU::S_AND_B64 : AMDGPU::S_AND_B32;
3213 const Register Exec = Is64 ? AMDGPU::EXEC : AMDGPU::EXEC_LO;
3214
3215 Register TmpReg = MRI->createVirtualRegister(TRI.getBoolRC());
3216 BuildMI(*BB, &I, DL, TII.get(Opcode), TmpReg)
3217 .addReg(CondReg)
3218 .addReg(Exec)
3219 .setOperandDead(3); // Dead scc
3220 CondReg = TmpReg;
3221 }
3222
3223 CondPhysReg = TRI.getVCC();
3224 BrOpcode = AMDGPU::S_CBRANCH_VCCNZ;
3225 ConstrainRC = TRI.getBoolRC();
3226 }
3227
3228 if (!MRI->getRegClassOrNull(CondReg))
3229 MRI->setRegClass(CondReg, ConstrainRC);
3230
3231 BuildMI(*BB, &I, DL, TII.get(AMDGPU::COPY), CondPhysReg)
3232 .addReg(CondReg);
3233 BuildMI(*BB, &I, DL, TII.get(BrOpcode))
3234 .addMBB(I.getOperand(1).getMBB());
3235
3236 I.eraseFromParent();
3237 return true;
3238}
3239
3240bool AMDGPUInstructionSelector::selectG_GLOBAL_VALUE(
3241 MachineInstr &I) const {
3242 Register DstReg = I.getOperand(0).getReg();
3243 const RegisterBank *DstRB = RBI.getRegBank(DstReg, *MRI, TRI);
3244 const bool IsVGPR = DstRB->getID() == AMDGPU::VGPRRegBankID;
3245 I.setDesc(TII.get(IsVGPR ? AMDGPU::V_MOV_B32_e32 : AMDGPU::S_MOV_B32));
3246 if (IsVGPR)
3247 I.addOperand(*MF, MachineOperand::CreateReg(AMDGPU::EXEC, false, true));
3248
3249 return RBI.constrainGenericRegister(
3250 DstReg, IsVGPR ? AMDGPU::VGPR_32RegClass : AMDGPU::SReg_32RegClass, *MRI);
3251}
3252
3253bool AMDGPUInstructionSelector::selectG_PTRMASK(MachineInstr &I) const {
3254 Register DstReg = I.getOperand(0).getReg();
3255 Register SrcReg = I.getOperand(1).getReg();
3256 Register MaskReg = I.getOperand(2).getReg();
3257 LLT Ty = MRI->getType(DstReg);
3258 LLT MaskTy = MRI->getType(MaskReg);
3259 MachineBasicBlock *BB = I.getParent();
3260 const DebugLoc &DL = I.getDebugLoc();
3261
3262 const RegisterBank *DstRB = RBI.getRegBank(DstReg, *MRI, TRI);
3263 const RegisterBank *SrcRB = RBI.getRegBank(SrcReg, *MRI, TRI);
3264 const RegisterBank *MaskRB = RBI.getRegBank(MaskReg, *MRI, TRI);
3265 const bool IsVGPR = DstRB->getID() == AMDGPU::VGPRRegBankID;
3266 if (DstRB != SrcRB) // Should only happen for hand written MIR.
3267 return false;
3268
3269 // Try to avoid emitting a bit operation when we only need to touch half of
3270 // the 64-bit pointer.
3271 APInt MaskOnes = VT->getKnownOnes(MaskReg).zext(64);
3272 const APInt MaskHi32 = APInt::getHighBitsSet(64, 32);
3273 const APInt MaskLo32 = APInt::getLowBitsSet(64, 32);
3274
3275 const bool CanCopyLow32 = (MaskOnes & MaskLo32) == MaskLo32;
3276 const bool CanCopyHi32 = (MaskOnes & MaskHi32) == MaskHi32;
3277
3278 if (!IsVGPR && Ty.getSizeInBits() == 64 &&
3279 !CanCopyLow32 && !CanCopyHi32) {
3280 auto MIB = BuildMI(*BB, &I, DL, TII.get(AMDGPU::S_AND_B64), DstReg)
3281 .addReg(SrcReg)
3282 .addReg(MaskReg)
3283 .setOperandDead(3); // Dead scc
3284 I.eraseFromParent();
3285 constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
3286 return true;
3287 }
3288
3289 unsigned NewOpc = IsVGPR ? AMDGPU::V_AND_B32_e64 : AMDGPU::S_AND_B32;
3290 const TargetRegisterClass &RegRC
3291 = IsVGPR ? AMDGPU::VGPR_32RegClass : AMDGPU::SReg_32RegClass;
3292
3293 const TargetRegisterClass *DstRC = TRI.getRegClassForTypeOnBank(Ty, *DstRB);
3294 const TargetRegisterClass *SrcRC = TRI.getRegClassForTypeOnBank(Ty, *SrcRB);
3295 const TargetRegisterClass *MaskRC =
3296 TRI.getRegClassForTypeOnBank(MaskTy, *MaskRB);
3297
3298 if (!RBI.constrainGenericRegister(DstReg, *DstRC, *MRI) ||
3299 !RBI.constrainGenericRegister(SrcReg, *SrcRC, *MRI) ||
3300 !RBI.constrainGenericRegister(MaskReg, *MaskRC, *MRI))
3301 return false;
3302
3303 if (Ty.getSizeInBits() == 32) {
3304 assert(MaskTy.getSizeInBits() == 32 &&
3305 "ptrmask should have been narrowed during legalize");
3306
3307 auto NewOp = BuildMI(*BB, &I, DL, TII.get(NewOpc), DstReg)
3308 .addReg(SrcReg)
3309 .addReg(MaskReg);
3310
3311 if (!IsVGPR)
3312 NewOp.setOperandDead(3); // Dead scc
3313 I.eraseFromParent();
3314 return true;
3315 }
3316
3317 Register HiReg = MRI->createVirtualRegister(&RegRC);
3318 Register LoReg = MRI->createVirtualRegister(&RegRC);
3319
3320 // Extract the subregisters from the source pointer.
3321 BuildMI(*BB, &I, DL, TII.get(AMDGPU::COPY), LoReg)
3322 .addReg(SrcReg, {}, AMDGPU::sub0);
3323 BuildMI(*BB, &I, DL, TII.get(AMDGPU::COPY), HiReg)
3324 .addReg(SrcReg, {}, AMDGPU::sub1);
3325
3326 Register MaskedLo, MaskedHi;
3327
3328 if (CanCopyLow32) {
3329 // If all the bits in the low half are 1, we only need a copy for it.
3330 MaskedLo = LoReg;
3331 } else {
3332 // Extract the mask subregister and apply the and.
3333 Register MaskLo = MRI->createVirtualRegister(&RegRC);
3334 MaskedLo = MRI->createVirtualRegister(&RegRC);
3335
3336 BuildMI(*BB, &I, DL, TII.get(AMDGPU::COPY), MaskLo)
3337 .addReg(MaskReg, {}, AMDGPU::sub0);
3338 BuildMI(*BB, &I, DL, TII.get(NewOpc), MaskedLo)
3339 .addReg(LoReg)
3340 .addReg(MaskLo);
3341 }
3342
3343 if (CanCopyHi32) {
3344 // If all the bits in the high half are 1, we only need a copy for it.
3345 MaskedHi = HiReg;
3346 } else {
3347 Register MaskHi = MRI->createVirtualRegister(&RegRC);
3348 MaskedHi = MRI->createVirtualRegister(&RegRC);
3349
3350 BuildMI(*BB, &I, DL, TII.get(AMDGPU::COPY), MaskHi)
3351 .addReg(MaskReg, {}, AMDGPU::sub1);
3352 BuildMI(*BB, &I, DL, TII.get(NewOpc), MaskedHi)
3353 .addReg(HiReg)
3354 .addReg(MaskHi);
3355 }
3356
3357 BuildMI(*BB, &I, DL, TII.get(AMDGPU::REG_SEQUENCE), DstReg)
3358 .addReg(MaskedLo)
3359 .addImm(AMDGPU::sub0)
3360 .addReg(MaskedHi)
3361 .addImm(AMDGPU::sub1);
3362 I.eraseFromParent();
3363 return true;
3364}
3365
3366/// Return the register to use for the index value, and the subregister to use
3367/// for the indirectly accessed register.
3368static std::pair<Register, unsigned>
3370 const TargetRegisterClass *SuperRC, Register IdxReg,
3371 unsigned EltSize, GISelValueTracking &ValueTracking) {
3372 Register IdxBaseReg;
3373 int Offset;
3374
3375 std::tie(IdxBaseReg, Offset) =
3376 AMDGPU::getBaseWithConstantOffset(MRI, IdxReg, &ValueTracking);
3377 if (IdxBaseReg == AMDGPU::NoRegister) {
3378 // This will happen if the index is a known constant. This should ordinarily
3379 // be legalized out, but handle it as a register just in case.
3380 assert(Offset == 0);
3381 IdxBaseReg = IdxReg;
3382 }
3383
3384 ArrayRef<int16_t> SubRegs = TRI.getRegSplitParts(SuperRC, EltSize);
3385
3386 // Skip out of bounds offsets, or else we would end up using an undefined
3387 // register.
3388 if (static_cast<unsigned>(Offset) >= SubRegs.size())
3389 return std::pair(IdxReg, SubRegs[0]);
3390 return std::pair(IdxBaseReg, SubRegs[Offset]);
3391}
3392
3393bool AMDGPUInstructionSelector::selectG_EXTRACT_VECTOR_ELT(
3394 MachineInstr &MI) const {
3395 Register DstReg = MI.getOperand(0).getReg();
3396 Register SrcReg = MI.getOperand(1).getReg();
3397 Register IdxReg = MI.getOperand(2).getReg();
3398
3399 LLT DstTy = MRI->getType(DstReg);
3400 LLT SrcTy = MRI->getType(SrcReg);
3401
3402 const RegisterBank *DstRB = RBI.getRegBank(DstReg, *MRI, TRI);
3403 const RegisterBank *SrcRB = RBI.getRegBank(SrcReg, *MRI, TRI);
3404 const RegisterBank *IdxRB = RBI.getRegBank(IdxReg, *MRI, TRI);
3405
3406 // The index must be scalar. If it wasn't RegBankSelect should have moved this
3407 // into a waterfall loop.
3408 if (IdxRB->getID() != AMDGPU::SGPRRegBankID)
3409 return false;
3410
3411 const TargetRegisterClass *SrcRC =
3412 TRI.getRegClassForTypeOnBank(SrcTy, *SrcRB);
3413 const TargetRegisterClass *DstRC =
3414 TRI.getRegClassForTypeOnBank(DstTy, *DstRB);
3415 if (!SrcRC || !DstRC)
3416 return false;
3417 if (!RBI.constrainGenericRegister(SrcReg, *SrcRC, *MRI) ||
3418 !RBI.constrainGenericRegister(DstReg, *DstRC, *MRI) ||
3419 !RBI.constrainGenericRegister(IdxReg, AMDGPU::SReg_32RegClass, *MRI))
3420 return false;
3421
3422 MachineBasicBlock *BB = MI.getParent();
3423 const DebugLoc &DL = MI.getDebugLoc();
3424 const bool Is64 = DstTy.getSizeInBits() == 64;
3425
3426 unsigned SubReg;
3427 std::tie(IdxReg, SubReg) = computeIndirectRegIndex(
3428 *MRI, TRI, SrcRC, IdxReg,
3429 static_cast<unsigned>(DstTy.getSizeInBits() / 8), *VT);
3430
3431 if (SrcRB->getID() == AMDGPU::SGPRRegBankID) {
3432 if (DstTy.getSizeInBits() != 32 && !Is64)
3433 return false;
3434
3435 BuildMI(*BB, &MI, DL, TII.get(AMDGPU::COPY), AMDGPU::M0)
3436 .addReg(IdxReg);
3437
3438 unsigned Opc = Is64 ? AMDGPU::S_MOVRELS_B64 : AMDGPU::S_MOVRELS_B32;
3439 BuildMI(*BB, &MI, DL, TII.get(Opc), DstReg)
3440 .addReg(SrcReg, {}, SubReg)
3441 .addReg(SrcReg, RegState::Implicit);
3442 MI.eraseFromParent();
3443 return true;
3444 }
3445
3446 if (SrcRB->getID() != AMDGPU::VGPRRegBankID || DstTy.getSizeInBits() != 32)
3447 return false;
3448
3449 if (!STI.useVGPRIndexMode()) {
3450 BuildMI(*BB, &MI, DL, TII.get(AMDGPU::COPY), AMDGPU::M0)
3451 .addReg(IdxReg);
3452 BuildMI(*BB, &MI, DL, TII.get(AMDGPU::V_MOVRELS_B32_e32), DstReg)
3453 .addReg(SrcReg, {}, SubReg)
3454 .addReg(SrcReg, RegState::Implicit);
3455 MI.eraseFromParent();
3456 return true;
3457 }
3458
3459 const MCInstrDesc &GPRIDXDesc = TII.getIndirectGPRIDXPseudo(
3460 static_cast<unsigned>(TRI.getRegSizeInBits(*SrcRC)), true);
3461 BuildMI(*BB, MI, DL, GPRIDXDesc, DstReg)
3462 .addReg(SrcReg)
3463 .addReg(IdxReg)
3464 .addImm(SubReg);
3465
3466 MI.eraseFromParent();
3467 return true;
3468}
3469
3470// TODO: Fold insert_vector_elt (extract_vector_elt) into movrelsd
3471bool AMDGPUInstructionSelector::selectG_INSERT_VECTOR_ELT(
3472 MachineInstr &MI) const {
3473 Register DstReg = MI.getOperand(0).getReg();
3474 Register VecReg = MI.getOperand(1).getReg();
3475 Register ValReg = MI.getOperand(2).getReg();
3476 Register IdxReg = MI.getOperand(3).getReg();
3477
3478 LLT VecTy = MRI->getType(DstReg);
3479 LLT ValTy = MRI->getType(ValReg);
3480 unsigned VecSize = static_cast<unsigned>(VecTy.getSizeInBits());
3481 unsigned ValSize = static_cast<unsigned>(ValTy.getSizeInBits());
3482
3483 const RegisterBank *VecRB = RBI.getRegBank(VecReg, *MRI, TRI);
3484 const RegisterBank *ValRB = RBI.getRegBank(ValReg, *MRI, TRI);
3485 const RegisterBank *IdxRB = RBI.getRegBank(IdxReg, *MRI, TRI);
3486
3487 assert(VecTy.getElementType() == ValTy);
3488
3489 // The index must be scalar. If it wasn't RegBankSelect should have moved this
3490 // into a waterfall loop.
3491 if (IdxRB->getID() != AMDGPU::SGPRRegBankID)
3492 return false;
3493
3494 const TargetRegisterClass *VecRC =
3495 TRI.getRegClassForTypeOnBank(VecTy, *VecRB);
3496 const TargetRegisterClass *ValRC =
3497 TRI.getRegClassForTypeOnBank(ValTy, *ValRB);
3498
3499 if (!RBI.constrainGenericRegister(VecReg, *VecRC, *MRI) ||
3500 !RBI.constrainGenericRegister(DstReg, *VecRC, *MRI) ||
3501 !RBI.constrainGenericRegister(ValReg, *ValRC, *MRI) ||
3502 !RBI.constrainGenericRegister(IdxReg, AMDGPU::SReg_32RegClass, *MRI))
3503 return false;
3504
3505 if (VecRB->getID() == AMDGPU::VGPRRegBankID && ValSize != 32)
3506 return false;
3507
3508 unsigned SubReg;
3509 std::tie(IdxReg, SubReg) =
3510 computeIndirectRegIndex(*MRI, TRI, VecRC, IdxReg, ValSize / 8, *VT);
3511
3512 const bool IndexMode = VecRB->getID() == AMDGPU::VGPRRegBankID &&
3513 STI.useVGPRIndexMode();
3514
3515 MachineBasicBlock *BB = MI.getParent();
3516 const DebugLoc &DL = MI.getDebugLoc();
3517
3518 if (!IndexMode) {
3519 BuildMI(*BB, &MI, DL, TII.get(AMDGPU::COPY), AMDGPU::M0)
3520 .addReg(IdxReg);
3521
3522 const MCInstrDesc &RegWriteOp = TII.getIndirectRegWriteMovRelPseudo(
3523 VecSize, ValSize, VecRB->getID() == AMDGPU::SGPRRegBankID);
3524 BuildMI(*BB, MI, DL, RegWriteOp, DstReg)
3525 .addReg(VecReg)
3526 .addReg(ValReg)
3527 .addImm(SubReg);
3528 MI.eraseFromParent();
3529 return true;
3530 }
3531
3532 const MCInstrDesc &GPRIDXDesc = TII.getIndirectGPRIDXPseudo(
3533 static_cast<unsigned>(TRI.getRegSizeInBits(*VecRC)), false);
3534 BuildMI(*BB, MI, DL, GPRIDXDesc, DstReg)
3535 .addReg(VecReg)
3536 .addReg(ValReg)
3537 .addReg(IdxReg)
3538 .addImm(SubReg);
3539
3540 MI.eraseFromParent();
3541 return true;
3542}
3543
3544static bool isAsyncLDSDMA(Intrinsic::ID Intr) {
3545 if (const AMDGPU::BufferIntrinsicInfo *BufInfo =
3547 return BufInfo->IsAsync;
3548 switch (Intr) {
3549 case Intrinsic::amdgcn_load_async_to_lds:
3550 case Intrinsic::amdgcn_global_load_async_lds:
3551 return true;
3552 }
3553 return false;
3554}
3555
3556bool AMDGPUInstructionSelector::selectBufferLoadLds(
3557 MachineInstr &MI, const AMDGPU::BufferIntrinsicInfo &Info) const {
3558 if (!Subtarget->hasVMemToLDSLoad())
3559 return false;
3560 auto GetArg = [&](unsigned Arg) -> MachineOperand & {
3561 return MI.getOperand(AMDGPU::getMIROperandIdx(MI, Arg));
3562 };
3563 unsigned Opc;
3564 unsigned Size = static_cast<unsigned>(GetArg(*Info.getSizeArg()).getImm());
3565
3566 std::optional<unsigned> VIndexArg = Info.getVIndexArg();
3567 const bool HasVIndex = VIndexArg.has_value();
3568 Register VIndex;
3569 if (HasVIndex)
3570 VIndex = GetArg(*VIndexArg).getReg();
3571
3572 Register VOffset = GetArg(*Info.getVOffsetArg()).getReg();
3573 std::optional<ValueAndVReg> MaybeVOffset =
3575 const bool HasVOffset = !MaybeVOffset || MaybeVOffset->Value.getZExtValue();
3576
3577 switch (Size) {
3578 default:
3579 return false;
3580 case 1:
3581 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_BOTHEN
3582 : AMDGPU::BUFFER_LOAD_UBYTE_LDS_IDXEN
3583 : HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFEN
3584 : AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFSET;
3585 break;
3586 case 2:
3587 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_BOTHEN
3588 : AMDGPU::BUFFER_LOAD_USHORT_LDS_IDXEN
3589 : HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFEN
3590 : AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFSET;
3591 break;
3592 case 4:
3593 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_BOTHEN
3594 : AMDGPU::BUFFER_LOAD_DWORD_LDS_IDXEN
3595 : HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFEN
3596 : AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFSET;
3597 break;
3598 case 12:
3599 if (!Subtarget->hasLDSLoadB96_B128())
3600 return false;
3601
3602 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_DWORDX3_LDS_BOTHEN
3603 : AMDGPU::BUFFER_LOAD_DWORDX3_LDS_IDXEN
3604 : HasVOffset ? AMDGPU::BUFFER_LOAD_DWORDX3_LDS_OFFEN
3605 : AMDGPU::BUFFER_LOAD_DWORDX3_LDS_OFFSET;
3606 break;
3607 case 16:
3608 if (!Subtarget->hasLDSLoadB96_B128())
3609 return false;
3610
3611 Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_DWORDX4_LDS_BOTHEN
3612 : AMDGPU::BUFFER_LOAD_DWORDX4_LDS_IDXEN
3613 : HasVOffset ? AMDGPU::BUFFER_LOAD_DWORDX4_LDS_OFFEN
3614 : AMDGPU::BUFFER_LOAD_DWORDX4_LDS_OFFSET;
3615 break;
3616 }
3617
3618 MachineBasicBlock *MBB = MI.getParent();
3619 const DebugLoc &DL = MI.getDebugLoc();
3620 BuildMI(*MBB, &MI, DL, TII.get(AMDGPU::COPY), AMDGPU::M0)
3621 .add(GetArg(*Info.getLDSPtrArg()));
3622
3623 auto MIB = BuildMI(*MBB, &MI, DL, TII.get(Opc));
3624
3625 if (HasVIndex && HasVOffset) {
3626 Register IdxReg = MRI->createVirtualRegister(TRI.getVGPR64Class());
3627 BuildMI(*MBB, &*MIB, DL, TII.get(AMDGPU::REG_SEQUENCE), IdxReg)
3628 .addReg(VIndex)
3629 .addImm(AMDGPU::sub0)
3630 .addReg(VOffset)
3631 .addImm(AMDGPU::sub1);
3632
3633 MIB.addReg(IdxReg);
3634 } else if (HasVIndex) {
3635 MIB.addReg(VIndex);
3636 } else if (HasVOffset) {
3637 MIB.addReg(VOffset);
3638 }
3639
3640 MIB.add(GetArg(Info.RsrcArg));
3641 MIB.add(GetArg(*Info.getSOffsetArg()));
3642 MIB.add(GetArg(*Info.getImmOffsetArg()));
3643 bool IsGFX12Plus = AMDGPU::isGFX12Plus(STI);
3644 int64_t Aux = GetArg(*Info.getAuxArg()).getImm();
3645 MIB.addImm(Aux & (IsGFX12Plus ? AMDGPU::CPol::ALL
3646 : AMDGPU::CPol::ALL_pregfx12)); // cpol
3647 MIB.addImm(
3648 Aux & (IsGFX12Plus ? AMDGPU::CPol::SWZ : AMDGPU::CPol::SWZ_pregfx12)
3649 ? 1
3650 : 0); // swz
3651 MIB.addImm(Info.IsAsync);
3652
3653 MachineMemOperand *LoadMMO = *MI.memoperands_begin();
3654 // Don't set the offset value here because the pointer points to the base of
3655 // the buffer.
3656 MachinePointerInfo LoadPtrI = LoadMMO->getPointerInfo();
3657
3658 MachinePointerInfo StorePtrI = LoadPtrI;
3659 LoadPtrI.V = PoisonValue::get(PointerType::get(MF->getFunction().getContext(),
3663
3664 auto F = LoadMMO->getFlags() &
3666 LoadMMO = MF->getMachineMemOperand(LoadPtrI, F | MachineMemOperand::MOLoad,
3667 Size, LoadMMO->getBaseAlign());
3668
3669 MachineMemOperand *StoreMMO =
3670 MF->getMachineMemOperand(StorePtrI, F | MachineMemOperand::MOStore,
3671 sizeof(int32_t), LoadMMO->getBaseAlign());
3672
3673 MIB.setMemRefs({LoadMMO, StoreMMO});
3674
3675 MI.eraseFromParent();
3676 constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
3677 return true;
3678}
3679
3680/// Match a zero extend from a 32-bit value to 64-bits.
3681Register AMDGPUInstructionSelector::matchZeroExtendFromS32(Register Reg) const {
3682 Register ZExtSrc;
3683 if (mi_match(Reg, *MRI, m_GZExt(m_Reg(ZExtSrc))))
3684 return MRI->getType(ZExtSrc) == LLT::scalar(32) ? ZExtSrc : Register();
3685
3686 // Match legalized form %zext = G_MERGE_VALUES (s32 %x), (s32 0)
3687 const MachineInstr *Def = getDefIgnoringCopies(Reg, *MRI);
3688 if (Def->getOpcode() != AMDGPU::G_MERGE_VALUES)
3689 return Register();
3690
3691 assert(Def->getNumOperands() == 3 &&
3692 MRI->getType(Def->getOperand(0).getReg()) == LLT::scalar(64));
3693 if (mi_match(Def->getOperand(2).getReg(), *MRI, m_ZeroInt())) {
3694 return Def->getOperand(1).getReg();
3695 }
3696
3697 return Register();
3698}
3699
3700/// Match a sign extend from a 32-bit value to 64-bits.
3701Register AMDGPUInstructionSelector::matchSignExtendFromS32(Register Reg) const {
3702 Register SExtSrc;
3703 if (mi_match(Reg, *MRI, m_GSExt(m_Reg(SExtSrc))))
3704 return MRI->getType(SExtSrc) == LLT::scalar(32) ? SExtSrc : Register();
3705
3706 // Match legalized form %sext = G_MERGE_VALUES (s32 %x), G_ASHR((S32 %x, 31))
3707 const MachineInstr *Def = getDefIgnoringCopies(Reg, *MRI);
3708 if (Def->getOpcode() != AMDGPU::G_MERGE_VALUES)
3709 return Register();
3710
3711 assert(Def->getNumOperands() == 3 &&
3712 MRI->getType(Def->getOperand(0).getReg()) == LLT::scalar(64));
3713 if (mi_match(Def->getOperand(2).getReg(), *MRI,
3714 m_GAShr(m_SpecificReg(Def->getOperand(1).getReg()),
3715 m_SpecificICst(31))))
3716 return Def->getOperand(1).getReg();
3717
3718 Register ZextSrc = matchZeroExtendFromS32(Reg);
3719 if (ZextSrc && VT->signBitIsZero(ZextSrc))
3720 return ZextSrc;
3721
3722 return Register();
3723}
3724
3725/// Match a zero extend from a 32-bit value to 64-bits, or \p Reg itself if it
3726/// is 32-bit.
3728AMDGPUInstructionSelector::matchZeroExtendFromS32OrS32(Register Reg) const {
3729 return MRI->getType(Reg) == LLT::scalar(32) ? Reg
3730 : matchZeroExtendFromS32(Reg);
3731}
3732
3733/// Match a sign extend from a 32-bit value to 64-bits, or \p Reg itself if it
3734/// is 32-bit.
3736AMDGPUInstructionSelector::matchSignExtendFromS32OrS32(Register Reg) const {
3737 return MRI->getType(Reg) == LLT::scalar(32) ? Reg
3738 : matchSignExtendFromS32(Reg);
3739}
3740
3742AMDGPUInstructionSelector::matchExtendFromS32OrS32(Register Reg,
3743 bool IsSigned) const {
3744 if (IsSigned)
3745 return matchSignExtendFromS32OrS32(Reg);
3746
3747 return matchZeroExtendFromS32OrS32(Reg);
3748}
3749
3750Register AMDGPUInstructionSelector::matchAnyExtendFromS32(Register Reg) const {
3751 Register AnyExtSrc;
3752 if (mi_match(Reg, *MRI, m_GAnyExt(m_Reg(AnyExtSrc))))
3753 return MRI->getType(AnyExtSrc) == LLT::scalar(32) ? AnyExtSrc : Register();
3754
3755 // Match legalized form %zext = G_MERGE_VALUES (s32 %x), (s32 G_IMPLICIT_DEF)
3756 const MachineInstr *Def = getDefIgnoringCopies(Reg, *MRI);
3757 if (Def->getOpcode() != AMDGPU::G_MERGE_VALUES)
3758 return Register();
3759
3760 assert(Def->getNumOperands() == 3 &&
3761 MRI->getType(Def->getOperand(0).getReg()) == LLT::scalar(64));
3762
3763 if (mi_match(Def->getOperand(2).getReg(), *MRI, m_GImplicitDef()))
3764 return Def->getOperand(1).getReg();
3765
3766 return Register();
3767}
3768
3769bool AMDGPUInstructionSelector::selectGlobalLoadLds(MachineInstr &MI) const{
3770 if (!Subtarget->hasVMemToLDSLoad())
3771 return false;
3772
3773 unsigned Opc;
3774 unsigned Size = static_cast<unsigned>(MI.getOperand(3).getImm());
3775 Intrinsic::ID IntrinsicID = cast<GIntrinsic>(MI).getIntrinsicID();
3776
3777 switch (Size) {
3778 default:
3779 return false;
3780 case 1:
3781 Opc = AMDGPU::GLOBAL_LOAD_LDS_UBYTE;
3782 break;
3783 case 2:
3784 Opc = AMDGPU::GLOBAL_LOAD_LDS_USHORT;
3785 break;
3786 case 4:
3787 Opc = AMDGPU::GLOBAL_LOAD_LDS_DWORD;
3788 break;
3789 case 12:
3790 if (!Subtarget->hasLDSLoadB96_B128())
3791 return false;
3792 Opc = AMDGPU::GLOBAL_LOAD_LDS_DWORDX3;
3793 break;
3794 case 16:
3795 if (!Subtarget->hasLDSLoadB96_B128())
3796 return false;
3797 Opc = AMDGPU::GLOBAL_LOAD_LDS_DWORDX4;
3798 break;
3799 }
3800
3801 MachineBasicBlock *MBB = MI.getParent();
3802 const DebugLoc &DL = MI.getDebugLoc();
3803 BuildMI(*MBB, &MI, DL, TII.get(AMDGPU::COPY), AMDGPU::M0)
3804 .add(MI.getOperand(2));
3805
3806 Register Addr = MI.getOperand(1).getReg();
3807 Register VOffset;
3808 // Try to split SAddr and VOffset. Global and LDS pointers share the same
3809 // immediate offset, so we cannot use a regular SelectGlobalSAddr().
3810 if (!isSGPR(Addr)) {
3811 auto AddrDef = getDefSrcRegIgnoringCopies(Addr, *MRI);
3812 if (isSGPR(AddrDef->Reg)) {
3813 Addr = AddrDef->Reg;
3814 } else if (AddrDef->MI->getOpcode() == AMDGPU::G_PTR_ADD) {
3815 Register SAddr =
3816 getSrcRegIgnoringCopies(AddrDef->MI->getOperand(1).getReg(), *MRI);
3817 if (isSGPR(SAddr)) {
3818 Register PtrBaseOffset = AddrDef->MI->getOperand(2).getReg();
3819 if (Register Off = matchZeroExtendFromS32(PtrBaseOffset)) {
3820 Addr = SAddr;
3821 VOffset = Off;
3822 }
3823 }
3824 }
3825 }
3826
3827 if (isSGPR(Addr)) {
3829 if (!VOffset) {
3830 VOffset = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3831 BuildMI(*MBB, &MI, DL, TII.get(AMDGPU::V_MOV_B32_e32), VOffset)
3832 .addImm(0);
3833 }
3834 }
3835
3836 auto MIB = BuildMI(*MBB, &MI, DL, TII.get(Opc))
3837 .addReg(Addr);
3838
3839 if (isSGPR(Addr))
3840 MIB.addReg(VOffset);
3841
3842 MIB.add(MI.getOperand(4)); // offset
3843
3844 unsigned Aux = static_cast<unsigned>(MI.getOperand(5).getImm());
3845 MIB.addImm(Aux & ~AMDGPU::CPol::VIRTUAL_BITS); // cpol
3846 MIB.addImm(isAsyncLDSDMA(IntrinsicID));
3847
3848 MachineMemOperand *LoadMMO = *MI.memoperands_begin();
3849 MachinePointerInfo LoadPtrI = LoadMMO->getPointerInfo();
3850 LoadPtrI.Offset = MI.getOperand(4).getImm();
3851 MachinePointerInfo StorePtrI = LoadPtrI;
3852 LoadPtrI.V = PoisonValue::get(PointerType::get(MF->getFunction().getContext(),
3856 auto F = LoadMMO->getFlags() &
3858 LoadMMO = MF->getMachineMemOperand(LoadPtrI, F | MachineMemOperand::MOLoad,
3859 Size, LoadMMO->getBaseAlign());
3860 MachineMemOperand *StoreMMO =
3861 MF->getMachineMemOperand(StorePtrI, F | MachineMemOperand::MOStore,
3862 sizeof(int32_t), Align(4));
3863
3864 MIB.setMemRefs({LoadMMO, StoreMMO});
3865
3866 MI.eraseFromParent();
3867 constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
3868 return true;
3869}
3870
3871bool AMDGPUInstructionSelector::selectTensorLoadStore(MachineInstr &MI,
3872 Intrinsic::ID IID) const {
3873 bool IsLoad = IID == Intrinsic::amdgcn_tensor_load_to_lds;
3874 unsigned Opc =
3875 IsLoad ? AMDGPU::TENSOR_LOAD_TO_LDS_d4 : AMDGPU::TENSOR_STORE_FROM_LDS_d4;
3876 int NumGroups = 4;
3877
3878 // A lamda function to check whether an operand is a vector of all 0s.
3879 const auto isAllZeros = [&](MachineOperand &Opnd) {
3880 const MachineInstr *DefMI = MRI->getVRegDef(Opnd.getReg());
3881 if (!DefMI)
3882 return false;
3883 return llvm::isBuildVectorAllZeros(*DefMI, *MRI, true);
3884 };
3885
3886 // Use _D2 version if both group 2 and 3 are zero-initialized.
3887 if (isAllZeros(MI.getOperand(3)) && isAllZeros(MI.getOperand(4))) {
3888 NumGroups = 2;
3889 Opc = IsLoad ? AMDGPU::TENSOR_LOAD_TO_LDS_d2
3890 : AMDGPU::TENSOR_STORE_FROM_LDS_d2;
3891 }
3892
3893 // TODO: Handle the fifth group: MI.getOpetand(5), which is silently ignored
3894 // for now because all existing targets only support up to 4 groups.
3895 MachineBasicBlock *MBB = MI.getParent();
3896 auto MIB = BuildMI(*MBB, &MI, MI.getDebugLoc(), TII.get(Opc))
3897 .add(MI.getOperand(1)) // D# group 0
3898 .add(MI.getOperand(2)); // D# group 1
3899
3900 if (NumGroups >= 4) { // Has at least 4 groups
3901 MIB.add(MI.getOperand(3)) // D# group 2
3902 .add(MI.getOperand(4)); // D# group 3
3903 }
3904
3905 MIB.addImm(0) // r128
3906 .add(MI.getOperand(6)); // cpol
3907
3908 MI.eraseFromParent();
3909 return true;
3910}
3911
3912bool AMDGPUInstructionSelector::selectBVHIntersectRayIntrinsic(
3913 MachineInstr &MI) const {
3914 unsigned OpcodeOpIdx =
3915 MI.getOpcode() == AMDGPU::G_AMDGPU_BVH_INTERSECT_RAY ? 1 : 3;
3916 MI.setDesc(
3917 TII.get(static_cast<unsigned>(MI.getOperand(OpcodeOpIdx).getImm())));
3918 MI.removeOperand(OpcodeOpIdx);
3919 MI.addImplicitDefUseOperands(*MI.getMF());
3920 constrainSelectedInstRegOperands(MI, TII, TRI, RBI);
3921 return true;
3922}
3923
3924// FIXME: This should be removed and let the patterns select. We just need the
3925// AGPR/VGPR combination versions.
3926bool AMDGPUInstructionSelector::selectSMFMACIntrin(MachineInstr &MI) const {
3927 unsigned Opc;
3928 switch (cast<GIntrinsic>(MI).getIntrinsicID()) {
3929 case Intrinsic::amdgcn_smfmac_f32_16x16x32_f16:
3930 Opc = AMDGPU::V_SMFMAC_F32_16X16X32_F16_e64;
3931 break;
3932 case Intrinsic::amdgcn_smfmac_f32_32x32x16_f16:
3933 Opc = AMDGPU::V_SMFMAC_F32_32X32X16_F16_e64;
3934 break;
3935 case Intrinsic::amdgcn_smfmac_f32_16x16x32_bf16:
3936 Opc = AMDGPU::V_SMFMAC_F32_16X16X32_BF16_e64;
3937 break;
3938 case Intrinsic::amdgcn_smfmac_f32_32x32x16_bf16:
3939 Opc = AMDGPU::V_SMFMAC_F32_32X32X16_BF16_e64;
3940 break;
3941 case Intrinsic::amdgcn_smfmac_i32_16x16x64_i8:
3942 Opc = AMDGPU::V_SMFMAC_I32_16X16X64_I8_e64;
3943 break;
3944 case Intrinsic::amdgcn_smfmac_i32_32x32x32_i8:
3945 Opc = AMDGPU::V_SMFMAC_I32_32X32X32_I8_e64;
3946 break;
3947 case Intrinsic::amdgcn_smfmac_f32_16x16x64_bf8_bf8:
3948 Opc = AMDGPU::V_SMFMAC_F32_16X16X64_BF8_BF8_e64;
3949 break;
3950 case Intrinsic::amdgcn_smfmac_f32_16x16x64_bf8_fp8:
3951 Opc = AMDGPU::V_SMFMAC_F32_16X16X64_BF8_FP8_e64;
3952 break;
3953 case Intrinsic::amdgcn_smfmac_f32_16x16x64_fp8_bf8:
3954 Opc = AMDGPU::V_SMFMAC_F32_16X16X64_FP8_BF8_e64;
3955 break;
3956 case Intrinsic::amdgcn_smfmac_f32_16x16x64_fp8_fp8:
3957 Opc = AMDGPU::V_SMFMAC_F32_16X16X64_FP8_FP8_e64;
3958 break;
3959 case Intrinsic::amdgcn_smfmac_f32_32x32x32_bf8_bf8:
3960 Opc = AMDGPU::V_SMFMAC_F32_32X32X32_BF8_BF8_e64;
3961 break;
3962 case Intrinsic::amdgcn_smfmac_f32_32x32x32_bf8_fp8:
3963 Opc = AMDGPU::V_SMFMAC_F32_32X32X32_BF8_FP8_e64;
3964 break;
3965 case Intrinsic::amdgcn_smfmac_f32_32x32x32_fp8_bf8:
3966 Opc = AMDGPU::V_SMFMAC_F32_32X32X32_FP8_BF8_e64;
3967 break;
3968 case Intrinsic::amdgcn_smfmac_f32_32x32x32_fp8_fp8:
3969 Opc = AMDGPU::V_SMFMAC_F32_32X32X32_FP8_FP8_e64;
3970 break;
3971 case Intrinsic::amdgcn_smfmac_f32_16x16x64_f16:
3972 Opc = AMDGPU::V_SMFMAC_F32_16X16X64_F16_e64;
3973 break;
3974 case Intrinsic::amdgcn_smfmac_f32_32x32x32_f16:
3975 Opc = AMDGPU::V_SMFMAC_F32_32X32X32_F16_e64;
3976 break;
3977 case Intrinsic::amdgcn_smfmac_f32_16x16x64_bf16:
3978 Opc = AMDGPU::V_SMFMAC_F32_16X16X64_BF16_e64;
3979 break;
3980 case Intrinsic::amdgcn_smfmac_f32_32x32x32_bf16:
3981 Opc = AMDGPU::V_SMFMAC_F32_32X32X32_BF16_e64;
3982 break;
3983 case Intrinsic::amdgcn_smfmac_i32_16x16x128_i8:
3984 Opc = AMDGPU::V_SMFMAC_I32_16X16X128_I8_e64;
3985 break;
3986 case Intrinsic::amdgcn_smfmac_i32_32x32x64_i8:
3987 Opc = AMDGPU::V_SMFMAC_I32_32X32X64_I8_e64;
3988 break;
3989 case Intrinsic::amdgcn_smfmac_f32_16x16x128_bf8_bf8:
3990 Opc = AMDGPU::V_SMFMAC_F32_16X16X128_BF8_BF8_e64;
3991 break;
3992 case Intrinsic::amdgcn_smfmac_f32_16x16x128_bf8_fp8:
3993 Opc = AMDGPU::V_SMFMAC_F32_16X16X128_BF8_FP8_e64;
3994 break;
3995 case Intrinsic::amdgcn_smfmac_f32_16x16x128_fp8_bf8:
3996 Opc = AMDGPU::V_SMFMAC_F32_16X16X128_FP8_BF8_e64;
3997 break;
3998 case Intrinsic::amdgcn_smfmac_f32_16x16x128_fp8_fp8:
3999 Opc = AMDGPU::V_SMFMAC_F32_16X16X128_FP8_FP8_e64;
4000 break;
4001 case Intrinsic::amdgcn_smfmac_f32_32x32x64_bf8_bf8:
4002 Opc = AMDGPU::V_SMFMAC_F32_32X32X64_BF8_BF8_e64;
4003 break;
4004 case Intrinsic::amdgcn_smfmac_f32_32x32x64_bf8_fp8:
4005 Opc = AMDGPU::V_SMFMAC_F32_32X32X64_BF8_FP8_e64;
4006 break;
4007 case Intrinsic::amdgcn_smfmac_f32_32x32x64_fp8_bf8:
4008 Opc = AMDGPU::V_SMFMAC_F32_32X32X64_FP8_BF8_e64;
4009 break;
4010 case Intrinsic::amdgcn_smfmac_f32_32x32x64_fp8_fp8:
4011 Opc = AMDGPU::V_SMFMAC_F32_32X32X64_FP8_FP8_e64;
4012 break;
4013 default:
4014 llvm_unreachable("unhandled smfmac intrinsic");
4015 }
4016
4017 auto VDst_In = MI.getOperand(4);
4018
4019 MI.setDesc(TII.get(Opc));
4020 MI.removeOperand(4); // VDst_In
4021 MI.removeOperand(1); // Intrinsic ID
4022 MI.addOperand(VDst_In); // Readd VDst_In to the end
4023 MI.addImplicitDefUseOperands(*MI.getMF());
4024 const MCInstrDesc &MCID = MI.getDesc();
4025 if (MCID.getOperandConstraint(0, MCOI::EARLY_CLOBBER) != -1) {
4026 MI.getOperand(0).setIsEarlyClobber(true);
4027 }
4028 return true;
4029}
4030
4031bool AMDGPUInstructionSelector::selectPermlaneSwapIntrin(
4032 MachineInstr &MI, Intrinsic::ID IntrID) const {
4033 if (IntrID == Intrinsic::amdgcn_permlane16_swap &&
4034 !Subtarget->hasPermlane16Swap())
4035 return false;
4036 if (IntrID == Intrinsic::amdgcn_permlane32_swap &&
4037 !Subtarget->hasPermlane32Swap())
4038 return false;
4039
4040 unsigned Opcode = IntrID == Intrinsic::amdgcn_permlane16_swap
4041 ? AMDGPU::V_PERMLANE16_SWAP_B32_e64
4042 : AMDGPU::V_PERMLANE32_SWAP_B32_e64;
4043
4044 MI.removeOperand(2);
4045 MI.setDesc(TII.get(Opcode));
4046 MI.addOperand(*MF, MachineOperand::CreateReg(AMDGPU::EXEC, false, true));
4047
4048 MachineOperand &FI = MI.getOperand(4);
4050
4051 constrainSelectedInstRegOperands(MI, TII, TRI, RBI);
4052 return true;
4053}
4054
4055bool AMDGPUInstructionSelector::selectWaveAddress(MachineInstr &MI) const {
4056 Register DstReg = MI.getOperand(0).getReg();
4057 Register SrcReg = MI.getOperand(1).getReg();
4058 const RegisterBank *DstRB = RBI.getRegBank(DstReg, *MRI, TRI);
4059 const bool IsVALU = DstRB->getID() == AMDGPU::VGPRRegBankID;
4060 MachineBasicBlock *MBB = MI.getParent();
4061 const DebugLoc &DL = MI.getDebugLoc();
4062
4063 if (IsVALU) {
4064 BuildMI(*MBB, MI, DL, TII.get(AMDGPU::V_LSHRREV_B32_e64), DstReg)
4065 .addImm(Subtarget->getWavefrontSizeLog2())
4066 .addReg(SrcReg);
4067 } else {
4068 BuildMI(*MBB, MI, DL, TII.get(AMDGPU::S_LSHR_B32), DstReg)
4069 .addReg(SrcReg)
4070 .addImm(Subtarget->getWavefrontSizeLog2())
4071 .setOperandDead(3); // Dead scc
4072 }
4073
4074 const TargetRegisterClass &RC =
4075 IsVALU ? AMDGPU::VGPR_32RegClass : AMDGPU::SReg_32RegClass;
4076 if (!RBI.constrainGenericRegister(DstReg, RC, *MRI))
4077 return false;
4078
4079 MI.eraseFromParent();
4080 return true;
4081}
4082
4083bool AMDGPUInstructionSelector::selectWaveShuffleIntrin(
4084 MachineInstr &MI) const {
4085 assert(MI.getNumOperands() == 4);
4086 MachineBasicBlock *MBB = MI.getParent();
4087 const DebugLoc &DL = MI.getDebugLoc();
4088
4089 Register DstReg = MI.getOperand(0).getReg();
4090 Register ValReg = MI.getOperand(2).getReg();
4091 Register IdxReg = MI.getOperand(3).getReg();
4092
4093 const LLT DstTy = MRI->getType(DstReg);
4094 uint64_t DstSize = DstTy.getSizeInBits();
4095 const RegisterBank *DstRB = RBI.getRegBank(DstReg, *MRI, TRI);
4096 const TargetRegisterClass *DstRC =
4097 TRI.getRegClassForSizeOnBank(DstSize, *DstRB);
4098
4099 if (DstTy != LLT::scalar(32))
4100 return false;
4101
4102 if (!Subtarget->supportsBPermute())
4103 return false;
4104
4105 // If we can bpermute across the whole wave, then just do that
4106 if (Subtarget->supportsWaveWideBPermute()) {
4107 Register ShiftIdxReg = MRI->createVirtualRegister(DstRC);
4108 BuildMI(*MBB, MI, DL, TII.get(AMDGPU::V_LSHLREV_B32_e64), ShiftIdxReg)
4109 .addImm(2)
4110 .addReg(IdxReg);
4111
4112 BuildMI(*MBB, MI, DL, TII.get(AMDGPU::DS_BPERMUTE_B32), DstReg)
4113 .addReg(ShiftIdxReg)
4114 .addReg(ValReg)
4115 .addImm(0);
4116 } else {
4117 // Otherwise, we need to make use of whole wave mode
4118 assert(Subtarget->isWave64());
4119
4120 // Set inactive lanes to poison
4121 Register UndefValReg =
4122 MRI->createVirtualRegister(TRI.getRegClass(AMDGPU::SReg_32RegClassID));
4123 BuildMI(*MBB, MI, DL, TII.get(AMDGPU::IMPLICIT_DEF), UndefValReg);
4124
4125 Register UndefExecReg = MRI->createVirtualRegister(
4126 TRI.getRegClass(AMDGPU::SReg_64_XEXECRegClassID));
4127 BuildMI(*MBB, MI, DL, TII.get(AMDGPU::IMPLICIT_DEF), UndefExecReg);
4128
4129 Register PoisonValReg = MRI->createVirtualRegister(DstRC);
4130 BuildMI(*MBB, MI, DL, TII.get(AMDGPU::V_SET_INACTIVE_B32), PoisonValReg)
4131 .addImm(0)
4132 .addReg(ValReg)
4133 .addImm(0)
4134 .addReg(UndefValReg)
4135 .addReg(UndefExecReg);
4136
4137 // ds_bpermute requires index to be multiplied by 4
4138 Register ShiftIdxReg = MRI->createVirtualRegister(DstRC);
4139 BuildMI(*MBB, MI, DL, TII.get(AMDGPU::V_LSHLREV_B32_e64), ShiftIdxReg)
4140 .addImm(2)
4141 .addReg(IdxReg);
4142
4143 Register PoisonIdxReg = MRI->createVirtualRegister(DstRC);
4144 BuildMI(*MBB, MI, DL, TII.get(AMDGPU::V_SET_INACTIVE_B32), PoisonIdxReg)
4145 .addImm(0)
4146 .addReg(ShiftIdxReg)
4147 .addImm(0)
4148 .addReg(UndefValReg)
4149 .addReg(UndefExecReg);
4150
4151 Register PoisonUnshiftedIdxReg = MRI->createVirtualRegister(DstRC);
4152 BuildMI(*MBB, MI, DL, TII.get(AMDGPU::V_SET_INACTIVE_B32),
4153 PoisonUnshiftedIdxReg)
4154 .addImm(0)
4155 .addReg(IdxReg)
4156 .addImm(0)
4157 .addReg(UndefValReg)
4158 .addReg(UndefExecReg);
4159
4160 // Get permutation of each half, then we'll select which one to use
4161 Register SameSidePermReg = MRI->createVirtualRegister(DstRC);
4162 BuildMI(*MBB, MI, DL, TII.get(AMDGPU::DS_BPERMUTE_B32), SameSidePermReg)
4163 .addReg(PoisonIdxReg)
4164 .addReg(PoisonValReg)
4165 .addImm(0);
4166
4167 Register SwappedValReg = MRI->createVirtualRegister(DstRC);
4168 BuildMI(*MBB, MI, DL, TII.get(AMDGPU::V_PERMLANE64_B32), SwappedValReg)
4169 .addReg(PoisonValReg);
4170
4171 Register OppSidePermReg = MRI->createVirtualRegister(DstRC);
4172 BuildMI(*MBB, MI, DL, TII.get(AMDGPU::DS_BPERMUTE_B32), OppSidePermReg)
4173 .addReg(PoisonIdxReg)
4174 .addReg(SwappedValReg)
4175 .addImm(0);
4176
4177 Register WWMSwapPermReg = MRI->createVirtualRegister(DstRC);
4178 BuildMI(*MBB, MI, DL, TII.get(AMDGPU::STRICT_WWM), WWMSwapPermReg)
4179 .addReg(OppSidePermReg);
4180
4181 // Select which side to take the permute from
4182 // We can get away with only using mbcnt_lo here since we're only
4183 // trying to detect which side of 32 each lane is on, and mbcnt_lo
4184 // returns 32 for lanes 32-63.
4185 Register ThreadIDReg = MRI->createVirtualRegister(DstRC);
4186 BuildMI(*MBB, MI, DL, TII.get(AMDGPU::V_MBCNT_LO_U32_B32_e64), ThreadIDReg)
4187 .addImm(-1)
4188 .addImm(0);
4189
4190 Register XORReg = MRI->createVirtualRegister(DstRC);
4191 BuildMI(*MBB, MI, DL, TII.get(AMDGPU::V_XOR_B32_e64), XORReg)
4192 .addReg(ThreadIDReg)
4193 .addReg(PoisonUnshiftedIdxReg);
4194
4195 Register ANDReg = MRI->createVirtualRegister(DstRC);
4196 BuildMI(*MBB, MI, DL, TII.get(AMDGPU::V_AND_B32_e64), ANDReg)
4197 .addReg(XORReg)
4198 .addImm(32);
4199
4200 Register CompareReg = MRI->createVirtualRegister(
4201 TRI.getRegClass(AMDGPU::SReg_64_XEXECRegClassID));
4202 BuildMI(*MBB, MI, DL, TII.get(AMDGPU::V_CMP_EQ_U32_e64), CompareReg)
4203 .addReg(ANDReg)
4204 .addImm(0);
4205
4206 // Finally do the selection
4207 BuildMI(*MBB, MI, DL, TII.get(AMDGPU::V_CNDMASK_B32_e64), DstReg)
4208 .addImm(0)
4209 .addReg(WWMSwapPermReg)
4210 .addImm(0)
4211 .addReg(SameSidePermReg)
4212 .addReg(CompareReg);
4213 }
4214
4215 MI.eraseFromParent();
4216 return true;
4217}
4218
4219// Match BITOP3 operation and return a number of matched instructions plus
4220// truth table.
4221static std::pair<unsigned, uint8_t> BitOp3_Op(Register R,
4223 const MachineRegisterInfo &MRI) {
4224 unsigned NumOpcodes = 0;
4225 uint8_t LHSBits, RHSBits;
4226
4227 auto getOperandBits = [&Src, R, &MRI](Register Op, uint8_t &Bits) -> bool {
4228 // Define truth table given Src0, Src1, Src2 bits permutations:
4229 // 0 0 0
4230 // 0 0 1
4231 // 0 1 0
4232 // 0 1 1
4233 // 1 0 0
4234 // 1 0 1
4235 // 1 1 0
4236 // 1 1 1
4237 const uint8_t SrcBits[3] = { 0xf0, 0xcc, 0xaa };
4238
4239 if (mi_match(Op, MRI, m_AllOnesInt())) {
4240 Bits = 0xff;
4241 return true;
4242 }
4243 if (mi_match(Op, MRI, m_ZeroInt())) {
4244 Bits = 0;
4245 return true;
4246 }
4247
4248 for (unsigned I = 0; I < Src.size(); ++I) {
4249 // Try to find existing reused operand
4250 if (Src[I] == Op) {
4251 Bits = SrcBits[I];
4252 return true;
4253 }
4254 // Try to replace parent operator
4255 if (Src[I] == R) {
4256 Bits = SrcBits[I];
4257 Src[I] = Op;
4258 return true;
4259 }
4260 }
4261
4262 if (Src.size() == 3) {
4263 // No room left for operands. Try one last time, there can be a 'not' of
4264 // one of our source operands. In this case we can compute the bits
4265 // without growing Src vector.
4266 Register LHS;
4267 if (mi_match(Op, MRI, m_Not(m_Reg(LHS)))) {
4269 for (unsigned I = 0; I < Src.size(); ++I) {
4270 if (Src[I] == LHS) {
4271 Bits = ~SrcBits[I];
4272 return true;
4273 }
4274 }
4275 }
4276
4277 return false;
4278 }
4279
4280 Bits = SrcBits[Src.size()];
4281 Src.push_back(Op);
4282 return true;
4283 };
4284
4285 MachineInstr *MI = MRI.getVRegDef(R);
4286 switch (MI->getOpcode()) {
4287 case TargetOpcode::G_AND:
4288 case TargetOpcode::G_OR:
4289 case TargetOpcode::G_XOR: {
4290 Register LHS = getSrcRegIgnoringCopies(MI->getOperand(1).getReg(), MRI);
4291 Register RHS = getSrcRegIgnoringCopies(MI->getOperand(2).getReg(), MRI);
4292
4293 SmallVector<Register, 3> Backup(Src.begin(), Src.end());
4294 if (!getOperandBits(LHS, LHSBits) ||
4295 !getOperandBits(RHS, RHSBits)) {
4296 Src = std::move(Backup);
4297 return {};
4298 }
4299
4300 // Recursion is naturally limited by the size of the operand vector.
4301 //
4302 // When LHS and RHS share a common sub-expression, one side's recursion
4303 // may decompose that sub-expression and replace the Src slot the other
4304 // side occupies with sub-operands via the "replace parent" path in
4305 // getOperandBits. The other side's cached bit-pattern then refers to a
4306 // slot whose contents changed, producing a wrong truth table.
4307 //
4308 // We detect this in three ways:
4309 // (A) If LHS recursed, its truth table is valid against the Src state
4310 // when LHS recursion completed (SrcAfterLHS). If RHS recursion
4311 // then mutates a Src slot that LHSBits depends on, LHSBits is
4312 // stale.
4313 // (B) If RHS did not recurse, RHSBits came from getOperandBits and
4314 // refers to a specific Src slot. If that slot's contents changed
4315 // (by either recursion), RHSBits is stale.
4316 // (C) Symmetrically for LHS if it did not recurse.
4317 SmallVector<Register, 3> SrcBeforeRecurse(Src.begin(), Src.end());
4318 uint8_t LHSBitsOrig = LHSBits;
4319 uint8_t RHSBitsOrig = RHSBits;
4320
4321 auto LHSOp = BitOp3_Op(LHS, Src, MRI);
4322 if (LHSOp.first) {
4323 NumOpcodes += LHSOp.first;
4324 LHSBits = LHSOp.second;
4325 }
4326
4327 SmallVector<Register, 3> SrcAfterLHS(Src.begin(), Src.end());
4328
4329 auto RHSOp = BitOp3_Op(RHS, Src, MRI);
4330 if (RHSOp.first) {
4331 NumOpcodes += RHSOp.first;
4332 RHSBits = RHSOp.second;
4333 }
4334
4335 // dependsOnSlot: true iff the truth table TT varies with slot Slot.
4336 auto dependsOnSlot = [](uint8_t TT, int Slot) -> bool {
4337 if (Slot < 0 || Slot > 2)
4338 return false;
4339 const uint8_t Masks[3] = {0x0f, 0x33, 0x55};
4340 const int Shifts[3] = {4, 2, 1};
4341 return ((TT ^ (TT >> Shifts[Slot])) & Masks[Slot]) != 0;
4342 };
4343
4344 // findSlot: locate the Src slot a getOperandBits result depends on,
4345 // including negated (NOT) patterns that getOperandBits resolves via
4346 // the ~SrcBits[I] shortcut.
4347 const uint8_t SrcBitsConst[3] = {0xf0, 0xcc, 0xaa};
4348 auto findSlot = [&](uint8_t Bits, Register Op,
4349 const SmallVectorImpl<Register> &S) -> int {
4350 Register NegatedInner;
4351 bool IsNegationOp = mi_match(Op, MRI, m_Not(m_Reg(NegatedInner)));
4352 if (IsNegationOp)
4353 NegatedInner = getSrcRegIgnoringCopies(NegatedInner, MRI);
4354 for (int I = 0; I < (int)S.size(); I++) {
4355 if (Bits == SrcBitsConst[I] && S[I] == Op)
4356 return I;
4357 if (IsNegationOp && Bits == (uint8_t)~SrcBitsConst[I] &&
4358 S[I] == NegatedInner)
4359 return I;
4360 }
4361 return -1;
4362 };
4363
4364 bool Stale = false;
4365
4366 // (A) LHS recursed: its truth table is against SrcAfterLHS.
4367 // Check if RHS recursion mutated a slot that LHSBits uses.
4368 if (LHSOp.first) {
4369 for (int I = 0; I < (int)SrcAfterLHS.size() && I < 3; I++) {
4370 if (I < (int)Src.size() && Src[I] != SrcAfterLHS[I] &&
4371 dependsOnSlot(LHSBits, I)) {
4372 Stale = true;
4373 break;
4374 }
4375 }
4376 }
4377
4378 // (B) RHS did not recurse: RHSBits from getOperandBits is against
4379 // SrcBeforeRecurse. Check if that slot was mutated since then.
4380 if (!Stale && !RHSOp.first) {
4381 int Slot = findSlot(RHSBitsOrig, RHS, SrcBeforeRecurse);
4382 if (Slot >= 0 &&
4383 (Slot >= (int)Src.size() || Src[Slot] != SrcBeforeRecurse[Slot]))
4384 Stale = true;
4385 }
4386
4387 // (C) LHS did not recurse: LHSBits from getOperandBits is against
4388 // SrcBeforeRecurse. Check if that slot was mutated since then.
4389 if (!Stale && !LHSOp.first) {
4390 int Slot = findSlot(LHSBitsOrig, LHS, SrcBeforeRecurse);
4391 if (Slot >= 0 &&
4392 (Slot >= (int)Src.size() || Src[Slot] != SrcBeforeRecurse[Slot]))
4393 Stale = true;
4394 }
4395
4396 if (Stale) {
4397 Src = std::move(SrcBeforeRecurse);
4398 LHSBits = LHSBitsOrig;
4399 RHSBits = RHSBitsOrig;
4400 NumOpcodes = 0;
4401 }
4402 break;
4403 }
4404 default:
4405 return {};
4406 }
4407
4408 uint8_t TTbl;
4409 switch (MI->getOpcode()) {
4410 case TargetOpcode::G_AND:
4411 TTbl = LHSBits & RHSBits;
4412 break;
4413 case TargetOpcode::G_OR:
4414 TTbl = LHSBits | RHSBits;
4415 break;
4416 case TargetOpcode::G_XOR:
4417 TTbl = LHSBits ^ RHSBits;
4418 break;
4419 default:
4420 break;
4421 }
4422
4423 return std::make_pair(NumOpcodes + 1, TTbl);
4424}
4425
4426bool AMDGPUInstructionSelector::selectBITOP3(MachineInstr &MI) const {
4427 if (!Subtarget->hasBitOp3Insts())
4428 return false;
4429
4430 Register DstReg = MI.getOperand(0).getReg();
4431 const RegisterBank *DstRB = RBI.getRegBank(DstReg, *MRI, TRI);
4432 const bool IsVALU = DstRB->getID() == AMDGPU::VGPRRegBankID;
4433 if (!IsVALU)
4434 return false;
4435
4437 uint8_t TTbl;
4438 unsigned NumOpcodes;
4439
4440 std::tie(NumOpcodes, TTbl) = BitOp3_Op(DstReg, Src, *MRI);
4441
4442 // Src.empty() case can happen if all operands are all zero or all ones.
4443 // Normally it shall be optimized out before reaching this.
4444 if (NumOpcodes < 2 || Src.empty())
4445 return false;
4446
4447 // RegBankSelect splits wider VALU logic ops and widens 1-bit ones, so only
4448 // 16 and 32 bit types reach here. Note that <2 x i16> is 32 bits wide.
4449 unsigned Size = MRI->getType(DstReg).getSizeInBits();
4450 assert((Size == 16 || Size == 32) && "unexpected VALU logic op size");
4451 const bool IsB32 = Size == 32;
4452 if (NumOpcodes == 2 && IsB32) {
4453 // Avoid using BITOP3 for OR3, XOR3, AND_OR. This is not faster but makes
4454 // asm more readable. This cannot be modeled with AddedComplexity because
4455 // selector does not know how many operations did we match.
4456 if (mi_match(MI, *MRI, m_GXor(m_GXor(m_Reg(), m_Reg()), m_Reg())) ||
4457 mi_match(MI, *MRI, m_GOr(m_GOr(m_Reg(), m_Reg()), m_Reg())) ||
4458 mi_match(MI, *MRI, m_GOr(m_GAnd(m_Reg(), m_Reg()), m_Reg())))
4459 return false;
4460 } else if (NumOpcodes < 4) {
4461 // For a uniform case threshold should be higher to account for moves
4462 // between VGPRs and SGPRs. It needs one operand in a VGPR, rest two can be
4463 // in SGPRs and a readtfirstlane after.
4464 return false;
4465 }
4466
4467 unsigned Opc = IsB32 ? AMDGPU::V_BITOP3_B32_e64 : AMDGPU::V_BITOP3_B16_e64;
4468 if (!IsB32 && STI.hasTrue16BitInsts())
4469 Opc = STI.useRealTrue16Insts() ? AMDGPU::V_BITOP3_B16_gfx1250_t16_e64
4470 : AMDGPU::V_BITOP3_B16_gfx1250_fake16_e64;
4471 unsigned CBL = STI.getConstantBusLimit(Opc);
4472 MachineBasicBlock *MBB = MI.getParent();
4473 const DebugLoc &DL = MI.getDebugLoc();
4474
4475 for (unsigned I = 0; I < Src.size(); ++I) {
4476 const RegisterBank *RB = RBI.getRegBank(Src[I], *MRI, TRI);
4477 if (RB->getID() != AMDGPU::SGPRRegBankID)
4478 continue;
4479 if (CBL > 0) {
4480 --CBL;
4481 continue;
4482 }
4483 Register NewReg = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4484 BuildMI(*MBB, MI, DL, TII.get(AMDGPU::COPY), NewReg)
4485 .addReg(Src[I]);
4486 Src[I] = NewReg;
4487 }
4488
4489 // Last operand can be ignored, turning a ternary operation into a binary.
4490 // For example: (~a & b & c) | (~a & b & ~c) -> (~a & b). We can replace
4491 // 'c' with 'a' here without changing the answer. In some pathological
4492 // cases it should be possible to get an operation with a single operand
4493 // too if optimizer would not catch it.
4494 while (Src.size() < 3)
4495 Src.push_back(Src[0]);
4496
4497 auto MIB = BuildMI(*MBB, MI, DL, TII.get(Opc), DstReg);
4498 if (!IsB32)
4499 MIB.addImm(0); // src_mod0
4500 MIB.addReg(Src[0]);
4501 if (!IsB32)
4502 MIB.addImm(0); // src_mod1
4503 MIB.addReg(Src[1]);
4504 if (!IsB32)
4505 MIB.addImm(0); // src_mod2
4506 MIB.addReg(Src[2])
4507 .addImm(TTbl);
4508 if (!IsB32)
4509 MIB.addImm(0); // op_sel
4510
4511 constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
4512 MI.eraseFromParent();
4513
4514 return true;
4515}
4516
4517bool AMDGPUInstructionSelector::selectWriteRegister(MachineInstr &MI) const {
4518 const MDString *RegStr =
4519 cast<MDString>(MI.getOperand(0).getMetadata()->getOperand(0));
4520 Register SrcReg = MI.getOperand(1).getReg();
4521 LLT Ty = MRI->getType(SrcReg);
4522
4523 Register PhysReg = Subtarget->getTargetLowering()->getRegisterByName(
4524 RegStr->getString().data(), Ty, *MF);
4525 if (!PhysReg) {
4526 const Function &Fn = MF->getFunction();
4527 Fn.getContext().diagnose(DiagnosticInfoGenericWithLoc(
4528 "invalid register \"" + Twine(RegStr->getString()) +
4529 "\" for llvm.write_register",
4530 Fn, MI.getDebugLoc()));
4531 MI.eraseFromParent();
4532 return true;
4533 }
4534
4535 if (!RBI.constrainGenericRegister(
4536 SrcReg, *TRI.getSGPRClassForBitWidth(Ty.getSizeInBits()), *MRI))
4537 return false;
4538
4539 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), TII.get(AMDGPU::COPY), PhysReg)
4540 .addReg(SrcReg);
4541 MI.eraseFromParent();
4542 return true;
4543}
4544
4545bool AMDGPUInstructionSelector::selectStackRestore(MachineInstr &MI) const {
4546 Register SrcReg = MI.getOperand(0).getReg();
4547 if (!RBI.constrainGenericRegister(SrcReg, AMDGPU::SReg_32RegClass, *MRI))
4548 return false;
4549
4550 MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
4551 Register SP =
4552 Subtarget->getTargetLowering()->getStackPointerRegisterToSaveRestore();
4553 Register WaveAddr = getWaveAddress(DefMI);
4554 MachineBasicBlock *MBB = MI.getParent();
4555 const DebugLoc &DL = MI.getDebugLoc();
4556
4557 if (!WaveAddr) {
4558 WaveAddr = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
4559 BuildMI(*MBB, MI, DL, TII.get(AMDGPU::S_LSHL_B32), WaveAddr)
4560 .addReg(SrcReg)
4561 .addImm(Subtarget->getWavefrontSizeLog2())
4562 .setOperandDead(3); // Dead scc
4563 }
4564
4565 BuildMI(*MBB, &MI, DL, TII.get(AMDGPU::COPY), SP)
4566 .addReg(WaveAddr);
4567
4568 MI.eraseFromParent();
4569 return true;
4570}
4571
4573
4574 if (!I.isPreISelOpcode()) {
4575 if (I.isCopy())
4576 return selectCOPY(I);
4577 return true;
4578 }
4579
4580 switch (I.getOpcode()) {
4581 case TargetOpcode::G_AND:
4582 case TargetOpcode::G_OR:
4583 case TargetOpcode::G_XOR:
4584 if (selectBITOP3(I))
4585 return true;
4586 if (selectImpl(I, *CoverageInfo))
4587 return true;
4588 return selectG_AND_OR_XOR(I);
4589 case TargetOpcode::G_ADD:
4590 case TargetOpcode::G_SUB:
4591 case TargetOpcode::G_PTR_ADD:
4592 if (selectImpl(I, *CoverageInfo))
4593 return true;
4594 return selectG_ADD_SUB(I);
4595 case TargetOpcode::G_UADDO:
4596 case TargetOpcode::G_USUBO:
4597 case TargetOpcode::G_UADDE:
4598 case TargetOpcode::G_USUBE:
4599 return selectG_UADDO_USUBO_UADDE_USUBE(I);
4600 case AMDGPU::G_AMDGPU_MAD_U64_U32:
4601 case AMDGPU::G_AMDGPU_MAD_I64_I32:
4602 return selectG_AMDGPU_MAD_64_32(I);
4603 case TargetOpcode::G_INTTOPTR:
4604 case TargetOpcode::G_BITCAST:
4605 case TargetOpcode::G_PTRTOINT:
4606 case TargetOpcode::G_FREEZE:
4607 return selectCOPY(I);
4608 case TargetOpcode::G_FNEG:
4609 if (selectImpl(I, *CoverageInfo))
4610 return true;
4611 return selectG_FNEG(I);
4612 case TargetOpcode::G_FABS:
4613 if (selectImpl(I, *CoverageInfo))
4614 return true;
4615 return selectG_FABS(I);
4616 case TargetOpcode::G_EXTRACT:
4617 return selectG_EXTRACT(I);
4618 case TargetOpcode::G_MERGE_VALUES:
4619 case TargetOpcode::G_CONCAT_VECTORS:
4620 return selectG_MERGE_VALUES(I);
4621 case TargetOpcode::G_UNMERGE_VALUES:
4622 return selectG_UNMERGE_VALUES(I);
4623 case TargetOpcode::G_BUILD_VECTOR:
4624 case TargetOpcode::G_BUILD_VECTOR_TRUNC:
4625 return selectG_BUILD_VECTOR(I);
4626 case TargetOpcode::G_IMPLICIT_DEF:
4627 return selectG_IMPLICIT_DEF(I);
4628 case TargetOpcode::G_INSERT:
4629 return selectG_INSERT(I);
4630 case TargetOpcode::G_INTRINSIC:
4631 case TargetOpcode::G_INTRINSIC_CONVERGENT:
4632 return selectG_INTRINSIC(I);
4633 case TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS:
4634 case TargetOpcode::G_INTRINSIC_CONVERGENT_W_SIDE_EFFECTS:
4635 return selectG_INTRINSIC_W_SIDE_EFFECTS(I);
4636 case TargetOpcode::G_ICMP:
4637 case TargetOpcode::G_FCMP:
4638 if (selectG_ICMP_or_FCMP(I))
4639 return true;
4640 return selectImpl(I, *CoverageInfo);
4641 case TargetOpcode::G_LOAD:
4642 case TargetOpcode::G_ZEXTLOAD:
4643 case TargetOpcode::G_SEXTLOAD:
4644 case TargetOpcode::G_STORE:
4645 case TargetOpcode::G_ATOMIC_CMPXCHG:
4646 case TargetOpcode::G_ATOMICRMW_XCHG:
4647 case TargetOpcode::G_ATOMICRMW_ADD:
4648 case TargetOpcode::G_ATOMICRMW_SUB:
4649 case TargetOpcode::G_ATOMICRMW_AND:
4650 case TargetOpcode::G_ATOMICRMW_OR:
4651 case TargetOpcode::G_ATOMICRMW_XOR:
4652 case TargetOpcode::G_ATOMICRMW_MIN:
4653 case TargetOpcode::G_ATOMICRMW_MAX:
4654 case TargetOpcode::G_ATOMICRMW_UMIN:
4655 case TargetOpcode::G_ATOMICRMW_UMAX:
4656 case TargetOpcode::G_ATOMICRMW_UINC_WRAP:
4657 case TargetOpcode::G_ATOMICRMW_UDEC_WRAP:
4658 case TargetOpcode::G_ATOMICRMW_USUB_COND:
4659 case TargetOpcode::G_ATOMICRMW_USUB_SAT:
4660 case TargetOpcode::G_ATOMICRMW_FADD:
4661 case TargetOpcode::G_ATOMICRMW_FMIN:
4662 case TargetOpcode::G_ATOMICRMW_FMAX:
4663 return selectG_LOAD_STORE_ATOMICRMW(I);
4664 case TargetOpcode::G_SELECT:
4665 return selectG_SELECT(I);
4666 case TargetOpcode::G_TRUNC:
4667 return selectG_TRUNC(I);
4668 case TargetOpcode::G_SEXT:
4669 case TargetOpcode::G_ZEXT:
4670 case TargetOpcode::G_ANYEXT:
4671 case TargetOpcode::G_SEXT_INREG:
4672 // This is a workaround. For extension from type i1, `selectImpl()` uses
4673 // patterns from TD file and generates an illegal VGPR to SGPR COPY as type
4674 // i1 can only be hold in a SGPR class.
4675 if (MRI->getType(I.getOperand(1).getReg()) != LLT::scalar(1) &&
4676 selectImpl(I, *CoverageInfo))
4677 return true;
4678 return selectG_SZA_EXT(I);
4679 case TargetOpcode::G_FPEXT:
4680 if (selectG_FPEXT(I))
4681 return true;
4682 return selectImpl(I, *CoverageInfo);
4683 case TargetOpcode::G_BRCOND:
4684 return selectG_BRCOND(I);
4685 case TargetOpcode::G_GLOBAL_VALUE:
4686 return selectG_GLOBAL_VALUE(I);
4687 case TargetOpcode::G_PTRMASK:
4688 return selectG_PTRMASK(I);
4689 case TargetOpcode::G_EXTRACT_VECTOR_ELT:
4690 return selectG_EXTRACT_VECTOR_ELT(I);
4691 case TargetOpcode::G_INSERT_VECTOR_ELT:
4692 return selectG_INSERT_VECTOR_ELT(I);
4693 case AMDGPU::G_AMDGPU_INTRIN_IMAGE_LOAD:
4694 case AMDGPU::G_AMDGPU_INTRIN_IMAGE_LOAD_D16:
4695 case AMDGPU::G_AMDGPU_INTRIN_IMAGE_LOAD_NORET:
4696 case AMDGPU::G_AMDGPU_INTRIN_IMAGE_STORE:
4697 case AMDGPU::G_AMDGPU_INTRIN_IMAGE_STORE_D16: {
4698 const AMDGPU::ImageDimIntrinsicInfo *Intr =
4700 assert(Intr && "not an image intrinsic with image pseudo");
4701 return selectImageIntrinsic(I, Intr);
4702 }
4703 case AMDGPU::G_AMDGPU_BVH_DUAL_INTERSECT_RAY:
4704 case AMDGPU::G_AMDGPU_BVH_INTERSECT_RAY:
4705 case AMDGPU::G_AMDGPU_BVH8_INTERSECT_RAY:
4706 return selectBVHIntersectRayIntrinsic(I);
4707 case AMDGPU::G_SBFX:
4708 case AMDGPU::G_UBFX:
4709 return selectG_SBFX_UBFX(I);
4710 case AMDGPU::G_SI_CALL:
4711 I.setDesc(TII.get(AMDGPU::SI_CALL));
4712 return true;
4713 case AMDGPU::G_AMDGPU_WAVE_ADDRESS:
4714 return selectWaveAddress(I);
4715 case AMDGPU::G_AMDGPU_WHOLE_WAVE_FUNC_RETURN: {
4716 I.setDesc(TII.get(AMDGPU::SI_WHOLE_WAVE_FUNC_RETURN));
4717 return true;
4718 }
4719 case AMDGPU::G_STACKRESTORE:
4720 return selectStackRestore(I);
4721 case TargetOpcode::G_WRITE_REGISTER:
4722 return selectWriteRegister(I);
4723 case AMDGPU::G_PHI:
4724 return selectPHI(I);
4725 case AMDGPU::G_AMDGPU_COPY_SCC_VCC:
4726 return selectCOPY_SCC_VCC(I);
4727 case AMDGPU::G_AMDGPU_COPY_VCC_SCC:
4728 return selectCOPY_VCC_SCC(I);
4729 case AMDGPU::G_AMDGPU_READANYLANE:
4730 return selectReadAnyLane(I);
4731 case TargetOpcode::G_CONSTANT:
4732 case TargetOpcode::G_FCONSTANT:
4733 default:
4734 return selectImpl(I, *CoverageInfo);
4735 }
4736 return false;
4737}
4738
4740AMDGPUInstructionSelector::selectVCSRC(MachineOperand &Root) const {
4741 return {{
4742 [=](MachineInstrBuilder &MIB) { MIB.add(Root); }
4743 }};
4744
4745}
4746
4747std::pair<Register, unsigned> AMDGPUInstructionSelector::selectVOP3ModsImpl(
4748 Register Src, bool IsCanonicalizing, bool AllowAbs, bool OpSel) const {
4749 unsigned Mods = 0;
4750 MachineInstr *MI = getDefIgnoringCopies(Src, *MRI);
4751
4752 if (MI->getOpcode() == AMDGPU::G_FNEG) {
4753 Src = MI->getOperand(1).getReg();
4754 Mods |= SISrcMods::NEG;
4755 MI = getDefIgnoringCopies(Src, *MRI);
4756 } else if (MI->getOpcode() == AMDGPU::G_FSUB && IsCanonicalizing) {
4757 // Fold fsub [+-]0 into fneg. This may not have folded depending on the
4758 // denormal mode, but we're implicitly canonicalizing in a source operand.
4759 const ConstantFP *LHS =
4760 getConstantFPVRegVal(MI->getOperand(1).getReg(), *MRI);
4761 if (LHS && LHS->isZero()) {
4762 Mods |= SISrcMods::NEG;
4763 Src = MI->getOperand(2).getReg();
4764 }
4765 }
4766
4767 if (AllowAbs && MI->getOpcode() == AMDGPU::G_FABS) {
4768 Src = MI->getOperand(1).getReg();
4769 Mods |= SISrcMods::ABS;
4770 }
4771
4772 if (OpSel)
4773 Mods |= SISrcMods::OP_SEL_0;
4774
4775 return std::pair(Src, Mods);
4776}
4777
4778std::pair<Register, unsigned>
4779AMDGPUInstructionSelector::selectVOP3PModsF32Impl(Register Src) const {
4780 unsigned Mods;
4781 std::tie(Src, Mods) = selectVOP3ModsImpl(Src);
4782 Mods |= SISrcMods::OP_SEL_1;
4783 return std::pair(Src, Mods);
4784}
4785
4786Register AMDGPUInstructionSelector::copyToVGPRIfSrcFolded(
4787 Register Src, unsigned Mods, MachineOperand Root, MachineInstr *InsertPt,
4788 bool ForceVGPR) const {
4789 if ((Mods != 0 || ForceVGPR) &&
4790 RBI.getRegBank(Src, *MRI, TRI)->getID() != AMDGPU::VGPRRegBankID) {
4791
4792 // If we looked through copies to find source modifiers on an SGPR operand,
4793 // we now have an SGPR register source. To avoid potentially violating the
4794 // constant bus restriction, we need to insert a copy to a VGPR.
4795 Register VGPRSrc = MRI->cloneVirtualRegister(Root.getReg());
4796 BuildMI(*InsertPt->getParent(), InsertPt, InsertPt->getDebugLoc(),
4797 TII.get(AMDGPU::COPY), VGPRSrc)
4798 .addReg(Src);
4799 Src = VGPRSrc;
4800 }
4801
4802 return Src;
4803}
4804
4805/// Some instructions must have 32-bit sources. With real true16 instructions a
4806/// 16-bit VALU value lives in a VGPR_16, which they cannot read, so place it in
4807/// the low half of a new 32-bit VGPR.
4809AMDGPUInstructionSelector::widenSrcIfVGPR16(Register Src,
4810 MachineInstr *InsertPt) const {
4811 if (!Subtarget->useRealTrue16Insts() || MRI->getType(Src) != LLT::scalar(16))
4812 return Src;
4813
4814 const RegisterBank *SrcRB = RBI.getRegBank(Src, *MRI, TRI);
4815 if (!SrcRB || SrcRB->getID() != AMDGPU::VGPRRegBankID)
4816 return Src;
4817
4818 MachineIRBuilder B(*InsertPt);
4819
4820 Register ImpDefReg = MRI->createVirtualRegister(&AMDGPU::VGPR_16RegClass);
4821 B.buildInstr(TargetOpcode::IMPLICIT_DEF).addDef(ImpDefReg);
4822
4823 Register DstReg = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4824 B.buildInstr(AMDGPU::REG_SEQUENCE)
4825 .addDef(DstReg)
4826 .addReg(Src)
4827 .addImm(AMDGPU::lo16)
4828 .addReg(ImpDefReg)
4829 .addImm(AMDGPU::hi16);
4830
4831 return DstReg;
4832}
4833
4834///
4835/// This will select either an SGPR or VGPR operand and will save us from
4836/// having to write an extra tablegen pattern.
4838AMDGPUInstructionSelector::selectVSRC0(MachineOperand &Root) const {
4839 return {{
4840 [=](MachineInstrBuilder &MIB) { MIB.add(Root); }
4841 }};
4842}
4843
4845AMDGPUInstructionSelector::selectVOP3Mods0(MachineOperand &Root) const {
4846 Register Src;
4847 unsigned Mods;
4848 std::tie(Src, Mods) = selectVOP3ModsImpl(Root.getReg());
4849
4850 return {{
4851 [=](MachineInstrBuilder &MIB) {
4852 MIB.addReg(copyToVGPRIfSrcFolded(Src, Mods, Root, MIB));
4853 },
4854 [=](MachineInstrBuilder &MIB) { MIB.addImm(Mods); }, // src0_mods
4855 [=](MachineInstrBuilder &MIB) { MIB.addImm(0); }, // clamp
4856 [=](MachineInstrBuilder &MIB) { MIB.addImm(0); } // omod
4857 }};
4858}
4859
4861AMDGPUInstructionSelector::selectVOP3BMods0(MachineOperand &Root) const {
4862 Register Src;
4863 unsigned Mods;
4864 std::tie(Src, Mods) = selectVOP3ModsImpl(Root.getReg(),
4865 /*IsCanonicalizing=*/true,
4866 /*AllowAbs=*/false);
4867
4868 return {{
4869 [=](MachineInstrBuilder &MIB) {
4870 MIB.addReg(copyToVGPRIfSrcFolded(Src, Mods, Root, MIB));
4871 },
4872 [=](MachineInstrBuilder &MIB) { MIB.addImm(Mods); }, // src0_mods
4873 [=](MachineInstrBuilder &MIB) { MIB.addImm(0); }, // clamp
4874 [=](MachineInstrBuilder &MIB) { MIB.addImm(0); } // omod
4875 }};
4876}
4877
4879AMDGPUInstructionSelector::selectVOP3OMods(MachineOperand &Root) const {
4880 return {{
4881 [=](MachineInstrBuilder &MIB) { MIB.add(Root); },
4882 [=](MachineInstrBuilder &MIB) { MIB.addImm(0); }, // clamp
4883 [=](MachineInstrBuilder &MIB) { MIB.addImm(0); } // omod
4884 }};
4885}
4886
4888AMDGPUInstructionSelector::selectVOP3Mods(MachineOperand &Root) const {
4889 Register Src;
4890 unsigned Mods;
4891 std::tie(Src, Mods) = selectVOP3ModsImpl(Root.getReg());
4892
4893 return {{
4894 [=](MachineInstrBuilder &MIB) {
4895 MIB.addReg(copyToVGPRIfSrcFolded(Src, Mods, Root, MIB));
4896 },
4897 [=](MachineInstrBuilder &MIB) { MIB.addImm(Mods); } // src_mods
4898 }};
4899}
4900
4902AMDGPUInstructionSelector::selectVOP3ModsNonCanonicalizing(
4903 MachineOperand &Root) const {
4904 Register Src;
4905 unsigned Mods;
4906 std::tie(Src, Mods) =
4907 selectVOP3ModsImpl(Root.getReg(), /*IsCanonicalizing=*/false);
4908
4909 return {{
4910 [=](MachineInstrBuilder &MIB) {
4911 MIB.addReg(copyToVGPRIfSrcFolded(Src, Mods, Root, MIB));
4912 },
4913 [=](MachineInstrBuilder &MIB) { MIB.addImm(Mods); } // src_mods
4914 }};
4915}
4916
4918AMDGPUInstructionSelector::selectVOP3BMods(MachineOperand &Root) const {
4919 Register Src;
4920 unsigned Mods;
4921 std::tie(Src, Mods) =
4922 selectVOP3ModsImpl(Root.getReg(), /*IsCanonicalizing=*/true,
4923 /*AllowAbs=*/false);
4924
4925 return {{
4926 [=](MachineInstrBuilder &MIB) {
4927 MIB.addReg(copyToVGPRIfSrcFolded(Src, Mods, Root, MIB));
4928 },
4929 [=](MachineInstrBuilder &MIB) { MIB.addImm(Mods); } // src_mods
4930 }};
4931}
4932
4934AMDGPUInstructionSelector::selectVOP3NoMods(MachineOperand &Root) const {
4935 Register Reg = Root.getReg();
4936 const MachineInstr *Def = getDefIgnoringCopies(Reg, *MRI);
4937 if (Def->getOpcode() == AMDGPU::G_FNEG || Def->getOpcode() == AMDGPU::G_FABS)
4938 return {};
4939 return {{
4940 [=](MachineInstrBuilder &MIB) { MIB.addReg(Reg); },
4941 }};
4942}
4943
4945AMDGPUInstructionSelector::selectVOP3NoOpSelMods(MachineOperand &Root) const {
4947 if (isExtractHiElt(*MRI, Root.getReg(), Unused))
4948 return {};
4949 return selectVOP3NoMods(Root);
4950}
4951
4952enum class SrcStatus {
4957 // This means current op = [op_upper, op_lower] and src = -op_lower.
4960 // This means current op = [op_upper, op_lower] and src = [op_upper,
4961 // -op_lower].
4969};
4970/// Test if the MI is truncating to half, such as `%reg0:n = G_TRUNC %reg1:2n`
4971static bool isTruncHalf(const MachineInstr *MI,
4972 const MachineRegisterInfo &MRI) {
4973 if (MI->getOpcode() != AMDGPU::G_TRUNC)
4974 return false;
4975
4976 uint64_t DstSize = MRI.getType(MI->getOperand(0).getReg()).getSizeInBits();
4977 uint64_t SrcSize = MRI.getType(MI->getOperand(1).getReg()).getSizeInBits();
4978 return DstSize * 2 == SrcSize;
4979}
4980
4981/// Test if the MI is logic shift right with half bits,
4982/// such as `%reg0:2n =G_LSHR %reg1:2n, CONST(n)`
4983static bool isLshrHalf(const MachineInstr *MI, const MachineRegisterInfo &MRI) {
4984 if (MI->getOpcode() != AMDGPU::G_LSHR)
4985 return false;
4986
4987 Register ShiftSrc;
4988 std::optional<ValueAndVReg> ShiftAmt;
4989 if (mi_match(MI->getOperand(0).getReg(), MRI,
4990 m_GLShr(m_Reg(ShiftSrc), m_GCst(ShiftAmt)))) {
4991 uint64_t SrcSize = MRI.getType(MI->getOperand(1).getReg()).getSizeInBits();
4992 unsigned Shift = static_cast<unsigned>(ShiftAmt->Value.getZExtValue());
4993 return Shift * 2 == SrcSize;
4994 }
4995 return false;
4996}
4997
4998/// Test if the MI is shift left with half bits,
4999/// such as `%reg0:2n =G_SHL %reg1:2n, CONST(n)`
5000static bool isShlHalf(const MachineInstr *MI, const MachineRegisterInfo &MRI) {
5001 if (MI->getOpcode() != AMDGPU::G_SHL)
5002 return false;
5003
5004 Register ShiftSrc;
5005 std::optional<ValueAndVReg> ShiftAmt;
5006 if (mi_match(MI->getOperand(0).getReg(), MRI,
5007 m_GShl(m_Reg(ShiftSrc), m_GCst(ShiftAmt)))) {
5008 uint64_t SrcSize = MRI.getType(MI->getOperand(1).getReg()).getSizeInBits();
5009 unsigned Shift = static_cast<unsigned>(ShiftAmt->Value.getZExtValue());
5010 return Shift * 2 == SrcSize;
5011 }
5012 return false;
5013}
5014
5015/// Test function, if the MI is `%reg0:n, %reg1:n = G_UNMERGE_VALUES %reg2:2n`
5016static bool isUnmergeHalf(const MachineInstr *MI,
5017 const MachineRegisterInfo &MRI) {
5018 if (MI->getOpcode() != AMDGPU::G_UNMERGE_VALUES)
5019 return false;
5020 return MI->getNumOperands() == 3 && MI->getOperand(0).isDef() &&
5021 MI->getOperand(1).isDef() && !MI->getOperand(2).isDef();
5022}
5023
5025
5027 const MachineRegisterInfo &MRI) {
5028 LLT OpTy = MRI.getType(Reg);
5029 if (OpTy.isScalar())
5030 return TypeClass::SCALAR;
5031 if (OpTy.isVector() && OpTy.getNumElements() == 2)
5034}
5035
5037 const MachineRegisterInfo &MRI) {
5039 if (NegType != TypeClass::VECTOR_OF_TWO && NegType != TypeClass::SCALAR)
5040 return SrcStatus::INVALID;
5041
5042 switch (S) {
5043 case SrcStatus::IS_SAME:
5044 if (NegType == TypeClass::VECTOR_OF_TWO) {
5045 // Vector of 2:
5046 // [SrcHi, SrcLo] = [CurrHi, CurrLo]
5047 // [CurrHi, CurrLo] = neg [OpHi, OpLo](2 x Type)
5048 // [CurrHi, CurrLo] = [-OpHi, -OpLo](2 x Type)
5049 // [SrcHi, SrcLo] = [-OpHi, -OpLo]
5051 }
5052 if (NegType == TypeClass::SCALAR) {
5053 // Scalar:
5054 // [SrcHi, SrcLo] = [CurrHi, CurrLo]
5055 // [CurrHi, CurrLo] = neg [OpHi, OpLo](Type)
5056 // [CurrHi, CurrLo] = [-OpHi, OpLo](Type)
5057 // [SrcHi, SrcLo] = [-OpHi, OpLo]
5058 return SrcStatus::IS_HI_NEG;
5059 }
5060 break;
5062 if (NegType == TypeClass::VECTOR_OF_TWO) {
5063 // Vector of 2:
5064 // [SrcHi, SrcLo] = [-CurrHi, CurrLo]
5065 // [CurrHi, CurrLo] = neg [OpHi, OpLo](2 x Type)
5066 // [CurrHi, CurrLo] = [-OpHi, -OpLo](2 x Type)
5067 // [SrcHi, SrcLo] = [-(-OpHi), -OpLo] = [OpHi, -OpLo]
5068 return SrcStatus::IS_LO_NEG;
5069 }
5070 if (NegType == TypeClass::SCALAR) {
5071 // Scalar:
5072 // [SrcHi, SrcLo] = [-CurrHi, CurrLo]
5073 // [CurrHi, CurrLo] = neg [OpHi, OpLo](Type)
5074 // [CurrHi, CurrLo] = [-OpHi, OpLo](Type)
5075 // [SrcHi, SrcLo] = [-(-OpHi), OpLo] = [OpHi, OpLo]
5076 return SrcStatus::IS_SAME;
5077 }
5078 break;
5080 if (NegType == TypeClass::VECTOR_OF_TWO) {
5081 // Vector of 2:
5082 // [SrcHi, SrcLo] = [CurrHi, -CurrLo]
5083 // [CurrHi, CurrLo] = fneg [OpHi, OpLo](2 x Type)
5084 // [CurrHi, CurrLo] = [-OpHi, -OpLo](2 x Type)
5085 // [SrcHi, SrcLo] = [-OpHi, -(-OpLo)] = [-OpHi, OpLo]
5086 return SrcStatus::IS_HI_NEG;
5087 }
5088 if (NegType == TypeClass::SCALAR) {
5089 // Scalar:
5090 // [SrcHi, SrcLo] = [CurrHi, -CurrLo]
5091 // [CurrHi, CurrLo] = fneg [OpHi, OpLo](Type)
5092 // [CurrHi, CurrLo] = [-OpHi, OpLo](Type)
5093 // [SrcHi, SrcLo] = [-OpHi, -OpLo]
5095 }
5096 break;
5098 if (NegType == TypeClass::VECTOR_OF_TWO) {
5099 // Vector of 2:
5100 // [SrcHi, SrcLo] = [-CurrHi, -CurrLo]
5101 // [CurrHi, CurrLo] = fneg [OpHi, OpLo](2 x Type)
5102 // [CurrHi, CurrLo] = [-OpHi, -OpLo](2 x Type)
5103 // [SrcHi, SrcLo] = [OpHi, OpLo]
5104 return SrcStatus::IS_SAME;
5105 }
5106 if (NegType == TypeClass::SCALAR) {
5107 // Scalar:
5108 // [SrcHi, SrcLo] = [-CurrHi, -CurrLo]
5109 // [CurrHi, CurrLo] = fneg [OpHi, OpLo](Type)
5110 // [CurrHi, CurrLo] = [-OpHi, OpLo](Type)
5111 // [SrcHi, SrcLo] = [OpHi, -OpLo]
5112 return SrcStatus::IS_LO_NEG;
5113 }
5114 break;
5116 // Vector of 2:
5117 // Src = CurrUpper
5118 // Curr = [CurrUpper, CurrLower]
5119 // [CurrUpper, CurrLower] = fneg [OpUpper, OpLower](2 x Type)
5120 // [CurrUpper, CurrLower] = [-OpUpper, -OpLower](2 x Type)
5121 // Src = -OpUpper
5122 //
5123 // Scalar:
5124 // Src = CurrUpper
5125 // Curr = [CurrUpper, CurrLower]
5126 // [CurrUpper, CurrLower] = fneg [OpUpper, OpLower](Type)
5127 // [CurrUpper, CurrLower] = [-OpUpper, OpLower](Type)
5128 // Src = -OpUpper
5131 if (NegType == TypeClass::VECTOR_OF_TWO) {
5132 // Vector of 2:
5133 // Src = CurrLower
5134 // Curr = [CurrUpper, CurrLower]
5135 // [CurrUpper, CurrLower] = fneg [OpUpper, OpLower](2 x Type)
5136 // [CurrUpper, CurrLower] = [-OpUpper, -OpLower](2 x Type)
5137 // Src = -OpLower
5139 }
5140 if (NegType == TypeClass::SCALAR) {
5141 // Scalar:
5142 // Src = CurrLower
5143 // Curr = [CurrUpper, CurrLower]
5144 // [CurrUpper, CurrLower] = fneg [OpUpper, OpLower](Type)
5145 // [CurrUpper, CurrLower] = [-OpUpper, OpLower](Type)
5146 // Src = OpLower
5148 }
5149 break;
5151 // Vector of 2:
5152 // Src = -CurrUpper
5153 // Curr = [CurrUpper, CurrLower]
5154 // [CurrUpper, CurrLower] = fneg [OpUpper, OpLower](2 x Type)
5155 // [CurrUpper, CurrLower] = [-OpUpper, -OpLower](2 x Type)
5156 // Src = -(-OpUpper) = OpUpper
5157 //
5158 // Scalar:
5159 // Src = -CurrUpper
5160 // Curr = [CurrUpper, CurrLower]
5161 // [CurrUpper, CurrLower] = fneg [OpUpper, OpLower](Type)
5162 // [CurrUpper, CurrLower] = [-OpUpper, OpLower](Type)
5163 // Src = -(-OpUpper) = OpUpper
5166 if (NegType == TypeClass::VECTOR_OF_TWO) {
5167 // Vector of 2:
5168 // Src = -CurrLower
5169 // Curr = [CurrUpper, CurrLower]
5170 // [CurrUpper, CurrLower] = fneg [OpUpper, OpLower](2 x Type)
5171 // [CurrUpper, CurrLower] = [-OpUpper, -OpLower](2 x Type)
5172 // Src = -(-OpLower) = OpLower
5174 }
5175 if (NegType == TypeClass::SCALAR) {
5176 // Scalar:
5177 // Src = -CurrLower
5178 // Curr = [CurrUpper, CurrLower]
5179 // [CurrUpper, CurrLower] = fneg [OpUpper, OpLower](Type)
5180 // [CurrUpper, CurrLower] = [-OpUpper, OpLower](Type)
5181 // Src = -OpLower
5183 }
5184 break;
5185 default:
5186 break;
5187 }
5188 llvm_unreachable("unexpected SrcStatus & NegType combination");
5189}
5190
5191static std::optional<std::pair<Register, SrcStatus>>
5192calcNextStatus(std::pair<Register, SrcStatus> Curr,
5193 const MachineRegisterInfo &MRI) {
5194 const MachineInstr *MI = MRI.getVRegDef(Curr.first);
5195
5196 unsigned Opc = MI->getOpcode();
5197
5198 // Handle general Opc cases.
5199 switch (Opc) {
5200 case AMDGPU::G_BITCAST:
5201 return std::optional<std::pair<Register, SrcStatus>>(
5202 {MI->getOperand(1).getReg(), Curr.second});
5203 case AMDGPU::COPY:
5204 if (MI->getOperand(1).getReg().isPhysical())
5205 return std::nullopt;
5206 return std::optional<std::pair<Register, SrcStatus>>(
5207 {MI->getOperand(1).getReg(), Curr.second});
5208 case AMDGPU::G_FNEG: {
5209 SrcStatus Stat = getNegStatus(Curr.first, Curr.second, MRI);
5210 if (Stat == SrcStatus::INVALID)
5211 return std::nullopt;
5212 return std::optional<std::pair<Register, SrcStatus>>(
5213 {MI->getOperand(1).getReg(), Stat});
5214 }
5215 default:
5216 break;
5217 }
5218
5219 // Calc next Stat from current Stat.
5220 switch (Curr.second) {
5221 case SrcStatus::IS_SAME:
5222 if (isTruncHalf(MI, MRI))
5223 return std::optional<std::pair<Register, SrcStatus>>(
5224 {MI->getOperand(1).getReg(), SrcStatus::IS_LOWER_HALF});
5225 else if (isUnmergeHalf(MI, MRI)) {
5226 if (Curr.first == MI->getOperand(0).getReg())
5227 return std::optional<std::pair<Register, SrcStatus>>(
5228 {MI->getOperand(2).getReg(), SrcStatus::IS_LOWER_HALF});
5229 return std::optional<std::pair<Register, SrcStatus>>(
5230 {MI->getOperand(2).getReg(), SrcStatus::IS_UPPER_HALF});
5231 }
5232 break;
5234 if (isTruncHalf(MI, MRI)) {
5235 // [SrcHi, SrcLo] = [-CurrHi, CurrLo]
5236 // [CurrHi, CurrLo] = trunc [OpUpper, OpLower] = OpLower
5237 // = [OpLowerHi, OpLowerLo]
5238 // Src = [SrcHi, SrcLo] = [-CurrHi, CurrLo]
5239 // = [-OpLowerHi, OpLowerLo]
5240 // = -OpLower
5241 return std::optional<std::pair<Register, SrcStatus>>(
5242 {MI->getOperand(1).getReg(), SrcStatus::IS_LOWER_HALF_NEG});
5243 }
5244 if (isUnmergeHalf(MI, MRI)) {
5245 if (Curr.first == MI->getOperand(0).getReg())
5246 return std::optional<std::pair<Register, SrcStatus>>(
5247 {MI->getOperand(2).getReg(), SrcStatus::IS_LOWER_HALF_NEG});
5248 return std::optional<std::pair<Register, SrcStatus>>(
5249 {MI->getOperand(2).getReg(), SrcStatus::IS_UPPER_HALF_NEG});
5250 }
5251 break;
5253 if (isShlHalf(MI, MRI))
5254 return std::optional<std::pair<Register, SrcStatus>>(
5255 {MI->getOperand(1).getReg(), SrcStatus::IS_LOWER_HALF});
5256 break;
5258 if (isLshrHalf(MI, MRI))
5259 return std::optional<std::pair<Register, SrcStatus>>(
5260 {MI->getOperand(1).getReg(), SrcStatus::IS_UPPER_HALF});
5261 break;
5263 if (isShlHalf(MI, MRI))
5264 return std::optional<std::pair<Register, SrcStatus>>(
5265 {MI->getOperand(1).getReg(), SrcStatus::IS_LOWER_HALF_NEG});
5266 break;
5268 if (isLshrHalf(MI, MRI))
5269 return std::optional<std::pair<Register, SrcStatus>>(
5270 {MI->getOperand(1).getReg(), SrcStatus::IS_UPPER_HALF_NEG});
5271 break;
5272 default:
5273 break;
5274 }
5275 return std::nullopt;
5276}
5277
5278/// This is used to control valid status that current MI supports. For example,
5279/// non floating point intrinsic such as @llvm.amdgcn.sdot2 does not support NEG
5280/// bit on VOP3P.
5281/// The class can be further extended to recognize support on SEL, NEG, ABS bit
5282/// for different MI on different arch
5284private:
5285 bool HasNeg = false;
5286 // Assume all complex pattern of VOP3P have opsel.
5287 bool HasOpsel = true;
5288
5289public:
5291 const MachineInstr *MI = MRI.getVRegDef(Reg);
5292 unsigned Opc = MI->getOpcode();
5293
5294 if (Opc == TargetOpcode::G_INTRINSIC) {
5295 Intrinsic::ID IntrinsicID = cast<GIntrinsic>(*MI).getIntrinsicID();
5296 // Only float point intrinsic has neg & neg_hi bits.
5297 if (IntrinsicID == Intrinsic::amdgcn_fdot2)
5298 HasNeg = true;
5300 // Keep same for generic op.
5301 HasNeg = true;
5302 }
5303 }
5304 bool checkOptions(SrcStatus Stat) const {
5305 if (!HasNeg &&
5306 (Stat >= SrcStatus::NEG_START && Stat <= SrcStatus::NEG_END)) {
5307 return false;
5308 }
5309 if (!HasOpsel &&
5310 (Stat >= SrcStatus::HALF_START && Stat <= SrcStatus::HALF_END)) {
5311 return false;
5312 }
5313 return true;
5314 }
5315};
5316
5319 int MaxDepth = 3) {
5320 int Depth = 0;
5321 auto Curr = calcNextStatus({Reg, SrcStatus::IS_SAME}, MRI);
5323
5324 while (Depth <= MaxDepth && Curr.has_value()) {
5325 Depth++;
5326 if (SO.checkOptions(Curr.value().second))
5327 Statlist.push_back(Curr.value());
5328 Curr = calcNextStatus(Curr.value(), MRI);
5329 }
5330
5331 return Statlist;
5332}
5333
5334static std::pair<Register, SrcStatus>
5336 int MaxDepth = 3) {
5337 int Depth = 0;
5338 std::pair<Register, SrcStatus> LastSameOrNeg = {Reg, SrcStatus::IS_SAME};
5339 auto Curr = calcNextStatus(LastSameOrNeg, MRI);
5340
5341 while (Depth <= MaxDepth && Curr.has_value()) {
5342 Depth++;
5343 SrcStatus Stat = Curr.value().second;
5344 if (SO.checkOptions(Stat)) {
5345 if (Stat == SrcStatus::IS_SAME || Stat == SrcStatus::IS_HI_NEG ||
5347 LastSameOrNeg = Curr.value();
5348 }
5349 Curr = calcNextStatus(Curr.value(), MRI);
5350 }
5351
5352 return LastSameOrNeg;
5353}
5354
5355static bool isSameBitWidth(Register Reg1, Register Reg2,
5356 const MachineRegisterInfo &MRI) {
5357 uint64_t Width1 = MRI.getType(Reg1).getSizeInBits();
5358 uint64_t Width2 = MRI.getType(Reg2).getSizeInBits();
5359 return Width1 == Width2;
5360}
5361
5362static unsigned updateMods(SrcStatus HiStat, SrcStatus LoStat, unsigned Mods) {
5363 // SrcStatus::IS_LOWER_HALF remain 0.
5364 if (HiStat == SrcStatus::IS_UPPER_HALF_NEG) {
5365 Mods ^= SISrcMods::NEG_HI;
5366 Mods |= SISrcMods::OP_SEL_1;
5367 } else if (HiStat == SrcStatus::IS_UPPER_HALF)
5368 Mods |= SISrcMods::OP_SEL_1;
5369 else if (HiStat == SrcStatus::IS_LOWER_HALF_NEG)
5370 Mods ^= SISrcMods::NEG_HI;
5371 else if (HiStat == SrcStatus::IS_HI_NEG)
5372 Mods ^= SISrcMods::NEG_HI;
5373
5374 if (LoStat == SrcStatus::IS_UPPER_HALF_NEG) {
5375 Mods ^= SISrcMods::NEG;
5376 Mods |= SISrcMods::OP_SEL_0;
5377 } else if (LoStat == SrcStatus::IS_UPPER_HALF)
5378 Mods |= SISrcMods::OP_SEL_0;
5379 else if (LoStat == SrcStatus::IS_LOWER_HALF_NEG)
5380 Mods |= SISrcMods::NEG;
5381 else if (LoStat == SrcStatus::IS_HI_NEG)
5382 Mods ^= SISrcMods::NEG;
5383
5384 return Mods;
5385}
5386
5387static bool isValidToPack(SrcStatus HiStat, SrcStatus LoStat, Register NewReg,
5388 Register RootReg, const SIInstrInfo &TII,
5389 const MachineRegisterInfo &MRI) {
5390 auto IsHalfState = [](SrcStatus S) {
5393 };
5394 return isSameBitWidth(NewReg, RootReg, MRI) && IsHalfState(LoStat) &&
5395 IsHalfState(HiStat);
5396}
5397
5398std::pair<Register, unsigned> AMDGPUInstructionSelector::selectVOP3PModsImpl(
5399 Register RootReg, const MachineRegisterInfo &MRI, bool IsDOT,
5400 bool NoOpSel0) const {
5401 unsigned Mods = 0;
5402 // No modification if Root type is not form of <2 x Type>.
5403 if (isVectorOfTwoOrScalar(RootReg, MRI) != TypeClass::VECTOR_OF_TWO) {
5404 Mods |= SISrcMods::OP_SEL_1;
5405 return {RootReg, Mods};
5406 }
5407
5408 SearchOptions SO(RootReg, MRI);
5409
5410 std::pair<Register, SrcStatus> Stat = getLastSameOrNeg(RootReg, MRI, SO);
5411
5412 if (Stat.second == SrcStatus::IS_BOTH_NEG)
5414 else if (Stat.second == SrcStatus::IS_HI_NEG)
5415 Mods ^= SISrcMods::NEG_HI;
5416 else if (Stat.second == SrcStatus::IS_LO_NEG)
5417 Mods ^= SISrcMods::NEG;
5418
5419 // 64-bit VOP3P instructions do not have OPSEL or ABS. Bail on v2f64 or v2i64.
5420 // TODO: Select NEG_LO and NEG_HI modifiers from BUILD_VECTOR.
5421 if (MRI.getType(RootReg).getSizeInBits() == 128) {
5422 Mods |= SISrcMods::OP_SEL_1; // Just the default, OPSEL unsupported.
5423 return {Stat.first, Mods};
5424 }
5425
5426 GBuildVector *MI;
5427 if (!mi_match(Stat.first, MRI, m_GBuildVector(MI)) ||
5428 MI->getNumOperands() != 3 || (IsDOT && Subtarget->hasDOTOpSelHazard())) {
5429 Mods |= SISrcMods::OP_SEL_1;
5430 return {Stat.first, Mods};
5431 }
5432
5434 getSrcStats(MI->getOperand(2).getReg(), MRI, SO);
5435
5436 if (StatlistHi.empty()) {
5437 Mods |= SISrcMods::OP_SEL_1;
5438 return {Stat.first, Mods};
5439 }
5440
5442 getSrcStats(MI->getOperand(1).getReg(), MRI, SO);
5443
5444 if (StatlistLo.empty()) {
5445 Mods |= SISrcMods::OP_SEL_1;
5446 return {Stat.first, Mods};
5447 }
5448
5449 for (int I = static_cast<int>(StatlistHi.size()) - 1; I >= 0; I--) {
5450 for (int J = static_cast<int>(StatlistLo.size()) - 1; J >= 0; J--) {
5451 if (StatlistHi[I].first == StatlistLo[J].first &&
5452 isValidToPack(StatlistHi[I].second, StatlistLo[J].second,
5453 StatlistHi[I].first, RootReg, TII, MRI)) {
5454 unsigned NewMods =
5455 updateMods(StatlistHi[I].second, StatlistLo[J].second, Mods);
5456 if (NoOpSel0 && (NewMods & SISrcMods::OP_SEL_0))
5457 continue;
5458 return {StatlistHi[I].first, NewMods};
5459 }
5460 }
5461 }
5462 // Packed instructions do not have abs modifiers.
5463 Mods |= SISrcMods::OP_SEL_1;
5464
5465 return {Stat.first, Mods};
5466}
5467
5468// Removed unused function `getAllKindImm` to eliminate dead code.
5469
5470static bool checkRB(Register Reg, unsigned int RBNo,
5471 const AMDGPURegisterBankInfo &RBI,
5472 const MachineRegisterInfo &MRI,
5473 const TargetRegisterInfo &TRI) {
5474 const RegisterBank *RB = RBI.getRegBank(Reg, MRI, TRI);
5475 return RB->getID() == RBNo;
5476}
5477
5478// This function is used to get the correct register bank for returned reg.
5479// Assume:
5480// 1. VOP3P is always legal for VGPR.
5481// 2. RootOp's regbank is legal.
5482// Thus
5483// 1. If RootOp is SGPR, then NewOp can be SGPR or VGPR.
5484// 2. If RootOp is VGPR, then NewOp must be VGPR.
5485static Register
5488 const TargetRegisterInfo &TRI, const SIInstrInfo &TII) {
5489 // RootOp can only be VGPR or SGPR (some hand written cases such as.
5490 // inst-select-ashr.v2s16.mir::ashr_v2s16_vs).
5491 if (checkRB(RootReg, AMDGPU::SGPRRegBankID, RBI, MRI, TRI) ||
5492 checkRB(NewReg, AMDGPU::VGPRRegBankID, RBI, MRI, TRI))
5493 return NewReg;
5494
5495 if (mi_match(RootReg, MRI, m_Copy(m_SpecificReg(NewReg)))) {
5496 // RootOp is VGPR, NewOp is not VGPR, but RootOp = COPY NewOp.
5497 return RootReg;
5498 }
5499
5500 Register DstReg = MRI.cloneVirtualRegister(RootReg);
5501 MachineInstrBuilder MIB = BuildMI(*Use.getParent(), Use, Use.getDebugLoc(),
5502 TII.get(AMDGPU::COPY), DstReg)
5503 .addReg(NewReg);
5504
5505 // Only accept VGPR.
5506 return MIB->getOperand(0).getReg();
5507}
5508
5510AMDGPUInstructionSelector::selectVOP3PRetHelper(MachineOperand &Root,
5511 bool IsDOT,
5512 bool NoOpSel0) const {
5513 MachineRegisterInfo &MRI = Root.getParent()->getMF()->getRegInfo();
5514 Register Reg;
5515 unsigned Mods;
5516 std::tie(Reg, Mods) =
5517 selectVOP3PModsImpl(Root.getReg(), MRI, IsDOT, NoOpSel0);
5518
5519 return {{
5520 [=, &Root, &MRI](MachineInstrBuilder &MIB) {
5521 MIB.addReg(getLegalRegBank(Reg, Root.getReg(), *MIB.getInstr(), RBI,
5522 MRI, TRI, TII));
5523 },
5524 [=](MachineInstrBuilder &MIB) { MIB.addImm(Mods); } // src_mods
5525 }};
5526}
5527
5529AMDGPUInstructionSelector::selectVOP3PMods(MachineOperand &Root) const {
5530
5531 return selectVOP3PRetHelper(Root);
5532}
5533
5535AMDGPUInstructionSelector::selectVOP3PModsPkFmaOpSel0(
5536 MachineOperand &Root) const {
5537 MachineRegisterInfo &MRI = Root.getParent()->getMF()->getRegInfo();
5538 LLT Ty = MRI.getType(Root.getReg());
5539 bool NoOpSel0 = Subtarget->hasPkF32InvalidOpSel() && Ty.isFixedVector() &&
5540 Ty.getNumElements() == 2 && Ty.getScalarSizeInBits() == 32;
5541 return selectVOP3PRetHelper(Root, /*IsDOT=*/false, NoOpSel0);
5542}
5543
5545AMDGPUInstructionSelector::selectVOP3PModsPkAddMulOpSel0(
5546 MachineOperand &Root) const {
5547 MachineRegisterInfo &MRI = Root.getParent()->getMF()->getRegInfo();
5548 LLT Ty = MRI.getType(Root.getReg());
5549 if (Subtarget->hasPkF32InvalidOpSel() && Ty.isFixedVector() &&
5550 Ty.getNumElements() == 2 && Ty.getScalarSizeInBits() == 32 &&
5551 (selectVOP3PModsImpl(Root.getReg(), MRI).second & SISrcMods::OP_SEL_0))
5552 return std::nullopt;
5553 return selectVOP3PRetHelper(Root);
5554}
5555
5557AMDGPUInstructionSelector::selectVOP3PModsDOT(MachineOperand &Root) const {
5558
5559 return selectVOP3PRetHelper(Root, true);
5560}
5561
5563AMDGPUInstructionSelector::selectVOP3PNoModsDOT(MachineOperand &Root) const {
5564 MachineRegisterInfo &MRI = Root.getParent()->getMF()->getRegInfo();
5565 Register Src;
5566 unsigned Mods;
5567 std::tie(Src, Mods) = selectVOP3PModsImpl(Root.getReg(), MRI, true /*IsDOT*/);
5568 if (Mods != SISrcMods::OP_SEL_1)
5569 return {};
5570
5571 return {{[=](MachineInstrBuilder &MIB) { MIB.addReg(Src); }}};
5572}
5573
5575AMDGPUInstructionSelector::selectVOP3PModsF32(MachineOperand &Root) const {
5576 Register Src;
5577 unsigned Mods;
5578 std::tie(Src, Mods) = selectVOP3PModsF32Impl(Root.getReg());
5579
5580 return {{
5581 [=](MachineInstrBuilder &MIB) { MIB.addReg(Src); },
5582 [=](MachineInstrBuilder &MIB) { MIB.addImm(Mods); } // src_mods
5583 }};
5584}
5585
5587AMDGPUInstructionSelector::selectVOP3PNoModsF32(MachineOperand &Root) const {
5588 Register Src;
5589 unsigned Mods;
5590 std::tie(Src, Mods) = selectVOP3PModsF32Impl(Root.getReg());
5591 if (Mods != SISrcMods::OP_SEL_1)
5592 return {};
5593
5594 return {{[=](MachineInstrBuilder &MIB) { MIB.addReg(Src); }}};
5595}
5596
5598AMDGPUInstructionSelector::selectWMMAOpSelVOP3PMods(
5599 MachineOperand &Root) const {
5600 assert((Root.isImm() && (Root.getImm() == -1 || Root.getImm() == 0)) &&
5601 "expected i1 value");
5602 unsigned Mods = SISrcMods::OP_SEL_1;
5603 if (Root.getImm() != 0)
5604 Mods |= SISrcMods::OP_SEL_0;
5605
5606 return {{
5607 [=](MachineInstrBuilder &MIB) { MIB.addImm(Mods); } // src_mods
5608 }};
5609}
5610
5614 const TargetRegisterClass *DstRegClass;
5615 switch (Elts.size()) {
5616 case 8:
5617 DstRegClass = &AMDGPU::VReg_256RegClass;
5618 break;
5619 case 4:
5620 DstRegClass = &AMDGPU::VReg_128RegClass;
5621 break;
5622 case 2:
5623 DstRegClass = &AMDGPU::VReg_64RegClass;
5624 break;
5625 default:
5626 llvm_unreachable("unhandled Reg sequence size");
5627 }
5628
5630 auto MIB = B.buildInstr(AMDGPU::REG_SEQUENCE)
5631 .addDef(MRI.createVirtualRegister(DstRegClass));
5632 for (unsigned i = 0; i < Elts.size(); ++i) {
5633 MIB.addReg(Elts[i]);
5635 }
5636 return MIB->getOperand(0).getReg();
5637}
5638
5639static void selectWMMAModsNegAbs(unsigned ModOpcode, unsigned &Mods,
5643 if (ModOpcode == TargetOpcode::G_FNEG) {
5644 Mods |= SISrcMods::NEG;
5645 // Check if all elements also have abs modifier
5646 SmallVector<Register, 8> NegAbsElts;
5647 for (auto El : Elts) {
5648 Register FabsSrc;
5649 if (!mi_match(El, MRI, m_GFabs(m_Reg(FabsSrc))))
5650 break;
5651 NegAbsElts.push_back(FabsSrc);
5652 }
5653 if (Elts.size() != NegAbsElts.size()) {
5654 // Neg
5655 Src = buildRegSequence(Elts, InsertPt, MRI);
5656 } else {
5657 // Neg and Abs
5658 Mods |= SISrcMods::NEG_HI;
5659 Src = buildRegSequence(NegAbsElts, InsertPt, MRI);
5660 }
5661 } else {
5662 assert(ModOpcode == TargetOpcode::G_FABS);
5663 // Abs
5664 Mods |= SISrcMods::NEG_HI;
5665 Src = buildRegSequence(Elts, InsertPt, MRI);
5666 }
5667}
5668
5670AMDGPUInstructionSelector::selectWMMAModsF32NegAbs(MachineOperand &Root) const {
5671 Register Src = Root.getReg();
5672 unsigned Mods = SISrcMods::OP_SEL_1;
5674
5675 GBuildVector *BV;
5676 if (mi_match(Src, *MRI, m_GBuildVector(BV))) {
5677 assert(BV->getNumSources() > 0);
5678 // Based on first element decide which mod we match, neg or abs
5679 MachineInstr *ElF32 = MRI->getVRegDef(BV->getSourceReg(0));
5680 unsigned ModOpcode = (ElF32->getOpcode() == AMDGPU::G_FNEG)
5681 ? AMDGPU::G_FNEG
5682 : AMDGPU::G_FABS;
5683 for (unsigned i = 0; i < BV->getNumSources(); ++i) {
5684 ElF32 = MRI->getVRegDef(BV->getSourceReg(i));
5685 if (ElF32->getOpcode() != ModOpcode)
5686 break;
5687 EltsF32.push_back(ElF32->getOperand(1).getReg());
5688 }
5689
5690 // All elements had ModOpcode modifier
5691 if (BV->getNumSources() == EltsF32.size()) {
5692 selectWMMAModsNegAbs(ModOpcode, Mods, EltsF32, Src, Root.getParent(),
5693 *MRI);
5694 }
5695 }
5696
5697 return {{[=](MachineInstrBuilder &MIB) { MIB.addReg(Src); },
5698 [=](MachineInstrBuilder &MIB) { MIB.addImm(Mods); }}};
5699}
5700
5702AMDGPUInstructionSelector::selectWMMAModsF16Neg(MachineOperand &Root) const {
5703 Register Src = Root.getReg();
5704 unsigned Mods = SISrcMods::OP_SEL_1;
5705 SmallVector<Register, 8> EltsV2F16;
5706
5707 GConcatVectors *CV;
5708 if (mi_match(Src, *MRI, m_GConcatVectors(CV))) {
5709 for (unsigned i = 0; i < CV->getNumSources(); ++i) {
5710 Register FNegSrc;
5711 if (!mi_match(CV->getSourceReg(i), *MRI, m_GFNeg(m_Reg(FNegSrc))))
5712 break;
5713 EltsV2F16.push_back(FNegSrc);
5714 }
5715
5716 // All elements had ModOpcode modifier
5717 if (CV->getNumSources() == EltsV2F16.size()) {
5718 Mods |= SISrcMods::NEG;
5719 Mods |= SISrcMods::NEG_HI;
5720 Src = buildRegSequence(EltsV2F16, Root.getParent(), *MRI);
5721 }
5722 }
5723
5724 return {{[=](MachineInstrBuilder &MIB) { MIB.addReg(Src); },
5725 [=](MachineInstrBuilder &MIB) { MIB.addImm(Mods); }}};
5726}
5727
5729AMDGPUInstructionSelector::selectWMMAModsF16NegAbs(MachineOperand &Root) const {
5730 Register Src = Root.getReg();
5731 unsigned Mods = SISrcMods::OP_SEL_1;
5732 SmallVector<Register, 8> EltsV2F16;
5733
5734 GConcatVectors *CV;
5735 if (mi_match(Src, *MRI, m_GConcatVectors(CV))) {
5736 assert(CV->getNumSources() > 0);
5737 MachineInstr *ElV2F16 = MRI->getVRegDef(CV->getSourceReg(0));
5738 // Based on first element decide which mod we match, neg or abs
5739 unsigned ModOpcode = (ElV2F16->getOpcode() == AMDGPU::G_FNEG)
5740 ? AMDGPU::G_FNEG
5741 : AMDGPU::G_FABS;
5742
5743 for (unsigned i = 0; i < CV->getNumSources(); ++i) {
5744 ElV2F16 = MRI->getVRegDef(CV->getSourceReg(i));
5745 if (ElV2F16->getOpcode() != ModOpcode)
5746 break;
5747 EltsV2F16.push_back(ElV2F16->getOperand(1).getReg());
5748 }
5749
5750 // All elements had ModOpcode modifier
5751 if (CV->getNumSources() == EltsV2F16.size()) {
5752 selectWMMAModsNegAbs(ModOpcode, Mods, EltsV2F16, Src, Root.getParent(),
5753 *MRI);
5754 }
5755 }
5756
5757 return {{[=](MachineInstrBuilder &MIB) { MIB.addReg(Src); },
5758 [=](MachineInstrBuilder &MIB) { MIB.addImm(Mods); }}};
5759}
5760
5762AMDGPUInstructionSelector::selectWMMAVISrc(MachineOperand &Root) const {
5763 std::optional<FPValueAndVReg> FPValReg;
5764 if (mi_match(Root.getReg(), *MRI, m_GFCstOrSplat(FPValReg))) {
5765 if (TII.isInlineConstant(FPValReg->Value)) {
5766 return {{[=](MachineInstrBuilder &MIB) {
5767 MIB.addImm(FPValReg->Value.bitcastToAPInt().getSExtValue());
5768 }}};
5769 }
5770 // Non-inlineable splat floats should not fall-through for integer immediate
5771 // checks.
5772 return {};
5773 }
5774
5775 APInt ICst;
5776 if (mi_match(Root.getReg(), *MRI, m_ICstOrSplat(ICst))) {
5777 if (TII.isInlineConstant(ICst)) {
5778 return {
5779 {[=](MachineInstrBuilder &MIB) { MIB.addImm(ICst.getSExtValue()); }}};
5780 }
5781 }
5782
5783 return {};
5784}
5785
5787AMDGPUInstructionSelector::selectSWMMACIndex8(MachineOperand &Root) const {
5788 Register Src =
5789 getDefIgnoringCopies(Root.getReg(), *MRI)->getOperand(0).getReg();
5790 unsigned Key = 0;
5791
5792 Register ShiftSrc;
5793 std::optional<ValueAndVReg> ShiftAmt;
5794 if (mi_match(Src, *MRI, m_GLShr(m_Reg(ShiftSrc), m_GCst(ShiftAmt))) &&
5795 MRI->getType(ShiftSrc).getSizeInBits() == 32 &&
5796 ShiftAmt->Value.getZExtValue() % 8 == 0) {
5797 Key = static_cast<unsigned>(ShiftAmt->Value.getZExtValue() / 8);
5798 Src = ShiftSrc;
5799 }
5800
5801 return {{
5802 [=](MachineInstrBuilder &MIB) { MIB.addReg(Src); },
5803 [=](MachineInstrBuilder &MIB) { MIB.addImm(Key); } // index_key
5804 }};
5805}
5806
5808AMDGPUInstructionSelector::selectSWMMACIndex16(MachineOperand &Root) const {
5809
5810 Register Src =
5811 getDefIgnoringCopies(Root.getReg(), *MRI)->getOperand(0).getReg();
5812 unsigned Key = 0;
5813
5814 Register ShiftSrc;
5815 std::optional<ValueAndVReg> ShiftAmt;
5816 if (mi_match(Src, *MRI, m_GLShr(m_Reg(ShiftSrc), m_GCst(ShiftAmt))) &&
5817 MRI->getType(ShiftSrc).getSizeInBits() == 32 &&
5818 ShiftAmt->Value.getZExtValue() == 16) {
5819 Src = ShiftSrc;
5820 Key = 1;
5821 }
5822
5823 return {{
5824 [=](MachineInstrBuilder &MIB) { MIB.addReg(Src); },
5825 [=](MachineInstrBuilder &MIB) { MIB.addImm(Key); } // index_key
5826 }};
5827}
5828
5830AMDGPUInstructionSelector::selectSWMMACIndex32(MachineOperand &Root) const {
5831 Register Src =
5832 getDefIgnoringCopies(Root.getReg(), *MRI)->getOperand(0).getReg();
5833 unsigned Key = 0;
5834
5835 Register S32 = matchZeroExtendFromS32(Src);
5836 if (!S32)
5837 S32 = matchAnyExtendFromS32(Src);
5838
5839 if (S32) {
5840 const MachineInstr *Def = getDefIgnoringCopies(S32, *MRI);
5841 if (Def->getOpcode() == TargetOpcode::G_UNMERGE_VALUES) {
5842 assert(Def->getNumOperands() == 3);
5843 Register DstReg1 = Def->getOperand(1).getReg();
5844 if (mi_match(S32, *MRI,
5845 m_any_of(m_SpecificReg(DstReg1), m_Copy(m_Reg(DstReg1))))) {
5846 Src = Def->getOperand(2).getReg();
5847 Key = 1;
5848 }
5849 }
5850 }
5851
5852 return {{
5853 [=](MachineInstrBuilder &MIB) { MIB.addReg(Src); },
5854 [=](MachineInstrBuilder &MIB) { MIB.addImm(Key); } // index_key
5855 }};
5856}
5857
5859AMDGPUInstructionSelector::selectVOP3OpSelMods(MachineOperand &Root) const {
5860 Register Src;
5861 unsigned Mods;
5862 std::tie(Src, Mods) = selectVOP3ModsImpl(Root.getReg());
5863
5864 Register ExtractSrc;
5865 if (!Subtarget->useRealTrue16Insts() &&
5866 MRI->getType(Root.getReg()).getSizeInBits() == 16 &&
5867 isExtractHiElt(*MRI, Src, ExtractSrc)) {
5868 Src = ExtractSrc;
5869 Mods |= SISrcMods::OP_SEL_0;
5870 }
5871
5872 return {{
5873 [=](MachineInstrBuilder &MIB) {
5874 MIB.addReg(copyToVGPRIfSrcFolded(Src, Mods, Root, MIB));
5875 },
5876 [=](MachineInstrBuilder &MIB) { MIB.addImm(Mods); } // src_mods
5877 }};
5878}
5879
5880// FIXME-TRUE16 remove when fake16 is removed
5882AMDGPUInstructionSelector::selectVINTERPMods(MachineOperand &Root) const {
5883 Register Src;
5884 unsigned Mods;
5885 std::tie(Src, Mods) = selectVOP3ModsImpl(Root.getReg(),
5886 /*IsCanonicalizing=*/true,
5887 /*AllowAbs=*/false,
5888 /*OpSel=*/false);
5889
5890 return {{
5891 [=](MachineInstrBuilder &MIB) {
5892 MIB.addReg(
5893 copyToVGPRIfSrcFolded(Src, Mods, Root, MIB, /* ForceVGPR */ true));
5894 },
5895 [=](MachineInstrBuilder &MIB) { MIB.addImm(Mods); }, // src0_mods
5896 }};
5897}
5898
5900AMDGPUInstructionSelector::selectVINTERPModsHi(MachineOperand &Root) const {
5901 Register Src;
5902 unsigned Mods;
5903 std::tie(Src, Mods) = selectVOP3ModsImpl(Root.getReg(),
5904 /*IsCanonicalizing=*/true,
5905 /*AllowAbs=*/false,
5906 /*OpSel=*/true);
5907
5908 return {{
5909 [=](MachineInstrBuilder &MIB) {
5910 MIB.addReg(
5911 copyToVGPRIfSrcFolded(Src, Mods, Root, MIB, /* ForceVGPR */ true));
5912 },
5913 [=](MachineInstrBuilder &MIB) { MIB.addImm(Mods); }, // src0_mods
5914 }};
5915}
5916
5917// Given \p Offset and load specified by the \p Root operand check if \p Offset
5918// is a multiple of the load byte size. If it is update \p Offset to a
5919// pre-scaled value and return true.
5920bool AMDGPUInstructionSelector::selectScaleOffset(MachineOperand &Root,
5922 bool IsSigned,
5923 bool IsSMEM) const {
5924 if (!Subtarget->hasScaleOffset())
5925 return false;
5926
5927 const MachineInstr &MI = *Root.getParent();
5928 MachineMemOperand *MMO = *MI.memoperands_begin();
5929
5930 if (!MMO->getSize().hasValue())
5931 return false;
5932
5933 uint64_t Size = MMO->getSize().getValue();
5934
5935 Register OffsetReg = matchExtendFromS32OrS32(Offset, IsSigned);
5936 bool IsExtended = OffsetReg && OffsetReg != Offset;
5937 if (!OffsetReg)
5938 OffsetReg = Offset;
5939
5940 if (auto Def = getDefSrcRegIgnoringCopies(OffsetReg, *MRI))
5941 OffsetReg = Def->Reg;
5942
5943 Register Op0;
5944 MachineInstr *Mul;
5945 bool ScaleOffset =
5946 (isPowerOf2_64(Size) &&
5947 mi_match(OffsetReg, *MRI,
5948 m_GShl(m_Reg(Op0),
5951 mi_match(OffsetReg, *MRI,
5953 m_Copy(m_SpecificICst(Size))))) ||
5954 mi_match(
5955 OffsetReg, *MRI,
5956 m_BinOp(IsSigned ? AMDGPU::S_MUL_I64_I32_PSEUDO : AMDGPU::S_MUL_U64,
5957 m_Reg(Op0), m_SpecificICst(Size))) ||
5958 // Match G_AMDGPU_MAD_U64_U32 offset, c, 0
5959 (mi_match(OffsetReg, *MRI, m_MInstr(Mul)) &&
5960 (Mul->getOpcode() == (IsSigned ? AMDGPU::G_AMDGPU_MAD_I64_I32
5961 : AMDGPU::G_AMDGPU_MAD_U64_U32) ||
5962 (IsSigned && Mul->getOpcode() == AMDGPU::G_AMDGPU_MAD_U64_U32 &&
5963 VT->signBitIsZero(Mul->getOperand(2).getReg()))) &&
5964 mi_match(Mul->getOperand(4).getReg(), *MRI, m_ZeroInt()) &&
5965 mi_match(Mul->getOperand(3).getReg(), *MRI,
5967 m_Copy(m_SpecificICst(Size))))) &&
5968 mi_match(Mul->getOperand(2).getReg(), *MRI, m_Reg(Op0)));
5969
5970 if (!ScaleOffset)
5971 return false;
5972
5973 // SMEM scales the offset in 32 bits, other instructions in 64 bits.
5974 unsigned Bits = Log2_64_Ceil(Size);
5975 if (IsSMEM) {
5976 if (!IsExtended && MRI->getType(Offset).getSizeInBits() == 64) {
5977 KnownBits Known = VT->getKnownBits(Op0);
5978 if (Known.countMaxActiveBits() + Bits > 32)
5979 return false;
5980 }
5981 } else if (IsExtended) {
5982 const MachineInstr *Scale = MRI->getVRegDef(OffsetReg);
5983 if (IsSigned && !Scale->getFlag(MachineInstr::NoSWrap) &&
5984 VT->computeNumSignBits(Op0) <= Bits)
5985 return false;
5986 if (!IsSigned && !Scale->getFlag(MachineInstr::NoUWrap) &&
5987 VT->getKnownBits(Op0).countMinLeadingZeros() < Bits)
5988 return false;
5989 }
5990
5991 Offset = Op0;
5992 return true;
5993}
5994
5995bool AMDGPUInstructionSelector::selectSmrdOffset(MachineOperand &Root,
5996 Register &Base,
5997 Register *SOffset,
5998 int64_t *Offset,
5999 bool *ScaleOffset) const {
6000 MachineInstr *MI = Root.getParent();
6001 MachineBasicBlock *MBB = MI->getParent();
6002
6003 // FIXME: We should shrink the GEP if the offset is known to be <= 32-bits,
6004 // then we can select all ptr + 32-bit offsets.
6005 SmallVector<GEPInfo, 4> AddrInfo;
6006 getAddrModeInfo(*MI, *MRI, AddrInfo);
6007
6008 if (AddrInfo.empty())
6009 return false;
6010
6011 const GEPInfo &GEPI = AddrInfo[0];
6012 std::optional<int64_t> EncodedImm;
6013
6014 if (ScaleOffset)
6015 *ScaleOffset = false;
6016
6017 if (SOffset && Offset) {
6018 EncodedImm = AMDGPU::getSMRDEncodedOffset(STI, GEPI.Imm, /*IsBuffer=*/false,
6019 /*HasSOffset=*/true);
6020 if (GEPI.SgprParts.size() == 1 && GEPI.Imm != 0 && EncodedImm &&
6021 AddrInfo.size() > 1) {
6022 const GEPInfo &GEPI2 = AddrInfo[1];
6023 if (GEPI2.SgprParts.size() == 2 && GEPI2.Imm == 0) {
6024 Register OffsetReg = GEPI2.SgprParts[1];
6025 if (ScaleOffset)
6026 *ScaleOffset = selectScaleOffset(
6027 Root, OffsetReg, false /* IsSigned */, true /* IsSMEM */);
6028 OffsetReg = matchZeroExtendFromS32OrS32(OffsetReg);
6029 if (OffsetReg) {
6030 Base = GEPI2.SgprParts[0];
6031 *SOffset = OffsetReg;
6032 *Offset = *EncodedImm;
6033 if (*Offset >= 0 || !AMDGPU::hasSMRDSignedImmOffset(STI))
6034 return true;
6035
6036 // For unbuffered smem loads, it is illegal for the Immediate Offset
6037 // to be negative if the resulting (Offset + (M0 or SOffset or zero)
6038 // is negative. Handle the case where the Immediate Offset + SOffset
6039 // is negative.
6040 auto SKnown = VT->getKnownBits(*SOffset);
6041 if (*Offset + SKnown.getMinValue().getSExtValue() < 0)
6042 return false;
6043
6044 return true;
6045 }
6046 }
6047 }
6048 return false;
6049 }
6050
6051 EncodedImm = AMDGPU::getSMRDEncodedOffset(STI, GEPI.Imm, /*IsBuffer=*/false,
6052 /*HasSOffset=*/false);
6053 if (Offset && GEPI.SgprParts.size() == 1 && EncodedImm) {
6054 Base = GEPI.SgprParts[0];
6055 *Offset = *EncodedImm;
6056 return true;
6057 }
6058
6059 // SGPR offset is unsigned.
6060 if (SOffset && GEPI.SgprParts.size() == 1 && isUInt<32>(GEPI.Imm) &&
6061 GEPI.Imm != 0) {
6062 // If we make it this far we have a load with an 32-bit immediate offset.
6063 // It is OK to select this using a sgpr offset, because we have already
6064 // failed trying to select this load into one of the _IMM variants since
6065 // the _IMM Patterns are considered before the _SGPR patterns.
6066 Base = GEPI.SgprParts[0];
6067 *SOffset = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
6068 BuildMI(*MBB, MI, MI->getDebugLoc(), TII.get(AMDGPU::S_MOV_B32), *SOffset)
6069 .addImm(GEPI.Imm);
6070 return true;
6071 }
6072
6073 if (SOffset && GEPI.SgprParts.size() && GEPI.Imm == 0) {
6074 Register OffsetReg = GEPI.SgprParts[1];
6075 if (ScaleOffset)
6076 *ScaleOffset = selectScaleOffset(Root, OffsetReg, false /* IsSigned */,
6077 true /* IsSMEM */);
6078 OffsetReg = matchZeroExtendFromS32OrS32(OffsetReg);
6079 if (OffsetReg) {
6080 Base = GEPI.SgprParts[0];
6081 *SOffset = OffsetReg;
6082 return true;
6083 }
6084 }
6085
6086 return false;
6087}
6088
6090AMDGPUInstructionSelector::selectSmrdImm(MachineOperand &Root) const {
6091 Register Base;
6092 int64_t Offset;
6093 if (!selectSmrdOffset(Root, Base, /* SOffset= */ nullptr, &Offset,
6094 /* ScaleOffset */ nullptr))
6095 return std::nullopt;
6096
6097 return {{[=](MachineInstrBuilder &MIB) { MIB.addReg(Base); },
6098 [=](MachineInstrBuilder &MIB) { MIB.addImm(Offset); }}};
6099}
6100
6102AMDGPUInstructionSelector::selectSmrdImm32(MachineOperand &Root) const {
6103 SmallVector<GEPInfo, 4> AddrInfo;
6104 getAddrModeInfo(*Root.getParent(), *MRI, AddrInfo);
6105
6106 if (AddrInfo.empty() || AddrInfo[0].SgprParts.size() != 1)
6107 return std::nullopt;
6108
6109 const GEPInfo &GEPInfo = AddrInfo[0];
6110 Register PtrReg = GEPInfo.SgprParts[0];
6111 std::optional<int64_t> EncodedImm =
6112 AMDGPU::getSMRDEncodedLiteralOffset32(STI, GEPInfo.Imm);
6113 if (!EncodedImm)
6114 return std::nullopt;
6115
6116 return {{
6117 [=](MachineInstrBuilder &MIB) { MIB.addReg(PtrReg); },
6118 [=](MachineInstrBuilder &MIB) { MIB.addImm(*EncodedImm); }
6119 }};
6120}
6121
6123AMDGPUInstructionSelector::selectSmrdSgpr(MachineOperand &Root) const {
6124 Register Base, SOffset;
6125 bool ScaleOffset;
6126 if (!selectSmrdOffset(Root, Base, &SOffset, /* Offset= */ nullptr,
6127 &ScaleOffset))
6128 return std::nullopt;
6129
6130 unsigned CPol = ScaleOffset ? AMDGPU::CPol::SCAL : 0;
6131 return {{[=](MachineInstrBuilder &MIB) { MIB.addReg(Base); },
6132 [=](MachineInstrBuilder &MIB) { MIB.addReg(SOffset); },
6133 [=](MachineInstrBuilder &MIB) { MIB.addImm(CPol); }}};
6134}
6135
6137AMDGPUInstructionSelector::selectSmrdSgprImm(MachineOperand &Root) const {
6138 Register Base, SOffset;
6139 int64_t Offset;
6140 bool ScaleOffset;
6141 if (!selectSmrdOffset(Root, Base, &SOffset, &Offset, &ScaleOffset))
6142 return std::nullopt;
6143
6144 unsigned CPol = ScaleOffset ? AMDGPU::CPol::SCAL : 0;
6145 return {{[=](MachineInstrBuilder &MIB) { MIB.addReg(Base); },
6146 [=](MachineInstrBuilder &MIB) { MIB.addReg(SOffset); },
6147 [=](MachineInstrBuilder &MIB) { MIB.addImm(Offset); },
6148 [=](MachineInstrBuilder &MIB) { MIB.addImm(CPol); }}};
6149}
6150
6151std::pair<Register, int64_t> AMDGPUInstructionSelector::selectFlatOffsetImpl(
6152 MachineOperand &Root, AMDGPU::FlatAddrSpace FlatVariant) const {
6153 MachineInstr *MI = Root.getParent();
6154
6155 auto Default = std::pair(Root.getReg(), 0);
6156
6157 if (!STI.hasFlatInstOffsets())
6158 return Default;
6159
6160 Register PtrBase;
6161 int64_t ConstOffset;
6162 bool IsInBounds;
6163 std::tie(PtrBase, ConstOffset, IsInBounds) =
6164 getPtrBaseWithConstantOffset(Root.getReg(), *MRI);
6165
6166 // Adding the offset to the base address with an immediate in a FLAT
6167 // instruction must not change the memory aperture in which the address falls.
6168 // Therefore we can only fold offsets from inbounds GEPs into FLAT
6169 // instructions.
6170 if (ConstOffset == 0 ||
6171 (FlatVariant == AMDGPU::FlatAddrSpace::FlatScratch &&
6172 !isFlatScratchBaseLegal(Root.getReg())) ||
6173 (FlatVariant == AMDGPU::FlatAddrSpace::FLAT && !IsInBounds))
6174 return Default;
6175
6176 unsigned AddrSpace = (*MI->memoperands_begin())->getAddrSpace();
6177 if (!TII.isLegalFLATOffset(ConstOffset, AddrSpace, FlatVariant))
6178 return Default;
6179
6180 return std::pair(PtrBase, ConstOffset);
6181}
6182
6184AMDGPUInstructionSelector::selectFlatOffset(MachineOperand &Root) const {
6185 auto PtrWithOffset = selectFlatOffsetImpl(Root, AMDGPU::FlatAddrSpace::FLAT);
6186
6187 return {{
6188 [=](MachineInstrBuilder &MIB) { MIB.addReg(PtrWithOffset.first); },
6189 [=](MachineInstrBuilder &MIB) { MIB.addImm(PtrWithOffset.second); },
6190 }};
6191}
6192
6194AMDGPUInstructionSelector::selectGlobalOffset(MachineOperand &Root) const {
6195 auto PtrWithOffset =
6196 selectFlatOffsetImpl(Root, AMDGPU::FlatAddrSpace::FlatGlobal);
6197
6198 return {{
6199 [=](MachineInstrBuilder &MIB) { MIB.addReg(PtrWithOffset.first); },
6200 [=](MachineInstrBuilder &MIB) { MIB.addImm(PtrWithOffset.second); },
6201 }};
6202}
6203
6205AMDGPUInstructionSelector::selectScratchOffset(MachineOperand &Root) const {
6206 auto PtrWithOffset =
6207 selectFlatOffsetImpl(Root, AMDGPU::FlatAddrSpace::FlatScratch);
6208
6209 return {{
6210 [=](MachineInstrBuilder &MIB) { MIB.addReg(PtrWithOffset.first); },
6211 [=](MachineInstrBuilder &MIB) { MIB.addImm(PtrWithOffset.second); },
6212 }};
6213}
6214
6215// Match (64-bit SGPR base) + (zext vgpr offset) + sext(imm offset)
6217AMDGPUInstructionSelector::selectGlobalSAddr(MachineOperand &Root,
6218 unsigned CPolBits,
6219 bool NeedIOffset) const {
6220 Register Addr = Root.getReg();
6221 Register PtrBase;
6222 int64_t ConstOffset;
6223 int64_t ImmOffset = 0;
6224
6225 // Match the immediate offset first, which canonically is moved as low as
6226 // possible.
6227 std::tie(PtrBase, ConstOffset, std::ignore) =
6228 getPtrBaseWithConstantOffset(Addr, *MRI);
6229
6230 if (ConstOffset != 0) {
6231 if (NeedIOffset &&
6232 TII.isLegalFLATOffset(ConstOffset, AMDGPUAS::GLOBAL_ADDRESS,
6234 Addr = PtrBase;
6235 ImmOffset = ConstOffset;
6236 } else {
6237 auto PtrBaseDef = getDefSrcRegIgnoringCopies(PtrBase, *MRI);
6238 if (isSGPR(PtrBaseDef->Reg)) {
6239 // Offset is too large.
6240 //
6241 // saddr + large_offset -> saddr +
6242 // (voffset = large_offset & ~MaxOffset) +
6243 // (large_offset & MaxOffset);
6244 int64_t SplitImmOffset = 0, RemainderOffset = ConstOffset;
6245 if (NeedIOffset) {
6246 std::tie(SplitImmOffset, RemainderOffset) =
6247 TII.splitFlatOffset(ConstOffset, AMDGPUAS::GLOBAL_ADDRESS,
6249 }
6250
6251 if (Subtarget->hasSignedGVSOffset() ? isInt<32>(RemainderOffset)
6252 : isUInt<32>(RemainderOffset)) {
6253 MachineInstr *MI = Root.getParent();
6254 MachineBasicBlock *MBB = MI->getParent();
6255 Register HighBits =
6256 MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6257
6258 BuildMI(*MBB, MI, MI->getDebugLoc(), TII.get(AMDGPU::V_MOV_B32_e32),
6259 HighBits)
6260 .addImm(RemainderOffset);
6261
6262 if (NeedIOffset)
6263 return {{
6264 [=](MachineInstrBuilder &MIB) { MIB.addReg(PtrBase); }, // saddr
6265 [=](MachineInstrBuilder &MIB) {
6266 MIB.addReg(HighBits);
6267 }, // voffset
6268 [=](MachineInstrBuilder &MIB) { MIB.addImm(SplitImmOffset); },
6269 [=](MachineInstrBuilder &MIB) { MIB.addImm(CPolBits); },
6270 }};
6271 return {{
6272 [=](MachineInstrBuilder &MIB) { MIB.addReg(PtrBase); }, // saddr
6273 [=](MachineInstrBuilder &MIB) {
6274 MIB.addReg(HighBits);
6275 }, // voffset
6276 [=](MachineInstrBuilder &MIB) { MIB.addImm(CPolBits); },
6277 }};
6278 }
6279
6280 // We are adding a 64 bit SGPR and a constant. If constant bus limit
6281 // is 1 we would need to perform 1 or 2 extra moves for each half of
6282 // the constant and it is better to do a scalar add and then issue a
6283 // single VALU instruction to materialize zero. Otherwise it is less
6284 // instructions to perform VALU adds with immediates or inline literals.
6285 unsigned NumLiterals =
6286 !TII.isInlineConstant(APInt(32, Lo_32(ConstOffset))) +
6287 !TII.isInlineConstant(APInt(32, Hi_32(ConstOffset)));
6288 if (STI.getConstantBusLimit(AMDGPU::V_ADD_U32_e64) > NumLiterals)
6289 return std::nullopt;
6290 }
6291 }
6292 }
6293
6294 // Match the variable offset.
6295 auto AddrDef = getDefSrcRegIgnoringCopies(Addr, *MRI);
6296 if (AddrDef->MI->getOpcode() == AMDGPU::G_PTR_ADD) {
6297 // Look through the SGPR->VGPR copy.
6298 Register SAddr =
6299 getSrcRegIgnoringCopies(AddrDef->MI->getOperand(1).getReg(), *MRI);
6300
6301 if (isSGPR(SAddr)) {
6302 Register PtrBaseOffset = AddrDef->MI->getOperand(2).getReg();
6303
6304 // It's possible voffset is an SGPR here, but the copy to VGPR will be
6305 // inserted later.
6306 bool ScaleOffset = selectScaleOffset(Root, PtrBaseOffset,
6307 Subtarget->hasSignedGVSOffset());
6308 if (Register VOffset = matchExtendFromS32OrS32(
6309 PtrBaseOffset, Subtarget->hasSignedGVSOffset())) {
6310 if (NeedIOffset)
6311 return {{[=](MachineInstrBuilder &MIB) { // saddr
6312 MIB.addReg(SAddr);
6313 },
6314 [=](MachineInstrBuilder &MIB) { // voffset
6315 MIB.addReg(VOffset);
6316 },
6317 [=](MachineInstrBuilder &MIB) { // offset
6318 MIB.addImm(ImmOffset);
6319 },
6320 [=](MachineInstrBuilder &MIB) { // cpol
6321 MIB.addImm(CPolBits |
6322 (ScaleOffset ? AMDGPU::CPol::SCAL : 0));
6323 }}};
6324 return {{[=](MachineInstrBuilder &MIB) { // saddr
6325 MIB.addReg(SAddr);
6326 },
6327 [=](MachineInstrBuilder &MIB) { // voffset
6328 MIB.addReg(VOffset);
6329 },
6330 [=](MachineInstrBuilder &MIB) { // cpol
6331 MIB.addImm(CPolBits |
6332 (ScaleOffset ? AMDGPU::CPol::SCAL : 0));
6333 }}};
6334 }
6335 }
6336 }
6337
6338 // FIXME: We should probably have folded COPY (G_IMPLICIT_DEF) earlier, and
6339 // drop this.
6340 if (AddrDef->MI->getOpcode() == AMDGPU::G_IMPLICIT_DEF ||
6341 AddrDef->MI->getOpcode() == AMDGPU::G_CONSTANT || !isSGPR(AddrDef->Reg))
6342 return std::nullopt;
6343
6344 // It's cheaper to materialize a single 32-bit zero for vaddr than the two
6345 // moves required to copy a 64-bit SGPR to VGPR.
6346 MachineInstr *MI = Root.getParent();
6347 MachineBasicBlock *MBB = MI->getParent();
6348 Register VOffset = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6349
6350 BuildMI(*MBB, MI, MI->getDebugLoc(), TII.get(AMDGPU::V_MOV_B32_e32), VOffset)
6351 .addImm(0);
6352
6353 if (NeedIOffset)
6354 return {{
6355 [=](MachineInstrBuilder &MIB) { MIB.addReg(AddrDef->Reg); }, // saddr
6356 [=](MachineInstrBuilder &MIB) { MIB.addReg(VOffset); }, // voffset
6357 [=](MachineInstrBuilder &MIB) { MIB.addImm(ImmOffset); }, // offset
6358 [=](MachineInstrBuilder &MIB) { MIB.addImm(CPolBits); } // cpol
6359 }};
6360 return {{
6361 [=](MachineInstrBuilder &MIB) { MIB.addReg(AddrDef->Reg); }, // saddr
6362 [=](MachineInstrBuilder &MIB) { MIB.addReg(VOffset); }, // voffset
6363 [=](MachineInstrBuilder &MIB) { MIB.addImm(CPolBits); } // cpol
6364 }};
6365}
6366
6368AMDGPUInstructionSelector::selectGlobalSAddr(MachineOperand &Root) const {
6369 return selectGlobalSAddr(Root, 0);
6370}
6371
6373AMDGPUInstructionSelector::selectGlobalSAddrCPol(MachineOperand &Root) const {
6374 const MachineInstr &I = *Root.getParent();
6375
6376 // We are assuming CPol is always the last operand of the intrinsic.
6377 auto PassedCPol =
6378 I.getOperand(I.getNumOperands() - 1).getImm() & ~AMDGPU::CPol::SCAL;
6379 return selectGlobalSAddr(Root, static_cast<unsigned>(PassedCPol));
6380}
6381
6383AMDGPUInstructionSelector::selectGlobalSAddrCPolM0(MachineOperand &Root) const {
6384 const MachineInstr &I = *Root.getParent();
6385
6386 // We are assuming CPol is second from last operand of the intrinsic.
6387 auto PassedCPol =
6388 I.getOperand(I.getNumOperands() - 2).getImm() & ~AMDGPU::CPol::SCAL;
6389 return selectGlobalSAddr(Root, static_cast<unsigned>(PassedCPol));
6390}
6391
6393AMDGPUInstructionSelector::selectGlobalSAddrGLC(MachineOperand &Root) const {
6394 return selectGlobalSAddr(Root, AMDGPU::CPol::GLC);
6395}
6396
6398AMDGPUInstructionSelector::selectGlobalSAddrNoIOffset(
6399 MachineOperand &Root) const {
6400 const MachineInstr &I = *Root.getParent();
6401
6402 // We are assuming CPol is always the last operand of the intrinsic.
6403 auto PassedCPol =
6404 I.getOperand(I.getNumOperands() - 1).getImm() & ~AMDGPU::CPol::SCAL;
6405 return selectGlobalSAddr(Root, static_cast<unsigned>(PassedCPol), false);
6406}
6407
6409AMDGPUInstructionSelector::selectGlobalSAddrNoIOffsetM0(
6410 MachineOperand &Root) const {
6411 const MachineInstr &I = *Root.getParent();
6412
6413 // We are assuming CPol is second from last operand of the intrinsic.
6414 auto PassedCPol =
6415 I.getOperand(I.getNumOperands() - 2).getImm() & ~AMDGPU::CPol::SCAL;
6416 return selectGlobalSAddr(Root, static_cast<unsigned>(PassedCPol), false);
6417}
6418
6420AMDGPUInstructionSelector::selectScratchSAddr(MachineOperand &Root) const {
6421 Register Addr = Root.getReg();
6422 Register PtrBase;
6423 int64_t ConstOffset;
6424 int64_t ImmOffset = 0;
6425
6426 // Match the immediate offset first, which canonically is moved as low as
6427 // possible.
6428 std::tie(PtrBase, ConstOffset, std::ignore) =
6429 getPtrBaseWithConstantOffset(Addr, *MRI);
6430
6431 if (ConstOffset != 0 && isFlatScratchBaseLegal(Addr) &&
6432 TII.isLegalFLATOffset(ConstOffset, AMDGPUAS::PRIVATE_ADDRESS,
6434 Addr = PtrBase;
6435 ImmOffset = ConstOffset;
6436 }
6437
6438 auto AddrDef = getDefSrcRegIgnoringCopies(Addr, *MRI);
6439 if (AddrDef->MI->getOpcode() == AMDGPU::G_FRAME_INDEX) {
6440 int FI = AddrDef->MI->getOperand(1).getIndex();
6441 return {{
6442 [=](MachineInstrBuilder &MIB) { MIB.addFrameIndex(FI); }, // saddr
6443 [=](MachineInstrBuilder &MIB) { MIB.addImm(ImmOffset); } // offset
6444 }};
6445 }
6446
6447 Register SAddr = AddrDef->Reg;
6448
6449 if (AddrDef->MI->getOpcode() == AMDGPU::G_PTR_ADD) {
6450 Register LHS = AddrDef->MI->getOperand(1).getReg();
6451 Register RHS = AddrDef->MI->getOperand(2).getReg();
6452 auto LHSDef = getDefSrcRegIgnoringCopies(LHS, *MRI);
6453 auto RHSDef = getDefSrcRegIgnoringCopies(RHS, *MRI);
6454
6455 if (LHSDef->MI->getOpcode() == AMDGPU::G_FRAME_INDEX &&
6456 isSGPR(RHSDef->Reg)) {
6457 int FI = LHSDef->MI->getOperand(1).getIndex();
6458 MachineInstr &I = *Root.getParent();
6459 MachineBasicBlock *BB = I.getParent();
6460 const DebugLoc &DL = I.getDebugLoc();
6461 SAddr = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
6462
6463 BuildMI(*BB, &I, DL, TII.get(AMDGPU::S_ADD_I32), SAddr)
6464 .addFrameIndex(FI)
6465 .addReg(RHSDef->Reg)
6466 .setOperandDead(3); // Dead scc
6467 }
6468 }
6469
6470 if (!isSGPR(SAddr))
6471 return std::nullopt;
6472
6473 return {{
6474 [=](MachineInstrBuilder &MIB) { MIB.addReg(SAddr); }, // saddr
6475 [=](MachineInstrBuilder &MIB) { MIB.addImm(ImmOffset); } // offset
6476 }};
6477}
6478
6479// Check whether the flat scratch SVS swizzle bug affects this access.
6480bool AMDGPUInstructionSelector::checkFlatScratchSVSSwizzleBug(
6481 Register VAddr, Register SAddr, uint64_t ImmOffset) const {
6482 if (!Subtarget->hasFlatScratchSVSSwizzleBug())
6483 return false;
6484
6485 // The bug affects the swizzling of SVS accesses if there is any carry out
6486 // from the two low order bits (i.e. from bit 1 into bit 2) when adding
6487 // voffset to (soffset + inst_offset).
6488 auto VKnown = VT->getKnownBits(VAddr);
6489 auto SKnown = KnownBits::add(VT->getKnownBits(SAddr),
6490 KnownBits::makeConstant(APInt(32, ImmOffset)));
6491 uint64_t VMax = VKnown.getMaxValue().getZExtValue();
6492 uint64_t SMax = SKnown.getMaxValue().getZExtValue();
6493 return (VMax & 3) + (SMax & 3) >= 4;
6494}
6495
6497AMDGPUInstructionSelector::selectScratchSVAddr(MachineOperand &Root) const {
6498 Register Addr = Root.getReg();
6499 Register PtrBase;
6500 int64_t ConstOffset;
6501 int64_t ImmOffset = 0;
6502
6503 // Match the immediate offset first, which canonically is moved as low as
6504 // possible.
6505 std::tie(PtrBase, ConstOffset, std::ignore) =
6506 getPtrBaseWithConstantOffset(Addr, *MRI);
6507
6508 Register OrigAddr = Addr;
6509 if (ConstOffset != 0 &&
6510 TII.isLegalFLATOffset(ConstOffset, AMDGPUAS::PRIVATE_ADDRESS,
6512 Addr = PtrBase;
6513 ImmOffset = ConstOffset;
6514 }
6515
6516 auto AddrDef = getDefSrcRegIgnoringCopies(Addr, *MRI);
6517 if (AddrDef->MI->getOpcode() != AMDGPU::G_PTR_ADD)
6518 return std::nullopt;
6519
6520 Register RHS = AddrDef->MI->getOperand(2).getReg();
6521 if (RBI.getRegBank(RHS, *MRI, TRI)->getID() != AMDGPU::VGPRRegBankID)
6522 return std::nullopt;
6523
6524 Register LHS = AddrDef->MI->getOperand(1).getReg();
6525 auto LHSDef = getDefSrcRegIgnoringCopies(LHS, *MRI);
6526
6527 if (OrigAddr != Addr) {
6528 if (!isFlatScratchBaseLegalSVImm(OrigAddr))
6529 return std::nullopt;
6530 } else {
6531 if (!isFlatScratchBaseLegalSV(OrigAddr))
6532 return std::nullopt;
6533 }
6534
6535 if (checkFlatScratchSVSSwizzleBug(RHS, LHS, ImmOffset))
6536 return std::nullopt;
6537
6538 unsigned CPol = selectScaleOffset(Root, RHS, true /* IsSigned */)
6540 : 0;
6541
6542 if (LHSDef->MI->getOpcode() == AMDGPU::G_FRAME_INDEX) {
6543 int FI = LHSDef->MI->getOperand(1).getIndex();
6544 return {{
6545 [=](MachineInstrBuilder &MIB) { MIB.addReg(RHS); }, // vaddr
6546 [=](MachineInstrBuilder &MIB) { MIB.addFrameIndex(FI); }, // saddr
6547 [=](MachineInstrBuilder &MIB) { MIB.addImm(ImmOffset); }, // offset
6548 [=](MachineInstrBuilder &MIB) { MIB.addImm(CPol); } // cpol
6549 }};
6550 }
6551
6552 if (!isSGPR(LHS))
6553 if (auto Def = getDefSrcRegIgnoringCopies(LHS, *MRI))
6554 LHS = Def->Reg;
6555
6556 if (!isSGPR(LHS))
6557 return std::nullopt;
6558
6559 return {{
6560 [=](MachineInstrBuilder &MIB) { MIB.addReg(RHS); }, // vaddr
6561 [=](MachineInstrBuilder &MIB) { MIB.addReg(LHS); }, // saddr
6562 [=](MachineInstrBuilder &MIB) { MIB.addImm(ImmOffset); }, // offset
6563 [=](MachineInstrBuilder &MIB) { MIB.addImm(CPol); } // cpol
6564 }};
6565}
6566
6568AMDGPUInstructionSelector::selectMUBUFScratchOffen(MachineOperand &Root) const {
6569 MachineInstr *MI = Root.getParent();
6570 MachineBasicBlock *MBB = MI->getParent();
6572 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
6573
6574 int64_t Offset = 0;
6575 if (mi_match(Root.getReg(), *MRI, m_ICst(Offset)) &&
6577 Register HighBits = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass);
6578
6579 // TODO: Should this be inside the render function? The iterator seems to
6580 // move.
6581 const int64_t MaxOffset = SIInstrInfo::getMaxMUBUFImmOffset(*Subtarget);
6582 BuildMI(*MBB, MI, MI->getDebugLoc(), TII.get(AMDGPU::V_MOV_B32_e32),
6583 HighBits)
6584 .addImm(Offset & ~MaxOffset);
6585
6586 return {{[=](MachineInstrBuilder &MIB) { // rsrc
6587 MIB.addReg(Info->getScratchRSrcReg());
6588 },
6589 [=](MachineInstrBuilder &MIB) { // vaddr
6590 MIB.addReg(HighBits);
6591 },
6592 [=](MachineInstrBuilder &MIB) { // soffset
6593 // Use constant zero for soffset and rely on eliminateFrameIndex
6594 // to choose the appropriate frame register if need be.
6595 MIB.addImm(0);
6596 },
6597 [=](MachineInstrBuilder &MIB) { // offset
6598 MIB.addImm(Offset & MaxOffset);
6599 }}};
6600 }
6601
6602 assert(Offset == 0 || Offset == -1);
6603
6604 // Try to fold a frame index directly into the MUBUF vaddr field, and any
6605 // offsets.
6606 std::optional<int> FI;
6607 Register VAddr = Root.getReg();
6608
6609 Register PtrBase;
6610 int64_t ConstOffset;
6611 std::tie(PtrBase, ConstOffset, std::ignore) =
6612 getPtrBaseWithConstantOffset(VAddr, *MRI);
6613 int MatchedFI;
6614 if (ConstOffset != 0) {
6615 if (TII.isLegalMUBUFImmOffset(ConstOffset) &&
6616 (!STI.privateMemoryResourceIsRangeChecked() ||
6617 VT->signBitIsZero(PtrBase))) {
6618 if (mi_match(PtrBase, *MRI, m_GFrameIndex(MatchedFI)))
6619 FI = MatchedFI;
6620 else
6621 VAddr = PtrBase;
6622 Offset = ConstOffset;
6623 }
6624 } else if (mi_match(Root.getReg(), *MRI, m_GFrameIndex(MatchedFI))) {
6625 FI = MatchedFI;
6626 }
6627
6628 return {{[=](MachineInstrBuilder &MIB) { // rsrc
6629 MIB.addReg(Info->getScratchRSrcReg());
6630 },
6631 [=](MachineInstrBuilder &MIB) { // vaddr
6632 if (FI)
6633 MIB.addFrameIndex(*FI);
6634 else
6635 MIB.addReg(VAddr);
6636 },
6637 [=](MachineInstrBuilder &MIB) { // soffset
6638 // Use constant zero for soffset and rely on eliminateFrameIndex
6639 // to choose the appropriate frame register if need be.
6640 MIB.addImm(0);
6641 },
6642 [=](MachineInstrBuilder &MIB) { // offset
6643 MIB.addImm(Offset);
6644 }}};
6645}
6646
6647bool AMDGPUInstructionSelector::isDSOffsetLegal(Register Base,
6648 int64_t Offset) const {
6649 if (!isUInt<16>(Offset))
6650 return false;
6651
6652 if (STI.hasUsableDSOffset() || STI.unsafeDSOffsetFoldingEnabled())
6653 return true;
6654
6655 // On Southern Islands instruction with a negative base value and an offset
6656 // don't seem to work.
6657 return VT->signBitIsZero(Base);
6658}
6659
6660bool AMDGPUInstructionSelector::isDSOffset2Legal(Register Base, int64_t Offset0,
6661 int64_t Offset1,
6662 unsigned Size) const {
6663 if (Offset0 % Size != 0 || Offset1 % Size != 0)
6664 return false;
6665 if (!isUInt<8>(Offset0 / Size) || !isUInt<8>(Offset1 / Size))
6666 return false;
6667
6668 if (STI.hasUsableDSOffset() || STI.unsafeDSOffsetFoldingEnabled())
6669 return true;
6670
6671 // On Southern Islands instruction with a negative base value and an offset
6672 // don't seem to work.
6673 return VT->signBitIsZero(Base);
6674}
6675
6676// Return whether the operation has NoUnsignedWrap property.
6677static bool isNoUnsignedWrap(MachineInstr *Addr) {
6678 return Addr->getOpcode() == TargetOpcode::G_OR ||
6679 (Addr->getOpcode() == TargetOpcode::G_PTR_ADD &&
6681}
6682
6683// Check that the base address of flat scratch load/store in the form of `base +
6684// offset` is legal to be put in SGPR/VGPR (i.e. unsigned per hardware
6685// requirement). We always treat the first operand as the base address here.
6686bool AMDGPUInstructionSelector::isFlatScratchBaseLegal(Register Addr) const {
6687 MachineInstr *AddrMI = getDefIgnoringCopies(Addr, *MRI);
6688
6689 if (isNoUnsignedWrap(AddrMI))
6690 return true;
6691
6692 // Starting with GFX12, VADDR and SADDR fields in VSCRATCH can use negative
6693 // values.
6694 if (STI.hasSignedScratchOffsets())
6695 return true;
6696
6697 Register LHS = AddrMI->getOperand(1).getReg();
6698 Register RHS = AddrMI->getOperand(2).getReg();
6699
6700 if (AddrMI->getOpcode() == TargetOpcode::G_PTR_ADD) {
6701 std::optional<ValueAndVReg> RhsValReg =
6703 // If the immediate offset is negative and within certain range, the base
6704 // address cannot also be negative. If the base is also negative, the sum
6705 // would be either negative or much larger than the valid range of scratch
6706 // memory a thread can access.
6707 if (RhsValReg && RhsValReg->Value.getSExtValue() < 0 &&
6708 RhsValReg->Value.getSExtValue() > -0x40000000)
6709 return true;
6710 }
6711
6712 return VT->signBitIsZero(LHS);
6713}
6714
6715// Check address value in SGPR/VGPR are legal for flat scratch in the form
6716// of: SGPR + VGPR.
6717bool AMDGPUInstructionSelector::isFlatScratchBaseLegalSV(Register Addr) const {
6718 MachineInstr *AddrMI = getDefIgnoringCopies(Addr, *MRI);
6719
6720 if (isNoUnsignedWrap(AddrMI))
6721 return true;
6722
6723 // Starting with GFX12, VADDR and SADDR fields in VSCRATCH can use negative
6724 // values.
6725 if (STI.hasSignedScratchOffsets())
6726 return true;
6727
6728 Register LHS = AddrMI->getOperand(1).getReg();
6729 Register RHS = AddrMI->getOperand(2).getReg();
6730 return VT->signBitIsZero(RHS) && VT->signBitIsZero(LHS);
6731}
6732
6733// Check address value in SGPR/VGPR are legal for flat scratch in the form
6734// of: SGPR + VGPR + Imm.
6735bool AMDGPUInstructionSelector::isFlatScratchBaseLegalSVImm(
6736 Register Addr) const {
6737 // Starting with GFX12, VADDR and SADDR fields in VSCRATCH can use negative
6738 // values.
6739 if (STI.hasSignedScratchOffsets())
6740 return true;
6741
6742 MachineInstr *AddrMI = getDefIgnoringCopies(Addr, *MRI);
6743 Register Base = AddrMI->getOperand(1).getReg();
6744 std::optional<DefinitionAndSourceRegister> BaseDef =
6746 std::optional<ValueAndVReg> RHSOffset =
6748 assert(RHSOffset);
6749
6750 // If the immediate offset is negative and within certain range, the base
6751 // address cannot also be negative. If the base is also negative, the sum
6752 // would be either negative or much larger than the valid range of scratch
6753 // memory a thread can access.
6754 if (isNoUnsignedWrap(BaseDef->MI) &&
6755 (isNoUnsignedWrap(AddrMI) ||
6756 (RHSOffset->Value.getSExtValue() < 0 &&
6757 RHSOffset->Value.getSExtValue() > -0x40000000)))
6758 return true;
6759
6760 Register LHS = BaseDef->MI->getOperand(1).getReg();
6761 Register RHS = BaseDef->MI->getOperand(2).getReg();
6762 return VT->signBitIsZero(RHS) && VT->signBitIsZero(LHS);
6763}
6764
6765bool AMDGPUInstructionSelector::isUnneededShiftMask(const MachineInstr &MI,
6766 unsigned ShAmtBits) const {
6767 assert(MI.getOpcode() == TargetOpcode::G_AND);
6768
6769 // The mask constant is an SGPR G_CONSTANT copied to VGPR; the matcher looks
6770 // through that COPY, so look through it here too.
6771 std::optional<ValueAndVReg> RHS =
6772 getIConstantVRegValWithLookThrough(MI.getOperand(2).getReg(), *MRI);
6773 if (!RHS)
6774 return false;
6775
6776 if (RHS->Value.countr_one() >= ShAmtBits)
6777 return true;
6778
6779 const APInt &LHSKnownZeros = VT->getKnownZeroes(MI.getOperand(1).getReg());
6780 return (LHSKnownZeros | RHS->Value).countr_one() >= ShAmtBits;
6781}
6782
6784AMDGPUInstructionSelector::selectMUBUFScratchOffset(
6785 MachineOperand &Root) const {
6786 Register Reg = Root.getReg();
6787 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
6788
6789 std::optional<DefinitionAndSourceRegister> Def =
6791 assert(Def && "this shouldn't be an optional result");
6792 Reg = Def->Reg;
6793
6794 if (Register WaveBase = getWaveAddress(Def->MI)) {
6795 return {{
6796 [=](MachineInstrBuilder &MIB) { // rsrc
6797 MIB.addReg(Info->getScratchRSrcReg());
6798 },
6799 [=](MachineInstrBuilder &MIB) { // soffset
6800 MIB.addReg(WaveBase);
6801 },
6802 [=](MachineInstrBuilder &MIB) { MIB.addImm(0); } // offset
6803 }};
6804 }
6805
6806 int64_t Offset = 0;
6807
6808 // FIXME: Copy check is a hack
6810 if (mi_match(Reg, *MRI,
6811 m_GPtrAdd(m_Reg(BasePtr),
6813 if (!TII.isLegalMUBUFImmOffset(Offset))
6814 return {};
6815 MachineInstr *BasePtrDef = getDefIgnoringCopies(BasePtr, *MRI);
6816 Register WaveBase = getWaveAddress(BasePtrDef);
6817 if (!WaveBase)
6818 return {};
6819
6820 return {{
6821 [=](MachineInstrBuilder &MIB) { // rsrc
6822 MIB.addReg(Info->getScratchRSrcReg());
6823 },
6824 [=](MachineInstrBuilder &MIB) { // soffset
6825 MIB.addReg(WaveBase);
6826 },
6827 [=](MachineInstrBuilder &MIB) { MIB.addImm(Offset); } // offset
6828 }};
6829 }
6830
6831 if (!mi_match(Root.getReg(), *MRI, m_ICst(Offset)) ||
6832 !TII.isLegalMUBUFImmOffset(Offset))
6833 return {};
6834
6835 return {{
6836 [=](MachineInstrBuilder &MIB) { // rsrc
6837 MIB.addReg(Info->getScratchRSrcReg());
6838 },
6839 [=](MachineInstrBuilder &MIB) { // soffset
6840 MIB.addImm(0);
6841 },
6842 [=](MachineInstrBuilder &MIB) { MIB.addImm(Offset); } // offset
6843 }};
6844}
6845
6846std::pair<Register, int64_t>
6847AMDGPUInstructionSelector::selectDS1Addr1OffsetImpl(
6848 MachineOperand &Root) const {
6849 int64_t ConstAddr = 0;
6850
6851 Register PtrBase;
6852 int64_t Offset;
6853 std::tie(PtrBase, Offset, std::ignore) =
6854 getPtrBaseWithConstantOffset(Root.getReg(), *MRI);
6855
6856 if (Offset) {
6857 if (isDSOffsetLegal(PtrBase, Offset)) {
6858 // (add n0, c0)
6859 return std::pair(PtrBase, Offset);
6860 }
6861 } else if (mi_match(Root.getReg(), *MRI, m_GSub(m_Reg(), m_Reg()))) {
6862 // TODO
6863
6864 } else if (mi_match(Root.getReg(), *MRI, m_ICst(ConstAddr))) {
6865 // TODO
6866 }
6867
6868 return std::pair(Root.getReg(), 0);
6869}
6870
6872AMDGPUInstructionSelector::selectDS1Addr1Offset(MachineOperand &Root) const {
6873 Register Reg;
6874 int64_t Offset;
6875 std::tie(Reg, Offset) = selectDS1Addr1OffsetImpl(Root);
6876 return {{
6877 [=](MachineInstrBuilder &MIB) { MIB.addReg(Reg); },
6878 [=](MachineInstrBuilder &MIB) { MIB.addImm(Offset); }
6879 }};
6880}
6881
6883AMDGPUInstructionSelector::selectDS64Bit4ByteAligned(MachineOperand &Root) const {
6884 return selectDSReadWrite2(Root, 4);
6885}
6886
6888AMDGPUInstructionSelector::selectDS128Bit8ByteAligned(MachineOperand &Root) const {
6889 return selectDSReadWrite2(Root, 8);
6890}
6891
6893AMDGPUInstructionSelector::selectDSReadWrite2(MachineOperand &Root,
6894 unsigned Size) const {
6895 Register Reg;
6896 int64_t Offset;
6897 std::tie(Reg, Offset) = selectDSReadWrite2Impl(Root, Size);
6898 return {{
6899 [=](MachineInstrBuilder &MIB) { MIB.addReg(Reg); },
6900 [=](MachineInstrBuilder &MIB) { MIB.addImm(Offset); },
6901 [=](MachineInstrBuilder &MIB) { MIB.addImm(Offset+1); }
6902 }};
6903}
6904
6905std::pair<Register, int64_t>
6906AMDGPUInstructionSelector::selectDSReadWrite2Impl(MachineOperand &Root,
6907 unsigned Size) const {
6908 int64_t ConstAddr = 0;
6909
6910 Register PtrBase;
6911 int64_t Offset;
6912 std::tie(PtrBase, Offset, std::ignore) =
6913 getPtrBaseWithConstantOffset(Root.getReg(), *MRI);
6914
6915 if (Offset) {
6916 int64_t OffsetValue0 = Offset;
6917 int64_t OffsetValue1 = Offset + Size;
6918 if (isDSOffset2Legal(PtrBase, OffsetValue0, OffsetValue1, Size)) {
6919 // (add n0, c0)
6920 return std::pair(PtrBase, OffsetValue0 / Size);
6921 }
6922 } else if (mi_match(Root.getReg(), *MRI, m_GSub(m_Reg(), m_Reg()))) {
6923 // TODO
6924
6925 } else if (mi_match(Root.getReg(), *MRI, m_ICst(ConstAddr))) {
6926 // TODO
6927 }
6928
6929 return std::pair(Root.getReg(), 0);
6930}
6931
6932/// If \p Root is a G_PTR_ADD with a G_CONSTANT on the right hand side, return
6933/// the base value with the constant offset, and if the offset computation is
6934/// known to be inbounds. There may be intervening copies between \p Root and
6935/// the identified constant. Returns \p Root, 0, false if this does not match
6936/// the pattern.
6937std::tuple<Register, int64_t, bool>
6938AMDGPUInstructionSelector::getPtrBaseWithConstantOffset(
6939 Register Root, const MachineRegisterInfo &MRI) const {
6940 MachineInstr *RootI = getDefIgnoringCopies(Root, MRI);
6941 if (RootI->getOpcode() != TargetOpcode::G_PTR_ADD)
6942 return {Root, 0, false};
6943
6944 MachineOperand &RHS = RootI->getOperand(2);
6945 std::optional<ValueAndVReg> MaybeOffset =
6947 if (!MaybeOffset)
6948 return {Root, 0, false};
6949 bool IsInBounds = RootI->getFlag(MachineInstr::MIFlag::InBounds);
6950 return {RootI->getOperand(1).getReg(), MaybeOffset->Value.getSExtValue(),
6951 IsInBounds};
6952}
6953
6955 MIB.addImm(0);
6956}
6957
6958/// Return a resource descriptor for use with an arbitrary 64-bit pointer. If \p
6959/// BasePtr is not valid, a null base pointer will be used.
6961 uint32_t FormatLo, uint32_t FormatHi,
6962 Register BasePtr) {
6963 Register RSrc2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6964 Register RSrc3 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
6965 Register RSrcHi = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
6966 Register RSrc = MRI.createVirtualRegister(&AMDGPU::SGPR_128RegClass);
6967
6968 B.buildInstr(AMDGPU::S_MOV_B32)
6969 .addDef(RSrc2)
6970 .addImm(FormatLo);
6971 B.buildInstr(AMDGPU::S_MOV_B32)
6972 .addDef(RSrc3)
6973 .addImm(FormatHi);
6974
6975 // Build the half of the subregister with the constants before building the
6976 // full 128-bit register. If we are building multiple resource descriptors,
6977 // this will allow CSEing of the 2-component register.
6978 B.buildInstr(AMDGPU::REG_SEQUENCE)
6979 .addDef(RSrcHi)
6980 .addReg(RSrc2)
6981 .addImm(AMDGPU::sub0)
6982 .addReg(RSrc3)
6983 .addImm(AMDGPU::sub1);
6984
6985 Register RSrcLo = BasePtr;
6986 if (!BasePtr) {
6987 RSrcLo = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
6988 B.buildInstr(AMDGPU::S_MOV_B64)
6989 .addDef(RSrcLo)
6990 .addImm(0);
6991 }
6992
6993 B.buildInstr(AMDGPU::REG_SEQUENCE)
6994 .addDef(RSrc)
6995 .addReg(RSrcLo)
6996 .addImm(AMDGPU::sub0_sub1)
6997 .addReg(RSrcHi)
6998 .addImm(AMDGPU::sub2_sub3);
6999
7000 return RSrc;
7001}
7002
7004 const SIInstrInfo &TII, Register BasePtr) {
7005 uint64_t DefaultFormat = TII.getDefaultRsrcDataFormat();
7006
7007 // FIXME: Why are half the "default" bits ignored based on the addressing
7008 // mode?
7009 return buildRSRC(B, MRI, 0, Hi_32(DefaultFormat), BasePtr);
7010}
7011
7013 const SIInstrInfo &TII, Register BasePtr) {
7014 uint64_t DefaultFormat = TII.getDefaultRsrcDataFormat();
7015
7016 // FIXME: Why are half the "default" bits ignored based on the addressing
7017 // mode?
7018 return buildRSRC(B, MRI, -1, Hi_32(DefaultFormat), BasePtr);
7019}
7020
7021AMDGPUInstructionSelector::MUBUFAddressData
7022AMDGPUInstructionSelector::parseMUBUFAddress(Register Src) const {
7023 MUBUFAddressData Data;
7024 Data.N0 = Src;
7025
7026 Register PtrBase;
7027 int64_t Offset;
7028
7029 std::tie(PtrBase, Offset, std::ignore) =
7030 getPtrBaseWithConstantOffset(Src, *MRI);
7031 if (isUInt<32>(Offset)) {
7032 Data.N0 = PtrBase;
7033 Data.Offset = Offset;
7034 }
7035
7036 if (MachineInstr *InputAdd
7037 = getOpcodeDef(TargetOpcode::G_PTR_ADD, Data.N0, *MRI)) {
7038 Data.N2 = InputAdd->getOperand(1).getReg();
7039 Data.N3 = InputAdd->getOperand(2).getReg();
7040
7041 // FIXME: Need to fix extra SGPR->VGPRcopies inserted
7042 // FIXME: Don't know this was defined by operand 0
7043 //
7044 // TODO: Remove this when we have copy folding optimizations after
7045 // RegBankSelect.
7046 Data.N2 = getDefIgnoringCopies(Data.N2, *MRI)->getOperand(0).getReg();
7047 Data.N3 = getDefIgnoringCopies(Data.N3, *MRI)->getOperand(0).getReg();
7048 }
7049
7050 return Data;
7051}
7052
7053/// Return if the addr64 mubuf mode should be used for the given address.
7054bool AMDGPUInstructionSelector::shouldUseAddr64(MUBUFAddressData Addr) const {
7055 // (ptr_add N2, N3) -> addr64, or
7056 // (ptr_add (ptr_add N2, N3), C1) -> addr64
7057 if (Addr.N2)
7058 return true;
7059
7060 const RegisterBank *N0Bank = RBI.getRegBank(Addr.N0, *MRI, TRI);
7061 return N0Bank->getID() == AMDGPU::VGPRRegBankID;
7062}
7063
7064/// Split an immediate offset \p ImmOffset depending on whether it fits in the
7065/// immediate field. Modifies \p ImmOffset and sets \p SOffset to the variable
7066/// component.
7067void AMDGPUInstructionSelector::splitIllegalMUBUFOffset(
7068 MachineIRBuilder &B, Register &SOffset, int64_t &ImmOffset) const {
7069 if (TII.isLegalMUBUFImmOffset(ImmOffset))
7070 return;
7071
7072 // Illegal offset, store it in soffset.
7073 SOffset = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
7074 B.buildInstr(AMDGPU::S_MOV_B32)
7075 .addDef(SOffset)
7076 .addImm(ImmOffset);
7077 ImmOffset = 0;
7078}
7079
7080bool AMDGPUInstructionSelector::selectMUBUFAddr64Impl(
7081 MachineOperand &Root, Register &VAddr, Register &RSrcReg,
7082 Register &SOffset, int64_t &Offset) const {
7083 // FIXME: Predicates should stop this from reaching here.
7084 // addr64 bit was removed for volcanic islands.
7085 if (!STI.hasAddr64() || STI.useFlatForGlobal())
7086 return false;
7087
7088 MUBUFAddressData AddrData = parseMUBUFAddress(Root.getReg());
7089 if (!shouldUseAddr64(AddrData))
7090 return false;
7091
7092 Register N0 = AddrData.N0;
7093 Register N2 = AddrData.N2;
7094 Register N3 = AddrData.N3;
7095 Offset = AddrData.Offset;
7096
7097 // Base pointer for the SRD.
7098 Register SRDPtr;
7099
7100 if (N2) {
7101 if (RBI.getRegBank(N2, *MRI, TRI)->getID() == AMDGPU::VGPRRegBankID) {
7102 assert(N3);
7103 if (RBI.getRegBank(N3, *MRI, TRI)->getID() == AMDGPU::VGPRRegBankID) {
7104 // Both N2 and N3 are divergent. Use N0 (the result of the add) as the
7105 // addr64, and construct the default resource from a 0 address.
7106 VAddr = N0;
7107 } else {
7108 SRDPtr = N3;
7109 VAddr = N2;
7110 }
7111 } else {
7112 // N2 is not divergent.
7113 SRDPtr = N2;
7114 VAddr = N3;
7115 }
7116 } else if (RBI.getRegBank(N0, *MRI, TRI)->getID() == AMDGPU::VGPRRegBankID) {
7117 // Use the default null pointer in the resource
7118 VAddr = N0;
7119 } else {
7120 // N0 -> offset, or
7121 // (N0 + C1) -> offset
7122 SRDPtr = N0;
7123 }
7124
7125 MachineIRBuilder B(*Root.getParent());
7126 RSrcReg = buildAddr64RSrc(B, *MRI, TII, SRDPtr);
7127 splitIllegalMUBUFOffset(B, SOffset, Offset);
7128 return true;
7129}
7130
7131bool AMDGPUInstructionSelector::selectMUBUFOffsetImpl(
7132 MachineOperand &Root, Register &RSrcReg, Register &SOffset,
7133 int64_t &Offset) const {
7134
7135 // FIXME: Pattern should not reach here.
7136 if (STI.useFlatForGlobal())
7137 return false;
7138
7139 MUBUFAddressData AddrData = parseMUBUFAddress(Root.getReg());
7140 if (shouldUseAddr64(AddrData))
7141 return false;
7142
7143 // N0 -> offset, or
7144 // (N0 + C1) -> offset
7145 Register SRDPtr = AddrData.N0;
7146 Offset = AddrData.Offset;
7147
7148 // TODO: Look through extensions for 32-bit soffset.
7149 MachineIRBuilder B(*Root.getParent());
7150
7151 RSrcReg = buildOffsetSrc(B, *MRI, TII, SRDPtr);
7152 splitIllegalMUBUFOffset(B, SOffset, Offset);
7153 return true;
7154}
7155
7157AMDGPUInstructionSelector::selectMUBUFAddr64(MachineOperand &Root) const {
7158 Register VAddr;
7159 Register RSrcReg;
7160 Register SOffset;
7161 int64_t Offset = 0;
7162
7163 if (!selectMUBUFAddr64Impl(Root, VAddr, RSrcReg, SOffset, Offset))
7164 return {};
7165
7166 // FIXME: Use defaulted operands for trailing 0s and remove from the complex
7167 // pattern.
7168 return {{
7169 [=](MachineInstrBuilder &MIB) { // rsrc
7170 MIB.addReg(RSrcReg);
7171 },
7172 [=](MachineInstrBuilder &MIB) { // vaddr
7173 MIB.addReg(VAddr);
7174 },
7175 [=](MachineInstrBuilder &MIB) { // soffset
7176 if (SOffset)
7177 MIB.addReg(SOffset);
7178 else if (STI.hasRestrictedSOffset())
7179 MIB.addReg(AMDGPU::SGPR_NULL);
7180 else
7181 MIB.addImm(0);
7182 },
7183 [=](MachineInstrBuilder &MIB) { // offset
7184 MIB.addImm(Offset);
7185 },
7186 addZeroImm, // cpol
7187 addZeroImm, // tfe
7188 addZeroImm // swz
7189 }};
7190}
7191
7193AMDGPUInstructionSelector::selectMUBUFOffset(MachineOperand &Root) const {
7194 Register RSrcReg;
7195 Register SOffset;
7196 int64_t Offset = 0;
7197
7198 if (!selectMUBUFOffsetImpl(Root, RSrcReg, SOffset, Offset))
7199 return {};
7200
7201 return {{
7202 [=](MachineInstrBuilder &MIB) { // rsrc
7203 MIB.addReg(RSrcReg);
7204 },
7205 [=](MachineInstrBuilder &MIB) { // soffset
7206 if (SOffset)
7207 MIB.addReg(SOffset);
7208 else if (STI.hasRestrictedSOffset())
7209 MIB.addReg(AMDGPU::SGPR_NULL);
7210 else
7211 MIB.addImm(0);
7212 },
7213 [=](MachineInstrBuilder &MIB) { MIB.addImm(Offset); }, // offset
7214 addZeroImm, // cpol
7215 addZeroImm, // tfe
7216 addZeroImm, // swz
7217 }};
7218}
7219
7221AMDGPUInstructionSelector::selectBUFSOffset(MachineOperand &Root) const {
7222
7223 Register SOffset = Root.getReg();
7224
7225 if (STI.hasRestrictedSOffset() && mi_match(SOffset, *MRI, m_ZeroInt()))
7226 SOffset = AMDGPU::SGPR_NULL;
7227
7228 return {{[=](MachineInstrBuilder &MIB) { MIB.addReg(SOffset); }}};
7229}
7230
7231/// Get an immediate that must be 32-bits, and treated as zero extended.
7232static std::optional<uint64_t>
7234 // getIConstantVRegVal sexts any values, so see if that matters.
7235 std::optional<int64_t> OffsetVal = getIConstantVRegSExtVal(Reg, MRI);
7236 if (!OffsetVal || !isInt<32>(*OffsetVal))
7237 return std::nullopt;
7238 return Lo_32(*OffsetVal);
7239}
7240
7242AMDGPUInstructionSelector::selectSMRDBufferImm(MachineOperand &Root) const {
7243 std::optional<uint64_t> OffsetVal =
7244 Root.isImm() ? Root.getImm() : getConstantZext32Val(Root.getReg(), *MRI);
7245 if (!OffsetVal)
7246 return {};
7247
7248 std::optional<int64_t> EncodedImm =
7249 AMDGPU::getSMRDEncodedOffset(STI, *OffsetVal, true);
7250 if (!EncodedImm)
7251 return {};
7252
7253 return {{ [=](MachineInstrBuilder &MIB) { MIB.addImm(*EncodedImm); } }};
7254}
7255
7257AMDGPUInstructionSelector::selectSMRDBufferImm32(MachineOperand &Root) const {
7258 assert(STI.getGeneration() == AMDGPUSubtarget::SEA_ISLANDS);
7259
7260 std::optional<uint64_t> OffsetVal = getConstantZext32Val(Root.getReg(), *MRI);
7261 if (!OffsetVal)
7262 return {};
7263
7264 std::optional<int64_t> EncodedImm =
7266 if (!EncodedImm)
7267 return {};
7268
7269 return {{ [=](MachineInstrBuilder &MIB) { MIB.addImm(*EncodedImm); } }};
7270}
7271
7273AMDGPUInstructionSelector::selectSMRDBufferSgprImm(MachineOperand &Root) const {
7274 // Match the (soffset + offset) pair as a 32-bit register base and
7275 // an immediate offset.
7276 Register SOffset;
7277 unsigned Offset;
7278 std::tie(SOffset, Offset) = AMDGPU::getBaseWithConstantOffset(
7279 *MRI, Root.getReg(), VT, /*CheckNUW*/ true);
7280 if (!SOffset)
7281 return std::nullopt;
7282
7283 std::optional<int64_t> EncodedOffset =
7284 AMDGPU::getSMRDEncodedOffset(STI, Offset, /* IsBuffer */ true);
7285 if (!EncodedOffset)
7286 return std::nullopt;
7287
7288 assert(MRI->getType(SOffset).getSizeInBits() == 32);
7289 return {{[=](MachineInstrBuilder &MIB) { MIB.addReg(SOffset); },
7290 [=](MachineInstrBuilder &MIB) { MIB.addImm(*EncodedOffset); }}};
7291}
7292
7293std::pair<Register, unsigned>
7294AMDGPUInstructionSelector::selectVOP3PMadMixModsImpl(MachineOperand &Root,
7295 bool &Matched) const {
7296 Matched = false;
7297
7298 Register Src;
7299 unsigned Mods;
7300 std::tie(Src, Mods) = selectVOP3ModsImpl(Root.getReg());
7301
7302 if (mi_match(Src, *MRI, m_GFPExt(m_Reg(Src)))) {
7303 assert(MRI->getType(Src) == LLT::scalar(16));
7304
7305 // Only change Src if src modifier could be gained. In such cases new Src
7306 // could be sgpr but this does not violate constant bus restriction for
7307 // instruction that is being selected.
7308 Src = stripBitCast(Src, *MRI);
7309
7310 const auto CheckAbsNeg = [&]() {
7311 // Be careful about folding modifiers if we already have an abs. fneg is
7312 // applied last, so we don't want to apply an earlier fneg.
7313 if ((Mods & SISrcMods::ABS) == 0) {
7314 unsigned ModsTmp;
7315 std::tie(Src, ModsTmp) = selectVOP3ModsImpl(Src);
7316
7317 if ((ModsTmp & SISrcMods::NEG) != 0)
7318 Mods ^= SISrcMods::NEG;
7319
7320 if ((ModsTmp & SISrcMods::ABS) != 0)
7321 Mods |= SISrcMods::ABS;
7322 }
7323 };
7324
7325 CheckAbsNeg();
7326
7327 // op_sel/op_sel_hi decide the source type and source.
7328 // If the source's op_sel_hi is set, it indicates to do a conversion from
7329 // fp16. If the sources's op_sel is set, it picks the high half of the
7330 // source register.
7331
7332 Mods |= SISrcMods::OP_SEL_1;
7333
7334 // The instruction reads a 32-bit source and selects a half of it, so look
7335 // for the 32-bit register the 16-bit value is a half of.
7336 if (isExtractHiElt(*MRI, Src, Src)) {
7337 // Src is now the 32-bit source and op_sel picks its high half.
7338 Mods |= SISrcMods::OP_SEL_0;
7339 CheckAbsNeg();
7340 } else if (isExtractLoElt(*MRI, Src, Src)) {
7341 // op_sel already picks the low half, so the 32-bit source can be used
7342 // directly. Unlike the high half, only an fneg/fabs that acts on each
7343 // 16-bit element can be folded here: one that acts on the 32-bit value
7344 // touches bit 31 and leaves the low half alone.
7345 if (MRI->getType(Src).isFixedVector(2, 16))
7346 CheckAbsNeg();
7347 }
7348 // Otherwise Src is genuinely 16 bits wide and widenSrcIfVGPR16 widens it
7349 // when the operand is rendered.
7350
7351 Matched = true;
7352 }
7353
7354 return {Src, Mods};
7355}
7356
7358AMDGPUInstructionSelector::selectVOP3PMadMixModsExt(
7359 MachineOperand &Root) const {
7360 Register Src;
7361 unsigned Mods;
7362 bool Matched;
7363 std::tie(Src, Mods) = selectVOP3PMadMixModsImpl(Root, Matched);
7364 if (!Matched)
7365 return {};
7366
7367 return {{
7368 [=](MachineInstrBuilder &MIB) { MIB.addReg(widenSrcIfVGPR16(Src, MIB)); },
7369 [=](MachineInstrBuilder &MIB) { MIB.addImm(Mods); } // src_mods
7370 }};
7371}
7372
7374AMDGPUInstructionSelector::selectVOP3PMadMixMods(MachineOperand &Root) const {
7375 Register Src;
7376 unsigned Mods;
7377 bool Matched;
7378 std::tie(Src, Mods) = selectVOP3PMadMixModsImpl(Root, Matched);
7379
7380 return {{
7381 [=](MachineInstrBuilder &MIB) { MIB.addReg(widenSrcIfVGPR16(Src, MIB)); },
7382 [=](MachineInstrBuilder &MIB) { MIB.addImm(Mods); } // src_mods
7383 }};
7384}
7385
7387AMDGPUInstructionSelector::selectVOP3PMadMixModsExtNeg(
7388 MachineOperand &Root) const {
7389 Register Src;
7390 unsigned Mods;
7391 bool Matched;
7392 std::tie(Src, Mods) = selectVOP3PMadMixModsImpl(Root, Matched);
7393 if (!Matched)
7394 return {};
7395
7396 return {{
7397 [=](MachineInstrBuilder &MIB) { MIB.addReg(widenSrcIfVGPR16(Src, MIB)); },
7398 [=](MachineInstrBuilder &MIB) {
7399 MIB.addImm(Mods ^ SISrcMods::NEG);
7400 } // src_mods
7401 }};
7402}
7403
7405AMDGPUInstructionSelector::selectVOP3PMadMixModsNeg(
7406 MachineOperand &Root) const {
7407 Register Src;
7408 unsigned Mods;
7409 bool Matched;
7410 std::tie(Src, Mods) = selectVOP3PMadMixModsImpl(Root, Matched);
7411
7412 return {{
7413 [=](MachineInstrBuilder &MIB) { MIB.addReg(widenSrcIfVGPR16(Src, MIB)); },
7414 [=](MachineInstrBuilder &MIB) {
7415 MIB.addImm(Mods ^ SISrcMods::NEG);
7416 } // src_mods
7417 }};
7418}
7419
7420bool AMDGPUInstructionSelector::selectSBarrierSignalIsfirst(
7421 MachineInstr &I, Intrinsic::ID IntrID) const {
7422 MachineBasicBlock *MBB = I.getParent();
7423 const DebugLoc &DL = I.getDebugLoc();
7424 Register CCReg = I.getOperand(0).getReg();
7425
7426 // Set SCC to true, in case the barrier instruction gets converted to a NOP.
7427 BuildMI(*MBB, &I, DL, TII.get(AMDGPU::S_CMP_EQ_U32)).addImm(0).addImm(0);
7428
7429 BuildMI(*MBB, &I, DL, TII.get(AMDGPU::S_BARRIER_SIGNAL_ISFIRST_IMM))
7430 .addImm(I.getOperand(2).getImm());
7431
7432 BuildMI(*MBB, &I, DL, TII.get(AMDGPU::COPY), CCReg).addReg(AMDGPU::SCC);
7433
7434 I.eraseFromParent();
7435 return RBI.constrainGenericRegister(CCReg, AMDGPU::SReg_32_XM0_XEXECRegClass,
7436 *MRI);
7437}
7438
7439bool AMDGPUInstructionSelector::selectSGetBarrierState(
7440 MachineInstr &I, Intrinsic::ID IntrID) const {
7441 MachineBasicBlock *MBB = I.getParent();
7442 const DebugLoc &DL = I.getDebugLoc();
7443 const MachineOperand &BarOp = I.getOperand(2);
7444 std::optional<int64_t> BarValImm =
7445 getIConstantVRegSExtVal(BarOp.getReg(), *MRI);
7446
7447 if (!BarValImm) {
7448 auto CopyMIB = BuildMI(*MBB, &I, DL, TII.get(AMDGPU::COPY), AMDGPU::M0)
7449 .addReg(BarOp.getReg());
7450 constrainSelectedInstRegOperands(*CopyMIB, TII, TRI, RBI);
7451 }
7452 MachineInstrBuilder MIB;
7453 unsigned Opc = BarValImm ? AMDGPU::S_GET_BARRIER_STATE_IMM
7454 : AMDGPU::S_GET_BARRIER_STATE_M0;
7455 MIB = BuildMI(*MBB, &I, DL, TII.get(Opc));
7456
7457 auto DstReg = I.getOperand(0).getReg();
7458 const TargetRegisterClass *DstRC =
7459 TRI.getConstrainedRegClassForReg(DstReg, *MRI);
7460 if (!DstRC || !RBI.constrainGenericRegister(DstReg, *DstRC, *MRI))
7461 return false;
7462 MIB.addDef(DstReg);
7463 if (BarValImm) {
7464 MIB.addImm(*BarValImm);
7465 }
7466 I.eraseFromParent();
7467 return true;
7468}
7469
7470/// Return the barrier ID for \p BarOp if it's statically known, mapping poison
7471/// to 0 and masking off the high bits, since they're ignored as reserved.
7472static std::optional<uint32_t>
7474 const MachineRegisterInfo &MRI) {
7475 Register BarReg = BarOp.getReg();
7476 if (std::optional<int64_t> BarValImm = getIConstantVRegSExtVal(BarReg, MRI))
7477 return *BarValImm & 0x3F;
7478 if (getOpcodeDef(AMDGPU::G_IMPLICIT_DEF, BarReg, MRI))
7479 return 0;
7480 return std::nullopt;
7481}
7482
7483unsigned getNamedBarrierOp(bool HasInlineConst, Intrinsic::ID IntrID) {
7484 if (HasInlineConst) {
7485 switch (IntrID) {
7486 default:
7487 llvm_unreachable("not a named barrier op");
7488 case Intrinsic::amdgcn_s_barrier_join:
7489 return AMDGPU::S_BARRIER_JOIN_IMM;
7490 case Intrinsic::amdgcn_s_wakeup_barrier:
7491 return AMDGPU::S_WAKEUP_BARRIER_IMM;
7492 case Intrinsic::amdgcn_s_get_named_barrier_state:
7493 return AMDGPU::S_GET_BARRIER_STATE_IMM;
7494 };
7495 } else {
7496 switch (IntrID) {
7497 default:
7498 llvm_unreachable("not a named barrier op");
7499 case Intrinsic::amdgcn_s_barrier_join:
7500 return AMDGPU::S_BARRIER_JOIN_M0;
7501 case Intrinsic::amdgcn_s_wakeup_barrier:
7502 return AMDGPU::S_WAKEUP_BARRIER_M0;
7503 case Intrinsic::amdgcn_s_get_named_barrier_state:
7504 return AMDGPU::S_GET_BARRIER_STATE_M0;
7505 };
7506 }
7507}
7508
7509bool AMDGPUInstructionSelector::selectNamedBarrierInit(
7510 MachineInstr &I, Intrinsic::ID IntrID) const {
7511 MachineBasicBlock *MBB = I.getParent();
7512 const DebugLoc &DL = I.getDebugLoc();
7513 const MachineOperand &BarOp = I.getOperand(1);
7514 const MachineOperand &CntOp = I.getOperand(2);
7515
7516 // A member count of 0 means "keep existing member count". That plus a known
7517 // constant value for the barrier ID lets us use the immarg form.
7518 if (IntrID == Intrinsic::amdgcn_s_barrier_signal_var) {
7519 std::optional<int64_t> CntImm =
7520 getIConstantVRegSExtVal(CntOp.getReg(), *MRI);
7521 if (CntImm && *CntImm == 0) {
7522 if (auto BarID = getConstantNamedBarrierNumber(BarOp, *MRI)) {
7523 BuildMI(*MBB, &I, DL, TII.get(AMDGPU::S_BARRIER_SIGNAL_IMM))
7524 .addImm(*BarID);
7525 I.eraseFromParent();
7526 return true;
7527 }
7528 }
7529 }
7530
7531 // BarID = BarOp & 0x3F
7532 Register TmpReg1 = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
7533 BuildMI(*MBB, &I, DL, TII.get(AMDGPU::S_AND_B32), TmpReg1)
7534 .add(BarOp)
7535 .addImm(0x3F)
7536 .setOperandDead(3); // Dead scc
7537
7538 // MO = ((CntOp & CntMask) << shAmt) | BarID
7539 unsigned CntMask =
7541 Register TmpReg2 = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
7542 BuildMI(*MBB, &I, DL, TII.get(AMDGPU::S_AND_B32), TmpReg2)
7543 .add(CntOp)
7544 .addImm(CntMask)
7545 .setOperandDead(3); // Dead scc
7546
7547 Register TmpReg3 = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
7548 constexpr unsigned ShAmt = 16;
7549 BuildMI(*MBB, &I, DL, TII.get(AMDGPU::S_LSHL_B32), TmpReg3)
7550 .addReg(TmpReg2)
7551 .addImm(ShAmt)
7552 .setOperandDead(3); // Dead scc
7553
7554 Register TmpReg4 = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
7555 BuildMI(*MBB, &I, DL, TII.get(AMDGPU::S_OR_B32), TmpReg4)
7556 .addReg(TmpReg1)
7557 .addReg(TmpReg3)
7558 .setOperandDead(3); // Dead scc;
7559
7560 auto CopyMIB =
7561 BuildMI(*MBB, &I, DL, TII.get(AMDGPU::COPY), AMDGPU::M0).addReg(TmpReg4);
7562 constrainSelectedInstRegOperands(*CopyMIB, TII, TRI, RBI);
7563
7564 unsigned Opc = IntrID == Intrinsic::amdgcn_s_barrier_init
7565 ? AMDGPU::S_BARRIER_INIT_M0
7566 : AMDGPU::S_BARRIER_SIGNAL_M0;
7567 MachineInstrBuilder MIB;
7568 MIB = BuildMI(*MBB, &I, DL, TII.get(Opc));
7569
7570 I.eraseFromParent();
7571 return true;
7572}
7573
7574bool AMDGPUInstructionSelector::selectNamedBarrierInst(
7575 MachineInstr &I, Intrinsic::ID IntrID) const {
7576 MachineBasicBlock *MBB = I.getParent();
7577 const DebugLoc &DL = I.getDebugLoc();
7578 MachineOperand BarOp = IntrID == Intrinsic::amdgcn_s_get_named_barrier_state
7579 ? I.getOperand(2)
7580 : I.getOperand(1);
7581 std::optional<uint32_t> BarValImm =
7582 getConstantNamedBarrierNumber(BarOp, *MRI);
7583
7584 if (!BarValImm) {
7585 // BarID = BarOp & 0x3F
7586 Register TmpReg1 = MRI->createVirtualRegister(&AMDGPU::SReg_32RegClass);
7587 BuildMI(*MBB, &I, DL, TII.get(AMDGPU::S_AND_B32), TmpReg1)
7588 .addReg(BarOp.getReg())
7589 .addImm(0x3F)
7590 .setOperandDead(3); // Dead scc;
7591
7592 auto CopyMIB = BuildMI(*MBB, &I, DL, TII.get(AMDGPU::COPY), AMDGPU::M0)
7593 .addReg(TmpReg1);
7594 constrainSelectedInstRegOperands(*CopyMIB, TII, TRI, RBI);
7595 }
7596
7597 MachineInstrBuilder MIB;
7598 unsigned Opc = getNamedBarrierOp(BarValImm.has_value(), IntrID);
7599 MIB = BuildMI(*MBB, &I, DL, TII.get(Opc));
7600
7601 if (IntrID == Intrinsic::amdgcn_s_get_named_barrier_state) {
7602 auto DstReg = I.getOperand(0).getReg();
7603 const TargetRegisterClass *DstRC =
7604 TRI.getConstrainedRegClassForReg(DstReg, *MRI);
7605 if (!DstRC || !RBI.constrainGenericRegister(DstReg, *DstRC, *MRI))
7606 return false;
7607 MIB.addDef(DstReg);
7608 }
7609
7610 if (BarValImm)
7611 MIB.addImm(*BarValImm);
7612
7613 I.eraseFromParent();
7614 return true;
7615}
7616
7617void AMDGPUInstructionSelector::renderNegateImm(MachineInstrBuilder &MIB,
7618 const MachineInstr &MI,
7619 int OpIdx) const {
7620 assert(MI.getOpcode() == TargetOpcode::G_CONSTANT && OpIdx == -1 &&
7621 "Expected G_CONSTANT");
7622 MIB.addImm(-MI.getOperand(1).getCImm()->getSExtValue());
7623}
7624
7625void AMDGPUInstructionSelector::renderBitcastFPImm(MachineInstrBuilder &MIB,
7626 const MachineInstr &MI,
7627 int OpIdx) const {
7628 const MachineOperand &Op = MI.getOperand(1);
7629 assert(MI.getOpcode() == TargetOpcode::G_FCONSTANT && OpIdx == -1);
7630 MIB.addImm(Op.getFPImm()->getValueAPF().bitcastToAPInt().getZExtValue());
7631}
7632
7633void AMDGPUInstructionSelector::renderCountTrailingOnesImm(
7634 MachineInstrBuilder &MIB, const MachineInstr &MI, int OpIdx) const {
7635 assert(MI.getOpcode() == TargetOpcode::G_CONSTANT && OpIdx == -1 &&
7636 "Expected G_CONSTANT");
7637 MIB.addImm(MI.getOperand(1).getCImm()->getValue().countTrailingOnes());
7638}
7639
7640/// This only really exists to satisfy DAG type checking machinery, so is a
7641/// no-op here.
7642void AMDGPUInstructionSelector::renderTruncTImm(MachineInstrBuilder &MIB,
7643 const MachineInstr &MI,
7644 int OpIdx) const {
7645 const MachineOperand &Op = MI.getOperand(OpIdx);
7646 int64_t Imm;
7647 if (Op.isReg() && mi_match(Op.getReg(), *MRI, m_ICst(Imm)))
7648 MIB.addImm(Imm);
7649 else
7650 MIB.addImm(Op.getImm());
7651}
7652
7653void AMDGPUInstructionSelector::renderPrefetchLen(MachineInstrBuilder &MIB,
7654 const MachineInstr &MI,
7655 int OpIdx) const {
7656 Register Len = MI.getOperand(OpIdx).getReg();
7657 MIB.addImm(*getIConstantVRegSExtVal(Len, *MRI) & 0x1f);
7658}
7659
7660void AMDGPUInstructionSelector::renderZextBoolTImm(MachineInstrBuilder &MIB,
7661 const MachineInstr &MI,
7662 int OpIdx) const {
7663 MIB.addImm(MI.getOperand(OpIdx).getImm() != 0);
7664}
7665
7666void AMDGPUInstructionSelector::renderOpSelTImm(MachineInstrBuilder &MIB,
7667 const MachineInstr &MI,
7668 int OpIdx) const {
7669 assert(OpIdx >= 0 && "expected to match an immediate operand");
7670 MIB.addImm(MI.getOperand(OpIdx).getImm() ? (int64_t)SISrcMods::OP_SEL_0 : 0);
7671}
7672
7673void AMDGPUInstructionSelector::renderSrcAndDstSelToOpSelXForm_0_0(
7674 MachineInstrBuilder &MIB, const MachineInstr &MI, int OpIdx) const {
7675 assert(OpIdx >= 0 && "expected to match an immediate operand");
7676 MIB.addImm(
7677 (MI.getOperand(OpIdx).getImm() & 0x1) ? (int64_t)SISrcMods::OP_SEL_0 : 0);
7678}
7679
7680void AMDGPUInstructionSelector::renderSrcAndDstSelToOpSelXForm_0_1(
7681 MachineInstrBuilder &MIB, const MachineInstr &MI, int OpIdx) const {
7682 assert(OpIdx >= 0 && "expected to match an immediate operand");
7683 MIB.addImm((MI.getOperand(OpIdx).getImm() & 0x1)
7685 : (int64_t)SISrcMods::DST_OP_SEL);
7686}
7687
7688void AMDGPUInstructionSelector::renderSrcAndDstSelToOpSelXForm_1_0(
7689 MachineInstrBuilder &MIB, const MachineInstr &MI, int OpIdx) const {
7690 assert(OpIdx >= 0 && "expected to match an immediate operand");
7691 MIB.addImm(
7692 (MI.getOperand(OpIdx).getImm() & 0x2) ? (int64_t)SISrcMods::OP_SEL_0 : 0);
7693}
7694
7695void AMDGPUInstructionSelector::renderSrcAndDstSelToOpSelXForm_1_1(
7696 MachineInstrBuilder &MIB, const MachineInstr &MI, int OpIdx) const {
7697 assert(OpIdx >= 0 && "expected to match an immediate operand");
7698 MIB.addImm((MI.getOperand(OpIdx).getImm() & 0x2)
7699 ? (int64_t)(SISrcMods::OP_SEL_0)
7700 : 0);
7701}
7702
7703void AMDGPUInstructionSelector::renderDstSelToOpSelXForm(
7704 MachineInstrBuilder &MIB, const MachineInstr &MI, int OpIdx) const {
7705 assert(OpIdx >= 0 && "expected to match an immediate operand");
7706 MIB.addImm(MI.getOperand(OpIdx).getImm() ? (int64_t)(SISrcMods::DST_OP_SEL)
7707 : 0);
7708}
7709
7710void AMDGPUInstructionSelector::renderSrcSelToOpSelXForm(
7711 MachineInstrBuilder &MIB, const MachineInstr &MI, int OpIdx) const {
7712 assert(OpIdx >= 0 && "expected to match an immediate operand");
7713 MIB.addImm(MI.getOperand(OpIdx).getImm() ? (int64_t)(SISrcMods::OP_SEL_0)
7714 : 0);
7715}
7716
7717void AMDGPUInstructionSelector::renderSrcAndDstSelToOpSelXForm_2_0(
7718 MachineInstrBuilder &MIB, const MachineInstr &MI, int OpIdx) const {
7719 assert(OpIdx >= 0 && "expected to match an immediate operand");
7720 MIB.addImm(
7721 (MI.getOperand(OpIdx).getImm() & 0x1) ? (int64_t)SISrcMods::OP_SEL_0 : 0);
7722}
7723
7724void AMDGPUInstructionSelector::renderDstSelToOpSel3XFormXForm(
7725 MachineInstrBuilder &MIB, const MachineInstr &MI, int OpIdx) const {
7726 assert(OpIdx >= 0 && "expected to match an immediate operand");
7727 MIB.addImm((MI.getOperand(OpIdx).getImm() & 0x2)
7728 ? (int64_t)SISrcMods::DST_OP_SEL
7729 : 0);
7730}
7731
7732void AMDGPUInstructionSelector::renderExtractCPol(MachineInstrBuilder &MIB,
7733 const MachineInstr &MI,
7734 int OpIdx) const {
7735 assert(OpIdx >= 0 && "expected to match an immediate operand");
7736 MIB.addImm(MI.getOperand(OpIdx).getImm() &
7739}
7740
7741void AMDGPUInstructionSelector::renderExtractSWZ(MachineInstrBuilder &MIB,
7742 const MachineInstr &MI,
7743 int OpIdx) const {
7744 assert(OpIdx >= 0 && "expected to match an immediate operand");
7745 const bool Swizzle = MI.getOperand(OpIdx).getImm() &
7748 MIB.addImm(Swizzle);
7749}
7750
7751void AMDGPUInstructionSelector::renderExtractCpolSetGLC(
7752 MachineInstrBuilder &MIB, const MachineInstr &MI, int OpIdx) const {
7753 assert(OpIdx >= 0 && "expected to match an immediate operand");
7754 const uint32_t Cpol = MI.getOperand(OpIdx).getImm() &
7757 MIB.addImm(Cpol | AMDGPU::CPol::GLC);
7758}
7759
7760void AMDGPUInstructionSelector::renderFPPow2ToExponent(MachineInstrBuilder &MIB,
7761 const MachineInstr &MI,
7762 int OpIdx) const {
7763 const APFloat &APF = MI.getOperand(1).getFPImm()->getValueAPF();
7764 int ExpVal = APF.getExactLog2Abs();
7765 assert(ExpVal != INT_MIN);
7766 MIB.addImm(ExpVal);
7767}
7768
7769void AMDGPUInstructionSelector::renderRoundMode(MachineInstrBuilder &MIB,
7770 const MachineInstr &MI,
7771 int OpIdx) const {
7772 // "round.towardzero" -> TowardZero 0 -> FP_ROUND_ROUND_TO_ZERO 3
7773 // "round.tonearest" -> NearestTiesToEven 1 -> FP_ROUND_ROUND_TO_NEAREST 0
7774 // "round.upward" -> TowardPositive 2 -> FP_ROUND_ROUND_TO_INF 1
7775 // "round.downward -> TowardNegative 3 -> FP_ROUND_ROUND_TO_NEGINF 2
7776 MIB.addImm((MI.getOperand(OpIdx).getImm() + 3) % 4);
7777}
7778
7779void AMDGPUInstructionSelector::renderVOP3PModsNeg(MachineInstrBuilder &MIB,
7780 const MachineInstr &MI,
7781 int OpIdx) const {
7782 unsigned Mods = SISrcMods::OP_SEL_1;
7783 if (MI.getOperand(OpIdx).getImm())
7784 Mods ^= SISrcMods::NEG;
7785 MIB.addImm((int64_t)Mods);
7786}
7787
7788void AMDGPUInstructionSelector::renderVOP3PModsNegs(MachineInstrBuilder &MIB,
7789 const MachineInstr &MI,
7790 int OpIdx) const {
7791 unsigned Mods = SISrcMods::OP_SEL_1;
7792 if (MI.getOperand(OpIdx).getImm())
7794 MIB.addImm((int64_t)Mods);
7795}
7796
7797void AMDGPUInstructionSelector::renderVOP3PModsNegAbs(MachineInstrBuilder &MIB,
7798 const MachineInstr &MI,
7799 int OpIdx) const {
7800 unsigned Val = static_cast<unsigned>(MI.getOperand(OpIdx).getImm());
7801 unsigned Mods = SISrcMods::OP_SEL_1; // default: none
7802 if (Val == 1) // neg
7803 Mods ^= SISrcMods::NEG;
7804 if (Val == 2) // abs
7805 Mods ^= SISrcMods::ABS;
7806 if (Val == 3) // neg and abs
7807 Mods ^= (SISrcMods::NEG | SISrcMods::ABS);
7808 MIB.addImm((int64_t)Mods);
7809}
7810
7811void AMDGPUInstructionSelector::renderPrefetchLoc(MachineInstrBuilder &MIB,
7812 const MachineInstr &MI,
7813 int OpIdx) const {
7814 uint32_t V = MI.getOperand(2).getImm() & AMDGPU::CPol::SCOPE_MASK;
7816 if (!Subtarget->hasSafeCUPrefetch())
7817 V = std::max(V, (uint32_t)AMDGPU::CPol::SCOPE_SE); // CU scope is unsafe
7818 MIB.addImm(V);
7819}
7820
7821/// Convert from 2-bit value to enum values used for op_sel* source modifiers.
7822void AMDGPUInstructionSelector::renderScaledMAIIntrinsicOperand(
7823 MachineInstrBuilder &MIB, const MachineInstr &MI, int OpIdx) const {
7824 int64_t Val = MI.getOperand(OpIdx).getImm();
7825 unsigned New = 0;
7826 if (Val & 0x1)
7828 if (Val & 0x2)
7830 MIB.addImm(New);
7831}
7832
7833bool AMDGPUInstructionSelector::isInlineImmediate(const APInt &Imm) const {
7834 return TII.isInlineConstant(Imm);
7835}
7836
7837bool AMDGPUInstructionSelector::isInlineImmediate(const APFloat &Imm) const {
7838 return TII.isInlineConstant(Imm);
7839}
MachineInstrBuilder MachineInstrBuilder & DefMI
static unsigned getIntrinsicID(const SDNode *N)
SDValue Pred
#define GET_GLOBALISEL_PREDICATES_INIT
#define GET_GLOBALISEL_TEMPORARIES_INIT
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo MachineBasicBlock::iterator InsertPt
const AArch64InstrInfo & TII
uint64_t uint64_t
uint64_t Imm
Contains the definition of a TargetInstrInfo class that is common to all AMD GPUs.
static bool isShlHalf(const MachineInstr *MI, const MachineRegisterInfo &MRI)
Test if the MI is shift left with half bits, such as reg0:2n =G_SHL reg1:2n, CONST(n)
static bool isNoUnsignedWrap(MachineInstr *Addr)
static Register buildOffsetSrc(MachineIRBuilder &B, MachineRegisterInfo &MRI, const SIInstrInfo &TII, Register BasePtr)
unsigned getNamedBarrierOp(bool HasInlineConst, Intrinsic::ID IntrID)
static Register getLegalRegBank(Register NewReg, Register RootReg, MachineInstr &Use, const AMDGPURegisterBankInfo &RBI, MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI, const SIInstrInfo &TII)
static bool checkRB(Register Reg, unsigned int RBNo, const AMDGPURegisterBankInfo &RBI, const MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI)
static unsigned updateMods(SrcStatus HiStat, SrcStatus LoStat, unsigned Mods)
static bool isTruncHalf(const MachineInstr *MI, const MachineRegisterInfo &MRI)
Test if the MI is truncating to half, such as reg0:n = G_TRUNC reg1:2n
static Register getWaveAddress(const MachineInstr *Def)
static int getV_CMPOpcode(CmpInst::Predicate P, uint64_t Size, const GCNSubtarget &ST)
static bool isExtractHiElt(MachineRegisterInfo &MRI, Register In, Register &Out)
static std::pair< unsigned, uint8_t > BitOp3_Op(Register R, SmallVectorImpl< Register > &Src, const MachineRegisterInfo &MRI)
static TypeClass isVectorOfTwoOrScalar(Register Reg, const MachineRegisterInfo &MRI)
static bool isLaneMaskFromSameBlock(Register Reg, MachineRegisterInfo &MRI, MachineBasicBlock *MBB)
static bool isExtractLoElt(MachineRegisterInfo &MRI, Register In, Register &Out)
static bool parseTexFail(uint64_t TexFailCtrl, bool &TFE, bool &LWE, bool &IsTexFail)
static void addZeroImm(MachineInstrBuilder &MIB)
static unsigned gwsIntrinToOpcode(unsigned IntrID)
static bool isConstant(const MachineInstr &MI)
static bool isSameBitWidth(Register Reg1, Register Reg2, const MachineRegisterInfo &MRI)
static Register buildRegSequence(SmallVectorImpl< Register > &Elts, MachineInstr *InsertPt, MachineRegisterInfo &MRI)
static Register buildRSRC(MachineIRBuilder &B, MachineRegisterInfo &MRI, uint32_t FormatLo, uint32_t FormatHi, Register BasePtr)
Return a resource descriptor for use with an arbitrary 64-bit pointer.
static bool isAsyncLDSDMA(Intrinsic::ID Intr)
static std::optional< uint32_t > getConstantNamedBarrierNumber(const MachineOperand &BarOp, const MachineRegisterInfo &MRI)
Return the barrier ID for BarOp if it's statically known, mapping poison to 0 and masking off the hig...
static std::pair< Register, unsigned > computeIndirectRegIndex(MachineRegisterInfo &MRI, const SIRegisterInfo &TRI, const TargetRegisterClass *SuperRC, Register IdxReg, unsigned EltSize, GISelValueTracking &ValueTracking)
Return the register to use for the index value, and the subregister to use for the indirectly accesse...
static bool shouldUseAndMask(uint64_t Size, unsigned &Mask)
static unsigned getLogicalBitOpcode(unsigned Opc, bool Is64)
static std::pair< Register, SrcStatus > getLastSameOrNeg(Register Reg, const MachineRegisterInfo &MRI, SearchOptions SO, int MaxDepth=3)
static Register stripCopy(Register Reg, MachineRegisterInfo &MRI)
static std::optional< std::pair< Register, SrcStatus > > calcNextStatus(std::pair< Register, SrcStatus > Curr, const MachineRegisterInfo &MRI)
static Register stripBitCast(Register Reg, MachineRegisterInfo &MRI)
static std::optional< uint64_t > getConstantZext32Val(Register Reg, const MachineRegisterInfo &MRI)
Get an immediate that must be 32-bits, and treated as zero extended.
static bool isValidToPack(SrcStatus HiStat, SrcStatus LoStat, Register NewReg, Register RootReg, const SIInstrInfo &TII, const MachineRegisterInfo &MRI)
static SmallVector< std::pair< Register, SrcStatus > > getSrcStats(Register Reg, const MachineRegisterInfo &MRI, SearchOptions SO, int MaxDepth=3)
static bool isUnmergeHalf(const MachineInstr *MI, const MachineRegisterInfo &MRI)
Test function, if the MI is reg0:n, reg1:n = G_UNMERGE_VALUES reg2:2n
static SrcStatus getNegStatus(Register Reg, SrcStatus S, const MachineRegisterInfo &MRI)
static bool isVCmpResult(Register Reg, MachineRegisterInfo &MRI)
static Register buildAddr64RSrc(MachineIRBuilder &B, MachineRegisterInfo &MRI, const SIInstrInfo &TII, Register BasePtr)
static bool isLshrHalf(const MachineInstr *MI, const MachineRegisterInfo &MRI)
Test if the MI is logic shift right with half bits, such as reg0:2n =G_LSHR reg1:2n,...
static void selectWMMAModsNegAbs(unsigned ModOpcode, unsigned &Mods, SmallVectorImpl< Register > &Elts, Register &Src, MachineInstr *InsertPt, MachineRegisterInfo &MRI)
This file declares the targeting of the InstructionSelector class for AMDGPU.
constexpr LLT S1
constexpr LLT S32
AMDGPU Register Bank Select
This file declares the targeting of the RegisterBankInfo class for AMDGPU.
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static bool isAllZeros(StringRef Arr)
Return true if the array is empty or all zeros.
dxil translate DXIL Translate Metadata
Provides analysis for querying information about KnownBits during GISel passes.
#define DEBUG_TYPE
Declares convenience wrapper classes for interpreting MachineInstr instances as specific generic oper...
IRTranslator LLVM IR MI
unsigned Opc
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Contains matchers for matching SSA Machine Instructions.
This file declares the MachineIRBuilder class.
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define P(N)
static std::vector< std::pair< int, unsigned > > Swizzle(std::vector< std::pair< int, unsigned > > Src, R600InstrInfo::BankSwizzle Swz)
MachineRegisterInfo & MRI
#define LLVM_DEBUG(...)
Definition Debug.h:119
Value * RHS
Value * LHS
This is used to control valid status that current MI supports.
bool checkOptions(SrcStatus Stat) const
SearchOptions(Register Reg, const MachineRegisterInfo &MRI)
AMDGPUInstructionSelector(const GCNSubtarget &STI, const AMDGPURegisterBankInfo &RBI)
static const char * getName()
bool select(MachineInstr &I) override
Select the (possibly generic) instruction I to only use target-specific opcodes.
void setupMF(MachineFunction &MF, GISelValueTracking *VT, CodeGenCoverage *CoverageInfo, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) override
Setup per-MF executor state.
LLVM_READONLY int getExactLog2Abs() const
Definition APFloat.h:1687
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:292
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1582
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:757
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:755
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:754
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:748
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:752
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:749
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:756
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:753
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:742
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition Constants.h:174
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
void checkSubtargetFeatures(const Function &F) const
Diagnose inconsistent subtarget features before attempting to codegen function F.
std::optional< SmallVector< std::function< void(MachineInstrBuilder &)>, 4 > > ComplexRendererFns
virtual void setupMF(MachineFunction &mf, GISelValueTracking *vt, CodeGenCoverage *covinfo=nullptr, ProfileSummaryInfo *psi=nullptr, BlockFrequencyInfo *bfi=nullptr)
Setup per-MF executor state.
Register getSourceReg(unsigned I) const
Returns the I'th source register.
unsigned getNumSources() const
Returns the number of source registers.
Represents a G_UNMERGE_VALUES.
unsigned getNumDefs() const
Returns the number of def registers.
Register getSourceReg() const
Get the unmerge source register.
constexpr unsigned getScalarSizeInBits() const
constexpr bool isScalar() const
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
constexpr bool isValid() const
constexpr uint16_t getNumElements() const
Returns the number of elements in a vector LLT.
constexpr bool isVector() const
constexpr TypeSize getSizeInBits() const
Returns the total size of the type. Must only be called on sized types.
constexpr unsigned getAddressSpace() const
static constexpr LLT fixed_vector(unsigned NumElements, unsigned ScalarSizeInBits)
Get a low-level fixed-width vector of some number of elements and element width.
constexpr bool isFixedVector() const
Returns true if the LLT is a fixed vector.
static LLT integer(unsigned SizeInBits)
LLT getElementType() const
Returns the vector's element type. Only valid for vector types.
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
bool hasValue() const
TypeSize getValue() const
int getOperandConstraint(unsigned OpNum, MCOI::OperandConstraint Constraint) const
Returns the value of the specified operand constraint if it is present.
bool hasSuperClassEq(const MCRegisterClass *RC) const
Returns true if RC is a super-class of or equal to this class.
unsigned getID() const
getID() - Return the register class ID number.
bool hasSubClassEq(const MCRegisterClass *RC) const
Returns true if RC is a sub-class of or equal to this class.
LLVM_ABI StringRef getString() const
Definition Metadata.cpp:613
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void setReturnAddressIsTaken(bool s)
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Helper class to build MachineInstr.
const MachineInstrBuilder & setMemRefs(ArrayRef< MachineMemOperand * > MMOs) const
const MachineInstrBuilder & setOperandDead(unsigned OpIdx) const
const MachineInstrBuilder & addUse(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addFrameIndex(int Idx) const
const MachineInstrBuilder & addGlobalAddress(const GlobalValue *GV, int64_t Offset=0, unsigned TargetFlags=0) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
const MachineInstrBuilder & cloneMemRefs(const MachineInstr &OtherMI) const
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
bool getFlag(MIFlag Flag) const
Return whether an MI flag is set.
unsigned getNumOperands() const
Retuns the total number of operands.
LLVM_ABI void tieOperands(unsigned DefIdx, unsigned UseIdx)
Add a tie between the register operands at DefIdx and UseIdx.
LLVM_ABI const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
const MachineOperand & getOperand(unsigned i) const
LocationSize getSize() const
Return the size in bytes of the memory reference.
unsigned getAddrSpace() const
@ MOLoad
The memory access reads data.
@ MOStore
The memory access writes data.
const MachinePointerInfo & getPointerInfo() const
Flags getFlags() const
Return the raw flags of the source value,.
const Value * getValue() const
Return the base address of the memory access.
Align getBaseAlign() const
Return the minimum known alignment in bytes of the base address, without the offset.
MachineOperand class - Representation of each machine instruction operand.
unsigned getSubReg() const
const ConstantInt * getCImm() const
void setImm(int64_t immVal)
int64_t getImm() 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.
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
static MachineOperand CreateImm(int64_t Val)
bool isEarlyClobber() const
Register getReg() const
getReg - Returns the register number.
bool isInternalRead() const
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:882
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Analysis providing profile information.
const RegisterBank & getRegBank(unsigned ID)
Get the register bank identified by ID.
This class implements the register bank concept.
unsigned getID() const
Get the identifier of this register bank.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
const SDValue & getOperand(unsigned i) const
static unsigned getMaxMUBUFImmOffset(const GCNSubtarget &ST)
static unsigned getDSShaderTypeValue(const MachineFunction &MF)
static unsigned getSubRegFromChannel(uint64_t Channel, uint64_t NumRegs=1)
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
static bool isGenericOpcode(unsigned Opc)
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:294
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI Value(Type *Ty, unsigned scid)
Definition Value.cpp:49
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ CONSTANT_ADDRESS_32BIT
Address space for 32-bit constant memory.
@ REGION_ADDRESS
Address space for region memory. (GDS)
@ LOCAL_ADDRESS
Address space for local memory.
@ GLOBAL_ADDRESS
Address space for global memory (RAT0, VTX0).
@ PRIVATE_ADDRESS
Address space for private memory.
@ BUFFER_RESOURCE
Address space for 128-bit buffer resources.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char SymbolName[]
Key for Kernel::Metadata::mSymbolName.
LLVM_READONLY const MIMGG16MappingInfo * getMIMGG16MappingInfo(unsigned G)
std::optional< int64_t > getSMRDEncodedLiteralOffset32(const MCSubtargetInfo &ST, int64_t ByteOffset)
bool isGFX12Plus(const MCSubtargetInfo &STI)
constexpr int64_t getNullPointerValue(unsigned AS)
Get the null pointer value for the given address space.
LLVM_ABI IsaVersion getIsaVersion(StringRef GPU)
unsigned getRegBitWidth(unsigned RCID)
Get the size in bits of a register from the register class RC.
LLVM_READONLY bool hasNamedOperand(uint32_t Opcode, OpName NamedIdx)
int getMIMGOpcode(unsigned BaseOpcode, unsigned MIMGEncoding, unsigned VDataDwords, unsigned VAddrDwords, bool IndexedRsrc, bool IndexedSamp)
bool isInlinableLiteral32(int32_t Literal, bool HasInv2Pi)
const BufferIntrinsicInfo * lookupBufferIntrinsic(unsigned Intr)
bool hasSMRDSignedImmOffset(const MCSubtargetInfo &ST)
LLVM_READONLY int32_t getGlobalSaddrOp(uint32_t Opcode)
bool isGFX13Plus(const MCSubtargetInfo &STI)
bool isGFX11Plus(const MCSubtargetInfo &STI)
bool isGFX10Plus(const MCSubtargetInfo &STI)
std::optional< int64_t > getSMRDEncodedOffset(const MCSubtargetInfo &ST, int64_t ByteOffset, bool IsBuffer, bool HasSOffset)
unsigned getMIROperandIdx(const MachineInstr &MI, unsigned Arg)
Convert IR argument index Arg of the intrinsic called by MI, a G_INTRINSIC* instruction,...
LLVM_READONLY const MIMGDimInfo * getMIMGDimInfo(unsigned DimEnum)
unsigned getBarrierMemberCountBitMask(const IsaVersion &Version)
LLVM_READONLY const MIMGBaseOpcodeInfo * getMIMGBaseOpcodeInfo(unsigned BaseOpcode)
Intrinsic::ID getIntrinsicID(const MachineInstr &I)
Return the intrinsic ID for opcodes with the G_AMDGPU_INTRIN_ prefix.
std::pair< Register, unsigned > getBaseWithConstantOffset(MachineRegisterInfo &MRI, Register Reg, GISelValueTracking *ValueTracking=nullptr, bool CheckNUW=false)
Returns base register and constant offset.
const ImageDimIntrinsicInfo * getImageDimIntrinsicInfo(unsigned Intr)
IndexMode
ARM Index Modes.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
operand_type_match m_Reg()
SpecificConstantMatch m_SpecificICst(const APInt &RequestedValue)
Matches a constant equal to RequestedValue.
GInstrBind< GBuildVector > m_GBuildVector(GBuildVector *&Inst)
GCstAndRegMatch m_GCst(std::optional< ValueAndVReg > &ValReg)
UnaryOp_match< SrcTy, TargetOpcode::COPY > m_Copy(SrcTy &&Src)
UnaryOp_match< SrcTy, TargetOpcode::G_ZEXT > m_GZExt(const SrcTy &Src)
BinaryOp_match< LHS, RHS, TargetOpcode::G_XOR, true > m_GXor(const LHS &L, const RHS &R)
UnaryOp_match< SrcTy, TargetOpcode::G_SEXT > m_GSExt(const SrcTy &Src)
UnaryOp_match< SrcTy, TargetOpcode::G_FPEXT > m_GFPExt(const SrcTy &Src)
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
ConstantMatch< APInt > m_ICst(APInt &Cst)
SpecificConstantMatch m_AllOnesInt()
BinaryOp_match< LHS, RHS, TargetOpcode::G_OR, true > m_GOr(const LHS &L, const RHS &R)
ICstOrSplatMatch< APInt > m_ICstOrSplat(APInt &Cst)
ImplicitDefMatch m_GImplicitDef()
GInstrBind< GConcatVectors > m_GConcatVectors(GConcatVectors *&Inst)
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
GInstrBind< GUnmerge > m_GUnmerge(GUnmerge *&Inst)
Instruction binders for ops with no operand-form matcher (constant-immediate or variadic-source ops).
BinaryOp_match< LHS, RHS, TargetOpcode::G_SUB > m_GSub(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, TargetOpcode::G_ASHR, false > m_GAShr(const LHS &L, const RHS &R)
bool mi_match(Reg R, const MachineRegisterInfo &MRI, Pattern &&P)
BinaryOp_match< LHS, RHS, TargetOpcode::G_PTR_ADD, false > m_GPtrAdd(const LHS &L, const RHS &R)
SpecificRegisterMatch m_SpecificReg(Register RequestedReg)
Matches a register only if it is equal to RequestedReg.
BinaryOp_match< LHS, RHS, TargetOpcode::G_SHL, false > m_GShl(const LHS &L, const RHS &R)
GFrameIndexMatch m_GFrameIndex(int &FI)
Or< Preds... > m_any_of(Preds &&... preds)
BinaryOp_match< LHS, RHS, TargetOpcode::G_AND, true > m_GAnd(const LHS &L, const RHS &R)
UnaryOp_match< SrcTy, TargetOpcode::G_BITCAST > m_GBitcast(const SrcTy &Src)
bind_ty< MachineInstr * > m_MInstr(MachineInstr *&MI)
UnaryOp_match< SrcTy, TargetOpcode::G_FNEG > m_GFNeg(const SrcTy &Src)
GFCstOrSplatGFCstMatch m_GFCstOrSplat(std::optional< FPValueAndVReg > &FPValReg)
UnaryOp_match< SrcTy, TargetOpcode::G_FABS > m_GFabs(const SrcTy &Src)
BinaryOp_match< LHS, RHS, TargetOpcode::G_LSHR, false > m_GLShr(const LHS &L, const RHS &R)
UnaryOp_match< SrcTy, TargetOpcode::G_ANYEXT > m_GAnyExt(const SrcTy &Src)
ShuffleVectorMatch< Src1Ty, Src2Ty > m_GShuffleVector(const Src1Ty &Src1, const Src2Ty &Src2, ArrayRef< int > &Mask)
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
BinaryOp_match< LHS, RHS, TargetOpcode::G_MUL, true > m_GMul(const LHS &L, const RHS &R)
UnaryOp_match< SrcTy, TargetOpcode::G_TRUNC > m_GTrunc(const SrcTy &Src)
constexpr MCPhysReg SP
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI Register getFunctionLiveInPhysReg(MachineFunction &MF, const TargetInstrInfo &TII, MCRegister PhysReg, const TargetRegisterClass &RC, const DebugLoc &DL, LLT RegTy=LLT())
Return a virtual register corresponding to the incoming argument register PhysReg.
Definition Utils.cpp:896
@ Offset
Definition DWP.cpp:577
LLVM_ABI bool isBuildVectorAllZeros(const MachineInstr &MI, const MachineRegisterInfo &MRI, bool AllowUndef=false)
Return true if the specified instruction is a G_BUILD_VECTOR or G_BUILD_VECTOR_TRUNC where all of the...
Definition Utils.cpp:1594
LLVM_ABI Register constrainOperandRegClass(const MachineFunction &MF, const TargetRegisterInfo &TRI, MachineRegisterInfo &MRI, const TargetInstrInfo &TII, const RegisterBankInfo &RBI, MachineInstr &InsertPt, const TargetRegisterClass &RegClass, MachineOperand &RegMO)
Constrain the Register operand OpIdx, so that it is now constrained to the TargetRegisterClass passed...
Definition Utils.cpp:64
LLVM_ABI MachineInstr * getOpcodeDef(unsigned Opcode, Register Reg, const MachineRegisterInfo &MRI)
See if Reg is defined by an single def instruction that is Opcode.
Definition Utils.cpp:679
PointerUnion< const TargetRegisterClass *, const RegisterBank * > RegClassOrRegBank
Convenient type to represent either a register class or a register bank.
LLVM_ABI const ConstantFP * getConstantFPVRegVal(Register VReg, const MachineRegisterInfo &MRI)
Definition Utils.cpp:487
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
@ Known
Known to have no common set bits.
@ Implicit
Not emitted register (e.g. carry, or temporary result).
@ Dead
Unused definition.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
unsigned Log2_64_Ceil(uint64_t Value)
Return the ceil log base 2 of the specified value, 64 if the value is zero.
Definition MathExtras.h:345
LLVM_ABI void constrainSelectedInstRegOperands(MachineInstr &I, const TargetInstrInfo &TII, const TargetRegisterInfo &TRI, const RegisterBankInfo &RBI)
Mutate the newly-selected instruction I to constrain its (possibly generic) virtual register operands...
Definition Utils.cpp:163
@ Load
The value being inserted comes from a load (InsertElement only).
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
LLVM_ABI MachineInstr * getDefIgnoringCopies(Register Reg, const MachineRegisterInfo &MRI)
Find the def instruction for Reg, folding away any trivial copies.
Definition Utils.cpp:520
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
unsigned Log2_64(uint64_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:332
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI std::optional< int64_t > getIConstantVRegSExtVal(Register VReg, const MachineRegisterInfo &MRI)
If VReg is defined by a G_CONSTANT fits in int64_t returns it.
Definition Utils.cpp:321
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
@ Off
Use window algorithm after SMS algorithm fails.
constexpr uint32_t Hi_32(uint64_t Value)
Return the high 32 bits of a 64 bit value.
Definition MathExtras.h:151
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI std::optional< ValueAndVReg > getAnyConstantVRegValWithLookThrough(Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs=true, bool LookThroughAnyExt=false)
If VReg is defined by a statically evaluable chain of instructions rooted on a G_CONSTANT or G_FCONST...
Definition Utils.cpp:446
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
constexpr uint32_t Lo_32(uint64_t Value)
Return the low 32 bits of a 64 bit value.
Definition MathExtras.h:156
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
@ Or
Bitwise or logical OR of integers.
@ Mul
Product of integers.
@ SMax
Signed integer max implemented in terms of select(cmp()).
@ And
Bitwise or logical AND of integers.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI std::optional< ValueAndVReg > getIConstantVRegValWithLookThrough(Register VReg, const MachineRegisterInfo &MRI, bool LookThroughInstrs=true)
If VReg is defined by a statically evaluable chain of instructions rooted on a G_CONSTANT returns its...
Definition Utils.cpp:440
LLVM_ABI std::optional< DefinitionAndSourceRegister > getDefSrcRegIgnoringCopies(Register Reg, const MachineRegisterInfo &MRI)
Find the def instruction for Reg, and underlying value Register folding away any copies.
Definition Utils.cpp:495
LLVM_ABI Register getSrcRegIgnoringCopies(Register Reg, const MachineRegisterInfo &MRI)
Find the source register for Reg, folding away any trivial copies.
Definition Utils.cpp:527
constexpr T maskTrailingOnes(unsigned N)
Create a bitmask with the N right-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:78
constexpr RegState getUndefRegState(bool B)
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
The argument layout of a buffer intrinsic.
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
static KnownBits add(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false, bool SelfAdd=false)
Compute knownbits resulting from addition of LHS and RHS.
Definition KnownBits.h:361
int64_t Offset
Offset - This is an offset from the base Value*.
PointerUnion< const Value *, const PseudoSourceValue * > V
This is the IR pointer value for the access, or it is null if unknown.