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