1//===-- AMDGPUISelDAGToDAG.cpp - A dag to dag inst selector for AMDGPU ----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//==-----------------------------------------------------------------------===//
8//
9/// \file
10/// Defines an instruction selector for the AMDGPU target.
11//
12//===----------------------------------------------------------------------===//
13
14#include "AMDGPUISelDAGToDAG.h"
15#include "AMDGPU.h"
16#include "AMDGPUInstrInfo.h"
17#include "AMDGPUSubtarget.h"
18#include "MCTargetDesc/R600MCTargetDesc.h"
19#include "R600RegisterInfo.h"
20#include "SIISelLowering.h"
21#include "SIMachineFunctionInfo.h"
22#include "llvm/Analysis/UniformityAnalysis.h"
23#include "llvm/CodeGen/FunctionLoweringInfo.h"
24#include "llvm/CodeGen/SelectionDAG.h"
25#include "llvm/CodeGen/SelectionDAGISel.h"
26#include "llvm/CodeGen/SelectionDAGNodes.h"
27#include "llvm/IR/IntrinsicsAMDGPU.h"
28#include "llvm/InitializePasses.h"
29#include "llvm/Support/ErrorHandling.h"
30
31#ifdef EXPENSIVE_CHECKS
32#include "llvm/Analysis/LoopInfo.h"
33#include "llvm/IR/Dominators.h"
34#endif
35
36#define DEBUG_TYPE "amdgpu-isel"
37
38using namespace llvm;
39
40//===----------------------------------------------------------------------===//
41// Instruction Selector Implementation
42//===----------------------------------------------------------------------===//
43
44namespace {
45static SDValue stripBitcast(SDValue Val) {
46 return Val.getOpcode() == ISD::BITCAST ? Val.getOperand(i: 0) : Val;
47}
48
49// Figure out if this is really an extract of the high 16-bits of a dword.
50static bool isExtractHiElt(SDValue In, SDValue &Out) {
51 In = stripBitcast(Val: In);
52
53 if (In.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
54 if (ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Val: In.getOperand(i: 1))) {
55 if (!Idx->isOne())
56 return false;
57 Out = In.getOperand(i: 0);
58 return true;
59 }
60 }
61
62 if (In.getOpcode() != ISD::TRUNCATE)
63 return false;
64
65 SDValue Srl = In.getOperand(i: 0);
66 if (Srl.getOpcode() == ISD::SRL) {
67 if (ConstantSDNode *ShiftAmt = dyn_cast<ConstantSDNode>(Val: Srl.getOperand(i: 1))) {
68 if (ShiftAmt->getZExtValue() == 16) {
69 Out = stripBitcast(Val: Srl.getOperand(i: 0));
70 return true;
71 }
72 }
73 }
74
75 return false;
76}
77
78static SDValue createVOP3PSrc32FromLo16(SDValue Lo, SDValue Src,
79 llvm::SelectionDAG *CurDAG,
80 const GCNSubtarget *Subtarget) {
81 if (!Subtarget->useRealTrue16Insts()) {
82 return Lo;
83 }
84
85 SDValue NewSrc;
86 SDLoc SL(Lo);
87
88 if (Lo->isDivergent()) {
89 SDValue Undef = SDValue(CurDAG->getMachineNode(Opcode: TargetOpcode::IMPLICIT_DEF,
90 dl: SL, VT: Lo.getValueType()),
91 0);
92 const SDValue Ops[] = {
93 CurDAG->getTargetConstant(Val: AMDGPU::VGPR_32RegClassID, DL: SL, VT: MVT::i32), Lo,
94 CurDAG->getTargetConstant(Val: AMDGPU::lo16, DL: SL, VT: MVT::i16), Undef,
95 CurDAG->getTargetConstant(Val: AMDGPU::hi16, DL: SL, VT: MVT::i16)};
96
97 NewSrc = SDValue(CurDAG->getMachineNode(Opcode: TargetOpcode::REG_SEQUENCE, dl: SL,
98 VT: Src.getValueType(), Ops),
99 0);
100 } else {
101 // the S_MOV is needed since the Lo could still be a VGPR16.
102 // With S_MOV, isel insert a "sgpr32 = copy vgpr16" and we reply on
103 // the fixvgpr2sgprcopy pass to legalize it
104 NewSrc = SDValue(
105 CurDAG->getMachineNode(Opcode: AMDGPU::S_MOV_B32, dl: SL, VT: Src.getValueType(), Op1: Lo),
106 0);
107 }
108
109 return NewSrc;
110}
111
112// Look through operations that obscure just looking at the low 16-bits of the
113// same register.
114static SDValue stripExtractLoElt(SDValue In) {
115 if (In.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
116 SDValue Idx = In.getOperand(i: 1);
117 if (isNullConstant(V: Idx) && In.getValueSizeInBits() <= 32)
118 return In.getOperand(i: 0);
119 }
120
121 if (In.getOpcode() == ISD::TRUNCATE) {
122 SDValue Src = In.getOperand(i: 0);
123 if (Src.getValueType().getSizeInBits() == 32)
124 return stripBitcast(Val: Src);
125 }
126
127 return In;
128}
129
130static SDValue emitRegSequence(llvm::SelectionDAG &CurDAG, unsigned DstRegClass,
131 EVT DstTy, ArrayRef<SDValue> Elts,
132 ArrayRef<unsigned> SubRegClass,
133 const SDLoc &DL) {
134 assert(Elts.size() == SubRegClass.size() && "array size mismatch");
135 unsigned NumElts = Elts.size();
136 SmallVector<SDValue, 17> Ops(2 * NumElts + 1);
137 Ops[0] = (CurDAG.getTargetConstant(Val: DstRegClass, DL, VT: MVT::i32));
138 for (unsigned i = 0; i < NumElts; ++i) {
139 Ops[2 * i + 1] = Elts[i];
140 Ops[2 * i + 2] = CurDAG.getTargetConstant(Val: SubRegClass[i], DL, VT: MVT::i32);
141 }
142 return SDValue(
143 CurDAG.getMachineNode(Opcode: TargetOpcode::REG_SEQUENCE, dl: DL, VT: DstTy, Ops), 0);
144}
145
146} // end anonymous namespace
147
148INITIALIZE_PASS_BEGIN(AMDGPUDAGToDAGISelLegacy, "amdgpu-isel",
149 "AMDGPU DAG->DAG Pattern Instruction Selection", false,
150 false)
151INITIALIZE_PASS_DEPENDENCY(AMDGPUPerfHintAnalysisLegacy)
152INITIALIZE_PASS_DEPENDENCY(UniformityInfoWrapperPass)
153#ifdef EXPENSIVE_CHECKS
154INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
155INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
156#endif
157INITIALIZE_PASS_END(AMDGPUDAGToDAGISelLegacy, "amdgpu-isel",
158 "AMDGPU DAG->DAG Pattern Instruction Selection", false,
159 false)
160
161/// This pass converts a legalized DAG into a AMDGPU-specific
162// DAG, ready for instruction scheduling.
163FunctionPass *llvm::createAMDGPUISelDag(TargetMachine &TM,
164 CodeGenOptLevel OptLevel) {
165 return new AMDGPUDAGToDAGISelLegacy(TM, OptLevel);
166}
167
168AMDGPUDAGToDAGISel::AMDGPUDAGToDAGISel(TargetMachine &TM,
169 CodeGenOptLevel OptLevel)
170 : SelectionDAGISel(TM, OptLevel) {}
171
172bool AMDGPUDAGToDAGISel::runOnMachineFunction(MachineFunction &MF) {
173 Subtarget = &MF.getSubtarget<GCNSubtarget>();
174 Subtarget->checkSubtargetFeatures(F: MF.getFunction());
175 Mode = SIModeRegisterDefaults(MF.getFunction(), *Subtarget);
176 return SelectionDAGISel::runOnMachineFunction(mf&: MF);
177}
178
179bool AMDGPUDAGToDAGISel::fp16SrcZerosHighBits(unsigned Opc) const {
180 // XXX - only need to list legal operations.
181 switch (Opc) {
182 case ISD::POISON:
183 return true;
184 case ISD::FADD:
185 case ISD::FSUB:
186 case ISD::FMUL:
187 case ISD::FDIV:
188 case ISD::FREM:
189 case ISD::FCANONICALIZE:
190 case ISD::UINT_TO_FP:
191 case ISD::SINT_TO_FP:
192 case ISD::FABS:
193 // Fabs is lowered to a bit operation, but it's an and which will clear the
194 // high bits anyway.
195 case ISD::FSQRT:
196 case ISD::FSIN:
197 case ISD::FCOS:
198 case ISD::FPOWI:
199 case ISD::FPOW:
200 case ISD::FLOG:
201 case ISD::FLOG2:
202 case ISD::FLOG10:
203 case ISD::FEXP:
204 case ISD::FEXP2:
205 case ISD::FCEIL:
206 case ISD::FTRUNC:
207 case ISD::FRINT:
208 case ISD::FNEARBYINT:
209 case ISD::FROUNDEVEN:
210 case ISD::FROUND:
211 case ISD::FFLOOR:
212 case ISD::FMINNUM:
213 case ISD::FMAXNUM:
214 case ISD::FLDEXP:
215 case AMDGPUISD::FRACT:
216 case AMDGPUISD::CLAMP:
217 case AMDGPUISD::COS_HW:
218 case AMDGPUISD::SIN_HW:
219 case AMDGPUISD::FMIN3:
220 case AMDGPUISD::FMAX3:
221 case AMDGPUISD::FMED3:
222 case AMDGPUISD::FMAD_FTZ:
223 case AMDGPUISD::RCP:
224 case AMDGPUISD::RSQ:
225 case AMDGPUISD::RCP_IFLAG:
226 // On gfx10, all 16-bit instructions preserve the high bits.
227 return Subtarget->getGeneration() <= AMDGPUSubtarget::GFX9;
228 case ISD::FP_ROUND:
229 // We may select fptrunc (fma/mad) to mad_mixlo, which does not zero the
230 // high bits on gfx9.
231 // TODO: If we had the source node we could see if the source was fma/mad
232 return Subtarget->getGeneration() == AMDGPUSubtarget::VOLCANIC_ISLANDS;
233 case ISD::FMA:
234 case ISD::FMAD:
235 case AMDGPUISD::DIV_FIXUP:
236 return Subtarget->getGeneration() == AMDGPUSubtarget::VOLCANIC_ISLANDS;
237 default:
238 // fcopysign, select and others may be lowered to 32-bit bit operations
239 // which don't zero the high bits.
240 return false;
241 }
242}
243
244bool AMDGPUDAGToDAGISelLegacy::runOnMachineFunction(MachineFunction &MF) {
245#ifdef EXPENSIVE_CHECKS
246 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
247 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
248 for (auto &L : LI->getLoopsInPreorder()) {
249 assert(L->isLCSSAForm(DT));
250 }
251#endif
252 return SelectionDAGISelLegacy::runOnMachineFunction(MF);
253}
254
255void AMDGPUDAGToDAGISelLegacy::getAnalysisUsage(AnalysisUsage &AU) const {
256 AU.addRequired<UniformityInfoWrapperPass>();
257#ifdef EXPENSIVE_CHECKS
258 AU.addRequired<DominatorTreeWrapperPass>();
259 AU.addRequired<LoopInfoWrapperPass>();
260#endif
261 SelectionDAGISelLegacy::getAnalysisUsage(AU);
262}
263
264bool AMDGPUDAGToDAGISel::matchLoadD16FromBuildVector(SDNode *N) const {
265 assert(Subtarget->d16PreservesUnusedBits());
266 MVT VT = N->getValueType(ResNo: 0).getSimpleVT();
267 if (VT != MVT::v2i16 && VT != MVT::v2f16)
268 return false;
269
270 SDValue Lo = N->getOperand(Num: 0);
271 SDValue Hi = N->getOperand(Num: 1);
272
273 LoadSDNode *LdHi = dyn_cast<LoadSDNode>(Val: stripBitcast(Val: Hi));
274
275 // build_vector lo, (load ptr) -> load_d16_hi ptr, lo
276 // build_vector lo, (zextload ptr from i8) -> load_d16_hi_u8 ptr, lo
277 // build_vector lo, (sextload ptr from i8) -> load_d16_hi_i8 ptr, lo
278
279 // Need to check for possible indirect dependencies on the other half of the
280 // vector to avoid introducing a cycle.
281 if (LdHi && Hi.hasOneUse() && !LdHi->isPredecessorOf(N: Lo.getNode())) {
282 SDVTList VTList = CurDAG->getVTList(VT1: VT, VT2: MVT::Other);
283
284 SDValue TiedIn = CurDAG->getNode(Opcode: ISD::SCALAR_TO_VECTOR, DL: SDLoc(N), VT, Operand: Lo);
285 SDValue Ops[] = {
286 LdHi->getChain(), LdHi->getBasePtr(), TiedIn
287 };
288
289 unsigned LoadOp = AMDGPUISD::LOAD_D16_HI;
290 if (LdHi->getMemoryVT() == MVT::i8) {
291 LoadOp = LdHi->getExtensionType() == ISD::SEXTLOAD ?
292 AMDGPUISD::LOAD_D16_HI_I8 : AMDGPUISD::LOAD_D16_HI_U8;
293 } else {
294 assert(LdHi->getMemoryVT() == MVT::i16);
295 }
296
297 SDValue NewLoadHi =
298 CurDAG->getMemIntrinsicNode(Opcode: LoadOp, dl: SDLoc(LdHi), VTList,
299 Ops, MemVT: LdHi->getMemoryVT(),
300 MMO: LdHi->getMemOperand());
301
302 CurDAG->ReplaceAllUsesOfValueWith(From: SDValue(N, 0), To: NewLoadHi);
303 CurDAG->ReplaceAllUsesOfValueWith(From: SDValue(LdHi, 1), To: NewLoadHi.getValue(R: 1));
304 return true;
305 }
306
307 // build_vector (load ptr), hi -> load_d16_lo ptr, hi
308 // build_vector (zextload ptr from i8), hi -> load_d16_lo_u8 ptr, hi
309 // build_vector (sextload ptr from i8), hi -> load_d16_lo_i8 ptr, hi
310 LoadSDNode *LdLo = dyn_cast<LoadSDNode>(Val: stripBitcast(Val: Lo));
311 if (LdLo && Lo.hasOneUse()) {
312 SDValue TiedIn = getHi16Elt(In: Hi);
313 if (!TiedIn || LdLo->isPredecessorOf(N: TiedIn.getNode()))
314 return false;
315
316 SDVTList VTList = CurDAG->getVTList(VT1: VT, VT2: MVT::Other);
317 unsigned LoadOp = AMDGPUISD::LOAD_D16_LO;
318 if (LdLo->getMemoryVT() == MVT::i8) {
319 LoadOp = LdLo->getExtensionType() == ISD::SEXTLOAD ?
320 AMDGPUISD::LOAD_D16_LO_I8 : AMDGPUISD::LOAD_D16_LO_U8;
321 } else {
322 assert(LdLo->getMemoryVT() == MVT::i16);
323 }
324
325 TiedIn = CurDAG->getNode(Opcode: ISD::BITCAST, DL: SDLoc(N), VT, Operand: TiedIn);
326
327 SDValue Ops[] = {
328 LdLo->getChain(), LdLo->getBasePtr(), TiedIn
329 };
330
331 SDValue NewLoadLo =
332 CurDAG->getMemIntrinsicNode(Opcode: LoadOp, dl: SDLoc(LdLo), VTList,
333 Ops, MemVT: LdLo->getMemoryVT(),
334 MMO: LdLo->getMemOperand());
335
336 CurDAG->ReplaceAllUsesOfValueWith(From: SDValue(N, 0), To: NewLoadLo);
337 CurDAG->ReplaceAllUsesOfValueWith(From: SDValue(LdLo, 1), To: NewLoadLo.getValue(R: 1));
338 return true;
339 }
340
341 return false;
342}
343
344bool AMDGPUDAGToDAGISel::widenRegionLoad16(SDNode *N) const {
345 auto *Mem = cast<MemSDNode>(Val: N);
346 EVT VT = N->getValueType(ResNo: 0);
347 if (Mem->getAddressSpace() != AMDGPUAS::REGION_ADDRESS || VT.isVector() ||
348 VT.getSizeInBits() != 16)
349 return false;
350
351 SDLoc SL(N);
352 auto *Ld = dyn_cast<LoadSDNode>(Val: N);
353 ISD::LoadExtType ExtType =
354 Ld ? Ld->getExtensionType() : cast<AtomicSDNode>(Val: N)->getExtensionType();
355 if (ExtType == ISD::NON_EXTLOAD)
356 ExtType = ISD::EXTLOAD;
357
358 SDValue NewLoad =
359 Ld ? CurDAG->getExtLoad(ExtType, dl: SL, VT: MVT::i32, Chain: Mem->getChain(),
360 Ptr: Mem->getBasePtr(), MemVT: Mem->getMemoryVT(),
361 MMO: Mem->getMemOperand())
362 : CurDAG->getAtomicLoad(ExtType, dl: SL, MemVT: Mem->getMemoryVT(), VT: MVT::i32,
363 Chain: Mem->getChain(), Ptr: Mem->getBasePtr(),
364 MMO: Mem->getMemOperand());
365
366 SDValue Trunc = CurDAG->getNode(Opcode: ISD::TRUNCATE, DL: SL, VT: MVT::i16, Operand: NewLoad);
367 SDValue Ops[] = {CurDAG->getBitcast(VT, V: Trunc), NewLoad.getValue(R: 1)};
368 CurDAG->ReplaceAllUsesWith(From: N, To: Ops);
369 return true;
370}
371
372void AMDGPUDAGToDAGISel::PreprocessISelDAG() {
373 SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();
374
375 bool MadeChange = false;
376 while (Position != CurDAG->allnodes_begin()) {
377 SDNode *N = &*--Position;
378 if (N->use_empty())
379 continue;
380
381 switch (N->getOpcode()) {
382 case ISD::BUILD_VECTOR:
383 // TODO: Match load d16 from shl (extload:i16), 16
384 if (Subtarget->d16PreservesUnusedBits())
385 MadeChange |= matchLoadD16FromBuildVector(N);
386 break;
387 case ISD::LOAD:
388 case ISD::ATOMIC_LOAD:
389 if (Subtarget->useRealTrue16Insts())
390 MadeChange |= widenRegionLoad16(N);
391 break;
392 default:
393 break;
394 }
395 }
396
397 if (MadeChange) {
398 CurDAG->RemoveDeadNodes();
399 LLVM_DEBUG(dbgs() << "After PreProcess:\n";
400 CurDAG->dump(););
401 }
402}
403
404bool AMDGPUDAGToDAGISel::isInlineImmediate(const SDNode *N) const {
405 if (N->isUndef())
406 return true;
407
408 const SIInstrInfo *TII = Subtarget->getInstrInfo();
409 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val: N))
410 return TII->isInlineConstant(Imm: C->getAPIntValue());
411
412 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val: N))
413 return TII->isInlineConstant(Imm: C->getValueAPF());
414
415 return false;
416}
417
418/// Determine the register class for \p OpNo
419/// \returns The register class of the virtual register that will be used for
420/// the given operand number \OpNo or NULL if the register class cannot be
421/// determined.
422const TargetRegisterClass *AMDGPUDAGToDAGISel::getOperandRegClass(SDNode *N,
423 unsigned OpNo) const {
424 if (!N->isMachineOpcode()) {
425 if (N->getOpcode() == ISD::CopyToReg) {
426 Register Reg = cast<RegisterSDNode>(Val: N->getOperand(Num: 1))->getReg();
427 if (Reg.isVirtual()) {
428 MachineRegisterInfo &MRI = CurDAG->getMachineFunction().getRegInfo();
429 return MRI.getRegClass(Reg);
430 }
431
432 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
433 return TRI->getPhysRegBaseClass(Reg);
434 }
435
436 return nullptr;
437 }
438
439 switch (N->getMachineOpcode()) {
440 default: {
441 const SIInstrInfo *TII = Subtarget->getInstrInfo();
442 const MCInstrDesc &Desc = TII->get(Opcode: N->getMachineOpcode());
443 unsigned OpIdx = Desc.getNumDefs() + OpNo;
444 if (OpIdx >= Desc.getNumOperands())
445 return nullptr;
446
447 int16_t RegClass = TII->getOpRegClassID(OpInfo: Desc.operands()[OpIdx]);
448 if (RegClass == -1)
449 return nullptr;
450
451 return Subtarget->getRegisterInfo()->getRegClass(i: RegClass);
452 }
453 case AMDGPU::REG_SEQUENCE: {
454 unsigned RCID = N->getConstantOperandVal(Num: 0);
455 const TargetRegisterClass *SuperRC =
456 Subtarget->getRegisterInfo()->getRegClass(i: RCID);
457
458 SDValue SubRegOp = N->getOperand(Num: OpNo + 1);
459 unsigned SubRegIdx = SubRegOp->getAsZExtVal();
460 return Subtarget->getRegisterInfo()->getSubClassWithSubReg(SuperRC,
461 SubRegIdx);
462 }
463 }
464}
465
466SDNode *AMDGPUDAGToDAGISel::glueCopyToOp(SDNode *N, SDValue NewChain,
467 SDValue Glue) const {
468 SmallVector <SDValue, 8> Ops;
469 Ops.push_back(Elt: NewChain); // Replace the chain.
470 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
471 Ops.push_back(Elt: N->getOperand(Num: i));
472
473 Ops.push_back(Elt: Glue);
474 return CurDAG->MorphNodeTo(N, Opc: N->getOpcode(), VTs: N->getVTList(), Ops);
475}
476
477SDNode *AMDGPUDAGToDAGISel::glueCopyToM0(SDNode *N, SDValue Val) const {
478 const SITargetLowering& Lowering =
479 *static_cast<const SITargetLowering*>(getTargetLowering());
480
481 assert(N->getOperand(0).getValueType() == MVT::Other && "Expected chain");
482
483 SDValue M0 = Lowering.copyToM0(DAG&: *CurDAG, Chain: N->getOperand(Num: 0), DL: SDLoc(N), V: Val);
484 return glueCopyToOp(N, NewChain: M0, Glue: M0.getValue(R: 1));
485}
486
487SDNode *AMDGPUDAGToDAGISel::glueCopyToM0LDSInit(SDNode *N) const {
488 unsigned AS = cast<MemSDNode>(Val: N)->getAddressSpace();
489 if (AS == AMDGPUAS::LOCAL_ADDRESS) {
490 if (Subtarget->ldsRequiresM0Init())
491 return glueCopyToM0(
492 N, Val: CurDAG->getSignedTargetConstant(Val: -1, DL: SDLoc(N), VT: MVT::i32));
493 } else if (AS == AMDGPUAS::REGION_ADDRESS) {
494 MachineFunction &MF = CurDAG->getMachineFunction();
495 unsigned Value = MF.getInfo<SIMachineFunctionInfo>()->getGDSSize();
496 return
497 glueCopyToM0(N, Val: CurDAG->getTargetConstant(Val: Value, DL: SDLoc(N), VT: MVT::i32));
498 }
499 return N;
500}
501
502MachineSDNode *AMDGPUDAGToDAGISel::buildSMovImm64(SDLoc &DL, uint64_t Imm,
503 EVT VT) const {
504 SDNode *Lo = CurDAG->getMachineNode(
505 Opcode: AMDGPU::S_MOV_B32, dl: DL, VT: MVT::i32,
506 Op1: CurDAG->getTargetConstant(Val: Lo_32(Value: Imm), DL, VT: MVT::i32));
507 SDNode *Hi = CurDAG->getMachineNode(
508 Opcode: AMDGPU::S_MOV_B32, dl: DL, VT: MVT::i32,
509 Op1: CurDAG->getTargetConstant(Val: Hi_32(Value: Imm), DL, VT: MVT::i32));
510 const SDValue Ops[] = {
511 CurDAG->getTargetConstant(Val: AMDGPU::SReg_64RegClassID, DL, VT: MVT::i32),
512 SDValue(Lo, 0), CurDAG->getTargetConstant(Val: AMDGPU::sub0, DL, VT: MVT::i32),
513 SDValue(Hi, 0), CurDAG->getTargetConstant(Val: AMDGPU::sub1, DL, VT: MVT::i32)};
514
515 return CurDAG->getMachineNode(Opcode: TargetOpcode::REG_SEQUENCE, dl: DL, VT, Ops);
516}
517
518SDNode *AMDGPUDAGToDAGISel::packConstantV2I16(const SDNode *N,
519 SelectionDAG &DAG) const {
520 // TODO: Handle undef as zero
521
522 assert(N->getOpcode() == ISD::BUILD_VECTOR && N->getNumOperands() == 2);
523 uint32_t LHSVal, RHSVal;
524 if (getConstantValue(N: N->getOperand(Num: 0), Out&: LHSVal) &&
525 getConstantValue(N: N->getOperand(Num: 1), Out&: RHSVal)) {
526 SDLoc SL(N);
527 uint32_t K = (LHSVal & 0xffff) | (RHSVal << 16);
528 return DAG.getMachineNode(
529 Opcode: isVGPRImm(N) ? AMDGPU::V_MOV_B32_e32 : AMDGPU::S_MOV_B32, dl: SL,
530 VT: N->getValueType(ResNo: 0), Op1: DAG.getTargetConstant(Val: K, DL: SL, VT: MVT::i32));
531 }
532
533 return nullptr;
534}
535
536void AMDGPUDAGToDAGISel::SelectBuildVector(SDNode *N, unsigned RegClassID) {
537 EVT VT = N->getValueType(ResNo: 0);
538 unsigned NumVectorElts = VT.getVectorNumElements();
539 EVT EltVT = VT.getVectorElementType();
540 SDLoc DL(N);
541 SDValue RegClass = CurDAG->getTargetConstant(Val: RegClassID, DL, VT: MVT::i32);
542
543 if (NumVectorElts == 1) {
544 CurDAG->SelectNodeTo(N, MachineOpc: AMDGPU::COPY_TO_REGCLASS, VT: EltVT, Op1: N->getOperand(Num: 0),
545 Op2: RegClass);
546 return;
547 }
548
549 bool IsGCN = CurDAG->getSubtarget().getTargetTriple().isAMDGCN();
550 if (IsGCN && Subtarget->has64BitLiterals() && VT.getSizeInBits() == 64 &&
551 CurDAG->isConstantValueOfAnyType(N: SDValue(N, 0))) {
552 uint64_t C = 0;
553 bool AllConst = true;
554 unsigned EltSize = EltVT.getSizeInBits();
555 for (unsigned I = 0; I < NumVectorElts; ++I) {
556 SDValue Op = N->getOperand(Num: I);
557 if (Op.isUndef()) {
558 AllConst = false;
559 break;
560 }
561 uint64_t Val;
562 if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Val&: Op)) {
563 Val = CF->getValueAPF().bitcastToAPInt().getZExtValue();
564 } else
565 Val = cast<ConstantSDNode>(Val&: Op)->getZExtValue();
566 C |= Val << (EltSize * I);
567 }
568 if (AllConst) {
569 SDValue CV = CurDAG->getTargetConstant(Val: C, DL, VT: MVT::i64);
570 MachineSDNode *Copy =
571 CurDAG->getMachineNode(Opcode: AMDGPU::S_MOV_B64_IMM_PSEUDO, dl: DL, VT, Op1: CV);
572 CurDAG->SelectNodeTo(N, MachineOpc: AMDGPU::COPY_TO_REGCLASS, VT, Op1: SDValue(Copy, 0),
573 Op2: RegClass);
574 return;
575 }
576 }
577
578 assert(NumVectorElts <= 32 && "Vectors with more than 32 elements not "
579 "supported yet");
580 // 32 = Max Num Vector Elements
581 // 2 = 2 REG_SEQUENCE operands per element (value, subreg index)
582 // 1 = Vector Register Class
583 SmallVector<SDValue, 32 * 2 + 1> RegSeqArgs(NumVectorElts * 2 + 1);
584
585 RegSeqArgs[0] = CurDAG->getTargetConstant(Val: RegClassID, DL, VT: MVT::i32);
586 bool IsRegSeq = true;
587 unsigned NOps = N->getNumOperands();
588 unsigned EltSizeInRegs = EltVT.getSizeInBits() / 32;
589 assert(IsGCN || EltSizeInRegs == 1);
590 for (unsigned i = 0; i < NOps; i++) {
591 // XXX: Why is this here?
592 if (isa<RegisterSDNode>(Val: N->getOperand(Num: i))) {
593 IsRegSeq = false;
594 break;
595 }
596 unsigned Sub = IsGCN ? SIRegisterInfo::getSubRegFromChannel(
597 Channel: i * EltSizeInRegs, NumRegs: EltSizeInRegs)
598 : R600RegisterInfo::getSubRegFromChannel(Channel: i);
599 RegSeqArgs[1 + (2 * i)] = N->getOperand(Num: i);
600 RegSeqArgs[1 + (2 * i) + 1] = CurDAG->getTargetConstant(Val: Sub, DL, VT: MVT::i32);
601 }
602 if (NOps != NumVectorElts) {
603 // Fill in the missing undef elements if this was a scalar_to_vector.
604 assert(N->getOpcode() == ISD::SCALAR_TO_VECTOR && NOps < NumVectorElts);
605 MachineSDNode *ImpDef = CurDAG->getMachineNode(Opcode: TargetOpcode::IMPLICIT_DEF,
606 dl: DL, VT: EltVT);
607 for (unsigned i = NOps; i < NumVectorElts; ++i) {
608 unsigned Sub = IsGCN ? SIRegisterInfo::getSubRegFromChannel(
609 Channel: i * EltSizeInRegs, NumRegs: EltSizeInRegs)
610 : R600RegisterInfo::getSubRegFromChannel(Channel: i);
611 RegSeqArgs[1 + (2 * i)] = SDValue(ImpDef, 0);
612 RegSeqArgs[1 + (2 * i) + 1] =
613 CurDAG->getTargetConstant(Val: Sub, DL, VT: MVT::i32);
614 }
615 }
616
617 if (!IsRegSeq)
618 SelectCode(N);
619 CurDAG->SelectNodeTo(N, MachineOpc: AMDGPU::REG_SEQUENCE, VTs: N->getVTList(), Ops: RegSeqArgs);
620}
621
622void AMDGPUDAGToDAGISel::SelectVectorShuffle(SDNode *N) {
623 EVT VT = N->getValueType(ResNo: 0);
624 EVT EltVT = VT.getVectorElementType();
625
626 // TODO: Handle 16-bit element vectors with even aligned masks.
627 if (!Subtarget->hasPkMovB32() || !EltVT.bitsEq(VT: MVT::i32) ||
628 VT.getVectorNumElements() != 2) {
629 SelectCode(N);
630 return;
631 }
632
633 auto *SVN = cast<ShuffleVectorSDNode>(Val: N);
634
635 SDValue Src0 = SVN->getOperand(Num: 0);
636 SDValue Src1 = SVN->getOperand(Num: 1);
637 ArrayRef<int> Mask = SVN->getMask();
638 SDLoc DL(N);
639
640 assert(Src0.getValueType().getVectorNumElements() == 2 && Mask.size() == 2 &&
641 Mask[0] < 4 && Mask[1] < 4);
642
643 SDValue VSrc0 = Mask[0] < 2 ? Src0 : Src1;
644 SDValue VSrc1 = Mask[1] < 2 ? Src0 : Src1;
645 unsigned Src0SubReg = Mask[0] & 1 ? AMDGPU::sub1 : AMDGPU::sub0;
646 unsigned Src1SubReg = Mask[1] & 1 ? AMDGPU::sub1 : AMDGPU::sub0;
647
648 if (Mask[0] < 0) {
649 Src0SubReg = Src1SubReg;
650 MachineSDNode *ImpDef =
651 CurDAG->getMachineNode(Opcode: TargetOpcode::IMPLICIT_DEF, dl: DL, VT);
652 VSrc0 = SDValue(ImpDef, 0);
653 }
654
655 if (Mask[1] < 0) {
656 Src1SubReg = Src0SubReg;
657 MachineSDNode *ImpDef =
658 CurDAG->getMachineNode(Opcode: TargetOpcode::IMPLICIT_DEF, dl: DL, VT);
659 VSrc1 = SDValue(ImpDef, 0);
660 }
661
662 // SGPR case needs to lower to copies.
663 //
664 // Also use subregister extract when we can directly blend the registers with
665 // a simple subregister copy.
666 //
667 // TODO: Maybe we should fold this out earlier
668 if (N->isDivergent() && Src0SubReg == AMDGPU::sub1 &&
669 Src1SubReg == AMDGPU::sub0) {
670 // The low element of the result always comes from src0.
671 // The high element of the result always comes from src1.
672 // op_sel selects the high half of src0.
673 // op_sel_hi selects the high half of src1.
674
675 unsigned Src0OpSel =
676 Src0SubReg == AMDGPU::sub1 ? SISrcMods::OP_SEL_0 : SISrcMods::NONE;
677 unsigned Src1OpSel =
678 Src1SubReg == AMDGPU::sub1 ? SISrcMods::OP_SEL_0 : SISrcMods::NONE;
679
680 // Enable op_sel_hi to avoid printing it. This should have no effect on the
681 // result.
682 Src0OpSel |= SISrcMods::OP_SEL_1;
683 Src1OpSel |= SISrcMods::OP_SEL_1;
684
685 SDValue Src0OpSelVal = CurDAG->getTargetConstant(Val: Src0OpSel, DL, VT: MVT::i32);
686 SDValue Src1OpSelVal = CurDAG->getTargetConstant(Val: Src1OpSel, DL, VT: MVT::i32);
687 SDValue ZeroMods = CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i32);
688
689 CurDAG->SelectNodeTo(N, MachineOpc: AMDGPU::V_PK_MOV_B32, VTs: N->getVTList(),
690 Ops: {Src0OpSelVal, VSrc0, Src1OpSelVal, VSrc1,
691 ZeroMods, // clamp
692 ZeroMods, // op_sel
693 ZeroMods, // op_sel_hi
694 ZeroMods, // neg_lo
695 ZeroMods}); // neg_hi
696 return;
697 }
698
699 SDValue ResultElt0 =
700 CurDAG->getTargetExtractSubreg(SRIdx: Src0SubReg, DL, VT: EltVT, Operand: VSrc0);
701 SDValue ResultElt1 =
702 CurDAG->getTargetExtractSubreg(SRIdx: Src1SubReg, DL, VT: EltVT, Operand: VSrc1);
703
704 const SDValue Ops[] = {
705 CurDAG->getTargetConstant(Val: AMDGPU::SReg_64RegClassID, DL, VT: MVT::i32),
706 ResultElt0, CurDAG->getTargetConstant(Val: AMDGPU::sub0, DL, VT: MVT::i32),
707 ResultElt1, CurDAG->getTargetConstant(Val: AMDGPU::sub1, DL, VT: MVT::i32)};
708 CurDAG->SelectNodeTo(N, MachineOpc: TargetOpcode::REG_SEQUENCE, VT, Ops);
709}
710
711void AMDGPUDAGToDAGISel::Select(SDNode *N) {
712 unsigned int Opc = N->getOpcode();
713 if (N->isMachineOpcode()) {
714 N->setNodeId(-1);
715 return; // Already selected.
716 }
717
718 // isa<MemSDNode> almost works but is slightly too permissive for some DS
719 // intrinsics.
720 if (Opc == ISD::LOAD || Opc == ISD::STORE || isa<AtomicSDNode>(Val: N)) {
721 N = glueCopyToM0LDSInit(N);
722 SelectCode(N);
723 return;
724 }
725
726 switch (Opc) {
727 default:
728 break;
729 case ISD::UADDO_CARRY:
730 case ISD::USUBO_CARRY:
731 if (N->getValueType(ResNo: 0) == MVT::i64) {
732 SelectAddcSubbI64(N);
733 return;
734 }
735
736 if (N->getValueType(ResNo: 0) != MVT::i32)
737 break;
738
739 SelectAddcSubb(N);
740 return;
741 case ISD::UADDO:
742 case ISD::USUBO: {
743 if (N->getValueType(ResNo: 0) == MVT::i64) {
744 SelectAddcSubbI64(N);
745 return;
746 }
747
748 SelectUADDO_USUBO(N);
749 return;
750 }
751 case AMDGPUISD::FMUL_W_CHAIN: {
752 SelectFMUL_W_CHAIN(N);
753 return;
754 }
755 case AMDGPUISD::FMA_W_CHAIN: {
756 SelectFMA_W_CHAIN(N);
757 return;
758 }
759
760 case ISD::SCALAR_TO_VECTOR:
761 case ISD::BUILD_VECTOR: {
762 EVT VT = N->getValueType(ResNo: 0);
763 unsigned NumVectorElts = VT.getVectorNumElements();
764 if (VT.getScalarSizeInBits() == 16) {
765 if (Opc == ISD::BUILD_VECTOR && NumVectorElts == 2) {
766 if (SDNode *Packed = packConstantV2I16(N, DAG&: *CurDAG)) {
767 ReplaceNode(F: N, T: Packed);
768 return;
769 }
770 }
771
772 break;
773 }
774
775 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
776 EVT EltTy = VT.getVectorElementType();
777 assert(EltTy.bitsEq(MVT::i32) || EltTy.bitsEq(MVT::i64));
778 unsigned VecInBits = NumVectorElts * EltTy.getScalarSizeInBits();
779 const TargetRegisterClass *RegClass =
780 N->isDivergent() ? TRI->getDefaultVectorSuperClassForBitWidth(BitWidth: VecInBits)
781 : SIRegisterInfo::getSGPRClassForBitWidth(BitWidth: VecInBits);
782
783 SelectBuildVector(N, RegClassID: RegClass->getID());
784 return;
785 }
786 case ISD::VECTOR_SHUFFLE:
787 SelectVectorShuffle(N);
788 return;
789 case ISD::BUILD_PAIR: {
790 SDValue RC, SubReg0, SubReg1;
791 SDLoc DL(N);
792 if (N->getValueType(ResNo: 0) == MVT::i128) {
793 RC = CurDAG->getTargetConstant(Val: AMDGPU::SGPR_128RegClassID, DL, VT: MVT::i32);
794 SubReg0 = CurDAG->getTargetConstant(Val: AMDGPU::sub0_sub1, DL, VT: MVT::i32);
795 SubReg1 = CurDAG->getTargetConstant(Val: AMDGPU::sub2_sub3, DL, VT: MVT::i32);
796 } else if (N->getValueType(ResNo: 0) == MVT::i64) {
797 RC = CurDAG->getTargetConstant(Val: AMDGPU::SReg_64RegClassID, DL, VT: MVT::i32);
798 SubReg0 = CurDAG->getTargetConstant(Val: AMDGPU::sub0, DL, VT: MVT::i32);
799 SubReg1 = CurDAG->getTargetConstant(Val: AMDGPU::sub1, DL, VT: MVT::i32);
800 } else {
801 llvm_unreachable("Unhandled value type for BUILD_PAIR");
802 }
803 const SDValue Ops[] = { RC, N->getOperand(Num: 0), SubReg0,
804 N->getOperand(Num: 1), SubReg1 };
805 ReplaceNode(F: N, T: CurDAG->getMachineNode(Opcode: TargetOpcode::REG_SEQUENCE, dl: DL,
806 VT: N->getValueType(ResNo: 0), Ops));
807 return;
808 }
809
810 case ISD::Constant:
811 case ISD::ConstantFP: {
812 if (N->getValueType(ResNo: 0).getSizeInBits() != 64 || isInlineImmediate(N) ||
813 Subtarget->has64BitLiterals())
814 break;
815
816 uint64_t Imm;
817 if (ConstantFPSDNode *FP = dyn_cast<ConstantFPSDNode>(Val: N)) {
818 Imm = FP->getValueAPF().bitcastToAPInt().getZExtValue();
819 if (AMDGPU::isValid32BitLiteral(Val: Imm, IsFP64: true))
820 break;
821 } else {
822 ConstantSDNode *C = cast<ConstantSDNode>(Val: N);
823 Imm = C->getZExtValue();
824 if (AMDGPU::isValid32BitLiteral(Val: Imm, IsFP64: false))
825 break;
826 }
827
828 SDLoc DL(N);
829 ReplaceNode(F: N, T: buildSMovImm64(DL, Imm, VT: N->getValueType(ResNo: 0)));
830 return;
831 }
832 case AMDGPUISD::BFE_I32:
833 case AMDGPUISD::BFE_U32: {
834 // There is a scalar version available, but unlike the vector version which
835 // has a separate operand for the offset and width, the scalar version packs
836 // the width and offset into a single operand. Try to move to the scalar
837 // version if the offsets are constant, so that we can try to keep extended
838 // loads of kernel arguments in SGPRs.
839
840 // TODO: Technically we could try to pattern match scalar bitshifts of
841 // dynamic values, but it's probably not useful.
842 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(Val: N->getOperand(Num: 1));
843 if (!Offset)
844 break;
845
846 ConstantSDNode *Width = dyn_cast<ConstantSDNode>(Val: N->getOperand(Num: 2));
847 if (!Width)
848 break;
849
850 bool Signed = Opc == AMDGPUISD::BFE_I32;
851
852 uint32_t OffsetVal = Offset->getZExtValue();
853 uint32_t WidthVal = Width->getZExtValue();
854
855 ReplaceNode(F: N, T: getBFE32(IsSigned: Signed, DL: SDLoc(N), Val: N->getOperand(Num: 0), Offset: OffsetVal,
856 Width: WidthVal));
857 return;
858 }
859 case AMDGPUISD::DIV_SCALE: {
860 SelectDIV_SCALE(N);
861 return;
862 }
863 case AMDGPUISD::MAD_I64_I32:
864 case AMDGPUISD::MAD_U64_U32: {
865 SelectMAD_64_32(N);
866 return;
867 }
868 case ISD::SMUL_LOHI:
869 case ISD::UMUL_LOHI:
870 return SelectMUL_LOHI(N);
871 case ISD::CopyToReg: {
872 const SITargetLowering& Lowering =
873 *static_cast<const SITargetLowering*>(getTargetLowering());
874 N = Lowering.legalizeTargetIndependentNode(Node: N, DAG&: *CurDAG);
875 break;
876 }
877 case ISD::AND:
878 case ISD::SRL:
879 case ISD::SRA:
880 case ISD::SIGN_EXTEND_INREG:
881 if (N->getValueType(ResNo: 0) != MVT::i32)
882 break;
883
884 SelectS_BFE(N);
885 return;
886 case ISD::BRCOND:
887 SelectBRCOND(N);
888 return;
889 case ISD::FP_EXTEND:
890 SelectFP_EXTEND(N);
891 return;
892 case AMDGPUISD::CVT_PKRTZ_F16_F32:
893 case AMDGPUISD::CVT_PKNORM_I16_F32:
894 case AMDGPUISD::CVT_PKNORM_U16_F32:
895 case AMDGPUISD::CVT_PK_U16_U32:
896 case AMDGPUISD::CVT_PK_I16_I32: {
897 // Hack around using a legal type if f16 is illegal.
898 if (N->getValueType(ResNo: 0) == MVT::i32) {
899 MVT NewVT = Opc == AMDGPUISD::CVT_PKRTZ_F16_F32 ? MVT::v2f16 : MVT::v2i16;
900 N = CurDAG->MorphNodeTo(N, Opc: N->getOpcode(), VTs: CurDAG->getVTList(VT: NewVT),
901 Ops: { N->getOperand(Num: 0), N->getOperand(Num: 1) });
902 SelectCode(N);
903 return;
904 }
905
906 break;
907 }
908 case ISD::INTRINSIC_W_CHAIN: {
909 SelectINTRINSIC_W_CHAIN(N);
910 return;
911 }
912 case ISD::INTRINSIC_WO_CHAIN: {
913 SelectINTRINSIC_WO_CHAIN(N);
914 return;
915 }
916 case ISD::INTRINSIC_VOID: {
917 SelectINTRINSIC_VOID(N);
918 return;
919 }
920 case AMDGPUISD::WAVE_ADDRESS: {
921 SelectWAVE_ADDRESS(N);
922 return;
923 }
924 case ISD::STACKRESTORE: {
925 SelectSTACKRESTORE(N);
926 return;
927 }
928 case ISD::WRITE_REGISTER: {
929 SelectWRITE_REGISTER(N);
930 return;
931 }
932 }
933
934 SelectCode(N);
935}
936
937bool AMDGPUDAGToDAGISel::isSDWAOperand(const SDNode *N) const {
938 if (!Subtarget->hasSDWA())
939 return false;
940
941 if (N->getOpcode() == ISD::SIGN_EXTEND_INREG) {
942 EVT VT = cast<VTSDNode>(Val: N->getOperand(Num: 1))->getVT();
943 return VT.getScalarSizeInBits() == 8 || VT.getScalarSizeInBits() == 16;
944 }
945
946 if (N->getOpcode() == ISD::AND)
947 if (auto *RHS = dyn_cast<ConstantSDNode>(Val: N->getOperand(Num: 1)))
948 return RHS->getZExtValue() == 0xFF || RHS->getZExtValue() == 0xFFFF;
949
950 if (N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL)
951 if (auto *RHS = dyn_cast<ConstantSDNode>(Val: N->getOperand(Num: 1)))
952 return (RHS->getZExtValue() % 8) == 0;
953
954 return false;
955}
956
957bool AMDGPUDAGToDAGISel::isUniformBr(const SDNode *N) const {
958 const BasicBlock *BB = FuncInfo->MBB->getBasicBlock();
959 const Instruction *Term = BB->getTerminator();
960 return Term->getMetadata(Kind: "amdgpu.uniform") ||
961 Term->getMetadata(Kind: "structurizecfg.uniform");
962}
963
964bool AMDGPUDAGToDAGISel::isUnneededShiftMask(const SDNode *N,
965 unsigned ShAmtBits) const {
966 assert(N->getOpcode() == ISD::AND);
967
968 const APInt &RHS = N->getConstantOperandAPInt(Num: 1);
969 if (RHS.countr_one() >= ShAmtBits)
970 return true;
971
972 const APInt &LHSKnownZeros = CurDAG->computeKnownBits(Op: N->getOperand(Num: 0)).Zero;
973 return (LHSKnownZeros | RHS).countr_one() >= ShAmtBits;
974}
975
976static bool getBaseWithOffsetUsingSplitOR(SelectionDAG &DAG, SDValue Addr,
977 SDValue &N0, SDValue &N1) {
978 if (Addr.getValueType() == MVT::i64 && Addr.getOpcode() == ISD::BITCAST &&
979 Addr.getOperand(i: 0).getOpcode() == ISD::BUILD_VECTOR) {
980 // As we split 64-bit `or` earlier, it's complicated pattern to match, i.e.
981 // (i64 (bitcast (v2i32 (build_vector
982 // (or (extract_vector_elt V, 0), OFFSET),
983 // (extract_vector_elt V, 1)))))
984 SDValue Lo = Addr.getOperand(i: 0).getOperand(i: 0);
985 if (Lo.getOpcode() == ISD::OR && DAG.isBaseWithConstantOffset(Op: Lo)) {
986 SDValue BaseLo = Lo.getOperand(i: 0);
987 SDValue BaseHi = Addr.getOperand(i: 0).getOperand(i: 1);
988 // Check that split base (Lo and Hi) are extracted from the same one.
989 if (BaseLo.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
990 BaseHi.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
991 BaseLo.getOperand(i: 0) == BaseHi.getOperand(i: 0) &&
992 // Lo is statically extracted from index 0.
993 isa<ConstantSDNode>(Val: BaseLo.getOperand(i: 1)) &&
994 BaseLo.getConstantOperandVal(i: 1) == 0 &&
995 // Hi is statically extracted from index 0.
996 isa<ConstantSDNode>(Val: BaseHi.getOperand(i: 1)) &&
997 BaseHi.getConstantOperandVal(i: 1) == 1) {
998 N0 = BaseLo.getOperand(i: 0).getOperand(i: 0);
999 N1 = Lo.getOperand(i: 1);
1000 return true;
1001 }
1002 }
1003 }
1004 return false;
1005}
1006
1007bool AMDGPUDAGToDAGISel::isBaseWithConstantOffset64(SDValue Addr, SDValue &LHS,
1008 SDValue &RHS) const {
1009 if (CurDAG->isBaseWithConstantOffset(Op: Addr)) {
1010 LHS = Addr.getOperand(i: 0);
1011 RHS = Addr.getOperand(i: 1);
1012 return true;
1013 }
1014
1015 if (getBaseWithOffsetUsingSplitOR(DAG&: *CurDAG, Addr, N0&: LHS, N1&: RHS)) {
1016 assert(LHS && RHS && isa<ConstantSDNode>(RHS));
1017 return true;
1018 }
1019
1020 return false;
1021}
1022
1023StringRef AMDGPUDAGToDAGISelLegacy::getPassName() const {
1024 return "AMDGPU DAG->DAG Pattern Instruction Selection";
1025}
1026
1027AMDGPUISelDAGToDAGPass::AMDGPUISelDAGToDAGPass(TargetMachine &TM)
1028 : SelectionDAGISelPass(
1029 std::make_unique<AMDGPUDAGToDAGISel>(args&: TM, args: TM.getOptLevel())) {}
1030
1031PreservedAnalyses
1032AMDGPUISelDAGToDAGPass::run(MachineFunction &MF,
1033 MachineFunctionAnalysisManager &MFAM) {
1034 auto &FAM = MFAM.getResult<FunctionAnalysisManagerMachineFunctionProxy>(IR&: MF)
1035 .getManager();
1036 auto &F = MF.getFunction();
1037 // UniformityInfoAnalysis is optional in generic dag isel,
1038 // AMDGPUISelDAGToDAGPass requires it, calculate it explicitly.
1039 FAM.getResult<UniformityInfoAnalysis>(IR&: F);
1040#ifdef EXPENSIVE_CHECKS
1041 DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F);
1042 LoopInfo &LI = FAM.getResult<LoopAnalysis>(F);
1043 for (auto &L : LI.getLoopsInPreorder())
1044 assert(L->isLCSSAForm(DT) && "Loop is not in LCSSA form!");
1045#endif
1046 return SelectionDAGISelPass::run(MF, MFAM);
1047}
1048
1049//===----------------------------------------------------------------------===//
1050// Complex Patterns
1051//===----------------------------------------------------------------------===//
1052
1053bool AMDGPUDAGToDAGISel::SelectADDRVTX_READ(SDValue Addr, SDValue &Base,
1054 SDValue &Offset) {
1055 return false;
1056}
1057
1058bool AMDGPUDAGToDAGISel::SelectADDRIndirect(SDValue Addr, SDValue &Base,
1059 SDValue &Offset) {
1060 ConstantSDNode *C;
1061 SDLoc DL(Addr);
1062
1063 if ((C = dyn_cast<ConstantSDNode>(Val&: Addr))) {
1064 Base = CurDAG->getRegister(Reg: R600::INDIRECT_BASE_ADDR, VT: MVT::i32);
1065 Offset = CurDAG->getTargetConstant(Val: C->getZExtValue(), DL, VT: MVT::i32);
1066 } else if ((Addr.getOpcode() == AMDGPUISD::DWORDADDR) &&
1067 (C = dyn_cast<ConstantSDNode>(Val: Addr.getOperand(i: 0)))) {
1068 Base = CurDAG->getRegister(Reg: R600::INDIRECT_BASE_ADDR, VT: MVT::i32);
1069 Offset = CurDAG->getTargetConstant(Val: C->getZExtValue(), DL, VT: MVT::i32);
1070 } else if ((Addr.getOpcode() == ISD::ADD || Addr.getOpcode() == ISD::OR) &&
1071 (C = dyn_cast<ConstantSDNode>(Val: Addr.getOperand(i: 1)))) {
1072 Base = Addr.getOperand(i: 0);
1073 Offset = CurDAG->getTargetConstant(Val: C->getZExtValue(), DL, VT: MVT::i32);
1074 } else {
1075 Base = Addr;
1076 Offset = CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i32);
1077 }
1078
1079 return true;
1080}
1081
1082SDValue AMDGPUDAGToDAGISel::getMaterializedScalarImm32(int64_t Val,
1083 const SDLoc &DL) const {
1084 SDNode *Mov = CurDAG->getMachineNode(
1085 Opcode: AMDGPU::S_MOV_B32, dl: DL, VT: MVT::i32,
1086 Op1: CurDAG->getTargetConstant(Val, DL, VT: MVT::i32));
1087 return SDValue(Mov, 0);
1088}
1089
1090void AMDGPUDAGToDAGISel::SelectAddcSubb(SDNode *N) {
1091 SDValue LHS = N->getOperand(Num: 0);
1092 SDValue RHS = N->getOperand(Num: 1);
1093 SDValue CI = N->getOperand(Num: 2);
1094
1095 if (N->isDivergent()) {
1096 unsigned Opc = N->getOpcode() == ISD::UADDO_CARRY ? AMDGPU::V_ADDC_U32_e64
1097 : AMDGPU::V_SUBB_U32_e64;
1098 CurDAG->SelectNodeTo(
1099 N, MachineOpc: Opc, VTs: N->getVTList(),
1100 Ops: {LHS, RHS, CI,
1101 CurDAG->getTargetConstant(Val: 0, DL: {}, VT: MVT::i1) /*clamp bit*/});
1102 } else {
1103 unsigned Opc = N->getOpcode() == ISD::UADDO_CARRY ? AMDGPU::S_ADD_CO_PSEUDO
1104 : AMDGPU::S_SUB_CO_PSEUDO;
1105 CurDAG->SelectNodeTo(N, MachineOpc: Opc, VTs: N->getVTList(), Ops: {LHS, RHS, CI});
1106 }
1107}
1108
1109void AMDGPUDAGToDAGISel::SelectAddcSubbI64(SDNode *N) {
1110 SDLoc DL(N);
1111 SDValue LHS = N->getOperand(Num: 0);
1112 SDValue RHS = N->getOperand(Num: 1);
1113
1114 unsigned Opcode = N->getOpcode();
1115 bool ConsumeCarry = Opcode == ISD::UADDO_CARRY || Opcode == ISD::USUBO_CARRY;
1116 bool IsAdd = Opcode == ISD::UADDO || Opcode == ISD::UADDO_CARRY;
1117
1118 SDValue Sub0 = CurDAG->getTargetConstant(Val: AMDGPU::sub0, DL, VT: MVT::i32);
1119 SDValue Sub1 = CurDAG->getTargetConstant(Val: AMDGPU::sub1, DL, VT: MVT::i32);
1120
1121 SDNode *Lo0 = CurDAG->getMachineNode(Opcode: TargetOpcode::EXTRACT_SUBREG, dl: DL,
1122 VT: MVT::i32, Op1: LHS, Op2: Sub0);
1123 SDNode *Hi0 = CurDAG->getMachineNode(Opcode: TargetOpcode::EXTRACT_SUBREG, dl: DL,
1124 VT: MVT::i32, Op1: LHS, Op2: Sub1);
1125
1126 SDNode *Lo1 = CurDAG->getMachineNode(Opcode: TargetOpcode::EXTRACT_SUBREG, dl: DL,
1127 VT: MVT::i32, Op1: RHS, Op2: Sub0);
1128 SDNode *Hi1 = CurDAG->getMachineNode(Opcode: TargetOpcode::EXTRACT_SUBREG, dl: DL,
1129 VT: MVT::i32, Op1: RHS, Op2: Sub1);
1130
1131 SDVTList VTList = CurDAG->getVTList(VT1: MVT::i32, VT2: N->getValueType(ResNo: 1));
1132
1133 static const unsigned NoCarryOpcMap[2][2] = {
1134 {AMDGPU::S_USUBO_PSEUDO, AMDGPU::S_UADDO_PSEUDO},
1135 {AMDGPU::V_SUB_CO_U32_e64, AMDGPU::V_ADD_CO_U32_e64}};
1136 static const unsigned CarryOpcMap[2][2] = {
1137 {AMDGPU::S_SUB_CO_PSEUDO, AMDGPU::S_ADD_CO_PSEUDO},
1138 {AMDGPU::V_SUBB_U32_e64, AMDGPU::V_ADDC_U32_e64}};
1139
1140 bool IsVALU = N->isDivergent();
1141
1142 unsigned NoCarryOpc = NoCarryOpcMap[IsVALU][IsAdd];
1143 unsigned CarryOpc = CarryOpcMap[IsVALU][IsAdd];
1144 SDValue Clamp = CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i1);
1145
1146 SDNode *AddLo;
1147 if (!ConsumeCarry) {
1148 if (IsVALU) {
1149 SDValue Args[] = {SDValue(Lo0, 0), SDValue(Lo1, 0), Clamp};
1150 AddLo = CurDAG->getMachineNode(Opcode: NoCarryOpc, dl: DL, VTs: VTList, Ops: Args);
1151 } else {
1152 SDValue Args[] = {SDValue(Lo0, 0), SDValue(Lo1, 0)};
1153 AddLo = CurDAG->getMachineNode(Opcode: NoCarryOpc, dl: DL, VTs: VTList, Ops: Args);
1154 }
1155 } else {
1156 if (IsVALU) {
1157 SDValue Args[] = {SDValue(Lo0, 0), SDValue(Lo1, 0), N->getOperand(Num: 2),
1158 Clamp};
1159 AddLo = CurDAG->getMachineNode(Opcode: CarryOpc, dl: DL, VTs: VTList, Ops: Args);
1160 } else {
1161 SDValue Args[] = {SDValue(Lo0, 0), SDValue(Lo1, 0), N->getOperand(Num: 2)};
1162 AddLo = CurDAG->getMachineNode(Opcode: CarryOpc, dl: DL, VTs: VTList, Ops: Args);
1163 }
1164 }
1165
1166 SDNode *AddHi;
1167 if (IsVALU) {
1168 SDValue Args[] = {SDValue(Hi0, 0), SDValue(Hi1, 0), SDValue(AddLo, 1),
1169 Clamp};
1170 AddHi = CurDAG->getMachineNode(Opcode: CarryOpc, dl: DL, VTs: VTList, Ops: Args);
1171 } else {
1172 SDValue Args[] = {SDValue(Hi0, 0), SDValue(Hi1, 0), SDValue(AddLo, 1)};
1173 AddHi = CurDAG->getMachineNode(Opcode: CarryOpc, dl: DL, VTs: VTList, Ops: Args);
1174 }
1175
1176 unsigned RC = IsVALU ? AMDGPU::VReg_64RegClassID : AMDGPU::SReg_64RegClassID;
1177 SDValue RegSequenceArgs[] = {CurDAG->getTargetConstant(Val: RC, DL, VT: MVT::i32),
1178 SDValue(AddLo, 0), Sub0, SDValue(AddHi, 0),
1179 Sub1};
1180 SDNode *RegSequence = CurDAG->getMachineNode(Opcode: AMDGPU::REG_SEQUENCE, dl: DL,
1181 VT: MVT::i64, Ops: RegSequenceArgs);
1182
1183 ReplaceUses(F: SDValue(N, 1), T: SDValue(AddHi, 1));
1184 ReplaceNode(F: N, T: RegSequence);
1185}
1186
1187void AMDGPUDAGToDAGISel::SelectUADDO_USUBO(SDNode *N) {
1188 // The name of the opcodes are misleading. v_add_i32/v_sub_i32 have unsigned
1189 // carry out despite the _i32 name. These were renamed in VI to _U32.
1190 // FIXME: We should probably rename the opcodes here.
1191 bool IsAdd = N->getOpcode() == ISD::UADDO;
1192 bool IsVALU = N->isDivergent();
1193
1194 for (SDNode::user_iterator UI = N->user_begin(), E = N->user_end(); UI != E;
1195 ++UI)
1196 if (UI.getUse().getResNo() == 1) {
1197 if (UI->isMachineOpcode()) {
1198 if (UI->getMachineOpcode() !=
1199 (IsAdd ? AMDGPU::S_ADD_CO_PSEUDO : AMDGPU::S_SUB_CO_PSEUDO)) {
1200 IsVALU = true;
1201 break;
1202 }
1203 } else {
1204 if (UI->getOpcode() != (IsAdd ? ISD::UADDO_CARRY : ISD::USUBO_CARRY)) {
1205 IsVALU = true;
1206 break;
1207 }
1208 }
1209 }
1210
1211 if (IsVALU) {
1212 unsigned Opc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
1213
1214 CurDAG->SelectNodeTo(
1215 N, MachineOpc: Opc, VTs: N->getVTList(),
1216 Ops: {N->getOperand(Num: 0), N->getOperand(Num: 1),
1217 CurDAG->getTargetConstant(Val: 0, DL: {}, VT: MVT::i1) /*clamp bit*/});
1218 } else {
1219 unsigned Opc = IsAdd ? AMDGPU::S_UADDO_PSEUDO : AMDGPU::S_USUBO_PSEUDO;
1220
1221 CurDAG->SelectNodeTo(N, MachineOpc: Opc, VTs: N->getVTList(),
1222 Ops: {N->getOperand(Num: 0), N->getOperand(Num: 1)});
1223 }
1224}
1225
1226void AMDGPUDAGToDAGISel::SelectFMA_W_CHAIN(SDNode *N) {
1227 // src0_modifiers, src0, src1_modifiers, src1, src2_modifiers, src2, clamp, omod
1228 SDValue Ops[10];
1229
1230 SelectVOP3Mods0(In: N->getOperand(Num: 1), Src&: Ops[1], SrcMods&: Ops[0], Clamp&: Ops[6], Omod&: Ops[7]);
1231 SelectVOP3Mods(In: N->getOperand(Num: 2), Src&: Ops[3], SrcMods&: Ops[2]);
1232 SelectVOP3Mods(In: N->getOperand(Num: 3), Src&: Ops[5], SrcMods&: Ops[4]);
1233 Ops[8] = N->getOperand(Num: 0);
1234 Ops[9] = N->getOperand(Num: 4);
1235
1236 // If there are no source modifiers, prefer fmac over fma because it can use
1237 // the smaller VOP2 encoding.
1238 bool UseFMAC = Subtarget->hasDLInsts() &&
1239 cast<ConstantSDNode>(Val&: Ops[0])->isZero() &&
1240 cast<ConstantSDNode>(Val&: Ops[2])->isZero() &&
1241 cast<ConstantSDNode>(Val&: Ops[4])->isZero();
1242 unsigned Opcode = UseFMAC ? AMDGPU::V_FMAC_F32_e64 : AMDGPU::V_FMA_F32_e64;
1243 CurDAG->SelectNodeTo(N, MachineOpc: Opcode, VTs: N->getVTList(), Ops);
1244}
1245
1246void AMDGPUDAGToDAGISel::SelectFMUL_W_CHAIN(SDNode *N) {
1247 // src0_modifiers, src0, src1_modifiers, src1, clamp, omod
1248 SDValue Ops[8];
1249
1250 SelectVOP3Mods0(In: N->getOperand(Num: 1), Src&: Ops[1], SrcMods&: Ops[0], Clamp&: Ops[4], Omod&: Ops[5]);
1251 SelectVOP3Mods(In: N->getOperand(Num: 2), Src&: Ops[3], SrcMods&: Ops[2]);
1252 Ops[6] = N->getOperand(Num: 0);
1253 Ops[7] = N->getOperand(Num: 3);
1254
1255 CurDAG->SelectNodeTo(N, MachineOpc: AMDGPU::V_MUL_F32_e64, VTs: N->getVTList(), Ops);
1256}
1257
1258// We need to handle this here because tablegen doesn't support matching
1259// instructions with multiple outputs.
1260void AMDGPUDAGToDAGISel::SelectDIV_SCALE(SDNode *N) {
1261 EVT VT = N->getValueType(ResNo: 0);
1262
1263 assert(VT == MVT::f32 || VT == MVT::f64);
1264
1265 unsigned Opc
1266 = (VT == MVT::f64) ? AMDGPU::V_DIV_SCALE_F64_e64 : AMDGPU::V_DIV_SCALE_F32_e64;
1267
1268 // src0_modifiers, src0, src1_modifiers, src1, src2_modifiers, src2, clamp,
1269 // omod
1270 SDValue Ops[8];
1271 SelectVOP3BMods0(In: N->getOperand(Num: 0), Src&: Ops[1], SrcMods&: Ops[0], Clamp&: Ops[6], Omod&: Ops[7]);
1272 SelectVOP3BMods(In: N->getOperand(Num: 1), Src&: Ops[3], SrcMods&: Ops[2]);
1273 SelectVOP3BMods(In: N->getOperand(Num: 2), Src&: Ops[5], SrcMods&: Ops[4]);
1274 CurDAG->SelectNodeTo(N, MachineOpc: Opc, VTs: N->getVTList(), Ops);
1275}
1276
1277// We need to handle this here because tablegen doesn't support matching
1278// instructions with multiple outputs.
1279void AMDGPUDAGToDAGISel::SelectMAD_64_32(SDNode *N) {
1280 SDLoc SL(N);
1281 bool Signed = N->getOpcode() == AMDGPUISD::MAD_I64_I32;
1282 unsigned Opc;
1283 bool UseNoCarry = Subtarget->hasMadNC64_32Insts() && !N->hasAnyUseOfValue(Value: 1);
1284 if (Subtarget->hasMADIntraFwdBug())
1285 Opc = Signed ? AMDGPU::V_MAD_I64_I32_gfx11_e64
1286 : AMDGPU::V_MAD_U64_U32_gfx11_e64;
1287 else if (UseNoCarry)
1288 Opc = Signed ? AMDGPU::V_MAD_NC_I64_I32_e64 : AMDGPU::V_MAD_NC_U64_U32_e64;
1289 else
1290 Opc = Signed ? AMDGPU::V_MAD_I64_I32_e64 : AMDGPU::V_MAD_U64_U32_e64;
1291
1292 SDValue Clamp = CurDAG->getTargetConstant(Val: 0, DL: SL, VT: MVT::i1);
1293 SDValue Ops[] = { N->getOperand(Num: 0), N->getOperand(Num: 1), N->getOperand(Num: 2),
1294 Clamp };
1295
1296 if (UseNoCarry) {
1297 MachineSDNode *Mad = CurDAG->getMachineNode(Opcode: Opc, dl: SL, VT: MVT::i64, Ops);
1298 ReplaceUses(F: SDValue(N, 0), T: SDValue(Mad, 0));
1299 CurDAG->RemoveDeadNode(N);
1300 return;
1301 }
1302
1303 CurDAG->SelectNodeTo(N, MachineOpc: Opc, VTs: N->getVTList(), Ops);
1304}
1305
1306// We need to handle this here because tablegen doesn't support matching
1307// instructions with multiple outputs.
1308void AMDGPUDAGToDAGISel::SelectMUL_LOHI(SDNode *N) {
1309 SDLoc SL(N);
1310 bool Signed = N->getOpcode() == ISD::SMUL_LOHI;
1311 SDVTList VTList;
1312 unsigned Opc;
1313 if (Subtarget->hasMadNC64_32Insts()) {
1314 VTList = CurDAG->getVTList(VT: MVT::i64);
1315 Opc = Signed ? AMDGPU::V_MAD_NC_I64_I32_e64 : AMDGPU::V_MAD_NC_U64_U32_e64;
1316 } else {
1317 VTList = CurDAG->getVTList(VT1: MVT::i64, VT2: MVT::i1);
1318 if (Subtarget->hasMADIntraFwdBug()) {
1319 Opc = Signed ? AMDGPU::V_MAD_I64_I32_gfx11_e64
1320 : AMDGPU::V_MAD_U64_U32_gfx11_e64;
1321 } else {
1322 Opc = Signed ? AMDGPU::V_MAD_I64_I32_e64 : AMDGPU::V_MAD_U64_U32_e64;
1323 }
1324 }
1325
1326 SDValue Zero = CurDAG->getTargetConstant(Val: 0, DL: SL, VT: MVT::i64);
1327 SDValue Clamp = CurDAG->getTargetConstant(Val: 0, DL: SL, VT: MVT::i1);
1328 SDValue Ops[] = {N->getOperand(Num: 0), N->getOperand(Num: 1), Zero, Clamp};
1329 SDNode *Mad = CurDAG->getMachineNode(Opcode: Opc, dl: SL, VTs: VTList, Ops);
1330 if (!SDValue(N, 0).use_empty()) {
1331 SDValue Sub0 = CurDAG->getTargetConstant(Val: AMDGPU::sub0, DL: SL, VT: MVT::i32);
1332 SDNode *Lo = CurDAG->getMachineNode(Opcode: TargetOpcode::EXTRACT_SUBREG, dl: SL,
1333 VT: MVT::i32, Op1: SDValue(Mad, 0), Op2: Sub0);
1334 ReplaceUses(F: SDValue(N, 0), T: SDValue(Lo, 0));
1335 }
1336 if (!SDValue(N, 1).use_empty()) {
1337 SDValue Sub1 = CurDAG->getTargetConstant(Val: AMDGPU::sub1, DL: SL, VT: MVT::i32);
1338 SDNode *Hi = CurDAG->getMachineNode(Opcode: TargetOpcode::EXTRACT_SUBREG, dl: SL,
1339 VT: MVT::i32, Op1: SDValue(Mad, 0), Op2: Sub1);
1340 ReplaceUses(F: SDValue(N, 1), T: SDValue(Hi, 0));
1341 }
1342 CurDAG->RemoveDeadNode(N);
1343}
1344
1345bool AMDGPUDAGToDAGISel::isDSOffsetLegal(SDValue Base, unsigned Offset) const {
1346 if (!isUInt<16>(x: Offset))
1347 return false;
1348
1349 if (!Base || Subtarget->hasUsableDSOffset() ||
1350 Subtarget->unsafeDSOffsetFoldingEnabled())
1351 return true;
1352
1353 // On Southern Islands instruction with a negative base value and an offset
1354 // don't seem to work.
1355 return CurDAG->SignBitIsZero(Op: Base);
1356}
1357
1358bool AMDGPUDAGToDAGISel::SelectDS1Addr1Offset(SDValue Addr, SDValue &Base,
1359 SDValue &Offset) const {
1360 SDLoc DL(Addr);
1361 if (CurDAG->isBaseWithConstantOffset(Op: Addr)) {
1362 SDValue N0 = Addr.getOperand(i: 0);
1363 SDValue N1 = Addr.getOperand(i: 1);
1364 ConstantSDNode *C1 = cast<ConstantSDNode>(Val&: N1);
1365 if (isDSOffsetLegal(Base: N0, Offset: C1->getSExtValue())) {
1366 // (add n0, c0)
1367 Base = N0;
1368 Offset = CurDAG->getTargetConstant(Val: C1->getZExtValue(), DL, VT: MVT::i16);
1369 return true;
1370 }
1371 } else if (Addr.getOpcode() == ISD::SUB) {
1372 // sub C, x -> add (sub 0, x), C
1373 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val: Addr.getOperand(i: 0))) {
1374 int64_t ByteOffset = C->getSExtValue();
1375 if (isDSOffsetLegal(Base: SDValue(), Offset: ByteOffset)) {
1376 SDValue Zero = CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i32);
1377
1378 // XXX - This is kind of hacky. Create a dummy sub node so we can check
1379 // the known bits in isDSOffsetLegal. We need to emit the selected node
1380 // here, so this is thrown away.
1381 SDValue Sub = CurDAG->getNode(Opcode: ISD::SUB, DL, VT: MVT::i32,
1382 N1: Zero, N2: Addr.getOperand(i: 1));
1383
1384 if (isDSOffsetLegal(Base: Sub, Offset: ByteOffset)) {
1385 SmallVector<SDValue, 3> Opnds;
1386 Opnds.push_back(Elt: Zero);
1387 Opnds.push_back(Elt: Addr.getOperand(i: 1));
1388
1389 // FIXME: Select to VOP3 version for with-carry.
1390 unsigned SubOp = AMDGPU::V_SUB_CO_U32_e32;
1391 if (Subtarget->hasAddNoCarryInsts()) {
1392 SubOp = AMDGPU::V_SUB_U32_e64;
1393 Opnds.push_back(
1394 Elt: CurDAG->getTargetConstant(Val: 0, DL: {}, VT: MVT::i1)); // clamp bit
1395 }
1396
1397 MachineSDNode *MachineSub =
1398 CurDAG->getMachineNode(Opcode: SubOp, dl: DL, VT: MVT::i32, Ops: Opnds);
1399
1400 Base = SDValue(MachineSub, 0);
1401 Offset = CurDAG->getTargetConstant(Val: ByteOffset, DL, VT: MVT::i16);
1402 return true;
1403 }
1404 }
1405 }
1406 } else if (const ConstantSDNode *CAddr = dyn_cast<ConstantSDNode>(Val&: Addr)) {
1407 // If we have a constant address, prefer to put the constant into the
1408 // offset. This can save moves to load the constant address since multiple
1409 // operations can share the zero base address register, and enables merging
1410 // into read2 / write2 instructions.
1411
1412 SDLoc DL(Addr);
1413
1414 if (isDSOffsetLegal(Base: SDValue(), Offset: CAddr->getZExtValue())) {
1415 SDValue Zero = CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i32);
1416 MachineSDNode *MovZero = CurDAG->getMachineNode(Opcode: AMDGPU::V_MOV_B32_e32,
1417 dl: DL, VT: MVT::i32, Op1: Zero);
1418 Base = SDValue(MovZero, 0);
1419 Offset = CurDAG->getTargetConstant(Val: CAddr->getZExtValue(), DL, VT: MVT::i16);
1420 return true;
1421 }
1422 }
1423
1424 // default case
1425 Base = Addr;
1426 Offset = CurDAG->getTargetConstant(Val: 0, DL: SDLoc(Addr), VT: MVT::i16);
1427 return true;
1428}
1429
1430bool AMDGPUDAGToDAGISel::isDSOffset2Legal(SDValue Base, unsigned Offset0,
1431 unsigned Offset1,
1432 unsigned Size) const {
1433 if (Offset0 % Size != 0 || Offset1 % Size != 0)
1434 return false;
1435 if (!isUInt<8>(x: Offset0 / Size) || !isUInt<8>(x: Offset1 / Size))
1436 return false;
1437
1438 if (!Base || Subtarget->hasUsableDSOffset() ||
1439 Subtarget->unsafeDSOffsetFoldingEnabled())
1440 return true;
1441
1442 // On Southern Islands instruction with a negative base value and an offset
1443 // don't seem to work.
1444 return CurDAG->SignBitIsZero(Op: Base);
1445}
1446
1447// Return whether the operation has NoUnsignedWrap property.
1448static bool isNoUnsignedWrap(SDValue Addr) {
1449 return (Addr.getOpcode() == ISD::ADD &&
1450 Addr->getFlags().hasNoUnsignedWrap()) ||
1451 Addr->getOpcode() == ISD::OR;
1452}
1453
1454// Check that the base address of flat scratch load/store in the form of `base +
1455// offset` is legal to be put in SGPR/VGPR (i.e. unsigned per hardware
1456// requirement). We always treat the first operand as the base address here.
1457bool AMDGPUDAGToDAGISel::isFlatScratchBaseLegal(SDValue Addr) const {
1458 if (isNoUnsignedWrap(Addr))
1459 return true;
1460
1461 // Starting with GFX12, VADDR and SADDR fields in VSCRATCH can use negative
1462 // values.
1463 if (Subtarget->hasSignedScratchOffsets())
1464 return true;
1465
1466 auto LHS = Addr.getOperand(i: 0);
1467 auto RHS = Addr.getOperand(i: 1);
1468
1469 // If the immediate offset is negative and within certain range, the base
1470 // address cannot also be negative. If the base is also negative, the sum
1471 // would be either negative or much larger than the valid range of scratch
1472 // memory a thread can access.
1473 ConstantSDNode *ImmOp = nullptr;
1474 if (Addr.getOpcode() == ISD::ADD && (ImmOp = dyn_cast<ConstantSDNode>(Val&: RHS))) {
1475 if (ImmOp->getSExtValue() < 0 && ImmOp->getSExtValue() > -0x40000000)
1476 return true;
1477 }
1478
1479 return CurDAG->SignBitIsZero(Op: LHS);
1480}
1481
1482// Check address value in SGPR/VGPR are legal for flat scratch in the form
1483// of: SGPR + VGPR.
1484bool AMDGPUDAGToDAGISel::isFlatScratchBaseLegalSV(SDValue Addr) const {
1485 if (isNoUnsignedWrap(Addr))
1486 return true;
1487
1488 // Starting with GFX12, VADDR and SADDR fields in VSCRATCH can use negative
1489 // values.
1490 if (Subtarget->hasSignedScratchOffsets())
1491 return true;
1492
1493 auto LHS = Addr.getOperand(i: 0);
1494 auto RHS = Addr.getOperand(i: 1);
1495 return CurDAG->SignBitIsZero(Op: RHS) && CurDAG->SignBitIsZero(Op: LHS);
1496}
1497
1498// Check address value in SGPR/VGPR are legal for flat scratch in the form
1499// of: SGPR + VGPR + Imm.
1500bool AMDGPUDAGToDAGISel::isFlatScratchBaseLegalSVImm(SDValue Addr) const {
1501 // Starting with GFX12, VADDR and SADDR fields in VSCRATCH can use negative
1502 // values.
1503 if (AMDGPU::isGFX12Plus(STI: *Subtarget))
1504 return true;
1505
1506 auto Base = Addr.getOperand(i: 0);
1507 auto *RHSImm = cast<ConstantSDNode>(Val: Addr.getOperand(i: 1));
1508 // If the immediate offset is negative and within certain range, the base
1509 // address cannot also be negative. If the base is also negative, the sum
1510 // would be either negative or much larger than the valid range of scratch
1511 // memory a thread can access.
1512 if (isNoUnsignedWrap(Addr: Base) &&
1513 (isNoUnsignedWrap(Addr) ||
1514 (RHSImm->getSExtValue() < 0 && RHSImm->getSExtValue() > -0x40000000)))
1515 return true;
1516
1517 auto LHS = Base.getOperand(i: 0);
1518 auto RHS = Base.getOperand(i: 1);
1519 return CurDAG->SignBitIsZero(Op: RHS) && CurDAG->SignBitIsZero(Op: LHS);
1520}
1521
1522// TODO: If offset is too big, put low 16-bit into offset.
1523bool AMDGPUDAGToDAGISel::SelectDS64Bit4ByteAligned(SDValue Addr, SDValue &Base,
1524 SDValue &Offset0,
1525 SDValue &Offset1) const {
1526 return SelectDSReadWrite2(Ptr: Addr, Base, Offset0, Offset1, Size: 4);
1527}
1528
1529bool AMDGPUDAGToDAGISel::SelectDS128Bit8ByteAligned(SDValue Addr, SDValue &Base,
1530 SDValue &Offset0,
1531 SDValue &Offset1) const {
1532 return SelectDSReadWrite2(Ptr: Addr, Base, Offset0, Offset1, Size: 8);
1533}
1534
1535bool AMDGPUDAGToDAGISel::SelectDSReadWrite2(SDValue Addr, SDValue &Base,
1536 SDValue &Offset0, SDValue &Offset1,
1537 unsigned Size) const {
1538 SDLoc DL(Addr);
1539
1540 if (CurDAG->isBaseWithConstantOffset(Op: Addr)) {
1541 SDValue N0 = Addr.getOperand(i: 0);
1542 SDValue N1 = Addr.getOperand(i: 1);
1543 ConstantSDNode *C1 = cast<ConstantSDNode>(Val&: N1);
1544 unsigned OffsetValue0 = C1->getZExtValue();
1545 unsigned OffsetValue1 = OffsetValue0 + Size;
1546
1547 // (add n0, c0)
1548 if (isDSOffset2Legal(Base: N0, Offset0: OffsetValue0, Offset1: OffsetValue1, Size)) {
1549 Base = N0;
1550 Offset0 = CurDAG->getTargetConstant(Val: OffsetValue0 / Size, DL, VT: MVT::i32);
1551 Offset1 = CurDAG->getTargetConstant(Val: OffsetValue1 / Size, DL, VT: MVT::i32);
1552 return true;
1553 }
1554 } else if (Addr.getOpcode() == ISD::SUB) {
1555 // sub C, x -> add (sub 0, x), C
1556 if (const ConstantSDNode *C =
1557 dyn_cast<ConstantSDNode>(Val: Addr.getOperand(i: 0))) {
1558 unsigned OffsetValue0 = C->getZExtValue();
1559 unsigned OffsetValue1 = OffsetValue0 + Size;
1560
1561 if (isDSOffset2Legal(Base: SDValue(), Offset0: OffsetValue0, Offset1: OffsetValue1, Size)) {
1562 SDLoc DL(Addr);
1563 SDValue Zero = CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i32);
1564
1565 // XXX - This is kind of hacky. Create a dummy sub node so we can check
1566 // the known bits in isDSOffsetLegal. We need to emit the selected node
1567 // here, so this is thrown away.
1568 SDValue Sub =
1569 CurDAG->getNode(Opcode: ISD::SUB, DL, VT: MVT::i32, N1: Zero, N2: Addr.getOperand(i: 1));
1570
1571 if (isDSOffset2Legal(Base: Sub, Offset0: OffsetValue0, Offset1: OffsetValue1, Size)) {
1572 SmallVector<SDValue, 3> Opnds;
1573 Opnds.push_back(Elt: Zero);
1574 Opnds.push_back(Elt: Addr.getOperand(i: 1));
1575 unsigned SubOp = AMDGPU::V_SUB_CO_U32_e32;
1576 if (Subtarget->hasAddNoCarryInsts()) {
1577 SubOp = AMDGPU::V_SUB_U32_e64;
1578 Opnds.push_back(
1579 Elt: CurDAG->getTargetConstant(Val: 0, DL: {}, VT: MVT::i1)); // clamp bit
1580 }
1581
1582 MachineSDNode *MachineSub = CurDAG->getMachineNode(
1583 Opcode: SubOp, dl: DL, VT: MVT::getIntegerVT(BitWidth: Size * 8), Ops: Opnds);
1584
1585 Base = SDValue(MachineSub, 0);
1586 Offset0 =
1587 CurDAG->getTargetConstant(Val: OffsetValue0 / Size, DL, VT: MVT::i32);
1588 Offset1 =
1589 CurDAG->getTargetConstant(Val: OffsetValue1 / Size, DL, VT: MVT::i32);
1590 return true;
1591 }
1592 }
1593 }
1594 } else if (const ConstantSDNode *CAddr = dyn_cast<ConstantSDNode>(Val&: Addr)) {
1595 unsigned OffsetValue0 = CAddr->getZExtValue();
1596 unsigned OffsetValue1 = OffsetValue0 + Size;
1597
1598 if (isDSOffset2Legal(Base: SDValue(), Offset0: OffsetValue0, Offset1: OffsetValue1, Size)) {
1599 SDValue Zero = CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i32);
1600 MachineSDNode *MovZero =
1601 CurDAG->getMachineNode(Opcode: AMDGPU::V_MOV_B32_e32, dl: DL, VT: MVT::i32, Op1: Zero);
1602 Base = SDValue(MovZero, 0);
1603 Offset0 = CurDAG->getTargetConstant(Val: OffsetValue0 / Size, DL, VT: MVT::i32);
1604 Offset1 = CurDAG->getTargetConstant(Val: OffsetValue1 / Size, DL, VT: MVT::i32);
1605 return true;
1606 }
1607 }
1608
1609 // default case
1610
1611 Base = Addr;
1612 Offset0 = CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i32);
1613 Offset1 = CurDAG->getTargetConstant(Val: 1, DL, VT: MVT::i32);
1614 return true;
1615}
1616
1617bool AMDGPUDAGToDAGISel::SelectMUBUF(SDValue Addr, SDValue &Ptr, SDValue &VAddr,
1618 SDValue &SOffset, SDValue &Offset,
1619 SDValue &Offen, SDValue &Idxen,
1620 SDValue &Addr64) const {
1621 // Subtarget prefers to use flat instruction
1622 // FIXME: This should be a pattern predicate and not reach here
1623 if (Subtarget->useFlatForGlobal())
1624 return false;
1625
1626 SDLoc DL(Addr);
1627
1628 Idxen = CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i1);
1629 Offen = CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i1);
1630 Addr64 = CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i1);
1631 SOffset = Subtarget->hasRestrictedSOffset()
1632 ? CurDAG->getRegister(Reg: AMDGPU::SGPR_NULL, VT: MVT::i32)
1633 : CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i32);
1634
1635 ConstantSDNode *C1 = nullptr;
1636 SDValue N0 = Addr;
1637 if (CurDAG->isBaseWithConstantOffset(Op: Addr)) {
1638 C1 = cast<ConstantSDNode>(Val: Addr.getOperand(i: 1));
1639 if (isUInt<32>(x: C1->getZExtValue()))
1640 N0 = Addr.getOperand(i: 0);
1641 else
1642 C1 = nullptr;
1643 }
1644
1645 if (N0->isAnyAdd()) {
1646 // (add N2, N3) -> addr64, or
1647 // (add (add N2, N3), C1) -> addr64
1648 SDValue N2 = N0.getOperand(i: 0);
1649 SDValue N3 = N0.getOperand(i: 1);
1650 Addr64 = CurDAG->getTargetConstant(Val: 1, DL, VT: MVT::i1);
1651
1652 if (N2->isDivergent()) {
1653 if (N3->isDivergent()) {
1654 // Both N2 and N3 are divergent. Use N0 (the result of the add) as the
1655 // addr64, and construct the resource from a 0 address.
1656 Ptr = SDValue(buildSMovImm64(DL, Imm: 0, VT: MVT::v2i32), 0);
1657 VAddr = N0;
1658 } else {
1659 // N2 is divergent, N3 is not.
1660 Ptr = N3;
1661 VAddr = N2;
1662 }
1663 } else {
1664 // N2 is not divergent.
1665 Ptr = N2;
1666 VAddr = N3;
1667 }
1668 Offset = CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i32);
1669 } else if (N0->isDivergent()) {
1670 // N0 is divergent. Use it as the addr64, and construct the resource from a
1671 // 0 address.
1672 Ptr = SDValue(buildSMovImm64(DL, Imm: 0, VT: MVT::v2i32), 0);
1673 VAddr = N0;
1674 Addr64 = CurDAG->getTargetConstant(Val: 1, DL, VT: MVT::i1);
1675 } else {
1676 // N0 -> offset, or
1677 // (N0 + C1) -> offset
1678 VAddr = CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i32);
1679 Ptr = N0;
1680 }
1681
1682 if (!C1) {
1683 // No offset.
1684 Offset = CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i32);
1685 return true;
1686 }
1687
1688 const SIInstrInfo *TII = Subtarget->getInstrInfo();
1689 if (TII->isLegalMUBUFImmOffset(Imm: C1->getZExtValue())) {
1690 // Legal offset for instruction.
1691 Offset = CurDAG->getTargetConstant(Val: C1->getZExtValue(), DL, VT: MVT::i32);
1692 return true;
1693 }
1694
1695 // Illegal offset, store it in soffset.
1696 Offset = CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i32);
1697 SOffset =
1698 SDValue(CurDAG->getMachineNode(
1699 Opcode: AMDGPU::S_MOV_B32, dl: DL, VT: MVT::i32,
1700 Op1: CurDAG->getTargetConstant(Val: C1->getZExtValue(), DL, VT: MVT::i32)),
1701 0);
1702 return true;
1703}
1704
1705bool AMDGPUDAGToDAGISel::SelectMUBUFAddr64(SDValue Addr, SDValue &SRsrc,
1706 SDValue &VAddr, SDValue &SOffset,
1707 SDValue &Offset) const {
1708 SDValue Ptr, Offen, Idxen, Addr64;
1709
1710 // addr64 bit was removed for volcanic islands.
1711 // FIXME: This should be a pattern predicate and not reach here
1712 if (!Subtarget->hasAddr64())
1713 return false;
1714
1715 if (!SelectMUBUF(Addr, Ptr, VAddr, SOffset, Offset, Offen, Idxen, Addr64))
1716 return false;
1717
1718 ConstantSDNode *C = cast<ConstantSDNode>(Val&: Addr64);
1719 if (C->getSExtValue()) {
1720 SDLoc DL(Addr);
1721
1722 const SITargetLowering& Lowering =
1723 *static_cast<const SITargetLowering*>(getTargetLowering());
1724
1725 SRsrc = SDValue(Lowering.wrapAddr64Rsrc(DAG&: *CurDAG, DL, Ptr), 0);
1726 return true;
1727 }
1728
1729 return false;
1730}
1731
1732std::pair<SDValue, SDValue> AMDGPUDAGToDAGISel::foldFrameIndex(SDValue N) const {
1733 SDLoc DL(N);
1734
1735 auto *FI = dyn_cast<FrameIndexSDNode>(Val&: N);
1736 SDValue TFI =
1737 FI ? CurDAG->getTargetFrameIndex(FI: FI->getIndex(), VT: FI->getValueType(ResNo: 0)) : N;
1738
1739 // We rebase the base address into an absolute stack address and hence
1740 // use constant 0 for soffset. This value must be retained until
1741 // frame elimination and eliminateFrameIndex will choose the appropriate
1742 // frame register if need be.
1743 return std::pair(TFI, CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i32));
1744}
1745
1746bool AMDGPUDAGToDAGISel::SelectMUBUFScratchOffen(SDNode *Parent,
1747 SDValue Addr, SDValue &Rsrc,
1748 SDValue &VAddr, SDValue &SOffset,
1749 SDValue &ImmOffset) const {
1750
1751 SDLoc DL(Addr);
1752 MachineFunction &MF = CurDAG->getMachineFunction();
1753 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1754
1755 Rsrc = CurDAG->getRegister(Reg: Info->getScratchRSrcReg(), VT: MVT::v4i32);
1756
1757 if (ConstantSDNode *CAddr = dyn_cast<ConstantSDNode>(Val&: Addr)) {
1758 int64_t Imm = CAddr->getSExtValue();
1759 const int64_t NullPtr =
1760 AMDGPU::getNullPointerValue(AS: AMDGPUAS::PRIVATE_ADDRESS);
1761 // Don't fold null pointer.
1762 if (Imm != NullPtr) {
1763 const int64_t MaxOffset = SIInstrInfo::getMaxMUBUFImmOffset(ST: *Subtarget);
1764 SDValue HighBits =
1765 CurDAG->getTargetConstant(Val: Imm & ~MaxOffset, DL, VT: MVT::i32);
1766 MachineSDNode *MovHighBits = CurDAG->getMachineNode(
1767 Opcode: AMDGPU::V_MOV_B32_e32, dl: DL, VT: MVT::i32, Op1: HighBits);
1768 VAddr = SDValue(MovHighBits, 0);
1769
1770 SOffset = CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i32);
1771 ImmOffset = CurDAG->getTargetConstant(Val: Imm & MaxOffset, DL, VT: MVT::i32);
1772 return true;
1773 }
1774 }
1775
1776 if (CurDAG->isBaseWithConstantOffset(Op: Addr)) {
1777 // (add n0, c1)
1778
1779 SDValue N0 = Addr.getOperand(i: 0);
1780 uint64_t C1 = Addr.getConstantOperandVal(i: 1);
1781
1782 // Offsets in vaddr must be positive if range checking is enabled.
1783 //
1784 // The total computation of vaddr + soffset + offset must not overflow. If
1785 // vaddr is negative, even if offset is 0 the sgpr offset add will end up
1786 // overflowing.
1787 //
1788 // Prior to gfx9, MUBUF instructions with the vaddr offset enabled would
1789 // always perform a range check. If a negative vaddr base index was used,
1790 // this would fail the range check. The overall address computation would
1791 // compute a valid address, but this doesn't happen due to the range
1792 // check. For out-of-bounds MUBUF loads, a 0 is returned.
1793 //
1794 // Therefore it should be safe to fold any VGPR offset on gfx9 into the
1795 // MUBUF vaddr, but not on older subtargets which can only do this if the
1796 // sign bit is known 0.
1797 const SIInstrInfo *TII = Subtarget->getInstrInfo();
1798 if (TII->isLegalMUBUFImmOffset(Imm: C1) &&
1799 (!Subtarget->privateMemoryResourceIsRangeChecked() ||
1800 CurDAG->SignBitIsZero(Op: N0))) {
1801 std::tie(args&: VAddr, args&: SOffset) = foldFrameIndex(N: N0);
1802 ImmOffset = CurDAG->getTargetConstant(Val: C1, DL, VT: MVT::i32);
1803 return true;
1804 }
1805 }
1806
1807 // (node)
1808 std::tie(args&: VAddr, args&: SOffset) = foldFrameIndex(N: Addr);
1809 ImmOffset = CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i32);
1810 return true;
1811}
1812
1813static bool IsCopyFromSGPR(const SIRegisterInfo &TRI, SDValue Val) {
1814 if (Val.getOpcode() != ISD::CopyFromReg)
1815 return false;
1816 auto Reg = cast<RegisterSDNode>(Val: Val.getOperand(i: 1))->getReg();
1817 if (!Reg.isPhysical())
1818 return false;
1819 const auto *RC = TRI.getPhysRegBaseClass(Reg);
1820 return RC && TRI.isSGPRClass(RC);
1821}
1822
1823bool AMDGPUDAGToDAGISel::SelectMUBUFScratchOffset(SDNode *Parent,
1824 SDValue Addr,
1825 SDValue &SRsrc,
1826 SDValue &SOffset,
1827 SDValue &Offset) const {
1828 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
1829 const SIInstrInfo *TII = Subtarget->getInstrInfo();
1830 MachineFunction &MF = CurDAG->getMachineFunction();
1831 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1832 SDLoc DL(Addr);
1833
1834 // CopyFromReg <sgpr>
1835 if (IsCopyFromSGPR(TRI: *TRI, Val: Addr)) {
1836 SRsrc = CurDAG->getRegister(Reg: Info->getScratchRSrcReg(), VT: MVT::v4i32);
1837 SOffset = Addr;
1838 Offset = CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i32);
1839 return true;
1840 }
1841
1842 ConstantSDNode *CAddr;
1843 if (Addr.getOpcode() == ISD::ADD) {
1844 // Add (CopyFromReg <sgpr>) <constant>
1845 CAddr = dyn_cast<ConstantSDNode>(Val: Addr.getOperand(i: 1));
1846 if (!CAddr || !TII->isLegalMUBUFImmOffset(Imm: CAddr->getZExtValue()))
1847 return false;
1848 if (!IsCopyFromSGPR(TRI: *TRI, Val: Addr.getOperand(i: 0)))
1849 return false;
1850
1851 SOffset = Addr.getOperand(i: 0);
1852 } else if ((CAddr = dyn_cast<ConstantSDNode>(Val&: Addr)) &&
1853 TII->isLegalMUBUFImmOffset(Imm: CAddr->getZExtValue())) {
1854 // <constant>
1855 SOffset = CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i32);
1856 } else {
1857 return false;
1858 }
1859
1860 SRsrc = CurDAG->getRegister(Reg: Info->getScratchRSrcReg(), VT: MVT::v4i32);
1861
1862 Offset = CurDAG->getTargetConstant(Val: CAddr->getZExtValue(), DL, VT: MVT::i32);
1863 return true;
1864}
1865
1866bool AMDGPUDAGToDAGISel::SelectMUBUFOffset(SDValue Addr, SDValue &SRsrc,
1867 SDValue &SOffset, SDValue &Offset
1868 ) const {
1869 SDValue Ptr, VAddr, Offen, Idxen, Addr64;
1870 const SIInstrInfo *TII = Subtarget->getInstrInfo();
1871
1872 if (!SelectMUBUF(Addr, Ptr, VAddr, SOffset, Offset, Offen, Idxen, Addr64))
1873 return false;
1874
1875 if (!cast<ConstantSDNode>(Val&: Offen)->getSExtValue() &&
1876 !cast<ConstantSDNode>(Val&: Idxen)->getSExtValue() &&
1877 !cast<ConstantSDNode>(Val&: Addr64)->getSExtValue()) {
1878 uint64_t Rsrc = TII->getDefaultRsrcDataFormat() |
1879 maskTrailingOnes<uint64_t>(N: 32); // Size
1880 SDLoc DL(Addr);
1881
1882 const SITargetLowering& Lowering =
1883 *static_cast<const SITargetLowering*>(getTargetLowering());
1884
1885 SRsrc = SDValue(Lowering.buildRSRC(DAG&: *CurDAG, DL, Ptr, RsrcDword1: 0, RsrcDword2And3: Rsrc), 0);
1886 return true;
1887 }
1888 return false;
1889}
1890
1891bool AMDGPUDAGToDAGISel::SelectBUFSOffset(SDValue ByteOffsetNode,
1892 SDValue &SOffset) const {
1893 if (Subtarget->hasRestrictedSOffset() && isNullConstant(V: ByteOffsetNode)) {
1894 SOffset = CurDAG->getRegister(Reg: AMDGPU::SGPR_NULL, VT: MVT::i32);
1895 return true;
1896 }
1897
1898 SOffset = ByteOffsetNode;
1899 return true;
1900}
1901
1902// Find a load or store from corresponding pattern root.
1903// Roots may be build_vector, bitconvert or their combinations.
1904static MemSDNode* findMemSDNode(SDNode *N) {
1905 N = AMDGPUTargetLowering::stripBitcast(Val: SDValue(N,0)).getNode();
1906 if (MemSDNode *MN = dyn_cast<MemSDNode>(Val: N))
1907 return MN;
1908 assert(isa<BuildVectorSDNode>(N));
1909 for (SDValue V : N->op_values())
1910 if (MemSDNode *MN =
1911 dyn_cast<MemSDNode>(Val: AMDGPUTargetLowering::stripBitcast(Val: V)))
1912 return MN;
1913 llvm_unreachable("cannot find MemSDNode in the pattern!");
1914}
1915
1916bool AMDGPUDAGToDAGISel::SelectFlatOffsetImpl(
1917 SDNode *N, SDValue Addr, SDValue &VAddr, SDValue &Offset,
1918 AMDGPU::FlatAddrSpace FlatVariant) const {
1919 using AMDGPU::FlatAddrSpace;
1920 int64_t OffsetVal = 0;
1921
1922 unsigned AS = findMemSDNode(N)->getAddressSpace();
1923
1924 bool CanHaveFlatSegmentOffsetBug =
1925 Subtarget->hasFlatSegmentOffsetBug() &&
1926 FlatVariant == FlatAddrSpace::FLAT &&
1927 (AS == AMDGPUAS::FLAT_ADDRESS || AS == AMDGPUAS::GLOBAL_ADDRESS);
1928
1929 if (Subtarget->hasFlatInstOffsets() && !CanHaveFlatSegmentOffsetBug) {
1930 SDValue N0, N1;
1931 if (isBaseWithConstantOffset64(Addr, LHS&: N0, RHS&: N1) &&
1932 (FlatVariant != FlatAddrSpace::FlatScratch ||
1933 isFlatScratchBaseLegal(Addr))) {
1934 int64_t COffsetVal = cast<ConstantSDNode>(Val&: N1)->getSExtValue();
1935
1936 // Adding the offset to the base address in a FLAT instruction must not
1937 // change the memory aperture in which the address falls. Therefore we can
1938 // only fold offsets from inbounds GEPs into FLAT instructions.
1939 bool IsInBounds =
1940 Addr.getOpcode() == ISD::PTRADD && Addr->getFlags().hasInBounds();
1941 if (COffsetVal == 0 || FlatVariant != FlatAddrSpace::FLAT || IsInBounds) {
1942 const SIInstrInfo *TII = Subtarget->getInstrInfo();
1943 if (TII->isLegalFLATOffset(Offset: COffsetVal, AddrSpace: AS, FlatVariant)) {
1944 Addr = N0;
1945 OffsetVal = COffsetVal;
1946 } else {
1947 // If the offset doesn't fit, put the low bits into the offset field
1948 // and add the rest.
1949 //
1950 // For a FLAT instruction the hardware decides whether to access
1951 // global/scratch/shared memory based on the high bits of vaddr,
1952 // ignoring the offset field, so we have to ensure that when we add
1953 // remainder to vaddr it still points into the same underlying object.
1954 // The easiest way to do that is to make sure that we split the offset
1955 // into two pieces that are both >= 0 or both <= 0.
1956
1957 SDLoc DL(N);
1958 uint64_t RemainderOffset;
1959
1960 std::tie(args&: OffsetVal, args&: RemainderOffset) =
1961 TII->splitFlatOffset(COffsetVal, AddrSpace: AS, FlatVariant);
1962
1963 SDValue AddOffsetLo =
1964 getMaterializedScalarImm32(Val: Lo_32(Value: RemainderOffset), DL);
1965 SDValue Clamp = CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i1);
1966
1967 if (Addr.getValueType().getSizeInBits() == 32) {
1968 SmallVector<SDValue, 3> Opnds;
1969 Opnds.push_back(Elt: N0);
1970 Opnds.push_back(Elt: AddOffsetLo);
1971 unsigned AddOp = AMDGPU::V_ADD_CO_U32_e32;
1972 if (Subtarget->hasAddNoCarryInsts()) {
1973 AddOp = AMDGPU::V_ADD_U32_e64;
1974 Opnds.push_back(Elt: Clamp);
1975 }
1976 Addr =
1977 SDValue(CurDAG->getMachineNode(Opcode: AddOp, dl: DL, VT: MVT::i32, Ops: Opnds), 0);
1978 } else {
1979 // TODO: Should this try to use a scalar add pseudo if the base
1980 // address is uniform and saddr is usable?
1981 SDValue Sub0 =
1982 CurDAG->getTargetConstant(Val: AMDGPU::sub0, DL, VT: MVT::i32);
1983 SDValue Sub1 =
1984 CurDAG->getTargetConstant(Val: AMDGPU::sub1, DL, VT: MVT::i32);
1985
1986 SDNode *N0Lo = CurDAG->getMachineNode(Opcode: TargetOpcode::EXTRACT_SUBREG,
1987 dl: DL, VT: MVT::i32, Op1: N0, Op2: Sub0);
1988 SDNode *N0Hi = CurDAG->getMachineNode(Opcode: TargetOpcode::EXTRACT_SUBREG,
1989 dl: DL, VT: MVT::i32, Op1: N0, Op2: Sub1);
1990
1991 SDValue AddOffsetHi =
1992 getMaterializedScalarImm32(Val: Hi_32(Value: RemainderOffset), DL);
1993
1994 SDVTList VTs = CurDAG->getVTList(VT1: MVT::i32, VT2: MVT::i1);
1995
1996 SDNode *Add =
1997 CurDAG->getMachineNode(Opcode: AMDGPU::V_ADD_CO_U32_e64, dl: DL, VTs,
1998 Ops: {AddOffsetLo, SDValue(N0Lo, 0), Clamp});
1999
2000 SDNode *Addc = CurDAG->getMachineNode(
2001 Opcode: AMDGPU::V_ADDC_U32_e64, dl: DL, VTs,
2002 Ops: {AddOffsetHi, SDValue(N0Hi, 0), SDValue(Add, 1), Clamp});
2003
2004 SDValue RegSequenceArgs[] = {
2005 CurDAG->getTargetConstant(Val: AMDGPU::VReg_64RegClassID, DL,
2006 VT: MVT::i32),
2007 SDValue(Add, 0), Sub0, SDValue(Addc, 0), Sub1};
2008
2009 Addr = SDValue(CurDAG->getMachineNode(Opcode: AMDGPU::REG_SEQUENCE, dl: DL,
2010 VT: MVT::i64, Ops: RegSequenceArgs),
2011 0);
2012 }
2013 }
2014 }
2015 }
2016 }
2017
2018 VAddr = Addr;
2019 Offset = CurDAG->getSignedTargetConstant(Val: OffsetVal, DL: SDLoc(), VT: MVT::i32);
2020 return true;
2021}
2022
2023bool AMDGPUDAGToDAGISel::SelectFlatOffset(SDNode *N, SDValue Addr,
2024 SDValue &VAddr,
2025 SDValue &Offset) const {
2026 return SelectFlatOffsetImpl(N, Addr, VAddr, Offset,
2027 FlatVariant: AMDGPU::FlatAddrSpace::FLAT);
2028}
2029
2030bool AMDGPUDAGToDAGISel::SelectGlobalOffset(SDNode *N, SDValue Addr,
2031 SDValue &VAddr,
2032 SDValue &Offset) const {
2033 return SelectFlatOffsetImpl(N, Addr, VAddr, Offset,
2034 FlatVariant: AMDGPU::FlatAddrSpace::FlatGlobal);
2035}
2036
2037bool AMDGPUDAGToDAGISel::SelectScratchOffset(SDNode *N, SDValue Addr,
2038 SDValue &VAddr,
2039 SDValue &Offset) const {
2040 return SelectFlatOffsetImpl(N, Addr, VAddr, Offset,
2041 FlatVariant: AMDGPU::FlatAddrSpace::FlatScratch);
2042}
2043
2044// If this matches *_extend i32:x, return x
2045// Otherwise if the value is I32 returns x.
2046static SDValue matchExtFromI32orI32(SDValue Op, bool IsSigned,
2047 const SelectionDAG *DAG) {
2048 if (Op.getValueType() == MVT::i32)
2049 return Op;
2050
2051 if (Op.getOpcode() != (IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND) &&
2052 Op.getOpcode() != ISD::ANY_EXTEND &&
2053 !(Op.getOpcode() == (IsSigned ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND) &&
2054 DAG->SignBitIsZero(Op: Op.getOperand(i: 0))))
2055 return SDValue();
2056
2057 SDValue ExtSrc = Op.getOperand(i: 0);
2058 return (ExtSrc.getValueType() == MVT::i32) ? ExtSrc : SDValue();
2059}
2060
2061// Match (64-bit SGPR base) + (zext vgpr offset) + sext(imm offset)
2062// or (64-bit SGPR base) + (sext vgpr offset) + sext(imm offset)
2063bool AMDGPUDAGToDAGISel::SelectGlobalSAddr(SDNode *N, SDValue Addr,
2064 SDValue &SAddr, SDValue &VOffset,
2065 SDValue &Offset, bool &ScaleOffset,
2066 bool NeedIOffset) const {
2067 using AMDGPU::FlatAddrSpace;
2068 int64_t ImmOffset = 0;
2069 ScaleOffset = false;
2070
2071 // Match the immediate offset first, which canonically is moved as low as
2072 // possible.
2073
2074 SDValue LHS, RHS;
2075 if (isBaseWithConstantOffset64(Addr, LHS, RHS)) {
2076 int64_t COffsetVal = cast<ConstantSDNode>(Val&: RHS)->getSExtValue();
2077 const SIInstrInfo *TII = Subtarget->getInstrInfo();
2078
2079 if (NeedIOffset &&
2080 TII->isLegalFLATOffset(Offset: COffsetVal, AddrSpace: AMDGPUAS::GLOBAL_ADDRESS,
2081 FlatVariant: FlatAddrSpace::FlatGlobal)) {
2082 Addr = LHS;
2083 ImmOffset = COffsetVal;
2084 } else if (!LHS->isDivergent()) {
2085 if (COffsetVal != 0) {
2086 SDLoc SL(N);
2087 // saddr + large_offset -> saddr +
2088 // (voffset = large_offset & ~MaxOffset) +
2089 // (large_offset & MaxOffset);
2090 int64_t SplitImmOffset = 0, RemainderOffset = COffsetVal;
2091 if (NeedIOffset) {
2092 std::tie(args&: SplitImmOffset, args&: RemainderOffset) = TII->splitFlatOffset(
2093 COffsetVal, AddrSpace: AMDGPUAS::GLOBAL_ADDRESS, FlatVariant: FlatAddrSpace::FlatGlobal);
2094 }
2095
2096 if (Subtarget->hasSignedGVSOffset() ? isInt<32>(x: RemainderOffset)
2097 : isUInt<32>(x: RemainderOffset)) {
2098 SDNode *VMov = CurDAG->getMachineNode(
2099 Opcode: AMDGPU::V_MOV_B32_e32, dl: SL, VT: MVT::i32,
2100 Op1: CurDAG->getTargetConstant(Val: Lo_32(Value: RemainderOffset), DL: SDLoc(),
2101 VT: MVT::i32));
2102 VOffset = SDValue(VMov, 0);
2103 SAddr = LHS;
2104 Offset = CurDAG->getSignedTargetConstant(Val: SplitImmOffset, DL: SDLoc(),
2105 VT: MVT::i32);
2106 return true;
2107 }
2108 }
2109
2110 // We are adding a 64 bit SGPR and a constant. If constant bus limit
2111 // is 1 we would need to perform 1 or 2 extra moves for each half of
2112 // the constant and it is better to do a scalar add and then issue a
2113 // single VALU instruction to materialize zero. Otherwise it is less
2114 // instructions to perform VALU adds with immediates or inline literals.
2115 unsigned NumLiterals =
2116 !TII->isInlineConstant(Imm: APInt(32, Lo_32(Value: COffsetVal))) +
2117 !TII->isInlineConstant(Imm: APInt(32, Hi_32(Value: COffsetVal)));
2118 if (Subtarget->getConstantBusLimit(Opcode: AMDGPU::V_ADD_U32_e64) > NumLiterals)
2119 return false;
2120 }
2121 }
2122
2123 // Match the variable offset.
2124 if (Addr->isAnyAdd()) {
2125 LHS = Addr.getOperand(i: 0);
2126
2127 if (!LHS->isDivergent()) {
2128 // add (i64 sgpr), (*_extend (i32 vgpr))
2129 RHS = Addr.getOperand(i: 1);
2130 ScaleOffset = SelectScaleOffset(N, Offset&: RHS, IsSigned: Subtarget->hasSignedGVSOffset());
2131 if (SDValue ExtRHS = matchExtFromI32orI32(
2132 Op: RHS, IsSigned: Subtarget->hasSignedGVSOffset(), DAG: CurDAG)) {
2133 SAddr = LHS;
2134 VOffset = ExtRHS;
2135 }
2136 }
2137
2138 RHS = Addr.getOperand(i: 1);
2139 if (!SAddr && !RHS->isDivergent()) {
2140 // add (*_extend (i32 vgpr)), (i64 sgpr)
2141 ScaleOffset = SelectScaleOffset(N, Offset&: LHS, IsSigned: Subtarget->hasSignedGVSOffset());
2142 if (SDValue ExtLHS = matchExtFromI32orI32(
2143 Op: LHS, IsSigned: Subtarget->hasSignedGVSOffset(), DAG: CurDAG)) {
2144 SAddr = RHS;
2145 VOffset = ExtLHS;
2146 }
2147 }
2148
2149 if (SAddr) {
2150 Offset = CurDAG->getSignedTargetConstant(Val: ImmOffset, DL: SDLoc(), VT: MVT::i32);
2151 return true;
2152 }
2153 }
2154
2155 if (Subtarget->hasScaleOffset() &&
2156 (Addr.getOpcode() == (Subtarget->hasSignedGVSOffset()
2157 ? AMDGPUISD::MAD_I64_I32
2158 : AMDGPUISD::MAD_U64_U32) ||
2159 (Addr.getOpcode() == AMDGPUISD::MAD_U64_U32 &&
2160 CurDAG->SignBitIsZero(Op: Addr.getOperand(i: 0)))) &&
2161 Addr.getOperand(i: 0)->isDivergent() &&
2162 isa<ConstantSDNode>(Val: Addr.getOperand(i: 1)) &&
2163 !Addr.getOperand(i: 2)->isDivergent()) {
2164 // mad_u64_u32 (i32 vgpr), (i32 c), (i64 sgpr)
2165 unsigned Size =
2166 (unsigned)cast<MemSDNode>(Val: N)->getMemoryVT().getFixedSizeInBits() / 8;
2167 ScaleOffset = Addr.getConstantOperandVal(i: 1) == Size;
2168 if (ScaleOffset) {
2169 SAddr = Addr.getOperand(i: 2);
2170 VOffset = Addr.getOperand(i: 0);
2171 Offset = CurDAG->getTargetConstant(Val: ImmOffset, DL: SDLoc(), VT: MVT::i32);
2172 return true;
2173 }
2174 }
2175
2176 if (Addr->isDivergent() || Addr.isUndef() || isa<ConstantSDNode>(Val: Addr))
2177 return false;
2178
2179 // It's cheaper to materialize a single 32-bit zero for vaddr than the two
2180 // moves required to copy a 64-bit SGPR to VGPR.
2181 SAddr = Addr;
2182 SDNode *VMov =
2183 CurDAG->getMachineNode(Opcode: AMDGPU::V_MOV_B32_e32, dl: SDLoc(Addr), VT: MVT::i32,
2184 Op1: CurDAG->getTargetConstant(Val: 0, DL: SDLoc(), VT: MVT::i32));
2185 VOffset = SDValue(VMov, 0);
2186 Offset = CurDAG->getSignedTargetConstant(Val: ImmOffset, DL: SDLoc(), VT: MVT::i32);
2187 return true;
2188}
2189
2190bool AMDGPUDAGToDAGISel::SelectGlobalSAddr(SDNode *N, SDValue Addr,
2191 SDValue &SAddr, SDValue &VOffset,
2192 SDValue &Offset,
2193 SDValue &CPol) const {
2194 bool ScaleOffset;
2195 if (!SelectGlobalSAddr(N, Addr, SAddr, VOffset, Offset, ScaleOffset))
2196 return false;
2197
2198 CPol = CurDAG->getTargetConstant(Val: ScaleOffset ? AMDGPU::CPol::SCAL : 0,
2199 DL: SDLoc(), VT: MVT::i32);
2200 return true;
2201}
2202
2203bool AMDGPUDAGToDAGISel::SelectGlobalSAddrCPol(SDNode *N, SDValue Addr,
2204 SDValue &SAddr, SDValue &VOffset,
2205 SDValue &Offset,
2206 SDValue &CPol) const {
2207 bool ScaleOffset;
2208 if (!SelectGlobalSAddr(N, Addr, SAddr, VOffset, Offset, ScaleOffset))
2209 return false;
2210
2211 // We are assuming CPol is always the last operand of the intrinsic.
2212 auto PassedCPol =
2213 N->getConstantOperandVal(Num: N->getNumOperands() - 1) & ~AMDGPU::CPol::SCAL;
2214 CPol = CurDAG->getTargetConstant(
2215 Val: (ScaleOffset ? AMDGPU::CPol::SCAL : 0) | PassedCPol, DL: SDLoc(), VT: MVT::i32);
2216 return true;
2217}
2218
2219bool AMDGPUDAGToDAGISel::SelectGlobalSAddrCPolM0(SDNode *N, SDValue Addr,
2220 SDValue &SAddr,
2221 SDValue &VOffset,
2222 SDValue &Offset,
2223 SDValue &CPol) const {
2224 bool ScaleOffset;
2225 if (!SelectGlobalSAddr(N, Addr, SAddr, VOffset, Offset, ScaleOffset))
2226 return false;
2227
2228 // We are assuming CPol is second from last operand of the intrinsic.
2229 auto PassedCPol =
2230 N->getConstantOperandVal(Num: N->getNumOperands() - 2) & ~AMDGPU::CPol::SCAL;
2231 CPol = CurDAG->getTargetConstant(
2232 Val: (ScaleOffset ? AMDGPU::CPol::SCAL : 0) | PassedCPol, DL: SDLoc(), VT: MVT::i32);
2233 return true;
2234}
2235
2236bool AMDGPUDAGToDAGISel::SelectGlobalSAddrGLC(SDNode *N, SDValue Addr,
2237 SDValue &SAddr, SDValue &VOffset,
2238 SDValue &Offset,
2239 SDValue &CPol) const {
2240 bool ScaleOffset;
2241 if (!SelectGlobalSAddr(N, Addr, SAddr, VOffset, Offset, ScaleOffset))
2242 return false;
2243
2244 unsigned CPolVal = (ScaleOffset ? AMDGPU::CPol::SCAL : 0) | AMDGPU::CPol::GLC;
2245 CPol = CurDAG->getTargetConstant(Val: CPolVal, DL: SDLoc(), VT: MVT::i32);
2246 return true;
2247}
2248
2249bool AMDGPUDAGToDAGISel::SelectGlobalSAddrNoIOffset(SDNode *N, SDValue Addr,
2250 SDValue &SAddr,
2251 SDValue &VOffset,
2252 SDValue &CPol) const {
2253 bool ScaleOffset;
2254 SDValue DummyOffset;
2255 if (!SelectGlobalSAddr(N, Addr, SAddr, VOffset, Offset&: DummyOffset, ScaleOffset,
2256 NeedIOffset: false))
2257 return false;
2258
2259 // We are assuming CPol is always the last operand of the intrinsic.
2260 auto PassedCPol =
2261 N->getConstantOperandVal(Num: N->getNumOperands() - 1) & ~AMDGPU::CPol::SCAL;
2262 CPol = CurDAG->getTargetConstant(
2263 Val: (ScaleOffset ? AMDGPU::CPol::SCAL : 0) | PassedCPol, DL: SDLoc(), VT: MVT::i32);
2264 return true;
2265}
2266
2267bool AMDGPUDAGToDAGISel::SelectGlobalSAddrNoIOffsetM0(SDNode *N, SDValue Addr,
2268 SDValue &SAddr,
2269 SDValue &VOffset,
2270 SDValue &CPol) const {
2271 bool ScaleOffset;
2272 SDValue DummyOffset;
2273 if (!SelectGlobalSAddr(N, Addr, SAddr, VOffset, Offset&: DummyOffset, ScaleOffset,
2274 NeedIOffset: false))
2275 return false;
2276
2277 // We are assuming CPol is second from last operand of the intrinsic.
2278 auto PassedCPol =
2279 N->getConstantOperandVal(Num: N->getNumOperands() - 2) & ~AMDGPU::CPol::SCAL;
2280 CPol = CurDAG->getTargetConstant(
2281 Val: (ScaleOffset ? AMDGPU::CPol::SCAL : 0) | PassedCPol, DL: SDLoc(), VT: MVT::i32);
2282 return true;
2283}
2284
2285static SDValue SelectSAddrFI(SelectionDAG *CurDAG, SDValue SAddr) {
2286 if (auto *FI = dyn_cast<FrameIndexSDNode>(Val&: SAddr)) {
2287 SAddr = CurDAG->getTargetFrameIndex(FI: FI->getIndex(), VT: FI->getValueType(ResNo: 0));
2288 } else if (SAddr.getOpcode() == ISD::ADD &&
2289 isa<FrameIndexSDNode>(Val: SAddr.getOperand(i: 0))) {
2290 // Materialize this into a scalar move for scalar address to avoid
2291 // readfirstlane.
2292 auto *FI = cast<FrameIndexSDNode>(Val: SAddr.getOperand(i: 0));
2293 SDValue TFI = CurDAG->getTargetFrameIndex(FI: FI->getIndex(),
2294 VT: FI->getValueType(ResNo: 0));
2295 SAddr = SDValue(CurDAG->getMachineNode(Opcode: AMDGPU::S_ADD_I32, dl: SDLoc(SAddr),
2296 VT: MVT::i32, Op1: TFI, Op2: SAddr.getOperand(i: 1)),
2297 0);
2298 }
2299
2300 return SAddr;
2301}
2302
2303// Match (32-bit SGPR base) + sext(imm offset)
2304bool AMDGPUDAGToDAGISel::SelectScratchSAddr(SDNode *Parent, SDValue Addr,
2305 SDValue &SAddr,
2306 SDValue &Offset) const {
2307 using AMDGPU::FlatAddrSpace;
2308 if (Addr->isDivergent())
2309 return false;
2310
2311 SDLoc DL(Addr);
2312
2313 int64_t COffsetVal = 0;
2314
2315 if (CurDAG->isBaseWithConstantOffset(Op: Addr) && isFlatScratchBaseLegal(Addr)) {
2316 COffsetVal = cast<ConstantSDNode>(Val: Addr.getOperand(i: 1))->getSExtValue();
2317 SAddr = Addr.getOperand(i: 0);
2318 } else {
2319 SAddr = Addr;
2320 }
2321
2322 SAddr = SelectSAddrFI(CurDAG, SAddr);
2323
2324 const SIInstrInfo *TII = Subtarget->getInstrInfo();
2325
2326 if (!TII->isLegalFLATOffset(Offset: COffsetVal, AddrSpace: AMDGPUAS::PRIVATE_ADDRESS,
2327 FlatVariant: FlatAddrSpace::FlatScratch)) {
2328 int64_t SplitImmOffset, RemainderOffset;
2329 std::tie(args&: SplitImmOffset, args&: RemainderOffset) = TII->splitFlatOffset(
2330 COffsetVal, AddrSpace: AMDGPUAS::PRIVATE_ADDRESS, FlatVariant: FlatAddrSpace::FlatScratch);
2331
2332 COffsetVal = SplitImmOffset;
2333
2334 SDValue AddOffset =
2335 SAddr.getOpcode() == ISD::TargetFrameIndex
2336 ? getMaterializedScalarImm32(Val: Lo_32(Value: RemainderOffset), DL)
2337 : CurDAG->getSignedTargetConstant(Val: RemainderOffset, DL, VT: MVT::i32);
2338 SAddr = SDValue(CurDAG->getMachineNode(Opcode: AMDGPU::S_ADD_I32, dl: DL, VT: MVT::i32,
2339 Op1: SAddr, Op2: AddOffset),
2340 0);
2341 }
2342
2343 Offset = CurDAG->getSignedTargetConstant(Val: COffsetVal, DL, VT: MVT::i32);
2344
2345 return true;
2346}
2347
2348// Check whether the flat scratch SVS swizzle bug affects this access.
2349bool AMDGPUDAGToDAGISel::checkFlatScratchSVSSwizzleBug(
2350 SDValue VAddr, SDValue SAddr, uint64_t ImmOffset) const {
2351 if (!Subtarget->hasFlatScratchSVSSwizzleBug())
2352 return false;
2353
2354 // The bug affects the swizzling of SVS accesses if there is any carry out
2355 // from the two low order bits (i.e. from bit 1 into bit 2) when adding
2356 // voffset to (soffset + inst_offset).
2357 KnownBits VKnown = CurDAG->computeKnownBits(Op: VAddr);
2358 KnownBits SKnown =
2359 KnownBits::add(LHS: CurDAG->computeKnownBits(Op: SAddr),
2360 RHS: KnownBits::makeConstant(C: APInt(32, ImmOffset,
2361 /*isSigned=*/true)));
2362 uint64_t VMax = VKnown.getMaxValue().getZExtValue();
2363 uint64_t SMax = SKnown.getMaxValue().getZExtValue();
2364 return (VMax & 3) + (SMax & 3) >= 4;
2365}
2366
2367bool AMDGPUDAGToDAGISel::SelectScratchSVAddr(SDNode *N, SDValue Addr,
2368 SDValue &VAddr, SDValue &SAddr,
2369 SDValue &Offset,
2370 SDValue &CPol) const {
2371 int64_t ImmOffset = 0;
2372
2373 SDValue LHS, RHS;
2374 SDValue OrigAddr = Addr;
2375 if (isBaseWithConstantOffset64(Addr, LHS, RHS)) {
2376 int64_t COffsetVal = cast<ConstantSDNode>(Val&: RHS)->getSExtValue();
2377 const SIInstrInfo *TII = Subtarget->getInstrInfo();
2378
2379 if (TII->isLegalFLATOffset(Offset: COffsetVal, AddrSpace: AMDGPUAS::PRIVATE_ADDRESS,
2380 FlatVariant: AMDGPU::FlatAddrSpace::FlatScratch)) {
2381 Addr = LHS;
2382 ImmOffset = COffsetVal;
2383 } else if (!LHS->isDivergent() && COffsetVal > 0) {
2384 SDLoc SL(N);
2385 // saddr + large_offset -> saddr + (vaddr = large_offset & ~MaxOffset) +
2386 // (large_offset & MaxOffset);
2387 int64_t SplitImmOffset, RemainderOffset;
2388 std::tie(args&: SplitImmOffset, args&: RemainderOffset) =
2389 TII->splitFlatOffset(COffsetVal, AddrSpace: AMDGPUAS::PRIVATE_ADDRESS,
2390 FlatVariant: AMDGPU::FlatAddrSpace::FlatScratch);
2391
2392 if (isUInt<32>(x: RemainderOffset)) {
2393 SDNode *VMov = CurDAG->getMachineNode(
2394 Opcode: AMDGPU::V_MOV_B32_e32, dl: SL, VT: MVT::i32,
2395 Op1: CurDAG->getTargetConstant(Val: RemainderOffset, DL: SDLoc(), VT: MVT::i32));
2396 VAddr = SDValue(VMov, 0);
2397 SAddr = LHS;
2398 if (!isFlatScratchBaseLegal(Addr))
2399 return false;
2400 if (checkFlatScratchSVSSwizzleBug(VAddr, SAddr, ImmOffset: SplitImmOffset))
2401 return false;
2402 Offset = CurDAG->getTargetConstant(Val: SplitImmOffset, DL: SDLoc(), VT: MVT::i32);
2403 CPol = CurDAG->getTargetConstant(Val: 0, DL: SDLoc(), VT: MVT::i32);
2404 return true;
2405 }
2406 }
2407 }
2408
2409 if (Addr.getOpcode() != ISD::ADD)
2410 return false;
2411
2412 LHS = Addr.getOperand(i: 0);
2413 RHS = Addr.getOperand(i: 1);
2414
2415 if (!LHS->isDivergent() && RHS->isDivergent()) {
2416 SAddr = LHS;
2417 VAddr = RHS;
2418 } else if (!RHS->isDivergent() && LHS->isDivergent()) {
2419 SAddr = RHS;
2420 VAddr = LHS;
2421 } else {
2422 return false;
2423 }
2424
2425 if (OrigAddr != Addr) {
2426 if (!isFlatScratchBaseLegalSVImm(Addr: OrigAddr))
2427 return false;
2428 } else {
2429 if (!isFlatScratchBaseLegalSV(Addr: OrigAddr))
2430 return false;
2431 }
2432
2433 if (checkFlatScratchSVSSwizzleBug(VAddr, SAddr, ImmOffset))
2434 return false;
2435 SAddr = SelectSAddrFI(CurDAG, SAddr);
2436 Offset = CurDAG->getSignedTargetConstant(Val: ImmOffset, DL: SDLoc(), VT: MVT::i32);
2437
2438 bool ScaleOffset = SelectScaleOffset(N, Offset&: VAddr, IsSigned: true /* IsSigned */);
2439 CPol = CurDAG->getTargetConstant(Val: ScaleOffset ? AMDGPU::CPol::SCAL : 0,
2440 DL: SDLoc(), VT: MVT::i32);
2441 return true;
2442}
2443
2444// For unbuffered smem loads, it is illegal for the Immediate Offset to be
2445// negative if the resulting (Offset + (M0 or SOffset or zero) is negative.
2446// Handle the case where the Immediate Offset + SOffset is negative.
2447bool AMDGPUDAGToDAGISel::isSOffsetLegalWithImmOffset(SDValue *SOffset,
2448 bool Imm32Only,
2449 bool IsBuffer,
2450 int64_t ImmOffset) const {
2451 if (!IsBuffer && !Imm32Only && ImmOffset < 0 &&
2452 AMDGPU::hasSMRDSignedImmOffset(ST: *Subtarget)) {
2453 KnownBits SKnown = CurDAG->computeKnownBits(Op: *SOffset);
2454 if (ImmOffset + SKnown.getMinValue().getSExtValue() < 0)
2455 return false;
2456 }
2457
2458 return true;
2459}
2460
2461// Given \p Offset and load node \p N check if an \p Offset is a multiple of
2462// the load byte size. If it is update \p Offset to a pre-scaled value and
2463// return true.
2464bool AMDGPUDAGToDAGISel::SelectScaleOffset(SDNode *N, SDValue &Offset,
2465 bool IsSigned) const {
2466 bool ScaleOffset = false;
2467 if (!Subtarget->hasScaleOffset() || !Offset)
2468 return false;
2469
2470 unsigned Size =
2471 (unsigned)cast<MemSDNode>(Val: N)->getMemoryVT().getFixedSizeInBits() / 8;
2472
2473 SDValue Off = Offset;
2474 if (SDValue Ext = matchExtFromI32orI32(Op: Offset, IsSigned, DAG: CurDAG))
2475 Off = Ext;
2476
2477 if (isPowerOf2_32(Value: Size) && Off.getOpcode() == ISD::SHL) {
2478 if (auto *C = dyn_cast<ConstantSDNode>(Val: Off.getOperand(i: 1)))
2479 ScaleOffset = C->getZExtValue() == Log2_32(Value: Size);
2480 } else if (Offset.getOpcode() == ISD::MUL ||
2481 (IsSigned && Offset.getOpcode() == AMDGPUISD::MUL_I24) ||
2482 Offset.getOpcode() == AMDGPUISD::MUL_U24 ||
2483 (Offset.isMachineOpcode() &&
2484 Offset.getMachineOpcode() ==
2485 (IsSigned ? AMDGPU::S_MUL_I64_I32_PSEUDO
2486 : AMDGPU::S_MUL_U64_U32_PSEUDO))) {
2487 if (auto *C = dyn_cast<ConstantSDNode>(Val: Offset.getOperand(i: 1)))
2488 ScaleOffset = C->getZExtValue() == Size;
2489 }
2490
2491 if (ScaleOffset)
2492 Offset = Off.getOperand(i: 0);
2493
2494 return ScaleOffset;
2495}
2496
2497// Match an immediate (if Offset is not null) or an SGPR (if SOffset is
2498// not null) offset. If Imm32Only is true, match only 32-bit immediate
2499// offsets available on CI.
2500bool AMDGPUDAGToDAGISel::SelectSMRDOffset(SDNode *N, SDValue ByteOffsetNode,
2501 SDValue *SOffset, SDValue *Offset,
2502 bool Imm32Only, bool IsBuffer,
2503 bool HasSOffset, int64_t ImmOffset,
2504 bool *ScaleOffset) const {
2505 assert((!SOffset || !Offset) &&
2506 "Cannot match both soffset and offset at the same time!");
2507
2508 if (ScaleOffset) {
2509 assert(N && SOffset);
2510
2511 *ScaleOffset = SelectScaleOffset(N, Offset&: ByteOffsetNode, IsSigned: false /* IsSigned */);
2512 }
2513
2514 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val&: ByteOffsetNode);
2515 if (!C) {
2516 if (!SOffset)
2517 return false;
2518
2519 if (ByteOffsetNode.getValueType().isScalarInteger() &&
2520 ByteOffsetNode.getValueType().getSizeInBits() == 32) {
2521 *SOffset = ByteOffsetNode;
2522 return isSOffsetLegalWithImmOffset(SOffset, Imm32Only, IsBuffer,
2523 ImmOffset);
2524 }
2525 if (ByteOffsetNode.getOpcode() == ISD::ZERO_EXTEND) {
2526 if (ByteOffsetNode.getOperand(i: 0).getValueType().getSizeInBits() == 32) {
2527 *SOffset = ByteOffsetNode.getOperand(i: 0);
2528 return isSOffsetLegalWithImmOffset(SOffset, Imm32Only, IsBuffer,
2529 ImmOffset);
2530 }
2531 }
2532 return false;
2533 }
2534
2535 SDLoc SL(ByteOffsetNode);
2536
2537 // GFX9 and GFX10 have signed byte immediate offsets. The immediate
2538 // offset for S_BUFFER instructions is unsigned.
2539 int64_t ByteOffset = IsBuffer ? C->getZExtValue() : C->getSExtValue();
2540 std::optional<int64_t> EncodedOffset = AMDGPU::getSMRDEncodedOffset(
2541 ST: *Subtarget, ByteOffset, IsBuffer, HasSOffset);
2542 if (EncodedOffset && Offset && !Imm32Only) {
2543 *Offset = CurDAG->getSignedTargetConstant(Val: *EncodedOffset, DL: SL, VT: MVT::i32);
2544 return true;
2545 }
2546
2547 // SGPR and literal offsets are unsigned.
2548 if (ByteOffset < 0)
2549 return false;
2550
2551 EncodedOffset = AMDGPU::getSMRDEncodedLiteralOffset32(ST: *Subtarget, ByteOffset);
2552 if (EncodedOffset && Offset && Imm32Only) {
2553 *Offset = CurDAG->getTargetConstant(Val: *EncodedOffset, DL: SL, VT: MVT::i32);
2554 return true;
2555 }
2556
2557 if (!isUInt<32>(x: ByteOffset) && !isInt<32>(x: ByteOffset))
2558 return false;
2559
2560 if (SOffset) {
2561 SDValue C32Bit = CurDAG->getTargetConstant(Val: ByteOffset, DL: SL, VT: MVT::i32);
2562 *SOffset = SDValue(
2563 CurDAG->getMachineNode(Opcode: AMDGPU::S_MOV_B32, dl: SL, VT: MVT::i32, Op1: C32Bit), 0);
2564 return true;
2565 }
2566
2567 return false;
2568}
2569
2570SDValue AMDGPUDAGToDAGISel::Expand32BitAddress(SDValue Addr) const {
2571 if (Addr.getValueType() != MVT::i32)
2572 return Addr;
2573
2574 // Zero-extend a 32-bit address.
2575 SDLoc SL(Addr);
2576
2577 const MachineFunction &MF = CurDAG->getMachineFunction();
2578 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2579 unsigned AddrHiVal = Info->get32BitAddressHighBits();
2580 SDValue AddrHi = CurDAG->getTargetConstant(Val: AddrHiVal, DL: SL, VT: MVT::i32);
2581
2582 const SDValue Ops[] = {
2583 CurDAG->getTargetConstant(Val: AMDGPU::SReg_64_XEXECRegClassID, DL: SL, VT: MVT::i32),
2584 Addr,
2585 CurDAG->getTargetConstant(Val: AMDGPU::sub0, DL: SL, VT: MVT::i32),
2586 SDValue(CurDAG->getMachineNode(Opcode: AMDGPU::S_MOV_B32, dl: SL, VT: MVT::i32, Op1: AddrHi),
2587 0),
2588 CurDAG->getTargetConstant(Val: AMDGPU::sub1, DL: SL, VT: MVT::i32),
2589 };
2590
2591 return SDValue(CurDAG->getMachineNode(Opcode: AMDGPU::REG_SEQUENCE, dl: SL, VT: MVT::i64,
2592 Ops), 0);
2593}
2594
2595// Match a base and an immediate (if Offset is not null) or an SGPR (if
2596// SOffset is not null) or an immediate+SGPR offset. If Imm32Only is
2597// true, match only 32-bit immediate offsets available on CI.
2598bool AMDGPUDAGToDAGISel::SelectSMRDBaseOffset(SDNode *N, SDValue Addr,
2599 SDValue &SBase, SDValue *SOffset,
2600 SDValue *Offset, bool Imm32Only,
2601 bool IsBuffer, bool HasSOffset,
2602 int64_t ImmOffset,
2603 bool *ScaleOffset) const {
2604 if (SOffset && Offset) {
2605 assert(!Imm32Only && !IsBuffer);
2606 SDValue B;
2607
2608 if (!SelectSMRDBaseOffset(N, Addr, SBase&: B, SOffset: nullptr, Offset, Imm32Only: false, IsBuffer: false, HasSOffset: true))
2609 return false;
2610
2611 int64_t ImmOff = 0;
2612 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val&: *Offset))
2613 ImmOff = C->getSExtValue();
2614
2615 return SelectSMRDBaseOffset(N, Addr: B, SBase, SOffset, Offset: nullptr, Imm32Only: false, IsBuffer: false,
2616 HasSOffset: true, ImmOffset: ImmOff, ScaleOffset);
2617 }
2618
2619 // A 32-bit (address + offset) should not cause unsigned 32-bit integer
2620 // wraparound, because s_load instructions perform the addition in 64 bits.
2621 if (Addr.getValueType() == MVT::i32 && Addr.getOpcode() == ISD::ADD &&
2622 !Addr->getFlags().hasNoUnsignedWrap())
2623 return false;
2624
2625 SDValue N0, N1;
2626 // Extract the base and offset if possible.
2627 if (Addr->isAnyAdd() || CurDAG->isADDLike(Op: Addr)) {
2628 N0 = Addr.getOperand(i: 0);
2629 N1 = Addr.getOperand(i: 1);
2630 } else if (getBaseWithOffsetUsingSplitOR(DAG&: *CurDAG, Addr, N0, N1)) {
2631 assert(N0 && N1 && isa<ConstantSDNode>(N1));
2632 }
2633 if (!N0 || !N1)
2634 return false;
2635
2636 if (SelectSMRDOffset(N, ByteOffsetNode: N1, SOffset, Offset, Imm32Only, IsBuffer, HasSOffset,
2637 ImmOffset, ScaleOffset)) {
2638 SBase = N0;
2639 return true;
2640 }
2641 if (SelectSMRDOffset(N, ByteOffsetNode: N0, SOffset, Offset, Imm32Only, IsBuffer, HasSOffset,
2642 ImmOffset, ScaleOffset)) {
2643 SBase = N1;
2644 return true;
2645 }
2646 return false;
2647}
2648
2649bool AMDGPUDAGToDAGISel::SelectSMRD(SDNode *N, SDValue Addr, SDValue &SBase,
2650 SDValue *SOffset, SDValue *Offset,
2651 bool Imm32Only, bool *ScaleOffset) const {
2652 if (SelectSMRDBaseOffset(N, Addr, SBase, SOffset, Offset, Imm32Only,
2653 /* IsBuffer */ false, /* HasSOffset */ false,
2654 /* ImmOffset */ 0, ScaleOffset)) {
2655 SBase = Expand32BitAddress(Addr: SBase);
2656 return true;
2657 }
2658
2659 if (Addr.getValueType() == MVT::i32 && Offset && !SOffset) {
2660 SBase = Expand32BitAddress(Addr);
2661 *Offset = CurDAG->getTargetConstant(Val: 0, DL: SDLoc(Addr), VT: MVT::i32);
2662 return true;
2663 }
2664
2665 return false;
2666}
2667
2668bool AMDGPUDAGToDAGISel::SelectSMRDImm(SDValue Addr, SDValue &SBase,
2669 SDValue &Offset) const {
2670 return SelectSMRD(/* N */ nullptr, Addr, SBase, /* SOffset */ nullptr,
2671 Offset: &Offset);
2672}
2673
2674bool AMDGPUDAGToDAGISel::SelectSMRDImm32(SDValue Addr, SDValue &SBase,
2675 SDValue &Offset) const {
2676 assert(Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS);
2677 return SelectSMRD(/* N */ nullptr, Addr, SBase, /* SOffset */ nullptr,
2678 Offset: &Offset, /* Imm32Only */ true);
2679}
2680
2681bool AMDGPUDAGToDAGISel::SelectSMRDSgpr(SDNode *N, SDValue Addr, SDValue &SBase,
2682 SDValue &SOffset, SDValue &CPol) const {
2683 bool ScaleOffset;
2684 if (!SelectSMRD(N, Addr, SBase, SOffset: &SOffset, /* Offset */ nullptr,
2685 /* Imm32Only */ false, ScaleOffset: &ScaleOffset))
2686 return false;
2687
2688 CPol = CurDAG->getTargetConstant(Val: ScaleOffset ? AMDGPU::CPol::SCAL : 0,
2689 DL: SDLoc(N), VT: MVT::i32);
2690 return true;
2691}
2692
2693bool AMDGPUDAGToDAGISel::SelectSMRDSgprImm(SDNode *N, SDValue Addr,
2694 SDValue &SBase, SDValue &SOffset,
2695 SDValue &Offset,
2696 SDValue &CPol) const {
2697 bool ScaleOffset;
2698 if (!SelectSMRD(N, Addr, SBase, SOffset: &SOffset, Offset: &Offset, Imm32Only: false, ScaleOffset: &ScaleOffset))
2699 return false;
2700
2701 CPol = CurDAG->getTargetConstant(Val: ScaleOffset ? AMDGPU::CPol::SCAL : 0,
2702 DL: SDLoc(N), VT: MVT::i32);
2703 return true;
2704}
2705
2706bool AMDGPUDAGToDAGISel::SelectSMRDBufferImm(SDValue N, SDValue &Offset) const {
2707 return SelectSMRDOffset(/* N */ nullptr, ByteOffsetNode: N, /* SOffset */ nullptr, Offset: &Offset,
2708 /* Imm32Only */ false, /* IsBuffer */ true);
2709}
2710
2711bool AMDGPUDAGToDAGISel::SelectSMRDBufferImm32(SDValue N,
2712 SDValue &Offset) const {
2713 assert(Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS);
2714 return SelectSMRDOffset(/* N */ nullptr, ByteOffsetNode: N, /* SOffset */ nullptr, Offset: &Offset,
2715 /* Imm32Only */ true, /* IsBuffer */ true);
2716}
2717
2718bool AMDGPUDAGToDAGISel::SelectSMRDBufferSgprImm(SDValue N, SDValue &SOffset,
2719 SDValue &Offset) const {
2720 // Match the (soffset + offset) pair as a 32-bit register base and
2721 // an immediate offset.
2722 return N.getValueType() == MVT::i32 &&
2723 SelectSMRDBaseOffset(/* N */ nullptr, Addr: N, /* SBase */ SOffset,
2724 /* SOffset*/ nullptr, Offset: &Offset,
2725 /* Imm32Only */ false, /* IsBuffer */ true);
2726}
2727
2728bool AMDGPUDAGToDAGISel::SelectMOVRELOffset(SDValue Index,
2729 SDValue &Base,
2730 SDValue &Offset) const {
2731 SDLoc DL(Index);
2732
2733 if (CurDAG->isBaseWithConstantOffset(Op: Index)) {
2734 SDValue N0 = Index.getOperand(i: 0);
2735 SDValue N1 = Index.getOperand(i: 1);
2736 ConstantSDNode *C1 = cast<ConstantSDNode>(Val&: N1);
2737
2738 // (add n0, c0)
2739 // Don't peel off the offset (c0) if doing so could possibly lead
2740 // the base (n0) to be negative.
2741 // (or n0, |c0|) can never change a sign given isBaseWithConstantOffset.
2742 if (C1->getSExtValue() <= 0 || CurDAG->SignBitIsZero(Op: N0) ||
2743 (Index->getOpcode() == ISD::OR && C1->getSExtValue() >= 0)) {
2744 Base = N0;
2745 Offset = CurDAG->getTargetConstant(Val: C1->getZExtValue(), DL, VT: MVT::i32);
2746 return true;
2747 }
2748 }
2749
2750 if (isa<ConstantSDNode>(Val: Index))
2751 return false;
2752
2753 Base = Index;
2754 Offset = CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i32);
2755 return true;
2756}
2757
2758SDNode *AMDGPUDAGToDAGISel::getBFE32(bool IsSigned, const SDLoc &DL,
2759 SDValue Val, uint32_t Offset,
2760 uint32_t Width) {
2761 if (Val->isDivergent()) {
2762 unsigned Opcode = IsSigned ? AMDGPU::V_BFE_I32_e64 : AMDGPU::V_BFE_U32_e64;
2763 SDValue Off = CurDAG->getTargetConstant(Val: Offset, DL, VT: MVT::i32);
2764 SDValue W = CurDAG->getTargetConstant(Val: Width, DL, VT: MVT::i32);
2765
2766 return CurDAG->getMachineNode(Opcode, dl: DL, VT: MVT::i32, Op1: Val, Op2: Off, Op3: W);
2767 }
2768 unsigned Opcode = IsSigned ? AMDGPU::S_BFE_I32 : AMDGPU::S_BFE_U32;
2769 // Transformation function, pack the offset and width of a BFE into
2770 // the format expected by the S_BFE_I32 / S_BFE_U32. In the second
2771 // source, bits [5:0] contain the offset and bits [22:16] the width.
2772 uint32_t PackedVal = Offset | (Width << 16);
2773 SDValue PackedConst = CurDAG->getTargetConstant(Val: PackedVal, DL, VT: MVT::i32);
2774
2775 return CurDAG->getMachineNode(Opcode, dl: DL, VT: MVT::i32, Op1: Val, Op2: PackedConst);
2776}
2777
2778void AMDGPUDAGToDAGISel::SelectS_BFEFromShifts(SDNode *N) {
2779 // "(a << b) srl c)" ---> "BFE_U32 a, (c-b), (32-c)
2780 // "(a << b) sra c)" ---> "BFE_I32 a, (c-b), (32-c)
2781 // Predicate: 0 < b <= c < 32
2782
2783 const SDValue &Shl = N->getOperand(Num: 0);
2784 ConstantSDNode *B = dyn_cast<ConstantSDNode>(Val: Shl->getOperand(Num: 1));
2785 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val: N->getOperand(Num: 1));
2786
2787 if (B && C) {
2788 uint32_t BVal = B->getZExtValue();
2789 uint32_t CVal = C->getZExtValue();
2790
2791 if (0 < BVal && BVal <= CVal && CVal < 32) {
2792 bool Signed = N->getOpcode() == ISD::SRA;
2793 ReplaceNode(F: N, T: getBFE32(IsSigned: Signed, DL: SDLoc(N), Val: Shl.getOperand(i: 0), Offset: CVal - BVal,
2794 Width: 32 - CVal));
2795 return;
2796 }
2797 }
2798 SelectCode(N);
2799}
2800
2801void AMDGPUDAGToDAGISel::SelectS_BFE(SDNode *N) {
2802 switch (N->getOpcode()) {
2803 case ISD::AND:
2804 if (N->getOperand(Num: 0).getOpcode() == ISD::SRL) {
2805 // "(a srl b) & mask" ---> "BFE_U32 a, b, popcount(mask)"
2806 // Predicate: isMask(mask)
2807 const SDValue &Srl = N->getOperand(Num: 0);
2808 ConstantSDNode *Shift = dyn_cast<ConstantSDNode>(Val: Srl.getOperand(i: 1));
2809 ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(Val: N->getOperand(Num: 1));
2810
2811 if (Shift && Mask) {
2812 uint32_t ShiftVal = Shift->getZExtValue();
2813 uint32_t MaskVal = Mask->getZExtValue();
2814
2815 if (isMask_32(Value: MaskVal)) {
2816 uint32_t WidthVal = llvm::popcount(Value: MaskVal);
2817 ReplaceNode(F: N, T: getBFE32(IsSigned: false, DL: SDLoc(N), Val: Srl.getOperand(i: 0), Offset: ShiftVal,
2818 Width: WidthVal));
2819 return;
2820 }
2821 }
2822 }
2823 break;
2824 case ISD::SRL:
2825 if (N->getOperand(Num: 0).getOpcode() == ISD::AND) {
2826 // "(a & mask) srl b)" ---> "BFE_U32 a, b, popcount(mask >> b)"
2827 // Predicate: isMask(mask >> b)
2828 const SDValue &And = N->getOperand(Num: 0);
2829 ConstantSDNode *Shift = dyn_cast<ConstantSDNode>(Val: N->getOperand(Num: 1));
2830 ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(Val: And->getOperand(Num: 1));
2831
2832 if (Shift && Mask) {
2833 uint32_t ShiftVal = Shift->getZExtValue();
2834 uint32_t MaskVal = Mask->getZExtValue() >> ShiftVal;
2835
2836 if (isMask_32(Value: MaskVal)) {
2837 uint32_t WidthVal = llvm::popcount(Value: MaskVal);
2838 ReplaceNode(F: N, T: getBFE32(IsSigned: false, DL: SDLoc(N), Val: And.getOperand(i: 0), Offset: ShiftVal,
2839 Width: WidthVal));
2840 return;
2841 }
2842 }
2843 } else if (N->getOperand(Num: 0).getOpcode() == ISD::SHL) {
2844 SelectS_BFEFromShifts(N);
2845 return;
2846 }
2847 break;
2848 case ISD::SRA:
2849 if (N->getOperand(Num: 0).getOpcode() == ISD::SHL) {
2850 SelectS_BFEFromShifts(N);
2851 return;
2852 }
2853 break;
2854
2855 case ISD::SIGN_EXTEND_INREG: {
2856 // sext_inreg (srl x, 16), i8 -> bfe_i32 x, 16, 8
2857 SDValue Src = N->getOperand(Num: 0);
2858 if (Src.getOpcode() != ISD::SRL)
2859 break;
2860
2861 const ConstantSDNode *Amt = dyn_cast<ConstantSDNode>(Val: Src.getOperand(i: 1));
2862 if (!Amt)
2863 break;
2864
2865 unsigned Width = cast<VTSDNode>(Val: N->getOperand(Num: 1))->getVT().getSizeInBits();
2866 ReplaceNode(F: N, T: getBFE32(IsSigned: true, DL: SDLoc(N), Val: Src.getOperand(i: 0),
2867 Offset: Amt->getZExtValue(), Width));
2868 return;
2869 }
2870 }
2871
2872 SelectCode(N);
2873}
2874
2875bool AMDGPUDAGToDAGISel::isCBranchSCC(const SDNode *N) const {
2876 assert(N->getOpcode() == ISD::BRCOND);
2877 if (!N->hasOneUse())
2878 return false;
2879
2880 SDValue Cond = N->getOperand(Num: 1);
2881 if (Cond.getOpcode() == ISD::CopyToReg)
2882 Cond = Cond.getOperand(i: 2);
2883
2884 if (Cond.getOpcode() != ISD::SETCC || !Cond.hasOneUse())
2885 return false;
2886
2887 MVT VT = Cond.getOperand(i: 0).getSimpleValueType();
2888 if (VT == MVT::i32)
2889 return true;
2890
2891 if (VT == MVT::i64) {
2892 ISD::CondCode CC = cast<CondCodeSDNode>(Val: Cond.getOperand(i: 2))->get();
2893 return (CC == ISD::SETEQ || CC == ISD::SETNE) &&
2894 Subtarget->hasScalarCompareEq64();
2895 }
2896
2897 if ((VT == MVT::f16 || VT == MVT::f32) && Subtarget->hasSALUFloatInsts())
2898 return true;
2899
2900 return false;
2901}
2902
2903static SDValue combineBallotPattern(SDValue VCMP, bool &Negate) {
2904 assert(VCMP->getOpcode() == AMDGPUISD::SETCC);
2905 // Special case for amdgcn.ballot:
2906 // %Cond = i1 (and/or combination of i1 ISD::SETCCs)
2907 // %VCMP = i(WaveSize) AMDGPUISD::SETCC (ext %Cond), 0, setne/seteq
2908 // =>
2909 // Use i1 %Cond value instead of i(WaveSize) %VCMP.
2910 // This is possible because divergent ISD::SETCC is selected as V_CMP and
2911 // Cond becomes a i(WaveSize) full mask value.
2912 // Note that ballot doesn't use SETEQ condition but its easy to support it
2913 // here for completeness, so in this case Negate is set true on return.
2914 auto VCMP_CC = cast<CondCodeSDNode>(Val: VCMP.getOperand(i: 2))->get();
2915 if ((VCMP_CC == ISD::SETEQ || VCMP_CC == ISD::SETNE) &&
2916 isNullConstant(V: VCMP.getOperand(i: 1))) {
2917
2918 auto Cond = VCMP.getOperand(i: 0);
2919 if (ISD::isExtOpcode(Opcode: Cond->getOpcode())) // Skip extension.
2920 Cond = Cond.getOperand(i: 0);
2921
2922 if (isBoolSGPR(V: Cond)) {
2923 Negate = VCMP_CC == ISD::SETEQ;
2924 return Cond;
2925 }
2926 }
2927 return SDValue();
2928}
2929
2930void AMDGPUDAGToDAGISel::SelectBRCOND(SDNode *N) {
2931 SDValue Cond = N->getOperand(Num: 1);
2932
2933 if (Cond.isUndef()) {
2934 CurDAG->SelectNodeTo(N, MachineOpc: AMDGPU::SI_BR_UNDEF, VT: MVT::Other,
2935 Op1: N->getOperand(Num: 2), Op2: N->getOperand(Num: 0));
2936 return;
2937 }
2938
2939 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2940
2941 bool UseSCCBr = isCBranchSCC(N) && isUniformBr(N);
2942 bool AndExec = !UseSCCBr;
2943 bool Negate = false;
2944
2945 if (Cond.getOpcode() == ISD::SETCC &&
2946 Cond->getOperand(Num: 0)->getOpcode() == AMDGPUISD::SETCC) {
2947 SDValue VCMP = Cond->getOperand(Num: 0);
2948 auto CC = cast<CondCodeSDNode>(Val: Cond->getOperand(Num: 2))->get();
2949 if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
2950 isNullConstant(V: Cond->getOperand(Num: 1)) &&
2951 // We may encounter ballot.i64 in wave32 mode on -O0.
2952 VCMP.getValueType().getSizeInBits() == Subtarget->getWavefrontSize()) {
2953 // %VCMP = i(WaveSize) AMDGPUISD::SETCC ...
2954 // %C = i1 ISD::SETCC %VCMP, 0, setne/seteq
2955 // BRCOND i1 %C, %BB
2956 // =>
2957 // %VCMP = i(WaveSize) AMDGPUISD::SETCC ...
2958 // VCC = COPY i(WaveSize) %VCMP
2959 // S_CBRANCH_VCCNZ/VCCZ %BB
2960 Negate = CC == ISD::SETEQ;
2961 bool NegatedBallot = false;
2962 if (auto BallotCond = combineBallotPattern(VCMP, Negate&: NegatedBallot)) {
2963 Cond = BallotCond;
2964 UseSCCBr = !BallotCond->isDivergent();
2965 Negate = Negate ^ NegatedBallot;
2966 } else {
2967 // TODO: don't use SCC here assuming that AMDGPUISD::SETCC is always
2968 // selected as V_CMP, but this may change for uniform condition.
2969 Cond = VCMP;
2970 UseSCCBr = false;
2971 }
2972 }
2973 // Cond is either V_CMP resulted from AMDGPUISD::SETCC or a combination of
2974 // V_CMPs resulted from ballot or ballot has uniform condition and SCC is
2975 // used.
2976 AndExec = false;
2977 }
2978
2979 unsigned BrOp =
2980 UseSCCBr ? (Negate ? AMDGPU::S_CBRANCH_SCC0 : AMDGPU::S_CBRANCH_SCC1)
2981 : (Negate ? AMDGPU::S_CBRANCH_VCCZ : AMDGPU::S_CBRANCH_VCCNZ);
2982 Register CondReg = UseSCCBr ? AMDGPU::SCC : TRI->getVCC();
2983 SDLoc SL(N);
2984
2985 if (AndExec) {
2986 // This is the case that we are selecting to S_CBRANCH_VCCNZ. We have not
2987 // analyzed what generates the vcc value, so we do not know whether vcc
2988 // bits for disabled lanes are 0. Thus we need to mask out bits for
2989 // disabled lanes.
2990 //
2991 // For the case that we select S_CBRANCH_SCC1 and it gets
2992 // changed to S_CBRANCH_VCCNZ in SIFixSGPRCopies, SIFixSGPRCopies calls
2993 // SIInstrInfo::moveToVALU which inserts the S_AND).
2994 //
2995 // We could add an analysis of what generates the vcc value here and omit
2996 // the S_AND when is unnecessary. But it would be better to add a separate
2997 // pass after SIFixSGPRCopies to do the unnecessary S_AND removal, so it
2998 // catches both cases.
2999 Cond = SDValue(
3000 CurDAG->getMachineNode(
3001 Opcode: Subtarget->isWave32() ? AMDGPU::S_AND_B32 : AMDGPU::S_AND_B64, dl: SL,
3002 VT: MVT::i1,
3003 Op1: CurDAG->getRegister(Reg: Subtarget->isWave32() ? AMDGPU::EXEC_LO
3004 : AMDGPU::EXEC,
3005 VT: MVT::i1),
3006 Op2: Cond),
3007 0);
3008 }
3009
3010 SDValue VCC = CurDAG->getCopyToReg(Chain: N->getOperand(Num: 0), dl: SL, Reg: CondReg, N: Cond);
3011 CurDAG->SelectNodeTo(N, MachineOpc: BrOp, VT: MVT::Other,
3012 Op1: N->getOperand(Num: 2), // Basic Block
3013 Op2: VCC.getValue(R: 0));
3014}
3015
3016void AMDGPUDAGToDAGISel::SelectFP_EXTEND(SDNode *N) {
3017 if (Subtarget->hasSALUFloatInsts() && N->getValueType(ResNo: 0) == MVT::f32 &&
3018 !N->isDivergent()) {
3019 SDValue Src = N->getOperand(Num: 0);
3020 if (Src.getValueType() == MVT::f16) {
3021 if (isExtractHiElt(In: Src, Out&: Src)) {
3022 CurDAG->SelectNodeTo(N, MachineOpc: AMDGPU::S_CVT_HI_F32_F16, VTs: N->getVTList(),
3023 Ops: {Src});
3024 return;
3025 }
3026 }
3027 }
3028
3029 SelectCode(N);
3030}
3031
3032void AMDGPUDAGToDAGISel::SelectDSAppendConsume(SDNode *N, unsigned IntrID) {
3033 // The address is assumed to be uniform, so if it ends up in a VGPR, it will
3034 // be copied to an SGPR with readfirstlane.
3035 unsigned Opc = IntrID == Intrinsic::amdgcn_ds_append ?
3036 AMDGPU::DS_APPEND : AMDGPU::DS_CONSUME;
3037
3038 SDValue Chain = N->getOperand(Num: 0);
3039 SDValue Ptr = N->getOperand(Num: 2);
3040 MemIntrinsicSDNode *M = cast<MemIntrinsicSDNode>(Val: N);
3041 MachineMemOperand *MMO = M->getMemOperand();
3042 bool IsGDS = M->getAddressSpace() == AMDGPUAS::REGION_ADDRESS;
3043
3044 SDValue Offset;
3045 if (CurDAG->isBaseWithConstantOffset(Op: Ptr)) {
3046 SDValue PtrBase = Ptr.getOperand(i: 0);
3047 SDValue PtrOffset = Ptr.getOperand(i: 1);
3048
3049 const APInt &OffsetVal = PtrOffset->getAsAPIntVal();
3050 if (isDSOffsetLegal(Base: PtrBase, Offset: OffsetVal.getZExtValue())) {
3051 N = glueCopyToM0(N, Val: PtrBase);
3052 Offset = CurDAG->getTargetConstant(Val: OffsetVal, DL: SDLoc(), VT: MVT::i32);
3053 }
3054 }
3055
3056 if (!Offset) {
3057 N = glueCopyToM0(N, Val: Ptr);
3058 Offset = CurDAG->getTargetConstant(Val: 0, DL: SDLoc(), VT: MVT::i32);
3059 }
3060
3061 SDValue Ops[] = {
3062 Offset,
3063 CurDAG->getTargetConstant(Val: IsGDS, DL: SDLoc(), VT: MVT::i32),
3064 Chain,
3065 N->getOperand(Num: N->getNumOperands() - 1) // New glue
3066 };
3067
3068 SDNode *Selected = CurDAG->SelectNodeTo(N, MachineOpc: Opc, VTs: N->getVTList(), Ops);
3069 CurDAG->setNodeMemRefs(N: cast<MachineSDNode>(Val: Selected), NewMemRefs: {MMO});
3070}
3071
3072// We need to handle this here because tablegen doesn't support matching
3073// instructions with multiple outputs.
3074void AMDGPUDAGToDAGISel::SelectDSBvhStackIntrinsic(SDNode *N, unsigned IntrID) {
3075 unsigned Opc;
3076 switch (IntrID) {
3077 case Intrinsic::amdgcn_ds_bvh_stack_rtn:
3078 case Intrinsic::amdgcn_ds_bvh_stack_push4_pop1_rtn:
3079 Opc = AMDGPU::DS_BVH_STACK_RTN_B32;
3080 break;
3081 case Intrinsic::amdgcn_ds_bvh_stack_push8_pop1_rtn:
3082 Opc = AMDGPU::DS_BVH_STACK_PUSH8_POP1_RTN_B32;
3083 break;
3084 case Intrinsic::amdgcn_ds_bvh_stack_push8_pop2_rtn:
3085 Opc = AMDGPU::DS_BVH_STACK_PUSH8_POP2_RTN_B64;
3086 break;
3087 }
3088 SDValue Ops[] = {N->getOperand(Num: 2), N->getOperand(Num: 3), N->getOperand(Num: 4),
3089 N->getOperand(Num: 5), N->getOperand(Num: 0)};
3090
3091 MemIntrinsicSDNode *M = cast<MemIntrinsicSDNode>(Val: N);
3092 MachineMemOperand *MMO = M->getMemOperand();
3093 SDNode *Selected = CurDAG->SelectNodeTo(N, MachineOpc: Opc, VTs: N->getVTList(), Ops);
3094 CurDAG->setNodeMemRefs(N: cast<MachineSDNode>(Val: Selected), NewMemRefs: {MMO});
3095}
3096
3097void AMDGPUDAGToDAGISel::SelectTensorLoadStore(SDNode *N, unsigned IntrID) {
3098 bool IsLoad = IntrID == Intrinsic::amdgcn_tensor_load_to_lds;
3099 unsigned Opc =
3100 IsLoad ? AMDGPU::TENSOR_LOAD_TO_LDS_d4 : AMDGPU::TENSOR_STORE_FROM_LDS_d4;
3101
3102 SmallVector<SDValue, 7> TensorOps;
3103 // First two groups
3104 TensorOps.push_back(Elt: N->getOperand(Num: 2)); // D# group 0
3105 TensorOps.push_back(Elt: N->getOperand(Num: 3)); // D# group 1
3106
3107 // Use _D2 version if both group 2 and 3 are zero-initialized.
3108 SDValue Group2 = N->getOperand(Num: 4);
3109 SDValue Group3 = N->getOperand(Num: 5);
3110 if (ISD::isBuildVectorAllZeros(N: Group2.getNode()) &&
3111 ISD::isBuildVectorAllZeros(N: Group3.getNode())) {
3112 Opc = IsLoad ? AMDGPU::TENSOR_LOAD_TO_LDS_d2
3113 : AMDGPU::TENSOR_STORE_FROM_LDS_d2;
3114 } else { // Has at least 4 groups
3115 TensorOps.push_back(Elt: Group2); // D# group 2
3116 TensorOps.push_back(Elt: Group3); // D# group 3
3117 }
3118
3119 // TODO: Handle the fifth group: N->getOperand(6), which is silently ignored
3120 // for now because all existing targets only support up to 4 groups.
3121 TensorOps.push_back(Elt: CurDAG->getTargetConstant(Val: 0, DL: SDLoc(N), VT: MVT::i1)); // r128
3122 TensorOps.push_back(Elt: N->getOperand(Num: 7)); // cache policy
3123 TensorOps.push_back(Elt: N->getOperand(Num: 0)); // chain
3124
3125 (void)CurDAG->SelectNodeTo(N, MachineOpc: Opc, VT: MVT::Other, Ops: TensorOps);
3126}
3127
3128static unsigned gwsIntrinToOpcode(unsigned IntrID) {
3129 switch (IntrID) {
3130 case Intrinsic::amdgcn_ds_gws_init:
3131 return AMDGPU::DS_GWS_INIT;
3132 case Intrinsic::amdgcn_ds_gws_barrier:
3133 return AMDGPU::DS_GWS_BARRIER;
3134 case Intrinsic::amdgcn_ds_gws_sema_v:
3135 return AMDGPU::DS_GWS_SEMA_V;
3136 case Intrinsic::amdgcn_ds_gws_sema_br:
3137 return AMDGPU::DS_GWS_SEMA_BR;
3138 case Intrinsic::amdgcn_ds_gws_sema_p:
3139 return AMDGPU::DS_GWS_SEMA_P;
3140 case Intrinsic::amdgcn_ds_gws_sema_release_all:
3141 return AMDGPU::DS_GWS_SEMA_RELEASE_ALL;
3142 default:
3143 llvm_unreachable("not a gws intrinsic");
3144 }
3145}
3146
3147void AMDGPUDAGToDAGISel::SelectDS_GWS(SDNode *N, unsigned IntrID) {
3148 if (!Subtarget->hasGWS() ||
3149 (IntrID == Intrinsic::amdgcn_ds_gws_sema_release_all &&
3150 !Subtarget->hasGWSSemaReleaseAll())) {
3151 // Let this error.
3152 SelectCode(N);
3153 return;
3154 }
3155
3156 // Chain, intrinsic ID, vsrc, offset
3157 const bool HasVSrc = N->getNumOperands() == 4;
3158 assert(HasVSrc || N->getNumOperands() == 3);
3159
3160 SDLoc SL(N);
3161 SDValue BaseOffset = N->getOperand(Num: HasVSrc ? 3 : 2);
3162 int ImmOffset = 0;
3163 MemIntrinsicSDNode *M = cast<MemIntrinsicSDNode>(Val: N);
3164 MachineMemOperand *MMO = M->getMemOperand();
3165
3166 // Don't worry if the offset ends up in a VGPR. Only one lane will have
3167 // effect, so SIFixSGPRCopies will validly insert readfirstlane.
3168
3169 // The resource id offset is computed as (<isa opaque base> + M0[21:16] +
3170 // offset field) % 64. Some versions of the programming guide omit the m0
3171 // part, or claim it's from offset 0.
3172 if (ConstantSDNode *ConstOffset = dyn_cast<ConstantSDNode>(Val&: BaseOffset)) {
3173 // If we have a constant offset, try to use the 0 in m0 as the base.
3174 // TODO: Look into changing the default m0 initialization value. If the
3175 // default -1 only set the low 16-bits, we could leave it as-is and add 1 to
3176 // the immediate offset.
3177 glueCopyToM0(N, Val: CurDAG->getTargetConstant(Val: 0, DL: SL, VT: MVT::i32));
3178 ImmOffset = ConstOffset->getZExtValue();
3179 } else {
3180 if (CurDAG->isBaseWithConstantOffset(Op: BaseOffset)) {
3181 ImmOffset = BaseOffset.getConstantOperandVal(i: 1);
3182 BaseOffset = BaseOffset.getOperand(i: 0);
3183 }
3184
3185 // Prefer to do the shift in an SGPR since it should be possible to use m0
3186 // as the result directly. If it's already an SGPR, it will be eliminated
3187 // later.
3188 SDNode *SGPROffset
3189 = CurDAG->getMachineNode(Opcode: AMDGPU::V_READFIRSTLANE_B32, dl: SL, VT: MVT::i32,
3190 Op1: BaseOffset);
3191 // Shift to offset in m0
3192 SDNode *M0Base
3193 = CurDAG->getMachineNode(Opcode: AMDGPU::S_LSHL_B32, dl: SL, VT: MVT::i32,
3194 Op1: SDValue(SGPROffset, 0),
3195 Op2: CurDAG->getTargetConstant(Val: 16, DL: SL, VT: MVT::i32));
3196 glueCopyToM0(N, Val: SDValue(M0Base, 0));
3197 }
3198
3199 SDValue Chain = N->getOperand(Num: 0);
3200 SDValue OffsetField = CurDAG->getTargetConstant(Val: ImmOffset, DL: SL, VT: MVT::i32);
3201
3202 const unsigned Opc = gwsIntrinToOpcode(IntrID);
3203
3204 const MCInstrDesc &InstrDesc = TII->get(Opcode: Opc);
3205 int Data0Idx = AMDGPU::getNamedOperandIdx(Opcode: Opc, Name: AMDGPU::OpName::data0);
3206
3207 const TargetRegisterClass *DataRC = TII->getRegClass(MCID: InstrDesc, OpNum: Data0Idx);
3208
3209 SmallVector<SDValue, 5> Ops;
3210 if (HasVSrc) {
3211 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
3212
3213 SDValue Data = N->getOperand(Num: 2);
3214 MVT DataVT = Data.getValueType().getSimpleVT();
3215 if (TRI->isTypeLegalForClass(RC: *DataRC, T: DataVT)) {
3216 // Normal 32-bit case.
3217 Ops.push_back(Elt: N->getOperand(Num: 2));
3218 } else {
3219 // Operand is really 32-bits, but requires 64-bit alignment, so use the
3220 // even aligned 64-bit register class.
3221 const SDValue RegSeqOps[] = {
3222 CurDAG->getTargetConstant(Val: DataRC->getID(), DL: SL, VT: MVT::i32), Data,
3223 CurDAG->getTargetConstant(Val: AMDGPU::sub0, DL: SL, VT: MVT::i32),
3224 SDValue(
3225 CurDAG->getMachineNode(Opcode: TargetOpcode::IMPLICIT_DEF, dl: SL, VT: MVT::i32),
3226 0),
3227 CurDAG->getTargetConstant(Val: AMDGPU::sub1, DL: SL, VT: MVT::i32)};
3228
3229 Ops.push_back(Elt: SDValue(CurDAG->getMachineNode(Opcode: TargetOpcode::REG_SEQUENCE,
3230 dl: SL, VT: MVT::v2i32, Ops: RegSeqOps),
3231 0));
3232 }
3233 }
3234
3235 Ops.push_back(Elt: OffsetField);
3236 Ops.push_back(Elt: Chain);
3237
3238 SDNode *Selected = CurDAG->SelectNodeTo(N, MachineOpc: Opc, VTs: N->getVTList(), Ops);
3239 CurDAG->setNodeMemRefs(N: cast<MachineSDNode>(Val: Selected), NewMemRefs: {MMO});
3240}
3241
3242void AMDGPUDAGToDAGISel::SelectInterpP1F16(SDNode *N) {
3243 if (Subtarget->getLDSBankCount() != 16) {
3244 // This is a single instruction with a pattern.
3245 SelectCode(N);
3246 return;
3247 }
3248
3249 SDLoc DL(N);
3250
3251 // This requires 2 instructions. It is possible to write a pattern to support
3252 // this, but the generated isel emitter doesn't correctly deal with multiple
3253 // output instructions using the same physical register input. The copy to m0
3254 // is incorrectly placed before the second instruction.
3255 //
3256 // TODO: Match source modifiers.
3257 //
3258 // def : Pat <
3259 // (int_amdgcn_interp_p1_f16
3260 // (VOP3Mods f32:$src0, i32:$src0_modifiers),
3261 // (i32 timm:$attrchan), (i32 timm:$attr),
3262 // (i1 timm:$high), M0),
3263 // (V_INTERP_P1LV_F16 $src0_modifiers, VGPR_32:$src0, timm:$attr,
3264 // timm:$attrchan, 0,
3265 // (V_INTERP_MOV_F32 2, timm:$attr, timm:$attrchan), timm:$high)> {
3266 // let Predicates = [has16BankLDS];
3267 // }
3268
3269 // 16 bank LDS
3270 SDValue ToM0 = CurDAG->getCopyToReg(Chain: CurDAG->getEntryNode(), dl: DL, Reg: AMDGPU::M0,
3271 N: N->getOperand(Num: 5), Glue: SDValue());
3272
3273 SDVTList VTs = CurDAG->getVTList(VT1: MVT::f32, VT2: MVT::Other);
3274
3275 SDNode *InterpMov =
3276 CurDAG->getMachineNode(Opcode: AMDGPU::V_INTERP_MOV_F32, dl: DL, VTs, Ops: {
3277 CurDAG->getTargetConstant(Val: 2, DL, VT: MVT::i32), // P0
3278 N->getOperand(Num: 3), // Attr
3279 N->getOperand(Num: 2), // Attrchan
3280 ToM0.getValue(R: 1) // In glue
3281 });
3282
3283 SDNode *InterpP1LV =
3284 CurDAG->getMachineNode(Opcode: AMDGPU::V_INTERP_P1LV_F16, dl: DL, VT: MVT::f32, Ops: {
3285 CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i32), // $src0_modifiers
3286 N->getOperand(Num: 1), // Src0
3287 N->getOperand(Num: 3), // Attr
3288 N->getOperand(Num: 2), // Attrchan
3289 CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i32), // $src2_modifiers
3290 SDValue(InterpMov, 0), // Src2 - holds two f16 values selected by high
3291 N->getOperand(Num: 4), // high
3292 CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i1), // $clamp
3293 CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i32), // $omod
3294 SDValue(InterpMov, 1)
3295 });
3296
3297 CurDAG->ReplaceAllUsesOfValueWith(From: SDValue(N, 0), To: SDValue(InterpP1LV, 0));
3298}
3299
3300void AMDGPUDAGToDAGISel::SelectINTRINSIC_W_CHAIN(SDNode *N) {
3301 unsigned IntrID = N->getConstantOperandVal(Num: 1);
3302 switch (IntrID) {
3303 case Intrinsic::amdgcn_ds_append:
3304 case Intrinsic::amdgcn_ds_consume: {
3305 if (N->getValueType(ResNo: 0) != MVT::i32)
3306 break;
3307 SelectDSAppendConsume(N, IntrID);
3308 return;
3309 }
3310 case Intrinsic::amdgcn_ds_bvh_stack_rtn:
3311 case Intrinsic::amdgcn_ds_bvh_stack_push4_pop1_rtn:
3312 case Intrinsic::amdgcn_ds_bvh_stack_push8_pop1_rtn:
3313 case Intrinsic::amdgcn_ds_bvh_stack_push8_pop2_rtn:
3314 SelectDSBvhStackIntrinsic(N, IntrID);
3315 return;
3316 case Intrinsic::amdgcn_init_whole_wave:
3317 CurDAG->getMachineFunction()
3318 .getInfo<SIMachineFunctionInfo>()
3319 ->setInitWholeWave();
3320 break;
3321 }
3322
3323 SelectCode(N);
3324}
3325
3326void AMDGPUDAGToDAGISel::SelectINTRINSIC_WO_CHAIN(SDNode *N) {
3327 unsigned IntrID = N->getConstantOperandVal(Num: 0);
3328 unsigned Opcode = AMDGPU::INSTRUCTION_LIST_END;
3329 SDNode *ConvGlueNode = N->getGluedNode();
3330 if (ConvGlueNode) {
3331 // FIXME: Possibly iterate over multiple glue nodes?
3332 assert(ConvGlueNode->getOpcode() == ISD::CONVERGENCECTRL_GLUE);
3333 ConvGlueNode = ConvGlueNode->getOperand(Num: 0).getNode();
3334 ConvGlueNode =
3335 CurDAG->getMachineNode(Opcode: TargetOpcode::CONVERGENCECTRL_GLUE, dl: {},
3336 VT: MVT::Glue, Op1: SDValue(ConvGlueNode, 0));
3337 } else {
3338 ConvGlueNode = nullptr;
3339 }
3340 switch (IntrID) {
3341 case Intrinsic::amdgcn_wqm:
3342 Opcode = AMDGPU::WQM;
3343 break;
3344 case Intrinsic::amdgcn_softwqm:
3345 Opcode = AMDGPU::SOFT_WQM;
3346 break;
3347 case Intrinsic::amdgcn_wwm:
3348 case Intrinsic::amdgcn_strict_wwm:
3349 Opcode = AMDGPU::STRICT_WWM;
3350 break;
3351 case Intrinsic::amdgcn_strict_wqm:
3352 Opcode = AMDGPU::STRICT_WQM;
3353 break;
3354 case Intrinsic::amdgcn_interp_p1_f16:
3355 SelectInterpP1F16(N);
3356 return;
3357 case Intrinsic::amdgcn_permlane16_swap:
3358 case Intrinsic::amdgcn_permlane32_swap: {
3359 if ((IntrID == Intrinsic::amdgcn_permlane16_swap &&
3360 !Subtarget->hasPermlane16Swap()) ||
3361 (IntrID == Intrinsic::amdgcn_permlane32_swap &&
3362 !Subtarget->hasPermlane32Swap())) {
3363 SelectCode(N); // Hit the default error
3364 return;
3365 }
3366
3367 Opcode = IntrID == Intrinsic::amdgcn_permlane16_swap
3368 ? AMDGPU::V_PERMLANE16_SWAP_B32_e64
3369 : AMDGPU::V_PERMLANE32_SWAP_B32_e64;
3370
3371 SmallVector<SDValue, 4> NewOps(N->op_begin() + 1, N->op_end());
3372 if (ConvGlueNode)
3373 NewOps.push_back(Elt: SDValue(ConvGlueNode, 0));
3374
3375 bool FI = N->getConstantOperandVal(Num: 3);
3376 NewOps[2] = CurDAG->getTargetConstant(
3377 Val: FI ? AMDGPU::DPP::DPP_FI_1 : AMDGPU::DPP::DPP_FI_0, DL: SDLoc(), VT: MVT::i32);
3378
3379 CurDAG->SelectNodeTo(N, MachineOpc: Opcode, VTs: N->getVTList(), Ops: NewOps);
3380 return;
3381 }
3382 default:
3383 SelectCode(N);
3384 break;
3385 }
3386
3387 if (Opcode != AMDGPU::INSTRUCTION_LIST_END) {
3388 SDValue Src = N->getOperand(Num: 1);
3389 CurDAG->SelectNodeTo(N, MachineOpc: Opcode, VTs: N->getVTList(), Ops: {Src});
3390 }
3391
3392 if (ConvGlueNode) {
3393 SmallVector<SDValue, 4> NewOps(N->ops());
3394 NewOps.push_back(Elt: SDValue(ConvGlueNode, 0));
3395 CurDAG->MorphNodeTo(N, Opc: N->getOpcode(), VTs: N->getVTList(), Ops: NewOps);
3396 }
3397}
3398
3399void AMDGPUDAGToDAGISel::SelectINTRINSIC_VOID(SDNode *N) {
3400 unsigned IntrID = N->getConstantOperandVal(Num: 1);
3401 switch (IntrID) {
3402 case Intrinsic::amdgcn_ds_gws_init:
3403 case Intrinsic::amdgcn_ds_gws_barrier:
3404 case Intrinsic::amdgcn_ds_gws_sema_v:
3405 case Intrinsic::amdgcn_ds_gws_sema_br:
3406 case Intrinsic::amdgcn_ds_gws_sema_p:
3407 case Intrinsic::amdgcn_ds_gws_sema_release_all:
3408 SelectDS_GWS(N, IntrID);
3409 return;
3410 case Intrinsic::amdgcn_tensor_load_to_lds:
3411 case Intrinsic::amdgcn_tensor_store_from_lds:
3412 SelectTensorLoadStore(N, IntrID);
3413 return;
3414 default:
3415 break;
3416 }
3417
3418 SelectCode(N);
3419}
3420
3421void AMDGPUDAGToDAGISel::SelectWAVE_ADDRESS(SDNode *N) {
3422 SDValue Log2WaveSize =
3423 CurDAG->getTargetConstant(Val: Subtarget->getWavefrontSizeLog2(), DL: SDLoc(N), VT: MVT::i32);
3424 CurDAG->SelectNodeTo(N, MachineOpc: AMDGPU::S_LSHR_B32, VTs: N->getVTList(),
3425 Ops: {N->getOperand(Num: 0), Log2WaveSize});
3426}
3427
3428void AMDGPUDAGToDAGISel::SelectSTACKRESTORE(SDNode *N) {
3429 SDValue SrcVal = N->getOperand(Num: 1);
3430 if (SrcVal.getValueType() != MVT::i32) {
3431 SelectCode(N); // Emit default error
3432 return;
3433 }
3434
3435 SDValue CopyVal;
3436 Register SP = TLI->getStackPointerRegisterToSaveRestore();
3437 SDLoc SL(N);
3438
3439 if (SrcVal.getOpcode() == AMDGPUISD::WAVE_ADDRESS) {
3440 CopyVal = SrcVal.getOperand(i: 0);
3441 } else {
3442 SDValue Log2WaveSize = CurDAG->getTargetConstant(
3443 Val: Subtarget->getWavefrontSizeLog2(), DL: SL, VT: MVT::i32);
3444
3445 if (N->isDivergent()) {
3446 SrcVal = SDValue(CurDAG->getMachineNode(Opcode: AMDGPU::V_READFIRSTLANE_B32, dl: SL,
3447 VT: MVT::i32, Op1: SrcVal),
3448 0);
3449 }
3450
3451 CopyVal = SDValue(CurDAG->getMachineNode(Opcode: AMDGPU::S_LSHL_B32, dl: SL, VT: MVT::i32,
3452 Ops: {SrcVal, Log2WaveSize}),
3453 0);
3454 }
3455
3456 SDValue CopyToSP = CurDAG->getCopyToReg(Chain: N->getOperand(Num: 0), dl: SL, Reg: SP, N: CopyVal);
3457 CurDAG->ReplaceAllUsesOfValueWith(From: SDValue(N, 0), To: CopyToSP);
3458}
3459
3460void AMDGPUDAGToDAGISel::SelectWRITE_REGISTER(SDNode *N) {
3461 const MDString *RegStr = cast<MDString>(
3462 Val: cast<MDNodeSDNode>(Val: N->getOperand(Num: 1))->getMD()->getOperand(I: 0));
3463 SDValue SrcVal = N->getOperand(Num: 2);
3464 EVT VT = SrcVal.getValueType();
3465 Register Reg = TLI->getRegisterByName(RegName: RegStr->getString().data(),
3466 Ty: getLLTForMVT(Ty: VT.getSimpleVT()),
3467 MF: CurDAG->getMachineFunction());
3468 if (!Reg) {
3469 const Function &Fn = CurDAG->getMachineFunction().getFunction();
3470 Fn.getContext().diagnose(DI: DiagnosticInfoGenericWithLoc(
3471 "invalid register \"" + Twine(RegStr->getString()) +
3472 "\" for llvm.write_register",
3473 Fn, N->getDebugLoc()));
3474 ReplaceUses(F: SDValue(N, 0), T: N->getOperand(Num: 0));
3475 CurDAG->RemoveDeadNode(N);
3476 return;
3477 }
3478
3479 // Speculatively insert a readfirstlane in case the source value ends up in a
3480 // VGPR, which hopefully will fold away if not.
3481 SDLoc SL(N);
3482 SDValue CopyVal;
3483 if (isa<ConstantSDNode>(Val: SrcVal)) {
3484 CopyVal = SrcVal;
3485 } else if (VT == MVT::i32) {
3486 CopyVal = SDValue(CurDAG->getMachineNode(Opcode: AMDGPU::V_READFIRSTLANE_B32, dl: SL,
3487 VT: MVT::i32, Op1: SrcVal),
3488 0);
3489 } else {
3490 assert(VT == MVT::i64);
3491 SDValue Lo =
3492 CurDAG->getTargetExtractSubreg(SRIdx: AMDGPU::sub0, DL: SL, VT: MVT::i32, Operand: SrcVal);
3493 SDValue Hi =
3494 CurDAG->getTargetExtractSubreg(SRIdx: AMDGPU::sub1, DL: SL, VT: MVT::i32, Operand: SrcVal);
3495 Lo = SDValue(
3496 CurDAG->getMachineNode(Opcode: AMDGPU::V_READFIRSTLANE_B32, dl: SL, VT: MVT::i32, Op1: Lo),
3497 0);
3498 Hi = SDValue(
3499 CurDAG->getMachineNode(Opcode: AMDGPU::V_READFIRSTLANE_B32, dl: SL, VT: MVT::i32, Op1: Hi),
3500 0);
3501 CopyVal = emitRegSequence(CurDAG&: *CurDAG, DstRegClass: AMDGPU::SReg_64RegClassID, DstTy: VT, Elts: {Lo, Hi},
3502 SubRegClass: {AMDGPU::sub0, AMDGPU::sub1}, DL: SL);
3503 }
3504
3505 SDValue CopyToReg = CurDAG->getCopyToReg(Chain: N->getOperand(Num: 0), dl: SL, Reg, N: CopyVal);
3506 CurDAG->ReplaceAllUsesOfValueWith(From: SDValue(N, 0), To: CopyToReg);
3507}
3508
3509bool AMDGPUDAGToDAGISel::SelectVOP3ModsImpl(SDValue In, SDValue &Src,
3510 unsigned &Mods,
3511 bool IsCanonicalizing,
3512 bool AllowAbs) const {
3513 Mods = SISrcMods::NONE;
3514 Src = In;
3515
3516 if (Src.getOpcode() == ISD::FNEG) {
3517 Mods |= SISrcMods::NEG;
3518 Src = Src.getOperand(i: 0);
3519 } else if (Src.getOpcode() == ISD::FSUB && IsCanonicalizing) {
3520 // Fold fsub [+-]0 into fneg. This may not have folded depending on the
3521 // denormal mode, but we're implicitly canonicalizing in a source operand.
3522 auto *LHS = dyn_cast<ConstantFPSDNode>(Val: Src.getOperand(i: 0));
3523 if (LHS && LHS->isZero()) {
3524 Mods |= SISrcMods::NEG;
3525 Src = Src.getOperand(i: 1);
3526 }
3527 }
3528
3529 if (AllowAbs && Src.getOpcode() == ISD::FABS) {
3530 Mods |= SISrcMods::ABS;
3531 Src = Src.getOperand(i: 0);
3532 }
3533
3534 if (Mods != SISrcMods::NONE)
3535 return true;
3536
3537 // Convert various sign-bit masks on integers to src mods. Currently disabled
3538 // for 16-bit types as the codegen replaces the operand without adding a
3539 // srcmod. This is intentionally finding the cases where we are performing
3540 // float neg and abs on int types, the goal is not to obtain two's complement
3541 // neg or abs. Limit converison to select operands via the nonCanonalizing
3542 // pattern.
3543 // TODO: Add 16-bit support.
3544 if (IsCanonicalizing)
3545 return true;
3546
3547 // v2i32 xor/or/and are legal. A vselect using these instructions as operands
3548 // is scalarised into two selects with EXTRACT_VECTOR_ELT operands. Peek
3549 // through the extract to the bitwise op.
3550 SDValue PeekSrc =
3551 Src->getOpcode() == ISD::EXTRACT_VECTOR_ELT ? Src->getOperand(Num: 0) : Src;
3552 // Convert various sign-bit masks to src mods. Currently disabled for 16-bit
3553 // types as the codegen replaces the operand without adding a srcmod.
3554 // This is intentionally finding the cases where we are performing float neg
3555 // and abs on int types, the goal is not to obtain two's complement neg or
3556 // abs.
3557 // TODO: Add 16-bit support.
3558 unsigned Opc = PeekSrc.getOpcode();
3559 EVT VT = Src.getValueType();
3560 if ((Opc != ISD::AND && Opc != ISD::OR && Opc != ISD::XOR) ||
3561 (VT != MVT::i32 && VT != MVT::v2i32 && VT != MVT::i64))
3562 return true;
3563
3564 ConstantSDNode *CRHS = isConstOrConstSplat(N: PeekSrc->getOperand(Num: 1));
3565 if (!CRHS)
3566 return true;
3567
3568 auto ReplaceSrc = [&]() -> SDValue {
3569 if (Src->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
3570 return Src.getOperand(i: 0);
3571
3572 SDValue LHS = PeekSrc->getOperand(Num: 0);
3573 SDValue Index = Src->getOperand(Num: 1);
3574 return CurDAG->getNode(Opcode: ISD::EXTRACT_VECTOR_ELT, DL: SDLoc(Src),
3575 VT: Src.getValueType(), N1: LHS, N2: Index);
3576 };
3577
3578 // Recognise Srcmods:
3579 // (xor a, 0x80000000) or v2i32 (xor a, {0x80000000,0x80000000}) as NEG.
3580 // (and a, 0x7fffffff) or v2i32 (and a, {0x7fffffff,0x7fffffff}) as ABS.
3581 // (or a, 0x80000000) or v2i32 (or a, {0x80000000,0x80000000}) as NEG+ABS
3582 // SrcModifiers.
3583 if (Opc == ISD::XOR && CRHS->getAPIntValue().isSignMask()) {
3584 Mods |= SISrcMods::NEG;
3585 Src = ReplaceSrc();
3586 } else if (Opc == ISD::AND && AllowAbs &&
3587 CRHS->getAPIntValue().isMaxSignedValue()) {
3588 Mods |= SISrcMods::ABS;
3589 Src = ReplaceSrc();
3590 } else if (Opc == ISD::OR && AllowAbs && CRHS->getAPIntValue().isSignMask()) {
3591 Mods |= SISrcMods::ABS | SISrcMods::NEG;
3592 Src = ReplaceSrc();
3593 }
3594
3595 return true;
3596}
3597
3598bool AMDGPUDAGToDAGISel::SelectVOP3Mods(SDValue In, SDValue &Src,
3599 SDValue &SrcMods) const {
3600 unsigned Mods;
3601 if (SelectVOP3ModsImpl(In, Src, Mods, /*IsCanonicalizing=*/true,
3602 /*AllowAbs=*/true)) {
3603 SrcMods = CurDAG->getTargetConstant(Val: Mods, DL: SDLoc(In), VT: MVT::i32);
3604 return true;
3605 }
3606
3607 return false;
3608}
3609
3610bool AMDGPUDAGToDAGISel::SelectVOP3ModsNonCanonicalizing(
3611 SDValue In, SDValue &Src, SDValue &SrcMods) const {
3612 unsigned Mods;
3613 if (SelectVOP3ModsImpl(In, Src, Mods, /*IsCanonicalizing=*/false,
3614 /*AllowAbs=*/true)) {
3615 SrcMods = CurDAG->getTargetConstant(Val: Mods, DL: SDLoc(In), VT: MVT::i32);
3616 return true;
3617 }
3618
3619 return false;
3620}
3621
3622bool AMDGPUDAGToDAGISel::SelectVOP3BMods(SDValue In, SDValue &Src,
3623 SDValue &SrcMods) const {
3624 unsigned Mods;
3625 if (SelectVOP3ModsImpl(In, Src, Mods,
3626 /*IsCanonicalizing=*/true,
3627 /*AllowAbs=*/false)) {
3628 SrcMods = CurDAG->getTargetConstant(Val: Mods, DL: SDLoc(In), VT: MVT::i32);
3629 return true;
3630 }
3631
3632 return false;
3633}
3634
3635bool AMDGPUDAGToDAGISel::SelectVOP3NoMods(SDValue In, SDValue &Src) const {
3636 if (In.getOpcode() == ISD::FABS || In.getOpcode() == ISD::FNEG)
3637 return false;
3638
3639 Src = In;
3640 return true;
3641}
3642
3643bool AMDGPUDAGToDAGISel::SelectVINTERPModsImpl(SDValue In, SDValue &Src,
3644 SDValue &SrcMods,
3645 bool OpSel) const {
3646 unsigned Mods;
3647 if (SelectVOP3ModsImpl(In, Src, Mods,
3648 /*IsCanonicalizing=*/true,
3649 /*AllowAbs=*/false)) {
3650 if (OpSel)
3651 Mods |= SISrcMods::OP_SEL_0;
3652 SrcMods = CurDAG->getTargetConstant(Val: Mods, DL: SDLoc(In), VT: MVT::i32);
3653 return true;
3654 }
3655
3656 return false;
3657}
3658
3659bool AMDGPUDAGToDAGISel::SelectVINTERPMods(SDValue In, SDValue &Src,
3660 SDValue &SrcMods) const {
3661 return SelectVINTERPModsImpl(In, Src, SrcMods, /* OpSel */ false);
3662}
3663
3664bool AMDGPUDAGToDAGISel::SelectVINTERPModsHi(SDValue In, SDValue &Src,
3665 SDValue &SrcMods) const {
3666 return SelectVINTERPModsImpl(In, Src, SrcMods, /* OpSel */ true);
3667}
3668
3669bool AMDGPUDAGToDAGISel::SelectVOP3Mods0(SDValue In, SDValue &Src,
3670 SDValue &SrcMods, SDValue &Clamp,
3671 SDValue &Omod) const {
3672 SDLoc DL(In);
3673 Clamp = CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i1);
3674 Omod = CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i1);
3675
3676 return SelectVOP3Mods(In, Src, SrcMods);
3677}
3678
3679bool AMDGPUDAGToDAGISel::SelectVOP3BMods0(SDValue In, SDValue &Src,
3680 SDValue &SrcMods, SDValue &Clamp,
3681 SDValue &Omod) const {
3682 SDLoc DL(In);
3683 Clamp = CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i1);
3684 Omod = CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i1);
3685
3686 return SelectVOP3BMods(In, Src, SrcMods);
3687}
3688
3689bool AMDGPUDAGToDAGISel::SelectVOP3OMods(SDValue In, SDValue &Src,
3690 SDValue &Clamp, SDValue &Omod) const {
3691 Src = In;
3692
3693 SDLoc DL(In);
3694 Clamp = CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i1);
3695 Omod = CurDAG->getTargetConstant(Val: 0, DL, VT: MVT::i1);
3696
3697 return true;
3698}
3699
3700bool AMDGPUDAGToDAGISel::SelectVOP3PMods(SDValue In, SDValue &Src,
3701 SDValue &SrcMods, bool IsDOT) const {
3702 unsigned Mods = SISrcMods::NONE;
3703 Src = In;
3704
3705 // TODO: Handle G_FSUB 0 as fneg
3706 if (Src.getOpcode() == ISD::FNEG) {
3707 Mods ^= (SISrcMods::NEG | SISrcMods::NEG_HI);
3708 Src = Src.getOperand(i: 0);
3709 }
3710
3711 // 64-bit VOP3P instructions do not have OPSEL or ABS.
3712 bool HasOpSel = Src.getValueSizeInBits() != 128;
3713
3714 if (Src.getOpcode() == ISD::BUILD_VECTOR && Src.getNumOperands() == 2 &&
3715 (!IsDOT || !Subtarget->hasDOTOpSelHazard())) {
3716 unsigned VecMods = Mods;
3717
3718 SDValue Lo = stripBitcast(Val: Src.getOperand(i: 0));
3719 SDValue Hi = stripBitcast(Val: Src.getOperand(i: 1));
3720
3721 if (Lo.getOpcode() == ISD::FNEG) {
3722 Lo = stripBitcast(Val: Lo.getOperand(i: 0));
3723 Mods ^= SISrcMods::NEG;
3724 }
3725
3726 if (Hi.getOpcode() == ISD::FNEG) {
3727 Hi = stripBitcast(Val: Hi.getOperand(i: 0));
3728 Mods ^= SISrcMods::NEG_HI;
3729 }
3730
3731 if (HasOpSel) {
3732 if (isExtractHiElt(In: Lo, Out&: Lo))
3733 Mods |= SISrcMods::OP_SEL_0;
3734
3735 if (isExtractHiElt(In: Hi, Out&: Hi))
3736 Mods |= SISrcMods::OP_SEL_1;
3737 }
3738
3739 unsigned VecSize = Src.getValueSizeInBits();
3740 Lo = stripExtractLoElt(In: Lo);
3741 Hi = stripExtractLoElt(In: Hi);
3742
3743 if (Lo.getValueSizeInBits() > VecSize) {
3744 Lo = CurDAG->getTargetExtractSubreg(
3745 SRIdx: (VecSize > 32) ? AMDGPU::sub0_sub1 : AMDGPU::sub0, DL: SDLoc(In),
3746 VT: MVT::getIntegerVT(BitWidth: VecSize), Operand: Lo);
3747 }
3748
3749 if (Hi.getValueSizeInBits() > VecSize) {
3750 Hi = CurDAG->getTargetExtractSubreg(
3751 SRIdx: (VecSize > 32) ? AMDGPU::sub0_sub1 : AMDGPU::sub0, DL: SDLoc(In),
3752 VT: MVT::getIntegerVT(BitWidth: VecSize), Operand: Hi);
3753 }
3754
3755 assert(Lo.getValueSizeInBits() <= VecSize &&
3756 Hi.getValueSizeInBits() <= VecSize);
3757
3758 if (Lo == Hi && !isInlineImmediate(N: Lo.getNode())) {
3759 // Really a scalar input. Just select from the low half of the register to
3760 // avoid packing.
3761
3762 if (VecSize == Lo.getValueSizeInBits()) {
3763 Src = Lo;
3764 } else if (VecSize == 32) {
3765 Src = createVOP3PSrc32FromLo16(Lo, Src, CurDAG, Subtarget);
3766 } else {
3767 assert((Lo.getValueSizeInBits() == 32 && VecSize == 64) ||
3768 (Lo.getValueSizeInBits() == 64 && VecSize == 128));
3769
3770 SDLoc SL(In);
3771 SDValue Undef = SDValue(
3772 CurDAG->getMachineNode(Opcode: TargetOpcode::IMPLICIT_DEF, dl: SL,
3773 VT: Lo.getValueType()), 0);
3774 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
3775 // <2 x 64> instructions do not have OPSEL and also replicate low 64
3776 // bits of a scalar input into high 64 bits. Use VGPRs in this case.
3777 // TODO: This fact can be exploited but we need to set proper OPSEL for
3778 // codegen folding purposes. It will not affect a final instruction.
3779 auto RC = Lo->isDivergent() ? TRI->getVGPRClassForBitWidth(BitWidth: VecSize)
3780 : TRI->getSGPRClassForBitWidth(BitWidth: VecSize);
3781 unsigned NumRegs = Lo.getValueSizeInBits() == 32 ? 1 : 2;
3782 const SDValue Ops[] = {
3783 CurDAG->getTargetConstant(Val: RC->getID(), DL: SL, VT: MVT::i32), Lo,
3784 CurDAG->getTargetConstant(Val: TRI->getSubRegFromChannel(Channel: 0, NumRegs), DL: SL,
3785 VT: MVT::i32),
3786 // For packed 64-bit ops without OPSEL support, a later pass will
3787 // optimize the splat sgpr patterns to save registers.
3788 HasOpSel ? Undef : Lo,
3789 CurDAG->getTargetConstant(
3790 Val: TRI->getSubRegFromChannel(Channel: NumRegs, NumRegs), DL: SL, VT: MVT::i32)};
3791
3792 Src = SDValue(CurDAG->getMachineNode(Opcode: TargetOpcode::REG_SEQUENCE, dl: SL,
3793 VT: Src.getValueType(), Ops), 0);
3794 // Check that both op_sel_0 and op_sel_1 are zero.
3795 assert(!(Mods & (SISrcMods::OP_SEL_0 | SISrcMods::OP_SEL_1)));
3796 }
3797 SrcMods = CurDAG->getTargetConstant(Val: Mods, DL: SDLoc(In), VT: MVT::i32);
3798 return true;
3799 }
3800
3801 if (VecSize == 64 && Lo == Hi && isa<ConstantFPSDNode>(Val: Lo)) {
3802 uint64_t Lit = cast<ConstantFPSDNode>(Val&: Lo)->getValueAPF()
3803 .bitcastToAPInt().getZExtValue();
3804 if (AMDGPU::isInlinableLiteral32(Literal: Lit, HasInv2Pi: Subtarget->hasInv2PiInlineImm())) {
3805 Src = CurDAG->getTargetConstant(Val: Lit, DL: SDLoc(In), VT: MVT::i64);
3806 SrcMods = CurDAG->getTargetConstant(Val: Mods, DL: SDLoc(In), VT: MVT::i32);
3807 return true;
3808 }
3809 }
3810
3811 Mods = VecMods;
3812 } else if (Src.getOpcode() == ISD::VECTOR_SHUFFLE &&
3813 Src.getNumOperands() == 2) {
3814
3815 // TODO: We should repeat the build_vector source check above for the
3816 // vector_shuffle for negates and casts of individual elements.
3817
3818 assert(Src.getValueSizeInBits() != 128 &&
3819 "<2 x 64> VECTOR_SHUFFLE should not be legal.");
3820
3821 auto *SVN = cast<ShuffleVectorSDNode>(Val&: Src);
3822 ArrayRef<int> Mask = SVN->getMask();
3823
3824 if (Mask[0] < 2 && Mask[1] < 2) {
3825 // src1 should be undef.
3826 SDValue ShuffleSrc = SVN->getOperand(Num: 0);
3827
3828 if (ShuffleSrc.getOpcode() == ISD::FNEG) {
3829 ShuffleSrc = ShuffleSrc.getOperand(i: 0);
3830 Mods ^= (SISrcMods::NEG | SISrcMods::NEG_HI);
3831 }
3832
3833 if (Mask[0] == 1)
3834 Mods |= SISrcMods::OP_SEL_0;
3835 if (Mask[1] == 1)
3836 Mods |= SISrcMods::OP_SEL_1;
3837
3838 Src = ShuffleSrc;
3839 SrcMods = CurDAG->getTargetConstant(Val: Mods, DL: SDLoc(In), VT: MVT::i32);
3840 return true;
3841 }
3842 }
3843
3844 // Packed instructions do not have abs modifiers.
3845 Mods |= SISrcMods::OP_SEL_1;
3846
3847 SrcMods = CurDAG->getTargetConstant(Val: Mods, DL: SDLoc(In), VT: MVT::i32);
3848 return true;
3849}
3850
3851bool AMDGPUDAGToDAGISel::SelectVOP3PModsDOT(SDValue In, SDValue &Src,
3852 SDValue &SrcMods) const {
3853 return SelectVOP3PMods(In, Src, SrcMods, IsDOT: true);
3854}
3855
3856bool AMDGPUDAGToDAGISel::SelectVOP3PNoModsDOT(SDValue In, SDValue &Src) const {
3857 SDValue SrcTmp, SrcModsTmp;
3858 SelectVOP3PMods(In, Src&: SrcTmp, SrcMods&: SrcModsTmp, IsDOT: true);
3859 if (cast<ConstantSDNode>(Val&: SrcModsTmp)->getZExtValue() == SISrcMods::OP_SEL_1) {
3860 Src = SrcTmp;
3861 return true;
3862 }
3863
3864 return false;
3865}
3866
3867bool AMDGPUDAGToDAGISel::SelectVOP3PModsF32(SDValue In, SDValue &Src,
3868 SDValue &SrcMods) const {
3869 SelectVOP3Mods(In, Src, SrcMods);
3870 unsigned Mods = SISrcMods::OP_SEL_1;
3871 Mods |= cast<ConstantSDNode>(Val&: SrcMods)->getZExtValue();
3872 SrcMods = CurDAG->getTargetConstant(Val: Mods, DL: SDLoc(In), VT: MVT::i32);
3873 return true;
3874}
3875
3876bool AMDGPUDAGToDAGISel::SelectVOP3PNoModsF32(SDValue In, SDValue &Src) const {
3877 SDValue SrcTmp, SrcModsTmp;
3878 SelectVOP3PModsF32(In, Src&: SrcTmp, SrcMods&: SrcModsTmp);
3879 if (cast<ConstantSDNode>(Val&: SrcModsTmp)->getZExtValue() == SISrcMods::OP_SEL_1) {
3880 Src = SrcTmp;
3881 return true;
3882 }
3883
3884 return false;
3885}
3886
3887bool AMDGPUDAGToDAGISel::SelectWMMAOpSelVOP3PMods(SDValue In,
3888 SDValue &Src) const {
3889 const ConstantSDNode *C = cast<ConstantSDNode>(Val&: In);
3890 assert(C->getAPIntValue().getBitWidth() == 1 && "expected i1 value");
3891
3892 unsigned Mods = SISrcMods::OP_SEL_1;
3893 unsigned SrcVal = C->getZExtValue();
3894 if (SrcVal == 1)
3895 Mods |= SISrcMods::OP_SEL_0;
3896
3897 Src = CurDAG->getTargetConstant(Val: Mods, DL: SDLoc(In), VT: MVT::i32);
3898 return true;
3899}
3900
3901MachineSDNode *
3902AMDGPUDAGToDAGISel::buildRegSequence32(SmallVectorImpl<SDValue> &Elts,
3903 const SDLoc &DL) const {
3904 unsigned DstRegClass;
3905 EVT DstTy;
3906 switch (Elts.size()) {
3907 case 8:
3908 DstRegClass = AMDGPU::VReg_256RegClassID;
3909 DstTy = MVT::v8i32;
3910 break;
3911 case 4:
3912 DstRegClass = AMDGPU::VReg_128RegClassID;
3913 DstTy = MVT::v4i32;
3914 break;
3915 case 2:
3916 DstRegClass = AMDGPU::VReg_64RegClassID;
3917 DstTy = MVT::v2i32;
3918 break;
3919 default:
3920 llvm_unreachable("unhandled Reg sequence size");
3921 }
3922
3923 SmallVector<SDValue, 17> Ops;
3924 Ops.push_back(Elt: CurDAG->getTargetConstant(Val: DstRegClass, DL, VT: MVT::i32));
3925 for (unsigned i = 0; i < Elts.size(); ++i) {
3926 Ops.push_back(Elt: Elts[i]);
3927 Ops.push_back(Elt: CurDAG->getTargetConstant(
3928 Val: SIRegisterInfo::getSubRegFromChannel(Channel: i), DL, VT: MVT::i32));
3929 }
3930 return CurDAG->getMachineNode(Opcode: TargetOpcode::REG_SEQUENCE, dl: DL, VT: DstTy, Ops);
3931}
3932
3933MachineSDNode *
3934AMDGPUDAGToDAGISel::buildRegSequence16(SmallVectorImpl<SDValue> &Elts,
3935 const SDLoc &DL) const {
3936 SmallVector<SDValue, 8> PackedElts;
3937 assert("unhandled Reg sequence size" &&
3938 (Elts.size() == 8 || Elts.size() == 16));
3939
3940 // Pack 16-bit elements in pairs into 32-bit register. If both elements are
3941 // unpacked from 32-bit source use it, otherwise pack them using v_perm.
3942 for (unsigned i = 0; i < Elts.size(); i += 2) {
3943 SDValue LoSrc = stripExtractLoElt(In: stripBitcast(Val: Elts[i]));
3944 SDValue HiSrc;
3945 if (isExtractHiElt(In: Elts[i + 1], Out&: HiSrc) && LoSrc == HiSrc) {
3946 PackedElts.push_back(Elt: HiSrc);
3947 } else {
3948 if (Subtarget->useRealTrue16Insts()) {
3949 // FIXME-TRUE16. For now pack VGPR_32 for 16-bit source before
3950 // passing to v_perm_b32. Eventually we should use replace v_perm_b32
3951 // by reg_sequence.
3952 SDValue Undef = SDValue(
3953 CurDAG->getMachineNode(Opcode: TargetOpcode::IMPLICIT_DEF, dl: DL, VT: MVT::i16),
3954 0);
3955 Elts[i] =
3956 emitRegSequence(CurDAG&: *CurDAG, DstRegClass: AMDGPU::VGPR_32RegClassID, DstTy: MVT::i32,
3957 Elts: {Elts[i], Undef}, SubRegClass: {AMDGPU::lo16, AMDGPU::hi16}, DL);
3958 Elts[i + 1] = emitRegSequence(CurDAG&: *CurDAG, DstRegClass: AMDGPU::VGPR_32RegClassID,
3959 DstTy: MVT::i32, Elts: {Elts[i + 1], Undef},
3960 SubRegClass: {AMDGPU::lo16, AMDGPU::hi16}, DL);
3961 }
3962 SDValue PackLoLo = CurDAG->getTargetConstant(Val: 0x05040100, DL, VT: MVT::i32);
3963 MachineSDNode *Packed =
3964 CurDAG->getMachineNode(Opcode: AMDGPU::V_PERM_B32_e64, dl: DL, VT: MVT::i32,
3965 Ops: {Elts[i + 1], Elts[i], PackLoLo});
3966 PackedElts.push_back(Elt: SDValue(Packed, 0));
3967 }
3968 }
3969 return buildRegSequence32(Elts&: PackedElts, DL);
3970}
3971
3972MachineSDNode *
3973AMDGPUDAGToDAGISel::buildRegSequence(SmallVectorImpl<SDValue> &Elts,
3974 const SDLoc &DL,
3975 unsigned ElementSize) const {
3976 if (ElementSize == 16)
3977 return buildRegSequence16(Elts, DL);
3978 if (ElementSize == 32)
3979 return buildRegSequence32(Elts, DL);
3980 llvm_unreachable("Unhandled element size");
3981}
3982
3983void AMDGPUDAGToDAGISel::selectWMMAModsNegAbs(unsigned ModOpcode,
3984 unsigned &Mods,
3985 SmallVectorImpl<SDValue> &Elts,
3986 SDValue &Src, const SDLoc &DL,
3987 unsigned ElementSize) const {
3988 if (ModOpcode == ISD::FNEG) {
3989 Mods |= SISrcMods::NEG;
3990 // Check if all elements also have abs modifier
3991 SmallVector<SDValue, 8> NegAbsElts;
3992 for (auto El : Elts) {
3993 if (El.getOpcode() != ISD::FABS)
3994 break;
3995 NegAbsElts.push_back(Elt: El->getOperand(Num: 0));
3996 }
3997 if (Elts.size() != NegAbsElts.size()) {
3998 // Neg
3999 Src = SDValue(buildRegSequence(Elts, DL, ElementSize), 0);
4000 } else {
4001 // Neg and Abs
4002 Mods |= SISrcMods::NEG_HI;
4003 Src = SDValue(buildRegSequence(Elts&: NegAbsElts, DL, ElementSize), 0);
4004 }
4005 } else {
4006 assert(ModOpcode == ISD::FABS);
4007 // Abs
4008 Mods |= SISrcMods::NEG_HI;
4009 Src = SDValue(buildRegSequence(Elts, DL, ElementSize), 0);
4010 }
4011}
4012
4013// Check all f16 elements for modifiers while looking through b32 and v2b16
4014// build vector, stop if element does not satisfy ModifierCheck.
4015static void
4016checkWMMAElementsModifiersF16(BuildVectorSDNode *BV,
4017 std::function<bool(SDValue)> ModifierCheck) {
4018 for (unsigned i = 0; i < BV->getNumOperands(); ++i) {
4019 if (auto *F16Pair =
4020 dyn_cast<BuildVectorSDNode>(Val: stripBitcast(Val: BV->getOperand(Num: i)))) {
4021 for (unsigned i = 0; i < F16Pair->getNumOperands(); ++i) {
4022 SDValue ElF16 = stripBitcast(Val: F16Pair->getOperand(Num: i));
4023 if (!ModifierCheck(ElF16))
4024 break;
4025 }
4026 }
4027 }
4028}
4029
4030bool AMDGPUDAGToDAGISel::SelectWMMAModsF16Neg(SDValue In, SDValue &Src,
4031 SDValue &SrcMods) const {
4032 Src = In;
4033 unsigned Mods = SISrcMods::OP_SEL_1;
4034
4035 // mods are on f16 elements
4036 if (auto *BV = dyn_cast<BuildVectorSDNode>(Val: stripBitcast(Val: In))) {
4037 SmallVector<SDValue, 8> EltsF16;
4038
4039 checkWMMAElementsModifiersF16(BV, ModifierCheck: [&](SDValue Element) -> bool {
4040 if (Element.getOpcode() != ISD::FNEG)
4041 return false;
4042 EltsF16.push_back(Elt: Element.getOperand(i: 0));
4043 return true;
4044 });
4045
4046 // All elements have neg modifier
4047 if (BV->getNumOperands() * 2 == EltsF16.size()) {
4048 Src = SDValue(buildRegSequence16(Elts&: EltsF16, DL: SDLoc(In)), 0);
4049 Mods |= SISrcMods::NEG;
4050 Mods |= SISrcMods::NEG_HI;
4051 }
4052 }
4053
4054 // mods are on v2f16 elements
4055 if (auto *BV = dyn_cast<BuildVectorSDNode>(Val: stripBitcast(Val: In))) {
4056 SmallVector<SDValue, 8> EltsV2F16;
4057 for (unsigned i = 0; i < BV->getNumOperands(); ++i) {
4058 SDValue ElV2f16 = stripBitcast(Val: BV->getOperand(Num: i));
4059 // Based on first element decide which mod we match, neg or abs
4060 if (ElV2f16.getOpcode() != ISD::FNEG)
4061 break;
4062 EltsV2F16.push_back(Elt: ElV2f16.getOperand(i: 0));
4063 }
4064
4065 // All pairs of elements have neg modifier
4066 if (BV->getNumOperands() == EltsV2F16.size()) {
4067 Src = SDValue(buildRegSequence32(Elts&: EltsV2F16, DL: SDLoc(In)), 0);
4068 Mods |= SISrcMods::NEG;
4069 Mods |= SISrcMods::NEG_HI;
4070 }
4071 }
4072
4073 SrcMods = CurDAG->getTargetConstant(Val: Mods, DL: SDLoc(In), VT: MVT::i32);
4074 return true;
4075}
4076
4077bool AMDGPUDAGToDAGISel::SelectWMMAModsF16NegAbs(SDValue In, SDValue &Src,
4078 SDValue &SrcMods) const {
4079 Src = In;
4080 unsigned Mods = SISrcMods::OP_SEL_1;
4081 unsigned ModOpcode;
4082
4083 // mods are on f16 elements
4084 if (auto *BV = dyn_cast<BuildVectorSDNode>(Val: stripBitcast(Val: In))) {
4085 SmallVector<SDValue, 8> EltsF16;
4086 checkWMMAElementsModifiersF16(BV, ModifierCheck: [&](SDValue ElF16) -> bool {
4087 // Based on first element decide which mod we match, neg or abs
4088 if (EltsF16.empty())
4089 ModOpcode = (ElF16.getOpcode() == ISD::FNEG) ? ISD::FNEG : ISD::FABS;
4090 if (ElF16.getOpcode() != ModOpcode)
4091 return false;
4092 EltsF16.push_back(Elt: ElF16.getOperand(i: 0));
4093 return true;
4094 });
4095
4096 // All elements have ModOpcode modifier
4097 if (BV->getNumOperands() * 2 == EltsF16.size())
4098 selectWMMAModsNegAbs(ModOpcode, Mods, Elts&: EltsF16, Src, DL: SDLoc(In), ElementSize: 16);
4099 }
4100
4101 // mods are on v2f16 elements
4102 if (auto *BV = dyn_cast<BuildVectorSDNode>(Val: stripBitcast(Val: In))) {
4103 SmallVector<SDValue, 8> EltsV2F16;
4104
4105 for (unsigned i = 0; i < BV->getNumOperands(); ++i) {
4106 SDValue ElV2f16 = stripBitcast(Val: BV->getOperand(Num: i));
4107 // Based on first element decide which mod we match, neg or abs
4108 if (EltsV2F16.empty())
4109 ModOpcode = (ElV2f16.getOpcode() == ISD::FNEG) ? ISD::FNEG : ISD::FABS;
4110 if (ElV2f16->getOpcode() != ModOpcode)
4111 break;
4112 EltsV2F16.push_back(Elt: ElV2f16->getOperand(Num: 0));
4113 }
4114
4115 // All elements have ModOpcode modifier
4116 if (BV->getNumOperands() == EltsV2F16.size())
4117 selectWMMAModsNegAbs(ModOpcode, Mods, Elts&: EltsV2F16, Src, DL: SDLoc(In), ElementSize: 32);
4118 }
4119
4120 SrcMods = CurDAG->getTargetConstant(Val: Mods, DL: SDLoc(In), VT: MVT::i32);
4121 return true;
4122}
4123
4124bool AMDGPUDAGToDAGISel::SelectWMMAModsF32NegAbs(SDValue In, SDValue &Src,
4125 SDValue &SrcMods) const {
4126 Src = In;
4127 unsigned Mods = SISrcMods::OP_SEL_1;
4128 SmallVector<SDValue, 8> EltsF32;
4129
4130 if (auto *BV = dyn_cast<BuildVectorSDNode>(Val: stripBitcast(Val: In))) {
4131 assert(BV->getNumOperands() > 0);
4132 // Based on first element decide which mod we match, neg or abs
4133 SDValue ElF32 = stripBitcast(Val: BV->getOperand(Num: 0));
4134 unsigned ModOpcode =
4135 (ElF32.getOpcode() == ISD::FNEG) ? ISD::FNEG : ISD::FABS;
4136 for (unsigned i = 0; i < BV->getNumOperands(); ++i) {
4137 SDValue ElF32 = stripBitcast(Val: BV->getOperand(Num: i));
4138 if (ElF32.getOpcode() != ModOpcode)
4139 break;
4140 EltsF32.push_back(Elt: ElF32.getOperand(i: 0));
4141 }
4142
4143 // All elements had ModOpcode modifier
4144 if (BV->getNumOperands() == EltsF32.size())
4145 selectWMMAModsNegAbs(ModOpcode, Mods, Elts&: EltsF32, Src, DL: SDLoc(In), ElementSize: 32);
4146 }
4147
4148 SrcMods = CurDAG->getTargetConstant(Val: Mods, DL: SDLoc(In), VT: MVT::i32);
4149 return true;
4150}
4151
4152bool AMDGPUDAGToDAGISel::SelectWMMAVISrc(SDValue In, SDValue &Src) const {
4153 if (auto *BV = dyn_cast<BuildVectorSDNode>(Val&: In)) {
4154 BitVector UndefElements;
4155 if (SDValue Splat = BV->getSplatValue(UndefElements: &UndefElements))
4156 if (isInlineImmediate(N: Splat.getNode())) {
4157 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val&: Splat)) {
4158 unsigned Imm = C->getAPIntValue().getSExtValue();
4159 Src = CurDAG->getTargetConstant(Val: Imm, DL: SDLoc(In), VT: MVT::i32);
4160 return true;
4161 }
4162 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val&: Splat)) {
4163 unsigned Imm = C->getValueAPF().bitcastToAPInt().getSExtValue();
4164 Src = CurDAG->getTargetConstant(Val: Imm, DL: SDLoc(In), VT: MVT::i32);
4165 return true;
4166 }
4167 llvm_unreachable("unhandled Constant node");
4168 }
4169 }
4170
4171 // 16 bit splat
4172 SDValue SplatSrc32 = stripBitcast(Val: In);
4173 if (auto *SplatSrc32BV = dyn_cast<BuildVectorSDNode>(Val&: SplatSrc32))
4174 if (SDValue Splat32 = SplatSrc32BV->getSplatValue()) {
4175 SDValue SplatSrc16 = stripBitcast(Val: Splat32);
4176 if (auto *SplatSrc16BV = dyn_cast<BuildVectorSDNode>(Val&: SplatSrc16))
4177 if (SDValue Splat = SplatSrc16BV->getSplatValue()) {
4178 const SIInstrInfo *TII = Subtarget->getInstrInfo();
4179 std::optional<APInt> RawValue;
4180 if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val&: Splat))
4181 RawValue = C->getValueAPF().bitcastToAPInt();
4182 else if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val&: Splat))
4183 RawValue = C->getAPIntValue();
4184
4185 if (RawValue.has_value()) {
4186 EVT VT = In.getValueType().getScalarType();
4187 if (VT.getSimpleVT() == MVT::f16 || VT.getSimpleVT() == MVT::bf16) {
4188 APFloat FloatVal(VT.getSimpleVT() == MVT::f16
4189 ? APFloatBase::IEEEhalf()
4190 : APFloatBase::BFloat(),
4191 RawValue.value());
4192 if (TII->isInlineConstant(Imm: FloatVal)) {
4193 Src = CurDAG->getTargetConstant(Val: RawValue.value(), DL: SDLoc(In),
4194 VT: MVT::i16);
4195 return true;
4196 }
4197 } else if (VT.getSimpleVT() == MVT::i16) {
4198 if (TII->isInlineConstant(Imm: RawValue.value())) {
4199 Src = CurDAG->getTargetConstant(Val: RawValue.value(), DL: SDLoc(In),
4200 VT: MVT::i16);
4201 return true;
4202 }
4203 } else
4204 llvm_unreachable("unknown 16-bit type");
4205 }
4206 }
4207 }
4208
4209 // Currently f64 immediate vectors are represented as vectors of v2i32, with
4210 // different lo and hi 32-bit values even though double values are splated.
4211 // So we have to manually compare to determine whether it is splated.
4212 if (CurDAG->isConstantIntBuildVectorOrConstantInt(N: SplatSrc32)) {
4213 int64_t Imm64 = 0;
4214 for (unsigned i = 0; i < SplatSrc32->getNumOperands(); i += 2) {
4215 auto Lo32 = cast<ConstantSDNode>(Val: SplatSrc32->getOperand(Num: i));
4216 auto Hi32 = cast<ConstantSDNode>(Val: SplatSrc32->getOperand(Num: i + 1));
4217 int64_t LoImm = Lo32->getAPIntValue().getSExtValue();
4218 int64_t HiImm = Hi32->getAPIntValue().getSExtValue();
4219 int64_t Imm64I = (HiImm << 32) + LoImm;
4220 if (i == 0) {
4221 if (!isInlineImmediate(Imm: APInt(64, Imm64I)))
4222 return false;
4223 Imm64 = Imm64I;
4224 } else if (Imm64I != Imm64)
4225 return false;
4226 } // end for
4227
4228 Src = CurDAG->getTargetConstant(Val: Imm64, DL: SDLoc(In), VT: MVT::i64);
4229 return true;
4230 }
4231
4232 return false;
4233}
4234
4235bool AMDGPUDAGToDAGISel::SelectSWMMACIndex8(SDValue In, SDValue &Src,
4236 SDValue &IndexKey) const {
4237 unsigned Key = 0;
4238 Src = In;
4239
4240 if (In.getOpcode() == ISD::SRL) {
4241 const llvm::SDValue &ShiftSrc = In.getOperand(i: 0);
4242 ConstantSDNode *ShiftAmt = dyn_cast<ConstantSDNode>(Val: In.getOperand(i: 1));
4243 if (ShiftSrc.getValueType().getSizeInBits() == 32 && ShiftAmt &&
4244 ShiftAmt->getZExtValue() % 8 == 0) {
4245 Key = ShiftAmt->getZExtValue() / 8;
4246 Src = ShiftSrc;
4247 }
4248 }
4249
4250 IndexKey = CurDAG->getTargetConstant(Val: Key, DL: SDLoc(In), VT: MVT::i32);
4251 return true;
4252}
4253
4254bool AMDGPUDAGToDAGISel::SelectSWMMACIndex16(SDValue In, SDValue &Src,
4255 SDValue &IndexKey) const {
4256 unsigned Key = 0;
4257 Src = In;
4258
4259 if (In.getOpcode() == ISD::SRL) {
4260 const llvm::SDValue &ShiftSrc = In.getOperand(i: 0);
4261 ConstantSDNode *ShiftAmt = dyn_cast<ConstantSDNode>(Val: In.getOperand(i: 1));
4262 if (ShiftSrc.getValueType().getSizeInBits() == 32 && ShiftAmt &&
4263 ShiftAmt->getZExtValue() == 16) {
4264 Key = 1;
4265 Src = ShiftSrc;
4266 }
4267 }
4268
4269 IndexKey = CurDAG->getTargetConstant(Val: Key, DL: SDLoc(In), VT: MVT::i32);
4270 return true;
4271}
4272
4273bool AMDGPUDAGToDAGISel::SelectSWMMACIndex32(SDValue In, SDValue &Src,
4274 SDValue &IndexKey) const {
4275 unsigned Key = 0;
4276 Src = In;
4277
4278 SDValue InI32;
4279
4280 if (In.getOpcode() == ISD::ANY_EXTEND || In.getOpcode() == ISD::ZERO_EXTEND) {
4281 const SDValue &ExtendSrc = In.getOperand(i: 0);
4282 if (ExtendSrc.getValueSizeInBits() == 32)
4283 InI32 = ExtendSrc;
4284 } else if (In->getOpcode() == ISD::BITCAST) {
4285 const SDValue &CastSrc = In.getOperand(i: 0);
4286 if (CastSrc.getOpcode() == ISD::BUILD_VECTOR &&
4287 CastSrc.getOperand(i: 0).getValueSizeInBits() == 32) {
4288 ConstantSDNode *Zero = dyn_cast<ConstantSDNode>(Val: CastSrc.getOperand(i: 1));
4289 if (Zero && Zero->getZExtValue() == 0)
4290 InI32 = CastSrc.getOperand(i: 0);
4291 }
4292 }
4293
4294 if (InI32 && InI32.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
4295 const SDValue &ExtractVecEltSrc = InI32.getOperand(i: 0);
4296 ConstantSDNode *EltIdx = dyn_cast<ConstantSDNode>(Val: InI32.getOperand(i: 1));
4297 if (ExtractVecEltSrc.getValueSizeInBits() == 64 && EltIdx &&
4298 EltIdx->getZExtValue() == 1) {
4299 Key = 1;
4300 Src = ExtractVecEltSrc;
4301 }
4302 }
4303
4304 IndexKey = CurDAG->getTargetConstant(Val: Key, DL: SDLoc(In), VT: MVT::i32);
4305 return true;
4306}
4307
4308bool AMDGPUDAGToDAGISel::SelectVOP3OpSel(SDValue In, SDValue &Src,
4309 SDValue &SrcMods) const {
4310 unsigned Mods = SISrcMods::NONE;
4311 Src = In;
4312 if (!Subtarget->useRealTrue16Insts() && In.getValueSizeInBits() == 16 &&
4313 isExtractHiElt(In: Src, Out&: Src))
4314 Mods |= SISrcMods::OP_SEL_0;
4315 SrcMods = CurDAG->getTargetConstant(Val: Mods, DL: SDLoc(In), VT: MVT::i32);
4316 return true;
4317}
4318
4319bool AMDGPUDAGToDAGISel::SelectVOP3OpSelMods(SDValue In, SDValue &Src,
4320 SDValue &SrcMods) const {
4321 unsigned Mods;
4322 if (!SelectVOP3ModsImpl(In, Src, Mods, /*IsCanonicalizing=*/true,
4323 /*AllowAbs=*/true))
4324 return false;
4325
4326 if (!Subtarget->useRealTrue16Insts() && In.getValueSizeInBits() == 16 &&
4327 isExtractHiElt(In: Src, Out&: Src))
4328 Mods |= SISrcMods::OP_SEL_0;
4329
4330 SrcMods = CurDAG->getTargetConstant(Val: Mods, DL: SDLoc(In), VT: MVT::i32);
4331 return true;
4332}
4333
4334// Match lowered fpext from bf16 to f32. This is a bit operation extending
4335// a 16-bit value with 16-bit of zeroes at LSB:
4336//
4337// 1. (f32 (bitcast (build_vector (i16 0), (i16 (bitcast bf16:val)))))
4338// 2. (f32 (bitcast (and i32:val, 0xffff0000))) -> IsExtractHigh = true
4339// 3. (f32 (bitcast (shl i32:va, 16) -> IsExtractHigh = false
4340static SDValue matchBF16FPExtendLike(SDValue Op, bool &IsExtractHigh) {
4341 if (Op.getValueType() != MVT::f32 || Op.getOpcode() != ISD::BITCAST)
4342 return SDValue();
4343 Op = Op.getOperand(i: 0);
4344
4345 IsExtractHigh = false;
4346 if (Op.getValueType() == MVT::v2i16 && Op.getOpcode() == ISD::BUILD_VECTOR) {
4347 auto Low16 = dyn_cast<ConstantSDNode>(Val: Op.getOperand(i: 0));
4348 if (!Low16 || !Low16->isZero())
4349 return SDValue();
4350 Op = stripBitcast(Val: Op.getOperand(i: 1));
4351 if (Op.getValueType() != MVT::bf16)
4352 return SDValue();
4353 return Op;
4354 }
4355
4356 if (Op.getValueType() != MVT::i32)
4357 return SDValue();
4358
4359 if (Op.getOpcode() == ISD::AND) {
4360 if (auto Mask = dyn_cast<ConstantSDNode>(Val: Op.getOperand(i: 1))) {
4361 if (Mask->getZExtValue() == 0xffff0000) {
4362 IsExtractHigh = true;
4363 return Op.getOperand(i: 0);
4364 }
4365 }
4366 return SDValue();
4367 }
4368
4369 if (Op.getOpcode() == ISD::SHL) {
4370 if (auto Amt = dyn_cast<ConstantSDNode>(Val: Op.getOperand(i: 1))) {
4371 if (Amt->getZExtValue() == 16)
4372 return Op.getOperand(i: 0);
4373 }
4374 }
4375
4376 return SDValue();
4377}
4378
4379// The return value is not whether the match is possible (which it always is),
4380// but whether or not it a conversion is really used.
4381bool AMDGPUDAGToDAGISel::SelectVOP3PMadMixModsImpl(SDValue In, SDValue &Src,
4382 unsigned &Mods,
4383 MVT VT) const {
4384 Mods = 0;
4385 SelectVOP3ModsImpl(In, Src, Mods);
4386
4387 bool IsExtractHigh = false;
4388 if (Src.getOpcode() == ISD::FP_EXTEND &&
4389 Src.getOperand(i: 0).getValueType() == VT) {
4390 Src = Src.getOperand(i: 0);
4391 } else if (VT == MVT::bf16) {
4392 SDValue B16 = matchBF16FPExtendLike(Op: Src, IsExtractHigh);
4393 if (!B16)
4394 return false;
4395 Src = B16;
4396 } else
4397 return false;
4398
4399 if (Src.getValueType() != VT &&
4400 (VT != MVT::bf16 || Src.getValueType() != MVT::i32))
4401 return false;
4402
4403 Src = stripBitcast(Val: Src);
4404
4405 // Be careful about folding modifiers if we already have an abs. fneg is
4406 // applied last, so we don't want to apply an earlier fneg.
4407 if ((Mods & SISrcMods::ABS) == 0) {
4408 unsigned ModsTmp;
4409 SelectVOP3ModsImpl(In: Src, Src, Mods&: ModsTmp);
4410
4411 if ((ModsTmp & SISrcMods::NEG) != 0)
4412 Mods ^= SISrcMods::NEG;
4413
4414 if ((ModsTmp & SISrcMods::ABS) != 0)
4415 Mods |= SISrcMods::ABS;
4416 }
4417
4418 // op_sel/op_sel_hi decide the source type and source.
4419 // If the source's op_sel_hi is set, it indicates to do a conversion from
4420 // fp16. If the sources's op_sel is set, it picks the high half of the source
4421 // register.
4422
4423 Mods |= SISrcMods::OP_SEL_1;
4424 if (Src.getValueSizeInBits() == 16) {
4425 if (isExtractHiElt(In: Src, Out&: Src)) {
4426 Mods |= SISrcMods::OP_SEL_0;
4427
4428 // TODO: Should we try to look for neg/abs here?
4429 return true;
4430 }
4431
4432 if (Src.getOpcode() == ISD::TRUNCATE &&
4433 Src.getOperand(i: 0).getValueType() == MVT::i32) {
4434 Src = Src.getOperand(i: 0);
4435 return true;
4436 }
4437
4438 if (Subtarget->useRealTrue16Insts())
4439 // In true16 mode, pack src to a 32bit
4440 Src = createVOP3PSrc32FromLo16(Lo: Src, Src: In, CurDAG, Subtarget);
4441 } else if (IsExtractHigh)
4442 Mods |= SISrcMods::OP_SEL_0;
4443
4444 return true;
4445}
4446
4447bool AMDGPUDAGToDAGISel::SelectVOP3PMadMixModsExt(SDValue In, SDValue &Src,
4448 SDValue &SrcMods) const {
4449 unsigned Mods = 0;
4450 if (!SelectVOP3PMadMixModsImpl(In, Src, Mods, VT: MVT::f16))
4451 return false;
4452 SrcMods = CurDAG->getTargetConstant(Val: Mods, DL: SDLoc(In), VT: MVT::i32);
4453 return true;
4454}
4455
4456bool AMDGPUDAGToDAGISel::SelectVOP3PMadMixMods(SDValue In, SDValue &Src,
4457 SDValue &SrcMods) const {
4458 unsigned Mods = 0;
4459 SelectVOP3PMadMixModsImpl(In, Src, Mods, VT: MVT::f16);
4460 SrcMods = CurDAG->getTargetConstant(Val: Mods, DL: SDLoc(In), VT: MVT::i32);
4461 return true;
4462}
4463
4464bool AMDGPUDAGToDAGISel::SelectVOP3PMadMixModsExtNeg(SDValue In, SDValue &Src,
4465 SDValue &SrcMods) const {
4466 unsigned Mods = 0;
4467 if (!SelectVOP3PMadMixModsImpl(In, Src, Mods, VT: MVT::f16))
4468 return false;
4469 SrcMods =
4470 CurDAG->getTargetConstant(Val: Mods ^ SISrcMods::NEG, DL: SDLoc(In), VT: MVT::i32);
4471 return true;
4472}
4473
4474bool AMDGPUDAGToDAGISel::SelectVOP3PMadMixModsNeg(SDValue In, SDValue &Src,
4475 SDValue &SrcMods) const {
4476 unsigned Mods = 0;
4477 SelectVOP3PMadMixModsImpl(In, Src, Mods, VT: MVT::f16);
4478 SrcMods =
4479 CurDAG->getTargetConstant(Val: Mods ^ SISrcMods::NEG, DL: SDLoc(In), VT: MVT::i32);
4480 return true;
4481}
4482
4483bool AMDGPUDAGToDAGISel::SelectVOP3PMadMixBF16ModsExt(SDValue In, SDValue &Src,
4484 SDValue &SrcMods) const {
4485 unsigned Mods = 0;
4486 if (!SelectVOP3PMadMixModsImpl(In, Src, Mods, VT: MVT::bf16))
4487 return false;
4488 SrcMods = CurDAG->getTargetConstant(Val: Mods, DL: SDLoc(In), VT: MVT::i32);
4489 return true;
4490}
4491
4492bool AMDGPUDAGToDAGISel::SelectVOP3PMadMixBF16Mods(SDValue In, SDValue &Src,
4493 SDValue &SrcMods) const {
4494 unsigned Mods = 0;
4495 SelectVOP3PMadMixModsImpl(In, Src, Mods, VT: MVT::bf16);
4496 SrcMods = CurDAG->getTargetConstant(Val: Mods, DL: SDLoc(In), VT: MVT::i32);
4497 return true;
4498}
4499
4500bool AMDGPUDAGToDAGISel::SelectVOP3PMadMixBF16ModsExtNeg(
4501 SDValue In, SDValue &Src, SDValue &SrcMods) const {
4502 unsigned Mods = 0;
4503 if (!SelectVOP3PMadMixModsImpl(In, Src, Mods, VT: MVT::bf16))
4504 return false;
4505 SrcMods =
4506 CurDAG->getTargetConstant(Val: Mods ^ SISrcMods::NEG, DL: SDLoc(In), VT: MVT::i32);
4507 return true;
4508}
4509
4510bool AMDGPUDAGToDAGISel::SelectVOP3PMadMixBF16ModsNeg(SDValue In, SDValue &Src,
4511 SDValue &SrcMods) const {
4512 unsigned Mods = 0;
4513 SelectVOP3PMadMixModsImpl(In, Src, Mods, VT: MVT::bf16);
4514 SrcMods =
4515 CurDAG->getTargetConstant(Val: Mods ^ SISrcMods::NEG, DL: SDLoc(In), VT: MVT::i32);
4516 return true;
4517}
4518
4519// Match BITOP3 operation and return a number of matched instructions plus
4520// truth table.
4521static std::pair<unsigned, uint8_t> BitOp3_Op(SDValue In,
4522 SmallVectorImpl<SDValue> &Src) {
4523 unsigned NumOpcodes = 0;
4524 uint8_t LHSBits, RHSBits;
4525
4526 auto getOperandBits = [&Src, In](SDValue Op, uint8_t &Bits) -> bool {
4527 // Define truth table given Src0, Src1, Src2 bits permutations:
4528 // 0 0 0
4529 // 0 0 1
4530 // 0 1 0
4531 // 0 1 1
4532 // 1 0 0
4533 // 1 0 1
4534 // 1 1 0
4535 // 1 1 1
4536 const uint8_t SrcBits[3] = { 0xf0, 0xcc, 0xaa };
4537
4538 if (auto *C = dyn_cast<ConstantSDNode>(Val&: Op)) {
4539 if (C->isAllOnes()) {
4540 Bits = 0xff;
4541 return true;
4542 }
4543 if (C->isZero()) {
4544 Bits = 0;
4545 return true;
4546 }
4547 }
4548
4549 for (unsigned I = 0; I < Src.size(); ++I) {
4550 // Try to find existing reused operand
4551 if (Src[I] == Op) {
4552 Bits = SrcBits[I];
4553 return true;
4554 }
4555 // Try to replace parent operator
4556 if (Src[I] == In) {
4557 Bits = SrcBits[I];
4558 Src[I] = Op;
4559 return true;
4560 }
4561 }
4562
4563 if (Src.size() == 3) {
4564 // No room left for operands. Try one last time, there can be a 'not' of
4565 // one of our source operands. In this case we can compute the bits
4566 // without growing Src vector.
4567 if (Op.getOpcode() == ISD::XOR) {
4568 if (auto *C = dyn_cast<ConstantSDNode>(Val: Op.getOperand(i: 1))) {
4569 if (C->isAllOnes()) {
4570 SDValue LHS = Op.getOperand(i: 0);
4571 for (unsigned I = 0; I < Src.size(); ++I) {
4572 if (Src[I] == LHS) {
4573 Bits = ~SrcBits[I];
4574 return true;
4575 }
4576 }
4577 }
4578 }
4579 }
4580
4581 return false;
4582 }
4583
4584 Bits = SrcBits[Src.size()];
4585 Src.push_back(Elt: Op);
4586 return true;
4587 };
4588
4589 switch (In.getOpcode()) {
4590 case ISD::AND:
4591 case ISD::OR:
4592 case ISD::XOR: {
4593 SDValue LHS = In.getOperand(i: 0);
4594 SDValue RHS = In.getOperand(i: 1);
4595
4596 SmallVector<SDValue, 3> Backup(Src.begin(), Src.end());
4597 if (!getOperandBits(LHS, LHSBits) ||
4598 !getOperandBits(RHS, RHSBits)) {
4599 Src = std::move(Backup);
4600 return std::make_pair(x: 0, y: 0);
4601 }
4602
4603 // Recursion is naturally limited by the size of the operand vector.
4604 //
4605 // When LHS and RHS share a common sub-expression, one side's recursion
4606 // may decompose that sub-expression and replace the Src slot the other
4607 // side occupies with sub-operands via the "replace parent" path in
4608 // getOperandBits. The other side's cached bit-pattern then refers to a
4609 // slot whose contents changed, producing a wrong truth table.
4610 //
4611 // We detect this in three ways:
4612 // (A) If LHS recursed, its truth table is valid against the Src state
4613 // when LHS recursion completed (SrcAfterLHS). If RHS recursion
4614 // then mutates a Src slot that LHSBits depends on, LHSBits is
4615 // stale.
4616 // (B) If RHS did not recurse, RHSBits came from getOperandBits and
4617 // refers to a specific Src slot. If that slot's contents changed
4618 // (by either recursion), RHSBits is stale.
4619 // (C) Symmetrically for LHS if it did not recurse.
4620 SmallVector<SDValue, 3> SrcBeforeRecurse(Src.begin(), Src.end());
4621 uint8_t LHSBitsOrig = LHSBits;
4622 uint8_t RHSBitsOrig = RHSBits;
4623
4624 auto LHSOp = BitOp3_Op(In: LHS, Src);
4625 if (LHSOp.first) {
4626 NumOpcodes += LHSOp.first;
4627 LHSBits = LHSOp.second;
4628 }
4629
4630 SmallVector<SDValue, 3> SrcAfterLHS(Src.begin(), Src.end());
4631
4632 auto RHSOp = BitOp3_Op(In: RHS, Src);
4633 if (RHSOp.first) {
4634 NumOpcodes += RHSOp.first;
4635 RHSBits = RHSOp.second;
4636 }
4637
4638 // dependsOnSlot: true iff the truth table TT varies with slot Slot.
4639 auto dependsOnSlot = [](uint8_t TT, int Slot) -> bool {
4640 if (Slot < 0 || Slot > 2)
4641 return false;
4642 const uint8_t Masks[3] = {0x0f, 0x33, 0x55};
4643 const int Shifts[3] = {4, 2, 1};
4644 return ((TT ^ (TT >> Shifts[Slot])) & Masks[Slot]) != 0;
4645 };
4646
4647 // findSlot: locate the Src slot a getOperandBits result depends on,
4648 // including negated (XOR with -1) patterns that getOperandBits
4649 // resolves via the NOT shortcut (~SrcBits[I]).
4650 const uint8_t SrcBitsConst[3] = {0xf0, 0xcc, 0xaa};
4651 auto findSlot = [&](uint8_t Bits, SDValue Op,
4652 const SmallVectorImpl<SDValue> &S) -> int {
4653 SDValue NegatedInner;
4654 bool IsNegationOp =
4655 Op.getOpcode() == ISD::XOR && isAllOnesConstant(V: Op.getOperand(i: 1));
4656 if (IsNegationOp)
4657 NegatedInner = Op.getOperand(i: 0);
4658 for (int I = 0; I < (int)S.size(); I++) {
4659 if (Bits == SrcBitsConst[I] && S[I] == Op)
4660 return I;
4661 if (IsNegationOp && Bits == (uint8_t)~SrcBitsConst[I] &&
4662 S[I] == NegatedInner)
4663 return I;
4664 }
4665 return -1;
4666 };
4667
4668 bool Stale = false;
4669
4670 // (A) LHS recursed: its truth table is against SrcAfterLHS.
4671 // Check if RHS recursion mutated a slot that LHSBits uses.
4672 if (LHSOp.first) {
4673 for (int I = 0; I < (int)SrcAfterLHS.size() && I < 3; I++) {
4674 if (I < (int)Src.size() && Src[I] != SrcAfterLHS[I] &&
4675 dependsOnSlot(LHSBits, I)) {
4676 Stale = true;
4677 break;
4678 }
4679 }
4680 }
4681
4682 // (B) RHS did not recurse: RHSBits from getOperandBits is against
4683 // SrcBeforeRecurse. Check if that slot was mutated since then.
4684 if (!Stale && !RHSOp.first) {
4685 int Slot = findSlot(RHSBitsOrig, RHS, SrcBeforeRecurse);
4686 if (Slot >= 0 &&
4687 (Slot >= (int)Src.size() || Src[Slot] != SrcBeforeRecurse[Slot]))
4688 Stale = true;
4689 }
4690
4691 // (C) LHS did not recurse: LHSBits from getOperandBits is against
4692 // SrcBeforeRecurse. Check if that slot was mutated since then.
4693 if (!Stale && !LHSOp.first) {
4694 int Slot = findSlot(LHSBitsOrig, LHS, SrcBeforeRecurse);
4695 if (Slot >= 0 &&
4696 (Slot >= (int)Src.size() || Src[Slot] != SrcBeforeRecurse[Slot]))
4697 Stale = true;
4698 }
4699
4700 if (Stale) {
4701 Src = std::move(SrcBeforeRecurse);
4702 LHSBits = LHSBitsOrig;
4703 RHSBits = RHSBitsOrig;
4704 NumOpcodes = 0;
4705 }
4706 break;
4707 }
4708 default:
4709 return std::make_pair(x: 0, y: 0);
4710 }
4711
4712 uint8_t TTbl;
4713 switch (In.getOpcode()) {
4714 case ISD::AND:
4715 TTbl = LHSBits & RHSBits;
4716 break;
4717 case ISD::OR:
4718 TTbl = LHSBits | RHSBits;
4719 break;
4720 case ISD::XOR:
4721 TTbl = LHSBits ^ RHSBits;
4722 break;
4723 default:
4724 break;
4725 }
4726
4727 return std::make_pair(x: NumOpcodes + 1, y&: TTbl);
4728}
4729
4730bool AMDGPUDAGToDAGISel::SelectBITOP3(SDValue In, SDValue &Src0, SDValue &Src1,
4731 SDValue &Src2, SDValue &Tbl) const {
4732 SmallVector<SDValue, 3> Src;
4733 uint8_t TTbl;
4734 unsigned NumOpcodes;
4735
4736 std::tie(args&: NumOpcodes, args&: TTbl) = BitOp3_Op(In, Src);
4737
4738 // Src.empty() case can happen if all operands are all zero or all ones.
4739 // Normally it shall be optimized out before reaching this.
4740 if (NumOpcodes < 2 || Src.empty())
4741 return false;
4742
4743 // For a uniform case threshold should be higher to account for moves between
4744 // VGPRs and SGPRs. It needs one operand in a VGPR, rest two can be in SGPRs
4745 // and a readtfirstlane after.
4746 if (NumOpcodes < 4 && !In->isDivergent())
4747 return false;
4748
4749 if (NumOpcodes == 2 && In.getValueType() == MVT::i32) {
4750 // Avoid using BITOP3 for OR3, XOR3, AND_OR. This is not faster but makes
4751 // asm more readable. This cannot be modeled with AddedComplexity because
4752 // selector does not know how many operations did we match.
4753 if ((In.getOpcode() == ISD::XOR || In.getOpcode() == ISD::OR) &&
4754 (In.getOperand(i: 0).getOpcode() == In.getOpcode() ||
4755 In.getOperand(i: 1).getOpcode() == In.getOpcode()))
4756 return false;
4757
4758 if (In.getOpcode() == ISD::OR &&
4759 (In.getOperand(i: 0).getOpcode() == ISD::AND ||
4760 In.getOperand(i: 1).getOpcode() == ISD::AND))
4761 return false;
4762 }
4763
4764 // Last operand can be ignored, turning a ternary operation into a binary.
4765 // For example: (~a & b & c) | (~a & b & ~c) -> (~a & b). We can replace
4766 // 'c' with 'a' here without changing the answer. In some pathological
4767 // cases it should be possible to get an operation with a single operand
4768 // too if optimizer would not catch it.
4769 while (Src.size() < 3)
4770 Src.push_back(Elt: Src[0]);
4771
4772 Src0 = Src[0];
4773 Src1 = Src[1];
4774 Src2 = Src[2];
4775
4776 Tbl = CurDAG->getTargetConstant(Val: TTbl, DL: SDLoc(In), VT: MVT::i32);
4777 return true;
4778}
4779
4780SDValue AMDGPUDAGToDAGISel::getHi16Elt(SDValue In) const {
4781 if (In.getOpcode() == ISD::POISON)
4782 return CurDAG->getPOISON(VT: MVT::i32);
4783
4784 if (In.getOpcode() == ISD::UNDEF)
4785 return CurDAG->getUNDEF(VT: MVT::i32);
4786
4787 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val&: In)) {
4788 SDLoc SL(In);
4789 return CurDAG->getConstant(Val: C->getZExtValue() << 16, DL: SL, VT: MVT::i32);
4790 }
4791
4792 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val&: In)) {
4793 SDLoc SL(In);
4794 return CurDAG->getConstant(
4795 Val: C->getValueAPF().bitcastToAPInt().getZExtValue() << 16, DL: SL, VT: MVT::i32);
4796 }
4797
4798 SDValue Src;
4799 if (isExtractHiElt(In, Out&: Src))
4800 return Src;
4801
4802 return SDValue();
4803}
4804
4805bool AMDGPUDAGToDAGISel::isVGPRImm(const SDNode * N) const {
4806 assert(CurDAG->getTarget().getTargetTriple().isAMDGCN());
4807
4808 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
4809 const SIInstrInfo *SII = Subtarget->getInstrInfo();
4810
4811 unsigned Limit = 0;
4812 bool AllUsesAcceptSReg = true;
4813 for (SDNode::use_iterator U = N->use_begin(), E = SDNode::use_end();
4814 Limit < 10 && U != E; ++U, ++Limit) {
4815 const TargetRegisterClass *RC =
4816 getOperandRegClass(N: U->getUser(), OpNo: U->getOperandNo());
4817
4818 // If the register class is unknown, it could be an unknown
4819 // register class that needs to be an SGPR, e.g. an inline asm
4820 // constraint
4821 if (!RC || SIRI->isSGPRClass(RC))
4822 return false;
4823
4824 if (RC != &AMDGPU::VS_32RegClass && RC != &AMDGPU::VS_64RegClass &&
4825 RC != &AMDGPU::VS_64_Align2RegClass) {
4826 AllUsesAcceptSReg = false;
4827 SDNode *User = U->getUser();
4828 if (User->isMachineOpcode()) {
4829 unsigned Opc = User->getMachineOpcode();
4830 const MCInstrDesc &Desc = SII->get(Opcode: Opc);
4831 if (Desc.isCommutable()) {
4832 unsigned OpIdx = Desc.getNumDefs() + U->getOperandNo();
4833 unsigned CommuteIdx1 = TargetInstrInfo::CommuteAnyOperandIndex;
4834 if (SII->findCommutedOpIndices(Desc, SrcOpIdx0&: OpIdx, SrcOpIdx1&: CommuteIdx1)) {
4835 unsigned CommutedOpNo = CommuteIdx1 - Desc.getNumDefs();
4836 const TargetRegisterClass *CommutedRC =
4837 getOperandRegClass(N: U->getUser(), OpNo: CommutedOpNo);
4838 if (CommutedRC == &AMDGPU::VS_32RegClass ||
4839 CommutedRC == &AMDGPU::VS_64RegClass ||
4840 CommutedRC == &AMDGPU::VS_64_Align2RegClass)
4841 AllUsesAcceptSReg = true;
4842 }
4843 }
4844 }
4845 // If "AllUsesAcceptSReg == false" so far we haven't succeeded
4846 // commuting current user. This means have at least one use
4847 // that strictly require VGPR. Thus, we will not attempt to commute
4848 // other user instructions.
4849 if (!AllUsesAcceptSReg)
4850 break;
4851 }
4852 }
4853 return !AllUsesAcceptSReg && (Limit < 10);
4854}
4855
4856void AMDGPUDAGToDAGISel::PostprocessISelDAG() {
4857 const AMDGPUTargetLowering& Lowering =
4858 *static_cast<const AMDGPUTargetLowering*>(getTargetLowering());
4859 bool IsModified = false;
4860 do {
4861 IsModified = false;
4862
4863 // Go over all selected nodes and try to fold them a bit more
4864 SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_begin();
4865 while (Position != CurDAG->allnodes_end()) {
4866 SDNode *Node = &*Position++;
4867 MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(Val: Node);
4868 if (!MachineNode)
4869 continue;
4870
4871 SDNode *ResNode = Lowering.PostISelFolding(N: MachineNode, DAG&: *CurDAG);
4872 if (ResNode != Node) {
4873 if (ResNode)
4874 ReplaceUses(F: Node, T: ResNode);
4875 IsModified = true;
4876 }
4877 }
4878 CurDAG->RemoveDeadNodes();
4879 } while (IsModified);
4880}
4881
4882AMDGPUDAGToDAGISelLegacy::AMDGPUDAGToDAGISelLegacy(TargetMachine &TM,
4883 CodeGenOptLevel OptLevel)
4884 : SelectionDAGISelLegacy(
4885 ID, std::make_unique<AMDGPUDAGToDAGISel>(args&: TM, args&: OptLevel)) {}
4886
4887char AMDGPUDAGToDAGISelLegacy::ID = 0;
4888