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