xref: /freebsd-src/contrib/llvm-project/llvm/lib/Target/AMDGPU/SIISelLowering.cpp (revision 46c59ea9b61755455ff6bf9f3e7b834e1af634ea)
1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
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 /// Custom DAG lowering for SI
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "SIISelLowering.h"
15 #include "AMDGPU.h"
16 #include "AMDGPUInstrInfo.h"
17 #include "AMDGPUTargetMachine.h"
18 #include "GCNSubtarget.h"
19 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
20 #include "SIMachineFunctionInfo.h"
21 #include "SIRegisterInfo.h"
22 #include "llvm/ADT/APInt.h"
23 #include "llvm/ADT/FloatingPointMode.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
26 #include "llvm/Analysis/UniformityAnalysis.h"
27 #include "llvm/BinaryFormat/ELF.h"
28 #include "llvm/CodeGen/Analysis.h"
29 #include "llvm/CodeGen/ByteProvider.h"
30 #include "llvm/CodeGen/FunctionLoweringInfo.h"
31 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
32 #include "llvm/CodeGen/GlobalISel/GenericMachineInstrs.h"
33 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h"
34 #include "llvm/CodeGen/MachineFrameInfo.h"
35 #include "llvm/CodeGen/MachineFunction.h"
36 #include "llvm/CodeGen/MachineLoopInfo.h"
37 #include "llvm/IR/DiagnosticInfo.h"
38 #include "llvm/IR/IRBuilder.h"
39 #include "llvm/IR/IntrinsicInst.h"
40 #include "llvm/IR/IntrinsicsAMDGPU.h"
41 #include "llvm/IR/IntrinsicsR600.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/KnownBits.h"
44 #include "llvm/Support/ModRef.h"
45 #include <optional>
46 
47 using namespace llvm;
48 
49 #define DEBUG_TYPE "si-lower"
50 
51 STATISTIC(NumTailCalls, "Number of tail calls");
52 
53 static cl::opt<bool> DisableLoopAlignment(
54   "amdgpu-disable-loop-alignment",
55   cl::desc("Do not align and prefetch loops"),
56   cl::init(false));
57 
58 static cl::opt<bool> UseDivergentRegisterIndexing(
59   "amdgpu-use-divergent-register-indexing",
60   cl::Hidden,
61   cl::desc("Use indirect register addressing for divergent indexes"),
62   cl::init(false));
63 
64 static bool denormalModeIsFlushAllF32(const MachineFunction &MF) {
65   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
66   return Info->getMode().FP32Denormals == DenormalMode::getPreserveSign();
67 }
68 
69 static bool denormalModeIsFlushAllF64F16(const MachineFunction &MF) {
70   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
71   return Info->getMode().FP64FP16Denormals == DenormalMode::getPreserveSign();
72 }
73 
74 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
75   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
76   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
77     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
78       return AMDGPU::SGPR0 + Reg;
79     }
80   }
81   llvm_unreachable("Cannot allocate sgpr");
82 }
83 
84 SITargetLowering::SITargetLowering(const TargetMachine &TM,
85                                    const GCNSubtarget &STI)
86     : AMDGPUTargetLowering(TM, STI),
87       Subtarget(&STI) {
88   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
89   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
90 
91   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
92   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
93 
94   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
95 
96   const SIRegisterInfo *TRI = STI.getRegisterInfo();
97   const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class();
98 
99   addRegisterClass(MVT::f64, V64RegClass);
100   addRegisterClass(MVT::v2f32, V64RegClass);
101 
102   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
103   addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96));
104 
105   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
106   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
107 
108   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
109   addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128));
110 
111   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
112   addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160));
113 
114   addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass);
115   addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192));
116 
117   addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass);
118   addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192));
119 
120   addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass);
121   addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224));
122 
123   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
124   addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256));
125 
126   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
127   addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256));
128 
129   addRegisterClass(MVT::v9i32, &AMDGPU::SGPR_288RegClass);
130   addRegisterClass(MVT::v9f32, TRI->getVGPRClassForBitWidth(288));
131 
132   addRegisterClass(MVT::v10i32, &AMDGPU::SGPR_320RegClass);
133   addRegisterClass(MVT::v10f32, TRI->getVGPRClassForBitWidth(320));
134 
135   addRegisterClass(MVT::v11i32, &AMDGPU::SGPR_352RegClass);
136   addRegisterClass(MVT::v11f32, TRI->getVGPRClassForBitWidth(352));
137 
138   addRegisterClass(MVT::v12i32, &AMDGPU::SGPR_384RegClass);
139   addRegisterClass(MVT::v12f32, TRI->getVGPRClassForBitWidth(384));
140 
141   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
142   addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512));
143 
144   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
145   addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512));
146 
147   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
148   addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024));
149 
150   if (Subtarget->has16BitInsts()) {
151     if (Subtarget->useRealTrue16Insts()) {
152       addRegisterClass(MVT::i16, &AMDGPU::VGPR_16RegClass);
153       addRegisterClass(MVT::f16, &AMDGPU::VGPR_16RegClass);
154       addRegisterClass(MVT::bf16, &AMDGPU::VGPR_16RegClass);
155     } else {
156       addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
157       addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
158       addRegisterClass(MVT::bf16, &AMDGPU::SReg_32RegClass);
159     }
160 
161     // Unless there are also VOP3P operations, not operations are really legal.
162     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
163     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
164     addRegisterClass(MVT::v2bf16, &AMDGPU::SReg_32RegClass);
165     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
166     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
167     addRegisterClass(MVT::v4bf16, &AMDGPU::SReg_64RegClass);
168     addRegisterClass(MVT::v8i16, &AMDGPU::SGPR_128RegClass);
169     addRegisterClass(MVT::v8f16, &AMDGPU::SGPR_128RegClass);
170     addRegisterClass(MVT::v8bf16, &AMDGPU::SGPR_128RegClass);
171     addRegisterClass(MVT::v16i16, &AMDGPU::SGPR_256RegClass);
172     addRegisterClass(MVT::v16f16, &AMDGPU::SGPR_256RegClass);
173     addRegisterClass(MVT::v16bf16, &AMDGPU::SGPR_256RegClass);
174     addRegisterClass(MVT::v32i16, &AMDGPU::SGPR_512RegClass);
175     addRegisterClass(MVT::v32f16, &AMDGPU::SGPR_512RegClass);
176     addRegisterClass(MVT::v32bf16, &AMDGPU::SGPR_512RegClass);
177   }
178 
179   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
180   addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024));
181 
182   computeRegisterProperties(Subtarget->getRegisterInfo());
183 
184   // The boolean content concept here is too inflexible. Compares only ever
185   // really produce a 1-bit result. Any copy/extend from these will turn into a
186   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
187   // it's what most targets use.
188   setBooleanContents(ZeroOrOneBooleanContent);
189   setBooleanVectorContents(ZeroOrOneBooleanContent);
190 
191   // We need to custom lower vector stores from local memory
192   setOperationAction(ISD::LOAD,
193                      {MVT::v2i32,  MVT::v3i32,  MVT::v4i32,  MVT::v5i32,
194                       MVT::v6i32,  MVT::v7i32,  MVT::v8i32,  MVT::v9i32,
195                       MVT::v10i32, MVT::v11i32, MVT::v12i32, MVT::v16i32,
196                       MVT::i1,     MVT::v32i32},
197                      Custom);
198 
199   setOperationAction(ISD::STORE,
200                      {MVT::v2i32,  MVT::v3i32,  MVT::v4i32,  MVT::v5i32,
201                       MVT::v6i32,  MVT::v7i32,  MVT::v8i32,  MVT::v9i32,
202                       MVT::v10i32, MVT::v11i32, MVT::v12i32, MVT::v16i32,
203                       MVT::i1,     MVT::v32i32},
204                      Custom);
205 
206   if (isTypeLegal(MVT::bf16)) {
207     for (unsigned Opc :
208          {ISD::FADD,     ISD::FSUB,       ISD::FMUL,    ISD::FDIV,
209           ISD::FREM,     ISD::FMA,        ISD::FMINNUM, ISD::FMAXNUM,
210           ISD::FMINIMUM, ISD::FMAXIMUM,   ISD::FSQRT,   ISD::FCBRT,
211           ISD::FSIN,     ISD::FCOS,       ISD::FPOW,    ISD::FPOWI,
212           ISD::FLDEXP,   ISD::FFREXP,     ISD::FLOG,    ISD::FLOG2,
213           ISD::FLOG10,   ISD::FEXP,       ISD::FEXP2,   ISD::FEXP10,
214           ISD::FCEIL,    ISD::FTRUNC,     ISD::FRINT,   ISD::FNEARBYINT,
215           ISD::FROUND,   ISD::FROUNDEVEN, ISD::FFLOOR,  ISD::FCANONICALIZE,
216           ISD::SETCC}) {
217       // FIXME: The promoted to type shouldn't need to be explicit
218       setOperationAction(Opc, MVT::bf16, Promote);
219       AddPromotedToType(Opc, MVT::bf16, MVT::f32);
220     }
221 
222     setOperationAction(ISD::FP_ROUND, MVT::bf16, Expand);
223 
224     setOperationAction(ISD::SELECT, MVT::bf16, Promote);
225     AddPromotedToType(ISD::SELECT, MVT::bf16, MVT::i16);
226 
227     // TODO: Could make these legal
228     setOperationAction(ISD::FABS, MVT::bf16, Expand);
229     setOperationAction(ISD::FNEG, MVT::bf16, Expand);
230     setOperationAction(ISD::FCOPYSIGN, MVT::bf16, Expand);
231 
232     // We only need to custom lower because we can't specify an action for bf16
233     // sources.
234     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
235     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
236 
237     setOperationAction(ISD::BUILD_VECTOR, MVT::v2bf16, Promote);
238     AddPromotedToType(ISD::BUILD_VECTOR, MVT::v2bf16, MVT::v2i16);
239   }
240 
241   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
242   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
243   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
244   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
245   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
246   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
247   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
248   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
249   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
250   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
251   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
252   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
253   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
254   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
255   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
256   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
257 
258   setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand);
259   setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand);
260   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
261   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
262   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
263   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
264   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
265 
266   setOperationAction(ISD::GlobalAddress, {MVT::i32, MVT::i64}, Custom);
267 
268   setOperationAction(ISD::SELECT, MVT::i1, Promote);
269   setOperationAction(ISD::SELECT, MVT::i64, Custom);
270   setOperationAction(ISD::SELECT, MVT::f64, Promote);
271   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
272 
273   setOperationAction(ISD::FSQRT, {MVT::f32, MVT::f64}, Custom);
274 
275   setOperationAction(ISD::SELECT_CC,
276                      {MVT::f32, MVT::i32, MVT::i64, MVT::f64, MVT::i1}, Expand);
277 
278   setOperationAction(ISD::SETCC, MVT::i1, Promote);
279   setOperationAction(ISD::SETCC, {MVT::v2i1, MVT::v4i1}, Expand);
280   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
281 
282   setOperationAction(ISD::TRUNCATE,
283                      {MVT::v2i32,  MVT::v3i32,  MVT::v4i32,  MVT::v5i32,
284                       MVT::v6i32,  MVT::v7i32,  MVT::v8i32,  MVT::v9i32,
285                       MVT::v10i32, MVT::v11i32, MVT::v12i32, MVT::v16i32},
286                      Expand);
287   setOperationAction(ISD::FP_ROUND,
288                      {MVT::v2f32,  MVT::v3f32,  MVT::v4f32,  MVT::v5f32,
289                       MVT::v6f32,  MVT::v7f32,  MVT::v8f32,  MVT::v9f32,
290                       MVT::v10f32, MVT::v11f32, MVT::v12f32, MVT::v16f32},
291                      Expand);
292 
293   setOperationAction(ISD::SIGN_EXTEND_INREG,
294                      {MVT::v2i1, MVT::v4i1, MVT::v2i8, MVT::v4i8, MVT::v2i16,
295                       MVT::v3i16, MVT::v4i16, MVT::Other},
296                      Custom);
297 
298   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
299   setOperationAction(ISD::BR_CC,
300                      {MVT::i1, MVT::i32, MVT::i64, MVT::f32, MVT::f64}, Expand);
301 
302   setOperationAction({ISD::UADDO, ISD::USUBO}, MVT::i32, Legal);
303 
304   setOperationAction({ISD::UADDO_CARRY, ISD::USUBO_CARRY}, MVT::i32, Legal);
305 
306   setOperationAction({ISD::SHL_PARTS, ISD::SRA_PARTS, ISD::SRL_PARTS}, MVT::i64,
307                      Expand);
308 
309 #if 0
310   setOperationAction({ISD::UADDO_CARRY, ISD::USUBO_CARRY}, MVT::i64, Legal);
311 #endif
312 
313   // We only support LOAD/STORE and vector manipulation ops for vectors
314   // with > 4 elements.
315   for (MVT VT :
316        {MVT::v8i32,   MVT::v8f32,  MVT::v9i32,  MVT::v9f32,  MVT::v10i32,
317         MVT::v10f32,  MVT::v11i32, MVT::v11f32, MVT::v12i32, MVT::v12f32,
318         MVT::v16i32,  MVT::v16f32, MVT::v2i64,  MVT::v2f64,  MVT::v4i16,
319         MVT::v4f16,   MVT::v4bf16, MVT::v3i64,  MVT::v3f64,  MVT::v6i32,
320         MVT::v6f32,   MVT::v4i64,  MVT::v4f64,  MVT::v8i64,  MVT::v8f64,
321         MVT::v8i16,   MVT::v8f16,  MVT::v8bf16, MVT::v16i16, MVT::v16f16,
322         MVT::v16bf16, MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32,
323         MVT::v32i16,  MVT::v32f16, MVT::v32bf16}) {
324     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
325       switch (Op) {
326       case ISD::LOAD:
327       case ISD::STORE:
328       case ISD::BUILD_VECTOR:
329       case ISD::BITCAST:
330       case ISD::UNDEF:
331       case ISD::EXTRACT_VECTOR_ELT:
332       case ISD::INSERT_VECTOR_ELT:
333       case ISD::SCALAR_TO_VECTOR:
334       case ISD::IS_FPCLASS:
335         break;
336       case ISD::EXTRACT_SUBVECTOR:
337       case ISD::INSERT_SUBVECTOR:
338       case ISD::CONCAT_VECTORS:
339         setOperationAction(Op, VT, Custom);
340         break;
341       default:
342         setOperationAction(Op, VT, Expand);
343         break;
344       }
345     }
346   }
347 
348   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
349 
350   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
351   // is expanded to avoid having two separate loops in case the index is a VGPR.
352 
353   // Most operations are naturally 32-bit vector operations. We only support
354   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
355   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
356     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
357     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
358 
359     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
360     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
361 
362     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
363     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
364 
365     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
366     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
367   }
368 
369   for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) {
370     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
371     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32);
372 
373     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
374     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32);
375 
376     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
377     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32);
378 
379     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
380     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32);
381   }
382 
383   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
384     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
385     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
386 
387     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
388     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
389 
390     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
391     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
392 
393     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
394     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
395   }
396 
397   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
398     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
399     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
400 
401     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
402     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
403 
404     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
405     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
406 
407     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
408     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
409   }
410 
411   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
412     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
413     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
414 
415     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
416     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
417 
418     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
419     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
420 
421     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
422     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
423   }
424 
425   setOperationAction(ISD::VECTOR_SHUFFLE,
426                      {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32},
427                      Expand);
428 
429   setOperationAction(ISD::BUILD_VECTOR, {MVT::v4f16, MVT::v4i16, MVT::v4bf16},
430                      Custom);
431 
432   // Avoid stack access for these.
433   // TODO: Generalize to more vector types.
434   setOperationAction({ISD::EXTRACT_VECTOR_ELT, ISD::INSERT_VECTOR_ELT},
435                      {MVT::v2i16, MVT::v2f16, MVT::v2bf16, MVT::v2i8, MVT::v4i8,
436                       MVT::v8i8, MVT::v4i16, MVT::v4f16, MVT::v4bf16},
437                      Custom);
438 
439   // Deal with vec3 vector operations when widened to vec4.
440   setOperationAction(ISD::INSERT_SUBVECTOR,
441                      {MVT::v3i32, MVT::v3f32, MVT::v4i32, MVT::v4f32}, Custom);
442 
443   // Deal with vec5/6/7 vector operations when widened to vec8.
444   setOperationAction(ISD::INSERT_SUBVECTOR,
445                      {MVT::v5i32,  MVT::v5f32,  MVT::v6i32,  MVT::v6f32,
446                       MVT::v7i32,  MVT::v7f32,  MVT::v8i32,  MVT::v8f32,
447                       MVT::v9i32,  MVT::v9f32,  MVT::v10i32, MVT::v10f32,
448                       MVT::v11i32, MVT::v11f32, MVT::v12i32, MVT::v12f32},
449                      Custom);
450 
451   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
452   // and output demarshalling
453   setOperationAction(ISD::ATOMIC_CMP_SWAP, {MVT::i32, MVT::i64}, Custom);
454 
455   // We can't return success/failure, only the old value,
456   // let LLVM add the comparison
457   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, {MVT::i32, MVT::i64},
458                      Expand);
459 
460   setOperationAction(ISD::ADDRSPACECAST, {MVT::i32, MVT::i64}, Custom);
461 
462   setOperationAction(ISD::BITREVERSE, {MVT::i32, MVT::i64}, Legal);
463 
464   // FIXME: This should be narrowed to i32, but that only happens if i64 is
465   // illegal.
466   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
467   setOperationAction(ISD::BSWAP, {MVT::i64, MVT::i32}, Legal);
468 
469   // On SI this is s_memtime and s_memrealtime on VI.
470   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
471   setOperationAction({ISD::TRAP, ISD::DEBUGTRAP}, MVT::Other, Custom);
472 
473   if (Subtarget->has16BitInsts()) {
474     setOperationAction({ISD::FPOW, ISD::FPOWI}, MVT::f16, Promote);
475     setOperationAction({ISD::FLOG, ISD::FEXP, ISD::FLOG10}, MVT::f16, Custom);
476   } else {
477     setOperationAction(ISD::FSQRT, MVT::f16, Custom);
478   }
479 
480   if (Subtarget->hasMadMacF32Insts())
481     setOperationAction(ISD::FMAD, MVT::f32, Legal);
482 
483   if (!Subtarget->hasBFI())
484     // fcopysign can be done in a single instruction with BFI.
485     setOperationAction(ISD::FCOPYSIGN, {MVT::f32, MVT::f64}, Expand);
486 
487   if (!Subtarget->hasBCNT(32))
488     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
489 
490   if (!Subtarget->hasBCNT(64))
491     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
492 
493   if (Subtarget->hasFFBH())
494     setOperationAction({ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF}, MVT::i32, Custom);
495 
496   if (Subtarget->hasFFBL())
497     setOperationAction({ISD::CTTZ, ISD::CTTZ_ZERO_UNDEF}, MVT::i32, Custom);
498 
499   // We only really have 32-bit BFE instructions (and 16-bit on VI).
500   //
501   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
502   // effort to match them now. We want this to be false for i64 cases when the
503   // extraction isn't restricted to the upper or lower half. Ideally we would
504   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
505   // span the midpoint are probably relatively rare, so don't worry about them
506   // for now.
507   if (Subtarget->hasBFE())
508     setHasExtractBitsInsn(true);
509 
510   // Clamp modifier on add/sub
511   if (Subtarget->hasIntClamp())
512     setOperationAction({ISD::UADDSAT, ISD::USUBSAT}, MVT::i32, Legal);
513 
514   if (Subtarget->hasAddNoCarry())
515     setOperationAction({ISD::SADDSAT, ISD::SSUBSAT}, {MVT::i16, MVT::i32},
516                        Legal);
517 
518   setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, {MVT::f32, MVT::f64},
519                      Custom);
520 
521   // These are really only legal for ieee_mode functions. We should be avoiding
522   // them for functions that don't have ieee_mode enabled, so just say they are
523   // legal.
524   setOperationAction({ISD::FMINNUM_IEEE, ISD::FMAXNUM_IEEE},
525                      {MVT::f32, MVT::f64}, Legal);
526 
527   if (Subtarget->haveRoundOpsF64())
528     setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FROUNDEVEN}, MVT::f64,
529                        Legal);
530   else
531     setOperationAction({ISD::FCEIL, ISD::FTRUNC, ISD::FROUNDEVEN, ISD::FFLOOR},
532                        MVT::f64, Custom);
533 
534   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
535   setOperationAction({ISD::FLDEXP, ISD::STRICT_FLDEXP}, {MVT::f32, MVT::f64},
536                      Legal);
537   setOperationAction(ISD::FFREXP, {MVT::f32, MVT::f64}, Custom);
538 
539   setOperationAction({ISD::FSIN, ISD::FCOS, ISD::FDIV}, MVT::f32, Custom);
540   setOperationAction(ISD::FDIV, MVT::f64, Custom);
541 
542   setOperationAction(ISD::BF16_TO_FP, {MVT::i16, MVT::f32, MVT::f64}, Expand);
543   setOperationAction(ISD::FP_TO_BF16, {MVT::i16, MVT::f32, MVT::f64}, Expand);
544 
545   // Custom lower these because we can't specify a rule based on an illegal
546   // source bf16.
547   setOperationAction({ISD::FP_EXTEND, ISD::STRICT_FP_EXTEND}, MVT::f32, Custom);
548   setOperationAction({ISD::FP_EXTEND, ISD::STRICT_FP_EXTEND}, MVT::f64, Custom);
549 
550   if (Subtarget->has16BitInsts()) {
551     setOperationAction({ISD::Constant, ISD::SMIN, ISD::SMAX, ISD::UMIN,
552                         ISD::UMAX, ISD::UADDSAT, ISD::USUBSAT},
553                        MVT::i16, Legal);
554 
555     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
556 
557     setOperationAction({ISD::ROTR, ISD::ROTL, ISD::SELECT_CC, ISD::BR_CC},
558                        MVT::i16, Expand);
559 
560     setOperationAction({ISD::SIGN_EXTEND, ISD::SDIV, ISD::UDIV, ISD::SREM,
561                         ISD::UREM, ISD::BITREVERSE, ISD::CTTZ,
562                         ISD::CTTZ_ZERO_UNDEF, ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF,
563                         ISD::CTPOP},
564                        MVT::i16, Promote);
565 
566     setOperationAction(ISD::LOAD, MVT::i16, Custom);
567 
568     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
569 
570     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
571     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
572     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
573     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
574 
575     setOperationAction({ISD::FP_TO_SINT, ISD::FP_TO_UINT}, MVT::i16, Custom);
576     setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP}, MVT::i16, Custom);
577     setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP}, MVT::i16, Custom);
578 
579     setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP}, MVT::i32, Custom);
580 
581     // F16 - Constant Actions.
582     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
583     setOperationAction(ISD::ConstantFP, MVT::bf16, Legal);
584 
585     // F16 - Load/Store Actions.
586     setOperationAction(ISD::LOAD, MVT::f16, Promote);
587     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
588     setOperationAction(ISD::STORE, MVT::f16, Promote);
589     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
590 
591     // BF16 - Load/Store Actions.
592     setOperationAction(ISD::LOAD, MVT::bf16, Promote);
593     AddPromotedToType(ISD::LOAD, MVT::bf16, MVT::i16);
594     setOperationAction(ISD::STORE, MVT::bf16, Promote);
595     AddPromotedToType(ISD::STORE, MVT::bf16, MVT::i16);
596 
597     // F16 - VOP1 Actions.
598     setOperationAction({ISD::FP_ROUND, ISD::STRICT_FP_ROUND, ISD::FCOS,
599                         ISD::FSIN, ISD::FROUND, ISD::FPTRUNC_ROUND},
600                        MVT::f16, Custom);
601 
602     setOperationAction({ISD::FP_TO_SINT, ISD::FP_TO_UINT}, MVT::f16, Promote);
603     setOperationAction({ISD::FP_TO_SINT, ISD::FP_TO_UINT}, MVT::bf16, Promote);
604 
605     // F16 - VOP2 Actions.
606     setOperationAction({ISD::BR_CC, ISD::SELECT_CC}, {MVT::f16, MVT::bf16},
607                        Expand);
608     setOperationAction({ISD::FLDEXP, ISD::STRICT_FLDEXP}, MVT::f16, Custom);
609     setOperationAction(ISD::FFREXP, MVT::f16, Custom);
610     setOperationAction(ISD::FDIV, MVT::f16, Custom);
611 
612     // F16 - VOP3 Actions.
613     setOperationAction(ISD::FMA, MVT::f16, Legal);
614     if (STI.hasMadF16())
615       setOperationAction(ISD::FMAD, MVT::f16, Legal);
616 
617     for (MVT VT :
618          {MVT::v2i16, MVT::v2f16, MVT::v2bf16, MVT::v4i16, MVT::v4f16,
619           MVT::v4bf16, MVT::v8i16, MVT::v8f16, MVT::v8bf16, MVT::v16i16,
620           MVT::v16f16, MVT::v16bf16, MVT::v32i16, MVT::v32f16}) {
621       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
622         switch (Op) {
623         case ISD::LOAD:
624         case ISD::STORE:
625         case ISD::BUILD_VECTOR:
626         case ISD::BITCAST:
627         case ISD::UNDEF:
628         case ISD::EXTRACT_VECTOR_ELT:
629         case ISD::INSERT_VECTOR_ELT:
630         case ISD::INSERT_SUBVECTOR:
631         case ISD::EXTRACT_SUBVECTOR:
632         case ISD::SCALAR_TO_VECTOR:
633         case ISD::IS_FPCLASS:
634           break;
635         case ISD::CONCAT_VECTORS:
636           setOperationAction(Op, VT, Custom);
637           break;
638         default:
639           setOperationAction(Op, VT, Expand);
640           break;
641         }
642       }
643     }
644 
645     // v_perm_b32 can handle either of these.
646     setOperationAction(ISD::BSWAP, {MVT::i16, MVT::v2i16}, Legal);
647     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
648 
649     // XXX - Do these do anything? Vector constants turn into build_vector.
650     setOperationAction(ISD::Constant, {MVT::v2i16, MVT::v2f16}, Legal);
651 
652     setOperationAction(ISD::UNDEF, {MVT::v2i16, MVT::v2f16, MVT::v2bf16},
653                        Legal);
654 
655     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
656     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
657     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
658     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
659 
660     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
661     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
662     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
663     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
664 
665     setOperationAction(ISD::AND, MVT::v2i16, Promote);
666     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
667     setOperationAction(ISD::OR, MVT::v2i16, Promote);
668     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
669     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
670     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
671 
672     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
673     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
674     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
675     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
676     setOperationAction(ISD::LOAD, MVT::v4bf16, Promote);
677     AddPromotedToType(ISD::LOAD, MVT::v4bf16, MVT::v2i32);
678 
679     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
680     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
681     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
682     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
683     setOperationAction(ISD::STORE, MVT::v4bf16, Promote);
684     AddPromotedToType(ISD::STORE, MVT::v4bf16, MVT::v2i32);
685 
686     setOperationAction(ISD::LOAD, MVT::v8i16, Promote);
687     AddPromotedToType(ISD::LOAD, MVT::v8i16, MVT::v4i32);
688     setOperationAction(ISD::LOAD, MVT::v8f16, Promote);
689     AddPromotedToType(ISD::LOAD, MVT::v8f16, MVT::v4i32);
690     setOperationAction(ISD::LOAD, MVT::v8bf16, Promote);
691     AddPromotedToType(ISD::LOAD, MVT::v8bf16, MVT::v4i32);
692 
693     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
694     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
695     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
696     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
697 
698     setOperationAction(ISD::STORE, MVT::v8i16, Promote);
699     AddPromotedToType(ISD::STORE, MVT::v8i16, MVT::v4i32);
700     setOperationAction(ISD::STORE, MVT::v8f16, Promote);
701     AddPromotedToType(ISD::STORE, MVT::v8f16, MVT::v4i32);
702     setOperationAction(ISD::STORE, MVT::v8bf16, Promote);
703     AddPromotedToType(ISD::STORE, MVT::v8bf16, MVT::v4i32);
704 
705     setOperationAction(ISD::LOAD, MVT::v16i16, Promote);
706     AddPromotedToType(ISD::LOAD, MVT::v16i16, MVT::v8i32);
707     setOperationAction(ISD::LOAD, MVT::v16f16, Promote);
708     AddPromotedToType(ISD::LOAD, MVT::v16f16, MVT::v8i32);
709     setOperationAction(ISD::LOAD, MVT::v16bf16, Promote);
710     AddPromotedToType(ISD::LOAD, MVT::v16bf16, MVT::v8i32);
711 
712     setOperationAction(ISD::STORE, MVT::v16i16, Promote);
713     AddPromotedToType(ISD::STORE, MVT::v16i16, MVT::v8i32);
714     setOperationAction(ISD::STORE, MVT::v16f16, Promote);
715     AddPromotedToType(ISD::STORE, MVT::v16f16, MVT::v8i32);
716     setOperationAction(ISD::STORE, MVT::v16bf16, Promote);
717     AddPromotedToType(ISD::STORE, MVT::v16bf16, MVT::v8i32);
718 
719     setOperationAction(ISD::LOAD, MVT::v32i16, Promote);
720     AddPromotedToType(ISD::LOAD, MVT::v32i16, MVT::v16i32);
721     setOperationAction(ISD::LOAD, MVT::v32f16, Promote);
722     AddPromotedToType(ISD::LOAD, MVT::v32f16, MVT::v16i32);
723     setOperationAction(ISD::LOAD, MVT::v32bf16, Promote);
724     AddPromotedToType(ISD::LOAD, MVT::v32bf16, MVT::v16i32);
725 
726     setOperationAction(ISD::STORE, MVT::v32i16, Promote);
727     AddPromotedToType(ISD::STORE, MVT::v32i16, MVT::v16i32);
728     setOperationAction(ISD::STORE, MVT::v32f16, Promote);
729     AddPromotedToType(ISD::STORE, MVT::v32f16, MVT::v16i32);
730     setOperationAction(ISD::STORE, MVT::v32bf16, Promote);
731     AddPromotedToType(ISD::STORE, MVT::v32bf16, MVT::v16i32);
732 
733     setOperationAction({ISD::ANY_EXTEND, ISD::ZERO_EXTEND, ISD::SIGN_EXTEND},
734                        MVT::v2i32, Expand);
735     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
736 
737     setOperationAction({ISD::ANY_EXTEND, ISD::ZERO_EXTEND, ISD::SIGN_EXTEND},
738                        MVT::v4i32, Expand);
739 
740     setOperationAction({ISD::ANY_EXTEND, ISD::ZERO_EXTEND, ISD::SIGN_EXTEND},
741                        MVT::v8i32, Expand);
742 
743     if (!Subtarget->hasVOP3PInsts())
744       setOperationAction(ISD::BUILD_VECTOR,
745                          {MVT::v2i16, MVT::v2f16, MVT::v2bf16}, Custom);
746 
747     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
748     // This isn't really legal, but this avoids the legalizer unrolling it (and
749     // allows matching fneg (fabs x) patterns)
750     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
751 
752     setOperationAction({ISD::FMAXNUM, ISD::FMINNUM}, MVT::f16, Custom);
753     setOperationAction({ISD::FMAXNUM_IEEE, ISD::FMINNUM_IEEE}, MVT::f16, Legal);
754 
755     setOperationAction({ISD::FMINNUM_IEEE, ISD::FMAXNUM_IEEE},
756                        {MVT::v4f16, MVT::v8f16, MVT::v16f16, MVT::v32f16},
757                        Custom);
758 
759     setOperationAction({ISD::FMINNUM, ISD::FMAXNUM},
760                        {MVT::v4f16, MVT::v8f16, MVT::v16f16, MVT::v32f16},
761                        Expand);
762 
763     for (MVT Vec16 :
764          {MVT::v8i16, MVT::v8f16, MVT::v8bf16, MVT::v16i16, MVT::v16f16,
765           MVT::v16bf16, MVT::v32i16, MVT::v32f16, MVT::v32bf16}) {
766       setOperationAction(
767           {ISD::BUILD_VECTOR, ISD::EXTRACT_VECTOR_ELT, ISD::SCALAR_TO_VECTOR},
768           Vec16, Custom);
769       setOperationAction(ISD::INSERT_VECTOR_ELT, Vec16, Expand);
770     }
771   }
772 
773   if (Subtarget->hasVOP3PInsts()) {
774     setOperationAction({ISD::ADD, ISD::SUB, ISD::MUL, ISD::SHL, ISD::SRL,
775                         ISD::SRA, ISD::SMIN, ISD::UMIN, ISD::SMAX, ISD::UMAX,
776                         ISD::UADDSAT, ISD::USUBSAT, ISD::SADDSAT, ISD::SSUBSAT},
777                        MVT::v2i16, Legal);
778 
779     setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA, ISD::FMINNUM_IEEE,
780                         ISD::FMAXNUM_IEEE, ISD::FCANONICALIZE},
781                        MVT::v2f16, Legal);
782 
783     setOperationAction(ISD::EXTRACT_VECTOR_ELT, {MVT::v2i16, MVT::v2f16, MVT::v2bf16},
784                        Custom);
785 
786     setOperationAction(ISD::VECTOR_SHUFFLE,
787                        {MVT::v4f16, MVT::v4i16, MVT::v8f16, MVT::v8i16,
788                         MVT::v16f16, MVT::v16i16, MVT::v32f16, MVT::v32i16},
789                        Custom);
790 
791     for (MVT VT : {MVT::v4i16, MVT::v8i16, MVT::v16i16, MVT::v32i16})
792       // Split vector operations.
793       setOperationAction({ISD::SHL, ISD::SRA, ISD::SRL, ISD::ADD, ISD::SUB,
794                           ISD::MUL, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX,
795                           ISD::UADDSAT, ISD::SADDSAT, ISD::USUBSAT,
796                           ISD::SSUBSAT},
797                          VT, Custom);
798 
799     for (MVT VT : {MVT::v4f16, MVT::v8f16, MVT::v16f16, MVT::v32f16})
800       // Split vector operations.
801       setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA, ISD::FCANONICALIZE},
802                          VT, Custom);
803 
804     setOperationAction({ISD::FMAXNUM, ISD::FMINNUM}, {MVT::v2f16, MVT::v4f16},
805                        Custom);
806 
807     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
808     setOperationAction(ISD::SELECT, {MVT::v4i16, MVT::v4f16, MVT::v4bf16},
809                        Custom);
810 
811     if (Subtarget->hasPackedFP32Ops()) {
812       setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA, ISD::FNEG},
813                          MVT::v2f32, Legal);
814       setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA},
815                          {MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32},
816                          Custom);
817     }
818   }
819 
820   setOperationAction({ISD::FNEG, ISD::FABS}, MVT::v4f16, Custom);
821 
822   if (Subtarget->has16BitInsts()) {
823     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
824     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
825     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
826     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
827   } else {
828     // Legalization hack.
829     setOperationAction(ISD::SELECT, {MVT::v2i16, MVT::v2f16}, Custom);
830 
831     setOperationAction({ISD::FNEG, ISD::FABS}, MVT::v2f16, Custom);
832   }
833 
834   setOperationAction(ISD::SELECT,
835                      {MVT::v4i16, MVT::v4f16, MVT::v4bf16, MVT::v2i8, MVT::v4i8,
836                       MVT::v8i8, MVT::v8i16, MVT::v8f16, MVT::v8bf16,
837                       MVT::v16i16, MVT::v16f16, MVT::v16bf16, MVT::v32i16,
838                       MVT::v32f16, MVT::v32bf16},
839                      Custom);
840 
841   setOperationAction({ISD::SMULO, ISD::UMULO}, MVT::i64, Custom);
842 
843   if (Subtarget->hasScalarSMulU64())
844     setOperationAction(ISD::MUL, MVT::i64, Custom);
845 
846   if (Subtarget->hasMad64_32())
847     setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, MVT::i32, Custom);
848 
849   if (Subtarget->hasPrefetch())
850     setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
851 
852   if (Subtarget->hasIEEEMinMax())
853     setOperationAction({ISD::FMAXIMUM, ISD::FMINIMUM},
854                        {MVT::f16, MVT::f32, MVT::f64, MVT::v2f16}, Legal);
855 
856   setOperationAction(ISD::INTRINSIC_WO_CHAIN,
857                      {MVT::Other, MVT::f32, MVT::v4f32, MVT::i16, MVT::f16,
858                       MVT::v2i16, MVT::v2f16, MVT::i128},
859                      Custom);
860 
861   setOperationAction(ISD::INTRINSIC_W_CHAIN,
862                      {MVT::v2f16, MVT::v2i16, MVT::v3f16, MVT::v3i16,
863                       MVT::v4f16, MVT::v4i16, MVT::v8f16, MVT::Other, MVT::f16,
864                       MVT::i16, MVT::i8, MVT::i128},
865                      Custom);
866 
867   setOperationAction(ISD::INTRINSIC_VOID,
868                      {MVT::Other, MVT::v2i16, MVT::v2f16, MVT::v3i16,
869                       MVT::v3f16, MVT::v4f16, MVT::v4i16, MVT::f16, MVT::i16,
870                       MVT::i8, MVT::i128},
871                      Custom);
872 
873   setOperationAction(ISD::STACKSAVE, MVT::Other, Custom);
874   setOperationAction(ISD::GET_ROUNDING, MVT::i32, Custom);
875 
876   // TODO: Could move this to custom lowering, could benefit from combines on
877   // extract of relevant bits.
878   setOperationAction(ISD::GET_FPMODE, MVT::i32, Legal);
879 
880   setOperationAction(ISD::MUL, MVT::i1, Promote);
881 
882   setTargetDAGCombine({ISD::ADD,
883                        ISD::UADDO_CARRY,
884                        ISD::SUB,
885                        ISD::USUBO_CARRY,
886                        ISD::FADD,
887                        ISD::FSUB,
888                        ISD::FDIV,
889                        ISD::FMINNUM,
890                        ISD::FMAXNUM,
891                        ISD::FMINNUM_IEEE,
892                        ISD::FMAXNUM_IEEE,
893                        ISD::FMINIMUM,
894                        ISD::FMAXIMUM,
895                        ISD::FMA,
896                        ISD::SMIN,
897                        ISD::SMAX,
898                        ISD::UMIN,
899                        ISD::UMAX,
900                        ISD::SETCC,
901                        ISD::AND,
902                        ISD::OR,
903                        ISD::XOR,
904                        ISD::FSHR,
905                        ISD::SINT_TO_FP,
906                        ISD::UINT_TO_FP,
907                        ISD::FCANONICALIZE,
908                        ISD::SCALAR_TO_VECTOR,
909                        ISD::ZERO_EXTEND,
910                        ISD::SIGN_EXTEND_INREG,
911                        ISD::EXTRACT_VECTOR_ELT,
912                        ISD::INSERT_VECTOR_ELT,
913                        ISD::FCOPYSIGN});
914 
915   if (Subtarget->has16BitInsts() && !Subtarget->hasMed3_16())
916     setTargetDAGCombine(ISD::FP_ROUND);
917 
918   // All memory operations. Some folding on the pointer operand is done to help
919   // matching the constant offsets in the addressing modes.
920   setTargetDAGCombine({ISD::LOAD,
921                        ISD::STORE,
922                        ISD::ATOMIC_LOAD,
923                        ISD::ATOMIC_STORE,
924                        ISD::ATOMIC_CMP_SWAP,
925                        ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
926                        ISD::ATOMIC_SWAP,
927                        ISD::ATOMIC_LOAD_ADD,
928                        ISD::ATOMIC_LOAD_SUB,
929                        ISD::ATOMIC_LOAD_AND,
930                        ISD::ATOMIC_LOAD_OR,
931                        ISD::ATOMIC_LOAD_XOR,
932                        ISD::ATOMIC_LOAD_NAND,
933                        ISD::ATOMIC_LOAD_MIN,
934                        ISD::ATOMIC_LOAD_MAX,
935                        ISD::ATOMIC_LOAD_UMIN,
936                        ISD::ATOMIC_LOAD_UMAX,
937                        ISD::ATOMIC_LOAD_FADD,
938                        ISD::ATOMIC_LOAD_UINC_WRAP,
939                        ISD::ATOMIC_LOAD_UDEC_WRAP,
940                        ISD::INTRINSIC_VOID,
941                        ISD::INTRINSIC_W_CHAIN});
942 
943   // FIXME: In other contexts we pretend this is a per-function property.
944   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
945 
946   setSchedulingPreference(Sched::RegPressure);
947 }
948 
949 const GCNSubtarget *SITargetLowering::getSubtarget() const {
950   return Subtarget;
951 }
952 
953 //===----------------------------------------------------------------------===//
954 // TargetLowering queries
955 //===----------------------------------------------------------------------===//
956 
957 // v_mad_mix* support a conversion from f16 to f32.
958 //
959 // There is only one special case when denormals are enabled we don't currently,
960 // where this is OK to use.
961 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
962                                        EVT DestVT, EVT SrcVT) const {
963   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
964           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
965          DestVT.getScalarType() == MVT::f32 &&
966          SrcVT.getScalarType() == MVT::f16 &&
967          // TODO: This probably only requires no input flushing?
968          denormalModeIsFlushAllF32(DAG.getMachineFunction());
969 }
970 
971 bool SITargetLowering::isFPExtFoldable(const MachineInstr &MI, unsigned Opcode,
972                                        LLT DestTy, LLT SrcTy) const {
973   return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) ||
974           (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) &&
975          DestTy.getScalarSizeInBits() == 32 &&
976          SrcTy.getScalarSizeInBits() == 16 &&
977          // TODO: This probably only requires no input flushing?
978          denormalModeIsFlushAllF32(*MI.getMF());
979 }
980 
981 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
982   // SI has some legal vector types, but no legal vector operations. Say no
983   // shuffles are legal in order to prefer scalarizing some vector operations.
984   return false;
985 }
986 
987 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
988                                                     CallingConv::ID CC,
989                                                     EVT VT) const {
990   if (CC == CallingConv::AMDGPU_KERNEL)
991     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
992 
993   if (VT.isVector()) {
994     EVT ScalarVT = VT.getScalarType();
995     unsigned Size = ScalarVT.getSizeInBits();
996     if (Size == 16) {
997       if (Subtarget->has16BitInsts()) {
998         if (VT.isInteger())
999           return MVT::v2i16;
1000         return (ScalarVT == MVT::bf16 ? MVT::i32 : MVT::v2f16);
1001       }
1002       return VT.isInteger() ? MVT::i32 : MVT::f32;
1003     }
1004 
1005     if (Size < 16)
1006       return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
1007     return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
1008   }
1009 
1010   if (VT.getSizeInBits() > 32)
1011     return MVT::i32;
1012 
1013   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1014 }
1015 
1016 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1017                                                          CallingConv::ID CC,
1018                                                          EVT VT) const {
1019   if (CC == CallingConv::AMDGPU_KERNEL)
1020     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1021 
1022   if (VT.isVector()) {
1023     unsigned NumElts = VT.getVectorNumElements();
1024     EVT ScalarVT = VT.getScalarType();
1025     unsigned Size = ScalarVT.getSizeInBits();
1026 
1027     // FIXME: Should probably promote 8-bit vectors to i16.
1028     if (Size == 16 && Subtarget->has16BitInsts())
1029       return (NumElts + 1) / 2;
1030 
1031     if (Size <= 32)
1032       return NumElts;
1033 
1034     if (Size > 32)
1035       return NumElts * ((Size + 31) / 32);
1036   } else if (VT.getSizeInBits() > 32)
1037     return (VT.getSizeInBits() + 31) / 32;
1038 
1039   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1040 }
1041 
1042 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
1043   LLVMContext &Context, CallingConv::ID CC,
1044   EVT VT, EVT &IntermediateVT,
1045   unsigned &NumIntermediates, MVT &RegisterVT) const {
1046   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
1047     unsigned NumElts = VT.getVectorNumElements();
1048     EVT ScalarVT = VT.getScalarType();
1049     unsigned Size = ScalarVT.getSizeInBits();
1050     // FIXME: We should fix the ABI to be the same on targets without 16-bit
1051     // support, but unless we can properly handle 3-vectors, it will be still be
1052     // inconsistent.
1053     if (Size == 16 && Subtarget->has16BitInsts()) {
1054       if (ScalarVT == MVT::bf16) {
1055         RegisterVT = MVT::i32;
1056         IntermediateVT = MVT::v2bf16;
1057       } else {
1058         RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
1059         IntermediateVT = RegisterVT;
1060       }
1061       NumIntermediates = (NumElts + 1) / 2;
1062       return NumIntermediates;
1063     }
1064 
1065     if (Size == 32) {
1066       RegisterVT = ScalarVT.getSimpleVT();
1067       IntermediateVT = RegisterVT;
1068       NumIntermediates = NumElts;
1069       return NumIntermediates;
1070     }
1071 
1072     if (Size < 16 && Subtarget->has16BitInsts()) {
1073       // FIXME: Should probably form v2i16 pieces
1074       RegisterVT = MVT::i16;
1075       IntermediateVT = ScalarVT;
1076       NumIntermediates = NumElts;
1077       return NumIntermediates;
1078     }
1079 
1080 
1081     if (Size != 16 && Size <= 32) {
1082       RegisterVT = MVT::i32;
1083       IntermediateVT = ScalarVT;
1084       NumIntermediates = NumElts;
1085       return NumIntermediates;
1086     }
1087 
1088     if (Size > 32) {
1089       RegisterVT = MVT::i32;
1090       IntermediateVT = RegisterVT;
1091       NumIntermediates = NumElts * ((Size + 31) / 32);
1092       return NumIntermediates;
1093     }
1094   }
1095 
1096   return TargetLowering::getVectorTypeBreakdownForCallingConv(
1097     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
1098 }
1099 
1100 static EVT memVTFromLoadIntrData(Type *Ty, unsigned MaxNumLanes) {
1101   assert(MaxNumLanes != 0);
1102 
1103   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1104     unsigned NumElts = std::min(MaxNumLanes, VT->getNumElements());
1105     return EVT::getVectorVT(Ty->getContext(),
1106                             EVT::getEVT(VT->getElementType()),
1107                             NumElts);
1108   }
1109 
1110   return EVT::getEVT(Ty);
1111 }
1112 
1113 // Peek through TFE struct returns to only use the data size.
1114 static EVT memVTFromLoadIntrReturn(Type *Ty, unsigned MaxNumLanes) {
1115   auto *ST = dyn_cast<StructType>(Ty);
1116   if (!ST)
1117     return memVTFromLoadIntrData(Ty, MaxNumLanes);
1118 
1119   // TFE intrinsics return an aggregate type.
1120   assert(ST->getNumContainedTypes() == 2 &&
1121          ST->getContainedType(1)->isIntegerTy(32));
1122   return memVTFromLoadIntrData(ST->getContainedType(0), MaxNumLanes);
1123 }
1124 
1125 /// Map address space 7 to MVT::v5i32 because that's its in-memory
1126 /// representation. This return value is vector-typed because there is no
1127 /// MVT::i160 and it is not clear if one can be added. While this could
1128 /// cause issues during codegen, these address space 7 pointers will be
1129 /// rewritten away by then. Therefore, we can return MVT::v5i32 in order
1130 /// to allow pre-codegen passes that query TargetTransformInfo, often for cost
1131 /// modeling, to work.
1132 MVT SITargetLowering::getPointerTy(const DataLayout &DL, unsigned AS) const {
1133   if (AMDGPUAS::BUFFER_FAT_POINTER == AS && DL.getPointerSizeInBits(AS) == 160)
1134     return MVT::v5i32;
1135   if (AMDGPUAS::BUFFER_STRIDED_POINTER == AS &&
1136       DL.getPointerSizeInBits(AS) == 192)
1137     return MVT::v6i32;
1138   return AMDGPUTargetLowering::getPointerTy(DL, AS);
1139 }
1140 /// Similarly, the in-memory representation of a p7 is {p8, i32}, aka
1141 /// v8i32 when padding is added.
1142 /// The in-memory representation of a p9 is {p8, i32, i32}, which is
1143 /// also v8i32 with padding.
1144 MVT SITargetLowering::getPointerMemTy(const DataLayout &DL, unsigned AS) const {
1145   if ((AMDGPUAS::BUFFER_FAT_POINTER == AS &&
1146        DL.getPointerSizeInBits(AS) == 160) ||
1147       (AMDGPUAS::BUFFER_STRIDED_POINTER == AS &&
1148        DL.getPointerSizeInBits(AS) == 192))
1149     return MVT::v8i32;
1150   return AMDGPUTargetLowering::getPointerMemTy(DL, AS);
1151 }
1152 
1153 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1154                                           const CallInst &CI,
1155                                           MachineFunction &MF,
1156                                           unsigned IntrID) const {
1157   Info.flags = MachineMemOperand::MONone;
1158   if (CI.hasMetadata(LLVMContext::MD_invariant_load))
1159     Info.flags |= MachineMemOperand::MOInvariant;
1160 
1161   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1162           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1163     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1164                                                   (Intrinsic::ID)IntrID);
1165     MemoryEffects ME = Attr.getMemoryEffects();
1166     if (ME.doesNotAccessMemory())
1167       return false;
1168 
1169     // TODO: Should images get their own address space?
1170     Info.fallbackAddressSpace = AMDGPUAS::BUFFER_RESOURCE;
1171 
1172     if (RsrcIntr->IsImage)
1173       Info.align.reset();
1174 
1175     Value *RsrcArg = CI.getArgOperand(RsrcIntr->RsrcArg);
1176     if (auto *RsrcPtrTy = dyn_cast<PointerType>(RsrcArg->getType())) {
1177       if (RsrcPtrTy->getAddressSpace() == AMDGPUAS::BUFFER_RESOURCE)
1178         // We conservatively set the memory operand of a buffer intrinsic to the
1179         // base resource pointer, so that we can access alias information about
1180         // those pointers. Cases like "this points at the same value
1181         // but with a different offset" are handled in
1182         // areMemAccessesTriviallyDisjoint.
1183         Info.ptrVal = RsrcArg;
1184     }
1185 
1186     Info.flags |= MachineMemOperand::MODereferenceable;
1187     if (ME.onlyReadsMemory()) {
1188       unsigned MaxNumLanes = 4;
1189 
1190       if (RsrcIntr->IsImage) {
1191         const AMDGPU::ImageDimIntrinsicInfo *Intr
1192           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1193         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1194           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1195 
1196         if (!BaseOpcode->Gather4) {
1197           // If this isn't a gather, we may have excess loaded elements in the
1198           // IR type. Check the dmask for the real number of elements loaded.
1199           unsigned DMask
1200             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1201           MaxNumLanes = DMask == 0 ? 1 : llvm::popcount(DMask);
1202         }
1203       }
1204 
1205       Info.memVT = memVTFromLoadIntrReturn(CI.getType(), MaxNumLanes);
1206 
1207       // FIXME: What does alignment mean for an image?
1208       Info.opc = ISD::INTRINSIC_W_CHAIN;
1209       Info.flags |= MachineMemOperand::MOLoad;
1210     } else if (ME.onlyWritesMemory()) {
1211       Info.opc = ISD::INTRINSIC_VOID;
1212 
1213       Type *DataTy = CI.getArgOperand(0)->getType();
1214       if (RsrcIntr->IsImage) {
1215         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1216         unsigned DMaskLanes = DMask == 0 ? 1 : llvm::popcount(DMask);
1217         Info.memVT = memVTFromLoadIntrData(DataTy, DMaskLanes);
1218       } else
1219         Info.memVT = EVT::getEVT(DataTy);
1220 
1221       Info.flags |= MachineMemOperand::MOStore;
1222     } else {
1223       // Atomic
1224       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1225                                             ISD::INTRINSIC_W_CHAIN;
1226       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1227       Info.flags |= MachineMemOperand::MOLoad |
1228                     MachineMemOperand::MOStore |
1229                     MachineMemOperand::MODereferenceable;
1230 
1231       switch (IntrID) {
1232       default:
1233         // XXX - Should this be volatile without known ordering?
1234         Info.flags |= MachineMemOperand::MOVolatile;
1235         break;
1236       case Intrinsic::amdgcn_raw_buffer_load_lds:
1237       case Intrinsic::amdgcn_raw_ptr_buffer_load_lds:
1238       case Intrinsic::amdgcn_struct_buffer_load_lds:
1239       case Intrinsic::amdgcn_struct_ptr_buffer_load_lds: {
1240         unsigned Width = cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue();
1241         Info.memVT = EVT::getIntegerVT(CI.getContext(), Width * 8);
1242         Info.ptrVal = CI.getArgOperand(1);
1243         return true;
1244       }
1245       }
1246     }
1247     return true;
1248   }
1249 
1250   switch (IntrID) {
1251   case Intrinsic::amdgcn_ds_ordered_add:
1252   case Intrinsic::amdgcn_ds_ordered_swap:
1253   case Intrinsic::amdgcn_ds_fadd:
1254   case Intrinsic::amdgcn_ds_fmin:
1255   case Intrinsic::amdgcn_ds_fmax: {
1256     Info.opc = ISD::INTRINSIC_W_CHAIN;
1257     Info.memVT = MVT::getVT(CI.getType());
1258     Info.ptrVal = CI.getOperand(0);
1259     Info.align.reset();
1260     Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1261 
1262     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1263     if (!Vol->isZero())
1264       Info.flags |= MachineMemOperand::MOVolatile;
1265 
1266     return true;
1267   }
1268   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1269     Info.opc = ISD::INTRINSIC_W_CHAIN;
1270     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1271     Info.fallbackAddressSpace = AMDGPUAS::BUFFER_RESOURCE;
1272     Info.align.reset();
1273     Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1274 
1275     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1276     if (!Vol || !Vol->isZero())
1277       Info.flags |= MachineMemOperand::MOVolatile;
1278 
1279     return true;
1280   }
1281   case Intrinsic::amdgcn_ds_add_gs_reg_rtn:
1282   case Intrinsic::amdgcn_ds_sub_gs_reg_rtn: {
1283     Info.opc = ISD::INTRINSIC_W_CHAIN;
1284     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1285     Info.ptrVal = nullptr;
1286     Info.fallbackAddressSpace = AMDGPUAS::STREAMOUT_REGISTER;
1287     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1288     return true;
1289   }
1290   case Intrinsic::amdgcn_ds_append:
1291   case Intrinsic::amdgcn_ds_consume: {
1292     Info.opc = ISD::INTRINSIC_W_CHAIN;
1293     Info.memVT = MVT::getVT(CI.getType());
1294     Info.ptrVal = CI.getOperand(0);
1295     Info.align.reset();
1296     Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1297 
1298     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1299     if (!Vol->isZero())
1300       Info.flags |= MachineMemOperand::MOVolatile;
1301 
1302     return true;
1303   }
1304   case Intrinsic::amdgcn_global_atomic_csub: {
1305     Info.opc = ISD::INTRINSIC_W_CHAIN;
1306     Info.memVT = MVT::getVT(CI.getType());
1307     Info.ptrVal = CI.getOperand(0);
1308     Info.align.reset();
1309     Info.flags |= MachineMemOperand::MOLoad |
1310                   MachineMemOperand::MOStore |
1311                   MachineMemOperand::MOVolatile;
1312     return true;
1313   }
1314   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1315     Info.opc = ISD::INTRINSIC_W_CHAIN;
1316     Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1317 
1318     Info.fallbackAddressSpace = AMDGPUAS::BUFFER_RESOURCE;
1319     Info.align.reset();
1320     Info.flags |= MachineMemOperand::MOLoad |
1321                   MachineMemOperand::MODereferenceable;
1322     return true;
1323   }
1324   case Intrinsic::amdgcn_global_atomic_fadd:
1325   case Intrinsic::amdgcn_global_atomic_fmin:
1326   case Intrinsic::amdgcn_global_atomic_fmax:
1327   case Intrinsic::amdgcn_global_atomic_fmin_num:
1328   case Intrinsic::amdgcn_global_atomic_fmax_num:
1329   case Intrinsic::amdgcn_global_atomic_ordered_add_b64:
1330   case Intrinsic::amdgcn_flat_atomic_fadd:
1331   case Intrinsic::amdgcn_flat_atomic_fmin:
1332   case Intrinsic::amdgcn_flat_atomic_fmax:
1333   case Intrinsic::amdgcn_flat_atomic_fmin_num:
1334   case Intrinsic::amdgcn_flat_atomic_fmax_num:
1335   case Intrinsic::amdgcn_global_atomic_fadd_v2bf16:
1336   case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16: {
1337     Info.opc = ISD::INTRINSIC_W_CHAIN;
1338     Info.memVT = MVT::getVT(CI.getType());
1339     Info.ptrVal = CI.getOperand(0);
1340     Info.align.reset();
1341     Info.flags |= MachineMemOperand::MOLoad |
1342                   MachineMemOperand::MOStore |
1343                   MachineMemOperand::MODereferenceable |
1344                   MachineMemOperand::MOVolatile;
1345     return true;
1346   }
1347   case Intrinsic::amdgcn_ds_gws_init:
1348   case Intrinsic::amdgcn_ds_gws_barrier:
1349   case Intrinsic::amdgcn_ds_gws_sema_v:
1350   case Intrinsic::amdgcn_ds_gws_sema_br:
1351   case Intrinsic::amdgcn_ds_gws_sema_p:
1352   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1353     Info.opc = ISD::INTRINSIC_VOID;
1354 
1355     const GCNTargetMachine &TM =
1356         static_cast<const GCNTargetMachine &>(getTargetMachine());
1357 
1358     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1359     Info.ptrVal = MFI->getGWSPSV(TM);
1360 
1361     // This is an abstract access, but we need to specify a type and size.
1362     Info.memVT = MVT::i32;
1363     Info.size = 4;
1364     Info.align = Align(4);
1365 
1366     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1367       Info.flags |= MachineMemOperand::MOLoad;
1368     else
1369       Info.flags |= MachineMemOperand::MOStore;
1370     return true;
1371   }
1372   case Intrinsic::amdgcn_global_load_lds: {
1373     Info.opc = ISD::INTRINSIC_VOID;
1374     unsigned Width = cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue();
1375     Info.memVT = EVT::getIntegerVT(CI.getContext(), Width * 8);
1376     Info.ptrVal = CI.getArgOperand(1);
1377     Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1378     return true;
1379   }
1380   case Intrinsic::amdgcn_ds_bvh_stack_rtn: {
1381     Info.opc = ISD::INTRINSIC_W_CHAIN;
1382 
1383     const GCNTargetMachine &TM =
1384         static_cast<const GCNTargetMachine &>(getTargetMachine());
1385 
1386     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1387     Info.ptrVal = MFI->getGWSPSV(TM);
1388 
1389     // This is an abstract access, but we need to specify a type and size.
1390     Info.memVT = MVT::i32;
1391     Info.size = 4;
1392     Info.align = Align(4);
1393 
1394     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1395     return true;
1396   }
1397   default:
1398     return false;
1399   }
1400 }
1401 
1402 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1403                                             SmallVectorImpl<Value*> &Ops,
1404                                             Type *&AccessTy) const {
1405   switch (II->getIntrinsicID()) {
1406   case Intrinsic::amdgcn_ds_ordered_add:
1407   case Intrinsic::amdgcn_ds_ordered_swap:
1408   case Intrinsic::amdgcn_ds_append:
1409   case Intrinsic::amdgcn_ds_consume:
1410   case Intrinsic::amdgcn_ds_fadd:
1411   case Intrinsic::amdgcn_ds_fmin:
1412   case Intrinsic::amdgcn_ds_fmax:
1413   case Intrinsic::amdgcn_global_atomic_fadd:
1414   case Intrinsic::amdgcn_flat_atomic_fadd:
1415   case Intrinsic::amdgcn_flat_atomic_fmin:
1416   case Intrinsic::amdgcn_flat_atomic_fmax:
1417   case Intrinsic::amdgcn_flat_atomic_fmin_num:
1418   case Intrinsic::amdgcn_flat_atomic_fmax_num:
1419   case Intrinsic::amdgcn_global_atomic_fadd_v2bf16:
1420   case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16:
1421   case Intrinsic::amdgcn_global_atomic_csub: {
1422     Value *Ptr = II->getArgOperand(0);
1423     AccessTy = II->getType();
1424     Ops.push_back(Ptr);
1425     return true;
1426   }
1427   default:
1428     return false;
1429   }
1430 }
1431 
1432 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM,
1433                                                  unsigned AddrSpace,
1434                                                  uint64_t FlatVariant) const {
1435   if (!Subtarget->hasFlatInstOffsets()) {
1436     // Flat instructions do not have offsets, and only have the register
1437     // address.
1438     return AM.BaseOffs == 0 && AM.Scale == 0;
1439   }
1440 
1441   return AM.Scale == 0 &&
1442          (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1443                                   AM.BaseOffs, AddrSpace, FlatVariant));
1444 }
1445 
1446 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1447   if (Subtarget->hasFlatGlobalInsts())
1448     return isLegalFlatAddressingMode(AM, AMDGPUAS::GLOBAL_ADDRESS,
1449                                      SIInstrFlags::FlatGlobal);
1450 
1451   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1452     // Assume the we will use FLAT for all global memory accesses
1453     // on VI.
1454     // FIXME: This assumption is currently wrong.  On VI we still use
1455     // MUBUF instructions for the r + i addressing mode.  As currently
1456     // implemented, the MUBUF instructions only work on buffer < 4GB.
1457     // It may be possible to support > 4GB buffers with MUBUF instructions,
1458     // by setting the stride value in the resource descriptor which would
1459     // increase the size limit to (stride * 4GB).  However, this is risky,
1460     // because it has never been validated.
1461     return isLegalFlatAddressingMode(AM, AMDGPUAS::FLAT_ADDRESS,
1462                                      SIInstrFlags::FLAT);
1463   }
1464 
1465   return isLegalMUBUFAddressingMode(AM);
1466 }
1467 
1468 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1469   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1470   // additionally can do r + r + i with addr64. 32-bit has more addressing
1471   // mode options. Depending on the resource constant, it can also do
1472   // (i64 r0) + (i32 r1) * (i14 i).
1473   //
1474   // Private arrays end up using a scratch buffer most of the time, so also
1475   // assume those use MUBUF instructions. Scratch loads / stores are currently
1476   // implemented as mubuf instructions with offen bit set, so slightly
1477   // different than the normal addr64.
1478   const SIInstrInfo *TII = Subtarget->getInstrInfo();
1479   if (!TII->isLegalMUBUFImmOffset(AM.BaseOffs))
1480     return false;
1481 
1482   // FIXME: Since we can split immediate into soffset and immediate offset,
1483   // would it make sense to allow any immediate?
1484 
1485   switch (AM.Scale) {
1486   case 0: // r + i or just i, depending on HasBaseReg.
1487     return true;
1488   case 1:
1489     return true; // We have r + r or r + i.
1490   case 2:
1491     if (AM.HasBaseReg) {
1492       // Reject 2 * r + r.
1493       return false;
1494     }
1495 
1496     // Allow 2 * r as r + r
1497     // Or  2 * r + i is allowed as r + r + i.
1498     return true;
1499   default: // Don't allow n * r
1500     return false;
1501   }
1502 }
1503 
1504 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1505                                              const AddrMode &AM, Type *Ty,
1506                                              unsigned AS, Instruction *I) const {
1507   // No global is ever allowed as a base.
1508   if (AM.BaseGV)
1509     return false;
1510 
1511   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1512     return isLegalGlobalAddressingMode(AM);
1513 
1514   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1515       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1516       AS == AMDGPUAS::BUFFER_FAT_POINTER || AS == AMDGPUAS::BUFFER_RESOURCE ||
1517       AS == AMDGPUAS::BUFFER_STRIDED_POINTER) {
1518     // If the offset isn't a multiple of 4, it probably isn't going to be
1519     // correctly aligned.
1520     // FIXME: Can we get the real alignment here?
1521     if (AM.BaseOffs % 4 != 0)
1522       return isLegalMUBUFAddressingMode(AM);
1523 
1524     // There are no SMRD extloads, so if we have to do a small type access we
1525     // will use a MUBUF load.
1526     // FIXME?: We also need to do this if unaligned, but we don't know the
1527     // alignment here.
1528     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1529       return isLegalGlobalAddressingMode(AM);
1530 
1531     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1532       // SMRD instructions have an 8-bit, dword offset on SI.
1533       if (!isUInt<8>(AM.BaseOffs / 4))
1534         return false;
1535     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1536       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1537       // in 8-bits, it can use a smaller encoding.
1538       if (!isUInt<32>(AM.BaseOffs / 4))
1539         return false;
1540     } else if (Subtarget->getGeneration() < AMDGPUSubtarget::GFX9) {
1541       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1542       if (!isUInt<20>(AM.BaseOffs))
1543         return false;
1544     } else if (Subtarget->getGeneration() < AMDGPUSubtarget::GFX12) {
1545       // On GFX9 the offset is signed 21-bit in bytes (but must not be negative
1546       // for S_BUFFER_* instructions).
1547       if (!isInt<21>(AM.BaseOffs))
1548         return false;
1549     } else {
1550       // On GFX12, all offsets are signed 24-bit in bytes.
1551       if (!isInt<24>(AM.BaseOffs))
1552         return false;
1553     }
1554 
1555     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1556       return true;
1557 
1558     if (AM.Scale == 1 && AM.HasBaseReg)
1559       return true;
1560 
1561     return false;
1562   }
1563 
1564   if (AS == AMDGPUAS::PRIVATE_ADDRESS)
1565     return Subtarget->enableFlatScratch()
1566                ? isLegalFlatAddressingMode(AM, AMDGPUAS::PRIVATE_ADDRESS,
1567                                            SIInstrFlags::FlatScratch)
1568                : isLegalMUBUFAddressingMode(AM);
1569 
1570   if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1571       (AS == AMDGPUAS::REGION_ADDRESS && Subtarget->hasGDS())) {
1572     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1573     // field.
1574     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1575     // an 8-bit dword offset but we don't know the alignment here.
1576     if (!isUInt<16>(AM.BaseOffs))
1577       return false;
1578 
1579     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1580       return true;
1581 
1582     if (AM.Scale == 1 && AM.HasBaseReg)
1583       return true;
1584 
1585     return false;
1586   }
1587 
1588   if (AS == AMDGPUAS::FLAT_ADDRESS || AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1589     // For an unknown address space, this usually means that this is for some
1590     // reason being used for pure arithmetic, and not based on some addressing
1591     // computation. We don't have instructions that compute pointers with any
1592     // addressing modes, so treat them as having no offset like flat
1593     // instructions.
1594     return isLegalFlatAddressingMode(AM, AMDGPUAS::FLAT_ADDRESS,
1595                                      SIInstrFlags::FLAT);
1596   }
1597 
1598   // Assume a user alias of global for unknown address spaces.
1599   return isLegalGlobalAddressingMode(AM);
1600 }
1601 
1602 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1603                                         const MachineFunction &MF) const {
1604   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1605     return (MemVT.getSizeInBits() <= 4 * 32);
1606   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1607     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1608     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1609   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1610     return (MemVT.getSizeInBits() <= 2 * 32);
1611   }
1612   return true;
1613 }
1614 
1615 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1616     unsigned Size, unsigned AddrSpace, Align Alignment,
1617     MachineMemOperand::Flags Flags, unsigned *IsFast) const {
1618   if (IsFast)
1619     *IsFast = 0;
1620 
1621   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1622       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1623     // Check if alignment requirements for ds_read/write instructions are
1624     // disabled.
1625     if (!Subtarget->hasUnalignedDSAccessEnabled() && Alignment < Align(4))
1626       return false;
1627 
1628     Align RequiredAlignment(PowerOf2Ceil(Size/8)); // Natural alignment.
1629     if (Subtarget->hasLDSMisalignedBug() && Size > 32 &&
1630         Alignment < RequiredAlignment)
1631       return false;
1632 
1633     // Either, the alignment requirements are "enabled", or there is an
1634     // unaligned LDS access related hardware bug though alignment requirements
1635     // are "disabled". In either case, we need to check for proper alignment
1636     // requirements.
1637     //
1638     switch (Size) {
1639     case 64:
1640       // SI has a hardware bug in the LDS / GDS bounds checking: if the base
1641       // address is negative, then the instruction is incorrectly treated as
1642       // out-of-bounds even if base + offsets is in bounds. Split vectorized
1643       // loads here to avoid emitting ds_read2_b32. We may re-combine the
1644       // load later in the SILoadStoreOptimizer.
1645       if (!Subtarget->hasUsableDSOffset() && Alignment < Align(8))
1646         return false;
1647 
1648       // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
1649       // can do a 4 byte aligned, 8 byte access in a single operation using
1650       // ds_read2/write2_b32 with adjacent offsets.
1651       RequiredAlignment = Align(4);
1652 
1653       if (Subtarget->hasUnalignedDSAccessEnabled()) {
1654         // We will either select ds_read_b64/ds_write_b64 or ds_read2_b32/
1655         // ds_write2_b32 depending on the alignment. In either case with either
1656         // alignment there is no faster way of doing this.
1657 
1658         // The numbers returned here and below are not additive, it is a 'speed
1659         // rank'. They are just meant to be compared to decide if a certain way
1660         // of lowering an operation is faster than another. For that purpose
1661         // naturally aligned operation gets it bitsize to indicate that "it
1662         // operates with a speed comparable to N-bit wide load". With the full
1663         // alignment ds128 is slower than ds96 for example. If underaligned it
1664         // is comparable to a speed of a single dword access, which would then
1665         // mean 32 < 128 and it is faster to issue a wide load regardless.
1666         // 1 is simply "slow, don't do it". I.e. comparing an aligned load to a
1667         // wider load which will not be aligned anymore the latter is slower.
1668         if (IsFast)
1669           *IsFast = (Alignment >= RequiredAlignment) ? 64
1670                     : (Alignment < Align(4))         ? 32
1671                                                      : 1;
1672         return true;
1673       }
1674 
1675       break;
1676     case 96:
1677       if (!Subtarget->hasDS96AndDS128())
1678         return false;
1679 
1680       // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
1681       // gfx8 and older.
1682 
1683       if (Subtarget->hasUnalignedDSAccessEnabled()) {
1684         // Naturally aligned access is fastest. However, also report it is Fast
1685         // if memory is aligned less than DWORD. A narrow load or store will be
1686         // be equally slow as a single ds_read_b96/ds_write_b96, but there will
1687         // be more of them, so overall we will pay less penalty issuing a single
1688         // instruction.
1689 
1690         // See comment on the values above.
1691         if (IsFast)
1692           *IsFast = (Alignment >= RequiredAlignment) ? 96
1693                     : (Alignment < Align(4))         ? 32
1694                                                      : 1;
1695         return true;
1696       }
1697 
1698       break;
1699     case 128:
1700       if (!Subtarget->hasDS96AndDS128() || !Subtarget->useDS128())
1701         return false;
1702 
1703       // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
1704       // gfx8 and older, but  we can do a 8 byte aligned, 16 byte access in a
1705       // single operation using ds_read2/write2_b64.
1706       RequiredAlignment = Align(8);
1707 
1708       if (Subtarget->hasUnalignedDSAccessEnabled()) {
1709         // Naturally aligned access is fastest. However, also report it is Fast
1710         // if memory is aligned less than DWORD. A narrow load or store will be
1711         // be equally slow as a single ds_read_b128/ds_write_b128, but there
1712         // will be more of them, so overall we will pay less penalty issuing a
1713         // single instruction.
1714 
1715         // See comment on the values above.
1716         if (IsFast)
1717           *IsFast = (Alignment >= RequiredAlignment) ? 128
1718                     : (Alignment < Align(4))         ? 32
1719                                                      : 1;
1720         return true;
1721       }
1722 
1723       break;
1724     default:
1725       if (Size > 32)
1726         return false;
1727 
1728       break;
1729     }
1730 
1731     // See comment on the values above.
1732     // Note that we have a single-dword or sub-dword here, so if underaligned
1733     // it is a slowest possible access, hence returned value is 0.
1734     if (IsFast)
1735       *IsFast = (Alignment >= RequiredAlignment) ? Size : 0;
1736 
1737     return Alignment >= RequiredAlignment ||
1738            Subtarget->hasUnalignedDSAccessEnabled();
1739   }
1740 
1741   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1742     bool AlignedBy4 = Alignment >= Align(4);
1743     if (IsFast)
1744       *IsFast = AlignedBy4;
1745 
1746     return AlignedBy4 ||
1747            Subtarget->enableFlatScratch() ||
1748            Subtarget->hasUnalignedScratchAccess();
1749   }
1750 
1751   // FIXME: We have to be conservative here and assume that flat operations
1752   // will access scratch.  If we had access to the IR function, then we
1753   // could determine if any private memory was used in the function.
1754   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1755       !Subtarget->hasUnalignedScratchAccess()) {
1756     bool AlignedBy4 = Alignment >= Align(4);
1757     if (IsFast)
1758       *IsFast = AlignedBy4;
1759 
1760     return AlignedBy4;
1761   }
1762 
1763   // So long as they are correct, wide global memory operations perform better
1764   // than multiple smaller memory ops -- even when misaligned
1765   if (AMDGPU::isExtendedGlobalAddrSpace(AddrSpace)) {
1766     if (IsFast)
1767       *IsFast = Size;
1768 
1769     return Alignment >= Align(4) ||
1770            Subtarget->hasUnalignedBufferAccessEnabled();
1771   }
1772 
1773   // Smaller than dword value must be aligned.
1774   if (Size < 32)
1775     return false;
1776 
1777   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1778   // byte-address are ignored, thus forcing Dword alignment.
1779   // This applies to private, global, and constant memory.
1780   if (IsFast)
1781     *IsFast = 1;
1782 
1783   return Size >= 32 && Alignment >= Align(4);
1784 }
1785 
1786 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1787     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1788     unsigned *IsFast) const {
1789   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1790                                             Alignment, Flags, IsFast);
1791 }
1792 
1793 EVT SITargetLowering::getOptimalMemOpType(
1794     const MemOp &Op, const AttributeList &FuncAttributes) const {
1795   // FIXME: Should account for address space here.
1796 
1797   // The default fallback uses the private pointer size as a guess for a type to
1798   // use. Make sure we switch these to 64-bit accesses.
1799 
1800   if (Op.size() >= 16 &&
1801       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1802     return MVT::v4i32;
1803 
1804   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1805     return MVT::v2i32;
1806 
1807   // Use the default.
1808   return MVT::Other;
1809 }
1810 
1811 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1812   const MemSDNode *MemNode = cast<MemSDNode>(N);
1813   return MemNode->getMemOperand()->getFlags() & MONoClobber;
1814 }
1815 
1816 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1817   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1818          AS == AMDGPUAS::PRIVATE_ADDRESS;
1819 }
1820 
1821 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1822                                            unsigned DestAS) const {
1823   // Flat -> private/local is a simple truncate.
1824   // Flat -> global is no-op
1825   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1826     return true;
1827 
1828   const GCNTargetMachine &TM =
1829       static_cast<const GCNTargetMachine &>(getTargetMachine());
1830   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1831 }
1832 
1833 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1834   const MemSDNode *MemNode = cast<MemSDNode>(N);
1835 
1836   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1837 }
1838 
1839 TargetLoweringBase::LegalizeTypeAction
1840 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1841   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1842       VT.getScalarType().bitsLE(MVT::i16))
1843     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1844   return TargetLoweringBase::getPreferredVectorAction(VT);
1845 }
1846 
1847 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1848                                                          Type *Ty) const {
1849   // FIXME: Could be smarter if called for vector constants.
1850   return true;
1851 }
1852 
1853 bool SITargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
1854                                                unsigned Index) const {
1855   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
1856     return false;
1857 
1858   // TODO: Add more cases that are cheap.
1859   return Index == 0;
1860 }
1861 
1862 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1863   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1864     switch (Op) {
1865     case ISD::LOAD:
1866     case ISD::STORE:
1867 
1868     // These operations are done with 32-bit instructions anyway.
1869     case ISD::AND:
1870     case ISD::OR:
1871     case ISD::XOR:
1872     case ISD::SELECT:
1873       // TODO: Extensions?
1874       return true;
1875     default:
1876       return false;
1877     }
1878   }
1879 
1880   // SimplifySetCC uses this function to determine whether or not it should
1881   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1882   if (VT == MVT::i1 && Op == ISD::SETCC)
1883     return false;
1884 
1885   return TargetLowering::isTypeDesirableForOp(Op, VT);
1886 }
1887 
1888 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1889                                                    const SDLoc &SL,
1890                                                    SDValue Chain,
1891                                                    uint64_t Offset) const {
1892   const DataLayout &DL = DAG.getDataLayout();
1893   MachineFunction &MF = DAG.getMachineFunction();
1894   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1895 
1896   const ArgDescriptor *InputPtrReg;
1897   const TargetRegisterClass *RC;
1898   LLT ArgTy;
1899   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1900 
1901   std::tie(InputPtrReg, RC, ArgTy) =
1902       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1903 
1904   // We may not have the kernarg segment argument if we have no kernel
1905   // arguments.
1906   if (!InputPtrReg)
1907     return DAG.getConstant(Offset, SL, PtrVT);
1908 
1909   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1910   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1911     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1912 
1913   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::getFixed(Offset));
1914 }
1915 
1916 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1917                                             const SDLoc &SL) const {
1918   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1919                                                FIRST_IMPLICIT);
1920   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1921 }
1922 
1923 SDValue SITargetLowering::getLDSKernelId(SelectionDAG &DAG,
1924                                          const SDLoc &SL) const {
1925 
1926   Function &F = DAG.getMachineFunction().getFunction();
1927   std::optional<uint32_t> KnownSize =
1928       AMDGPUMachineFunction::getLDSKernelIdMetadata(F);
1929   if (KnownSize.has_value())
1930     return DAG.getConstant(*KnownSize, SL, MVT::i32);
1931   return SDValue();
1932 }
1933 
1934 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1935                                          const SDLoc &SL, SDValue Val,
1936                                          bool Signed,
1937                                          const ISD::InputArg *Arg) const {
1938   // First, if it is a widened vector, narrow it.
1939   if (VT.isVector() &&
1940       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1941     EVT NarrowedVT =
1942         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1943                          VT.getVectorNumElements());
1944     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1945                       DAG.getConstant(0, SL, MVT::i32));
1946   }
1947 
1948   // Then convert the vector elements or scalar value.
1949   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1950       VT.bitsLT(MemVT)) {
1951     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1952     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1953   }
1954 
1955   if (MemVT.isFloatingPoint())
1956     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1957   else if (Signed)
1958     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1959   else
1960     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1961 
1962   return Val;
1963 }
1964 
1965 SDValue SITargetLowering::lowerKernargMemParameter(
1966     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1967     uint64_t Offset, Align Alignment, bool Signed,
1968     const ISD::InputArg *Arg) const {
1969   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1970 
1971   // Try to avoid using an extload by loading earlier than the argument address,
1972   // and extracting the relevant bits. The load should hopefully be merged with
1973   // the previous argument.
1974   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1975     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1976     int64_t AlignDownOffset = alignDown(Offset, 4);
1977     int64_t OffsetDiff = Offset - AlignDownOffset;
1978 
1979     EVT IntVT = MemVT.changeTypeToInteger();
1980 
1981     // TODO: If we passed in the base kernel offset we could have a better
1982     // alignment than 4, but we don't really need it.
1983     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1984     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1985                                MachineMemOperand::MODereferenceable |
1986                                    MachineMemOperand::MOInvariant);
1987 
1988     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1989     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1990 
1991     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1992     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1993     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1994 
1995 
1996     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1997   }
1998 
1999   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
2000   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
2001                              MachineMemOperand::MODereferenceable |
2002                                  MachineMemOperand::MOInvariant);
2003 
2004   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
2005   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
2006 }
2007 
2008 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
2009                                               const SDLoc &SL, SDValue Chain,
2010                                               const ISD::InputArg &Arg) const {
2011   MachineFunction &MF = DAG.getMachineFunction();
2012   MachineFrameInfo &MFI = MF.getFrameInfo();
2013 
2014   if (Arg.Flags.isByVal()) {
2015     unsigned Size = Arg.Flags.getByValSize();
2016     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
2017     return DAG.getFrameIndex(FrameIdx, MVT::i32);
2018   }
2019 
2020   unsigned ArgOffset = VA.getLocMemOffset();
2021   unsigned ArgSize = VA.getValVT().getStoreSize();
2022 
2023   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
2024 
2025   // Create load nodes to retrieve arguments from the stack.
2026   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
2027   SDValue ArgValue;
2028 
2029   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2030   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2031   MVT MemVT = VA.getValVT();
2032 
2033   switch (VA.getLocInfo()) {
2034   default:
2035     break;
2036   case CCValAssign::BCvt:
2037     MemVT = VA.getLocVT();
2038     break;
2039   case CCValAssign::SExt:
2040     ExtType = ISD::SEXTLOAD;
2041     break;
2042   case CCValAssign::ZExt:
2043     ExtType = ISD::ZEXTLOAD;
2044     break;
2045   case CCValAssign::AExt:
2046     ExtType = ISD::EXTLOAD;
2047     break;
2048   }
2049 
2050   ArgValue = DAG.getExtLoad(
2051     ExtType, SL, VA.getLocVT(), Chain, FIN,
2052     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2053     MemVT);
2054   return ArgValue;
2055 }
2056 
2057 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
2058   const SIMachineFunctionInfo &MFI,
2059   EVT VT,
2060   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
2061   const ArgDescriptor *Reg;
2062   const TargetRegisterClass *RC;
2063   LLT Ty;
2064 
2065   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
2066   if (!Reg) {
2067     if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) {
2068       // It's possible for a kernarg intrinsic call to appear in a kernel with
2069       // no allocated segment, in which case we do not add the user sgpr
2070       // argument, so just return null.
2071       return DAG.getConstant(0, SDLoc(), VT);
2072     }
2073 
2074     // It's undefined behavior if a function marked with the amdgpu-no-*
2075     // attributes uses the corresponding intrinsic.
2076     return DAG.getUNDEF(VT);
2077   }
2078 
2079   return loadInputValue(DAG, RC, VT, SDLoc(DAG.getEntryNode()), *Reg);
2080 }
2081 
2082 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
2083                                CallingConv::ID CallConv,
2084                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
2085                                FunctionType *FType,
2086                                SIMachineFunctionInfo *Info) {
2087   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
2088     const ISD::InputArg *Arg = &Ins[I];
2089 
2090     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
2091            "vector type argument should have been split");
2092 
2093     // First check if it's a PS input addr.
2094     if (CallConv == CallingConv::AMDGPU_PS &&
2095         !Arg->Flags.isInReg() && PSInputNum <= 15) {
2096       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
2097 
2098       // Inconveniently only the first part of the split is marked as isSplit,
2099       // so skip to the end. We only want to increment PSInputNum once for the
2100       // entire split argument.
2101       if (Arg->Flags.isSplit()) {
2102         while (!Arg->Flags.isSplitEnd()) {
2103           assert((!Arg->VT.isVector() ||
2104                   Arg->VT.getScalarSizeInBits() == 16) &&
2105                  "unexpected vector split in ps argument type");
2106           if (!SkipArg)
2107             Splits.push_back(*Arg);
2108           Arg = &Ins[++I];
2109         }
2110       }
2111 
2112       if (SkipArg) {
2113         // We can safely skip PS inputs.
2114         Skipped.set(Arg->getOrigArgIndex());
2115         ++PSInputNum;
2116         continue;
2117       }
2118 
2119       Info->markPSInputAllocated(PSInputNum);
2120       if (Arg->Used)
2121         Info->markPSInputEnabled(PSInputNum);
2122 
2123       ++PSInputNum;
2124     }
2125 
2126     Splits.push_back(*Arg);
2127   }
2128 }
2129 
2130 // Allocate special inputs passed in VGPRs.
2131 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
2132                                                       MachineFunction &MF,
2133                                                       const SIRegisterInfo &TRI,
2134                                                       SIMachineFunctionInfo &Info) const {
2135   const LLT S32 = LLT::scalar(32);
2136   MachineRegisterInfo &MRI = MF.getRegInfo();
2137 
2138   if (Info.hasWorkItemIDX()) {
2139     Register Reg = AMDGPU::VGPR0;
2140     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
2141 
2142     CCInfo.AllocateReg(Reg);
2143     unsigned Mask = (Subtarget->hasPackedTID() &&
2144                      Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
2145     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2146   }
2147 
2148   if (Info.hasWorkItemIDY()) {
2149     assert(Info.hasWorkItemIDX());
2150     if (Subtarget->hasPackedTID()) {
2151       Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
2152                                                         0x3ff << 10));
2153     } else {
2154       unsigned Reg = AMDGPU::VGPR1;
2155       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
2156 
2157       CCInfo.AllocateReg(Reg);
2158       Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
2159     }
2160   }
2161 
2162   if (Info.hasWorkItemIDZ()) {
2163     assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
2164     if (Subtarget->hasPackedTID()) {
2165       Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
2166                                                         0x3ff << 20));
2167     } else {
2168       unsigned Reg = AMDGPU::VGPR2;
2169       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
2170 
2171       CCInfo.AllocateReg(Reg);
2172       Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
2173     }
2174   }
2175 }
2176 
2177 // Try to allocate a VGPR at the end of the argument list, or if no argument
2178 // VGPRs are left allocating a stack slot.
2179 // If \p Mask is is given it indicates bitfield position in the register.
2180 // If \p Arg is given use it with new ]p Mask instead of allocating new.
2181 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
2182                                          ArgDescriptor Arg = ArgDescriptor()) {
2183   if (Arg.isSet())
2184     return ArgDescriptor::createArg(Arg, Mask);
2185 
2186   ArrayRef<MCPhysReg> ArgVGPRs = ArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
2187   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
2188   if (RegIdx == ArgVGPRs.size()) {
2189     // Spill to stack required.
2190     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
2191 
2192     return ArgDescriptor::createStack(Offset, Mask);
2193   }
2194 
2195   unsigned Reg = ArgVGPRs[RegIdx];
2196   Reg = CCInfo.AllocateReg(Reg);
2197   assert(Reg != AMDGPU::NoRegister);
2198 
2199   MachineFunction &MF = CCInfo.getMachineFunction();
2200   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
2201   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
2202   return ArgDescriptor::createRegister(Reg, Mask);
2203 }
2204 
2205 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
2206                                              const TargetRegisterClass *RC,
2207                                              unsigned NumArgRegs) {
2208   ArrayRef<MCPhysReg> ArgSGPRs = ArrayRef(RC->begin(), 32);
2209   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
2210   if (RegIdx == ArgSGPRs.size())
2211     report_fatal_error("ran out of SGPRs for arguments");
2212 
2213   unsigned Reg = ArgSGPRs[RegIdx];
2214   Reg = CCInfo.AllocateReg(Reg);
2215   assert(Reg != AMDGPU::NoRegister);
2216 
2217   MachineFunction &MF = CCInfo.getMachineFunction();
2218   MF.addLiveIn(Reg, RC);
2219   return ArgDescriptor::createRegister(Reg);
2220 }
2221 
2222 // If this has a fixed position, we still should allocate the register in the
2223 // CCInfo state. Technically we could get away with this for values passed
2224 // outside of the normal argument range.
2225 static void allocateFixedSGPRInputImpl(CCState &CCInfo,
2226                                        const TargetRegisterClass *RC,
2227                                        MCRegister Reg) {
2228   Reg = CCInfo.AllocateReg(Reg);
2229   assert(Reg != AMDGPU::NoRegister);
2230   MachineFunction &MF = CCInfo.getMachineFunction();
2231   MF.addLiveIn(Reg, RC);
2232 }
2233 
2234 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
2235   if (Arg) {
2236     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
2237                                Arg.getRegister());
2238   } else
2239     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
2240 }
2241 
2242 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
2243   if (Arg) {
2244     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
2245                                Arg.getRegister());
2246   } else
2247     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
2248 }
2249 
2250 /// Allocate implicit function VGPR arguments at the end of allocated user
2251 /// arguments.
2252 void SITargetLowering::allocateSpecialInputVGPRs(
2253   CCState &CCInfo, MachineFunction &MF,
2254   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2255   const unsigned Mask = 0x3ff;
2256   ArgDescriptor Arg;
2257 
2258   if (Info.hasWorkItemIDX()) {
2259     Arg = allocateVGPR32Input(CCInfo, Mask);
2260     Info.setWorkItemIDX(Arg);
2261   }
2262 
2263   if (Info.hasWorkItemIDY()) {
2264     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
2265     Info.setWorkItemIDY(Arg);
2266   }
2267 
2268   if (Info.hasWorkItemIDZ())
2269     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
2270 }
2271 
2272 /// Allocate implicit function VGPR arguments in fixed registers.
2273 void SITargetLowering::allocateSpecialInputVGPRsFixed(
2274   CCState &CCInfo, MachineFunction &MF,
2275   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2276   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
2277   if (!Reg)
2278     report_fatal_error("failed to allocated VGPR for implicit arguments");
2279 
2280   const unsigned Mask = 0x3ff;
2281   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2282   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
2283   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
2284 }
2285 
2286 void SITargetLowering::allocateSpecialInputSGPRs(
2287   CCState &CCInfo,
2288   MachineFunction &MF,
2289   const SIRegisterInfo &TRI,
2290   SIMachineFunctionInfo &Info) const {
2291   auto &ArgInfo = Info.getArgInfo();
2292   const GCNUserSGPRUsageInfo &UserSGPRInfo = Info.getUserSGPRInfo();
2293 
2294   // TODO: Unify handling with private memory pointers.
2295   if (UserSGPRInfo.hasDispatchPtr())
2296     allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
2297 
2298   const Module *M = MF.getFunction().getParent();
2299   if (UserSGPRInfo.hasQueuePtr() &&
2300       AMDGPU::getCodeObjectVersion(*M) < AMDGPU::AMDHSA_COV5)
2301     allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
2302 
2303   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
2304   // constant offset from the kernarg segment.
2305   if (Info.hasImplicitArgPtr())
2306     allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
2307 
2308   if (UserSGPRInfo.hasDispatchID())
2309     allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2310 
2311   // flat_scratch_init is not applicable for non-kernel functions.
2312 
2313   if (Info.hasWorkGroupIDX())
2314     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2315 
2316   if (Info.hasWorkGroupIDY())
2317     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2318 
2319   if (Info.hasWorkGroupIDZ())
2320     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2321 
2322   if (Info.hasLDSKernelId())
2323     allocateSGPR32Input(CCInfo, ArgInfo.LDSKernelId);
2324 }
2325 
2326 // Allocate special inputs passed in user SGPRs.
2327 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2328                                             MachineFunction &MF,
2329                                             const SIRegisterInfo &TRI,
2330                                             SIMachineFunctionInfo &Info) const {
2331   const GCNUserSGPRUsageInfo &UserSGPRInfo = Info.getUserSGPRInfo();
2332   if (UserSGPRInfo.hasImplicitBufferPtr()) {
2333     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2334     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2335     CCInfo.AllocateReg(ImplicitBufferPtrReg);
2336   }
2337 
2338   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2339   if (UserSGPRInfo.hasPrivateSegmentBuffer()) {
2340     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2341     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2342     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2343   }
2344 
2345   if (UserSGPRInfo.hasDispatchPtr()) {
2346     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2347     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2348     CCInfo.AllocateReg(DispatchPtrReg);
2349   }
2350 
2351   const Module *M = MF.getFunction().getParent();
2352   if (UserSGPRInfo.hasQueuePtr() &&
2353       AMDGPU::getCodeObjectVersion(*M) < AMDGPU::AMDHSA_COV5) {
2354     Register QueuePtrReg = Info.addQueuePtr(TRI);
2355     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2356     CCInfo.AllocateReg(QueuePtrReg);
2357   }
2358 
2359   if (UserSGPRInfo.hasKernargSegmentPtr()) {
2360     MachineRegisterInfo &MRI = MF.getRegInfo();
2361     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2362     CCInfo.AllocateReg(InputPtrReg);
2363 
2364     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2365     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2366   }
2367 
2368   if (UserSGPRInfo.hasDispatchID()) {
2369     Register DispatchIDReg = Info.addDispatchID(TRI);
2370     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2371     CCInfo.AllocateReg(DispatchIDReg);
2372   }
2373 
2374   if (UserSGPRInfo.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2375     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2376     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2377     CCInfo.AllocateReg(FlatScratchInitReg);
2378   }
2379 
2380   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2381   // these from the dispatch pointer.
2382 }
2383 
2384 // Allocate pre-loaded kernel arguemtns. Arguments to be preloading must be
2385 // sequential starting from the first argument.
2386 void SITargetLowering::allocatePreloadKernArgSGPRs(
2387     CCState &CCInfo, SmallVectorImpl<CCValAssign> &ArgLocs,
2388     const SmallVectorImpl<ISD::InputArg> &Ins, MachineFunction &MF,
2389     const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2390   Function &F = MF.getFunction();
2391   unsigned LastExplicitArgOffset =
2392       MF.getSubtarget<GCNSubtarget>().getExplicitKernelArgOffset();
2393   GCNUserSGPRUsageInfo &SGPRInfo = Info.getUserSGPRInfo();
2394   bool InPreloadSequence = true;
2395   unsigned InIdx = 0;
2396   for (auto &Arg : F.args()) {
2397     if (!InPreloadSequence || !Arg.hasInRegAttr())
2398       break;
2399 
2400     int ArgIdx = Arg.getArgNo();
2401     // Don't preload non-original args or parts not in the current preload
2402     // sequence.
2403     if (InIdx < Ins.size() && (!Ins[InIdx].isOrigArg() ||
2404                                (int)Ins[InIdx].getOrigArgIndex() != ArgIdx))
2405       break;
2406 
2407     for (; InIdx < Ins.size() && Ins[InIdx].isOrigArg() &&
2408            (int)Ins[InIdx].getOrigArgIndex() == ArgIdx;
2409          InIdx++) {
2410       assert(ArgLocs[ArgIdx].isMemLoc());
2411       auto &ArgLoc = ArgLocs[InIdx];
2412       const Align KernelArgBaseAlign = Align(16);
2413       unsigned ArgOffset = ArgLoc.getLocMemOffset();
2414       Align Alignment = commonAlignment(KernelArgBaseAlign, ArgOffset);
2415       unsigned NumAllocSGPRs =
2416           alignTo(ArgLoc.getLocVT().getFixedSizeInBits(), 32) / 32;
2417 
2418       // Arg is preloaded into the previous SGPR.
2419       if (ArgLoc.getLocVT().getStoreSize() < 4 && Alignment < 4) {
2420         Info.getArgInfo().PreloadKernArgs[InIdx].Regs.push_back(
2421             Info.getArgInfo().PreloadKernArgs[InIdx - 1].Regs[0]);
2422         continue;
2423       }
2424 
2425       unsigned Padding = ArgOffset - LastExplicitArgOffset;
2426       unsigned PaddingSGPRs = alignTo(Padding, 4) / 4;
2427       // Check for free user SGPRs for preloading.
2428       if (PaddingSGPRs + NumAllocSGPRs + 1 /*Synthetic SGPRs*/ >
2429           SGPRInfo.getNumFreeUserSGPRs()) {
2430         InPreloadSequence = false;
2431         break;
2432       }
2433 
2434       // Preload this argument.
2435       const TargetRegisterClass *RC =
2436           TRI.getSGPRClassForBitWidth(NumAllocSGPRs * 32);
2437       SmallVectorImpl<MCRegister> *PreloadRegs =
2438           Info.addPreloadedKernArg(TRI, RC, NumAllocSGPRs, InIdx, PaddingSGPRs);
2439 
2440       if (PreloadRegs->size() > 1)
2441         RC = &AMDGPU::SGPR_32RegClass;
2442       for (auto &Reg : *PreloadRegs) {
2443         assert(Reg);
2444         MF.addLiveIn(Reg, RC);
2445         CCInfo.AllocateReg(Reg);
2446       }
2447 
2448       LastExplicitArgOffset = NumAllocSGPRs * 4 + ArgOffset;
2449     }
2450   }
2451 }
2452 
2453 void SITargetLowering::allocateLDSKernelId(CCState &CCInfo, MachineFunction &MF,
2454                                            const SIRegisterInfo &TRI,
2455                                            SIMachineFunctionInfo &Info) const {
2456   // Always allocate this last since it is a synthetic preload.
2457   if (Info.hasLDSKernelId()) {
2458     Register Reg = Info.addLDSKernelId();
2459     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2460     CCInfo.AllocateReg(Reg);
2461   }
2462 }
2463 
2464 // Allocate special input registers that are initialized per-wave.
2465 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2466                                            MachineFunction &MF,
2467                                            SIMachineFunctionInfo &Info,
2468                                            CallingConv::ID CallConv,
2469                                            bool IsShader) const {
2470   bool HasArchitectedSGPRs = Subtarget->hasArchitectedSGPRs();
2471   if (Subtarget->hasUserSGPRInit16Bug() && !IsShader) {
2472     // Note: user SGPRs are handled by the front-end for graphics shaders
2473     // Pad up the used user SGPRs with dead inputs.
2474 
2475     // TODO: NumRequiredSystemSGPRs computation should be adjusted appropriately
2476     // before enabling architected SGPRs for workgroup IDs.
2477     assert(!HasArchitectedSGPRs && "Unhandled feature for the subtarget");
2478 
2479     unsigned CurrentUserSGPRs = Info.getNumUserSGPRs();
2480     // Note we do not count the PrivateSegmentWaveByteOffset. We do not want to
2481     // rely on it to reach 16 since if we end up having no stack usage, it will
2482     // not really be added.
2483     unsigned NumRequiredSystemSGPRs = Info.hasWorkGroupIDX() +
2484                                       Info.hasWorkGroupIDY() +
2485                                       Info.hasWorkGroupIDZ() +
2486                                       Info.hasWorkGroupInfo();
2487     for (unsigned i = NumRequiredSystemSGPRs + CurrentUserSGPRs; i < 16; ++i) {
2488       Register Reg = Info.addReservedUserSGPR();
2489       MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2490       CCInfo.AllocateReg(Reg);
2491     }
2492   }
2493 
2494   if (Info.hasWorkGroupIDX()) {
2495     Register Reg = Info.addWorkGroupIDX(HasArchitectedSGPRs);
2496     if (!HasArchitectedSGPRs)
2497       MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2498 
2499     CCInfo.AllocateReg(Reg);
2500   }
2501 
2502   if (Info.hasWorkGroupIDY()) {
2503     Register Reg = Info.addWorkGroupIDY(HasArchitectedSGPRs);
2504     if (!HasArchitectedSGPRs)
2505       MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2506 
2507     CCInfo.AllocateReg(Reg);
2508   }
2509 
2510   if (Info.hasWorkGroupIDZ()) {
2511     Register Reg = Info.addWorkGroupIDZ(HasArchitectedSGPRs);
2512     if (!HasArchitectedSGPRs)
2513       MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2514 
2515     CCInfo.AllocateReg(Reg);
2516   }
2517 
2518   if (Info.hasWorkGroupInfo()) {
2519     Register Reg = Info.addWorkGroupInfo();
2520     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2521     CCInfo.AllocateReg(Reg);
2522   }
2523 
2524   if (Info.hasPrivateSegmentWaveByteOffset()) {
2525     // Scratch wave offset passed in system SGPR.
2526     unsigned PrivateSegmentWaveByteOffsetReg;
2527 
2528     if (IsShader) {
2529       PrivateSegmentWaveByteOffsetReg =
2530         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2531 
2532       // This is true if the scratch wave byte offset doesn't have a fixed
2533       // location.
2534       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2535         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2536         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2537       }
2538     } else
2539       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2540 
2541     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2542     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2543   }
2544 
2545   assert(!Subtarget->hasUserSGPRInit16Bug() || IsShader ||
2546          Info.getNumPreloadedSGPRs() >= 16);
2547 }
2548 
2549 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2550                                      MachineFunction &MF,
2551                                      const SIRegisterInfo &TRI,
2552                                      SIMachineFunctionInfo &Info) {
2553   // Now that we've figured out where the scratch register inputs are, see if
2554   // should reserve the arguments and use them directly.
2555   MachineFrameInfo &MFI = MF.getFrameInfo();
2556   bool HasStackObjects = MFI.hasStackObjects();
2557   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2558 
2559   // Record that we know we have non-spill stack objects so we don't need to
2560   // check all stack objects later.
2561   if (HasStackObjects)
2562     Info.setHasNonSpillStackObjects(true);
2563 
2564   // Everything live out of a block is spilled with fast regalloc, so it's
2565   // almost certain that spilling will be required.
2566   if (TM.getOptLevel() == CodeGenOptLevel::None)
2567     HasStackObjects = true;
2568 
2569   // For now assume stack access is needed in any callee functions, so we need
2570   // the scratch registers to pass in.
2571   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2572 
2573   if (!ST.enableFlatScratch()) {
2574     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2575       // If we have stack objects, we unquestionably need the private buffer
2576       // resource. For the Code Object V2 ABI, this will be the first 4 user
2577       // SGPR inputs. We can reserve those and use them directly.
2578 
2579       Register PrivateSegmentBufferReg =
2580           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2581       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2582     } else {
2583       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2584       // We tentatively reserve the last registers (skipping the last registers
2585       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2586       // we'll replace these with the ones immediately after those which were
2587       // really allocated. In the prologue copies will be inserted from the
2588       // argument to these reserved registers.
2589 
2590       // Without HSA, relocations are used for the scratch pointer and the
2591       // buffer resource setup is always inserted in the prologue. Scratch wave
2592       // offset is still in an input SGPR.
2593       Info.setScratchRSrcReg(ReservedBufferReg);
2594     }
2595   }
2596 
2597   MachineRegisterInfo &MRI = MF.getRegInfo();
2598 
2599   // For entry functions we have to set up the stack pointer if we use it,
2600   // whereas non-entry functions get this "for free". This means there is no
2601   // intrinsic advantage to using S32 over S34 in cases where we do not have
2602   // calls but do need a frame pointer (i.e. if we are requested to have one
2603   // because frame pointer elimination is disabled). To keep things simple we
2604   // only ever use S32 as the call ABI stack pointer, and so using it does not
2605   // imply we need a separate frame pointer.
2606   //
2607   // Try to use s32 as the SP, but move it if it would interfere with input
2608   // arguments. This won't work with calls though.
2609   //
2610   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2611   // registers.
2612   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2613     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2614   } else {
2615     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2616 
2617     if (MFI.hasCalls())
2618       report_fatal_error("call in graphics shader with too many input SGPRs");
2619 
2620     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2621       if (!MRI.isLiveIn(Reg)) {
2622         Info.setStackPtrOffsetReg(Reg);
2623         break;
2624       }
2625     }
2626 
2627     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2628       report_fatal_error("failed to find register for SP");
2629   }
2630 
2631   // hasFP should be accurate for entry functions even before the frame is
2632   // finalized, because it does not rely on the known stack size, only
2633   // properties like whether variable sized objects are present.
2634   if (ST.getFrameLowering()->hasFP(MF)) {
2635     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2636   }
2637 }
2638 
2639 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2640   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2641   return !Info->isEntryFunction();
2642 }
2643 
2644 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2645 
2646 }
2647 
2648 void SITargetLowering::insertCopiesSplitCSR(
2649   MachineBasicBlock *Entry,
2650   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2651   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2652 
2653   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2654   if (!IStart)
2655     return;
2656 
2657   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2658   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2659   MachineBasicBlock::iterator MBBI = Entry->begin();
2660   for (const MCPhysReg *I = IStart; *I; ++I) {
2661     const TargetRegisterClass *RC = nullptr;
2662     if (AMDGPU::SReg_64RegClass.contains(*I))
2663       RC = &AMDGPU::SGPR_64RegClass;
2664     else if (AMDGPU::SReg_32RegClass.contains(*I))
2665       RC = &AMDGPU::SGPR_32RegClass;
2666     else
2667       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2668 
2669     Register NewVR = MRI->createVirtualRegister(RC);
2670     // Create copy from CSR to a virtual register.
2671     Entry->addLiveIn(*I);
2672     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2673       .addReg(*I);
2674 
2675     // Insert the copy-back instructions right before the terminator.
2676     for (auto *Exit : Exits)
2677       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2678               TII->get(TargetOpcode::COPY), *I)
2679         .addReg(NewVR);
2680   }
2681 }
2682 
2683 SDValue SITargetLowering::LowerFormalArguments(
2684     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2685     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2686     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2687   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2688 
2689   MachineFunction &MF = DAG.getMachineFunction();
2690   const Function &Fn = MF.getFunction();
2691   FunctionType *FType = MF.getFunction().getFunctionType();
2692   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2693 
2694   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2695     DiagnosticInfoUnsupported NoGraphicsHSA(
2696         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2697     DAG.getContext()->diagnose(NoGraphicsHSA);
2698     return DAG.getEntryNode();
2699   }
2700 
2701   SmallVector<ISD::InputArg, 16> Splits;
2702   SmallVector<CCValAssign, 16> ArgLocs;
2703   BitVector Skipped(Ins.size());
2704   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2705                  *DAG.getContext());
2706 
2707   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2708   bool IsKernel = AMDGPU::isKernel(CallConv);
2709   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2710 
2711   if (IsGraphics) {
2712     const GCNUserSGPRUsageInfo &UserSGPRInfo = Info->getUserSGPRInfo();
2713     assert(!UserSGPRInfo.hasDispatchPtr() &&
2714            !UserSGPRInfo.hasKernargSegmentPtr() && !Info->hasWorkGroupInfo() &&
2715            !Info->hasLDSKernelId() && !Info->hasWorkItemIDX() &&
2716            !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ());
2717     (void)UserSGPRInfo;
2718     if (!Subtarget->enableFlatScratch())
2719       assert(!UserSGPRInfo.hasFlatScratchInit());
2720     if (CallConv != CallingConv::AMDGPU_CS || !Subtarget->hasArchitectedSGPRs())
2721       assert(!Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2722              !Info->hasWorkGroupIDZ());
2723   }
2724 
2725   if (CallConv == CallingConv::AMDGPU_PS) {
2726     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2727 
2728     // At least one interpolation mode must be enabled or else the GPU will
2729     // hang.
2730     //
2731     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2732     // set PSInputAddr, the user wants to enable some bits after the compilation
2733     // based on run-time states. Since we can't know what the final PSInputEna
2734     // will look like, so we shouldn't do anything here and the user should take
2735     // responsibility for the correct programming.
2736     //
2737     // Otherwise, the following restrictions apply:
2738     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2739     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2740     //   enabled too.
2741     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2742         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2743       CCInfo.AllocateReg(AMDGPU::VGPR0);
2744       CCInfo.AllocateReg(AMDGPU::VGPR1);
2745       Info->markPSInputAllocated(0);
2746       Info->markPSInputEnabled(0);
2747     }
2748     if (Subtarget->isAmdPalOS()) {
2749       // For isAmdPalOS, the user does not enable some bits after compilation
2750       // based on run-time states; the register values being generated here are
2751       // the final ones set in hardware. Therefore we need to apply the
2752       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2753       // a bit is set in PSInputAddr but not PSInputEnable is where the
2754       // frontend set up an input arg for a particular interpolation mode, but
2755       // nothing uses that input arg. Really we should have an earlier pass
2756       // that removes such an arg.)
2757       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2758       if ((PsInputBits & 0x7F) == 0 ||
2759           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2760         Info->markPSInputEnabled(llvm::countr_zero(Info->getPSInputAddr()));
2761     }
2762   } else if (IsKernel) {
2763     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2764   } else {
2765     Splits.append(Ins.begin(), Ins.end());
2766   }
2767 
2768   if (IsKernel)
2769     analyzeFormalArgumentsCompute(CCInfo, Ins);
2770 
2771   if (IsEntryFunc) {
2772     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2773     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2774     if (IsKernel && Subtarget->hasKernargPreload() &&
2775         !Subtarget->needsKernargPreloadBackwardsCompatibility())
2776       allocatePreloadKernArgSGPRs(CCInfo, ArgLocs, Ins, MF, *TRI, *Info);
2777 
2778     allocateLDSKernelId(CCInfo, MF, *TRI, *Info);
2779   } else if (!IsGraphics) {
2780     // For the fixed ABI, pass workitem IDs in the last argument register.
2781     allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2782   }
2783 
2784   if (!IsKernel) {
2785     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2786     if (!IsGraphics && !Subtarget->enableFlatScratch()) {
2787       CCInfo.AllocateRegBlock(ArrayRef<MCPhysReg>{AMDGPU::SGPR0, AMDGPU::SGPR1,
2788                                                   AMDGPU::SGPR2, AMDGPU::SGPR3},
2789                               4);
2790     }
2791     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2792   }
2793 
2794   SmallVector<SDValue, 16> Chains;
2795 
2796   // FIXME: This is the minimum kernel argument alignment. We should improve
2797   // this to the maximum alignment of the arguments.
2798   //
2799   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2800   // kern arg offset.
2801   const Align KernelArgBaseAlign = Align(16);
2802 
2803   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2804     const ISD::InputArg &Arg = Ins[i];
2805     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2806       InVals.push_back(DAG.getUNDEF(Arg.VT));
2807       continue;
2808     }
2809 
2810     CCValAssign &VA = ArgLocs[ArgIdx++];
2811     MVT VT = VA.getLocVT();
2812 
2813     if (IsEntryFunc && VA.isMemLoc()) {
2814       VT = Ins[i].VT;
2815       EVT MemVT = VA.getLocVT();
2816 
2817       const uint64_t Offset = VA.getLocMemOffset();
2818       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2819 
2820       if (Arg.Flags.isByRef()) {
2821         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2822 
2823         const GCNTargetMachine &TM =
2824             static_cast<const GCNTargetMachine &>(getTargetMachine());
2825         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2826                                     Arg.Flags.getPointerAddrSpace())) {
2827           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2828                                      Arg.Flags.getPointerAddrSpace());
2829         }
2830 
2831         InVals.push_back(Ptr);
2832         continue;
2833       }
2834 
2835       SDValue NewArg;
2836       if (Arg.isOrigArg() && Info->getArgInfo().PreloadKernArgs.count(i)) {
2837         if (MemVT.getStoreSize() < 4 && Alignment < 4) {
2838           // In this case the argument is packed into the previous preload SGPR.
2839           int64_t AlignDownOffset = alignDown(Offset, 4);
2840           int64_t OffsetDiff = Offset - AlignDownOffset;
2841           EVT IntVT = MemVT.changeTypeToInteger();
2842 
2843           const SIMachineFunctionInfo *Info =
2844               MF.getInfo<SIMachineFunctionInfo>();
2845           MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
2846           Register Reg =
2847               Info->getArgInfo().PreloadKernArgs.find(i)->getSecond().Regs[0];
2848 
2849           assert(Reg);
2850           Register VReg = MRI.getLiveInVirtReg(Reg);
2851           SDValue Copy = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i32);
2852 
2853           SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, DL, MVT::i32);
2854           SDValue Extract = DAG.getNode(ISD::SRL, DL, MVT::i32, Copy, ShiftAmt);
2855 
2856           SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, Extract);
2857           ArgVal = DAG.getNode(ISD::BITCAST, DL, MemVT, ArgVal);
2858           NewArg = convertArgType(DAG, VT, MemVT, DL, ArgVal,
2859                                   Ins[i].Flags.isSExt(), &Ins[i]);
2860 
2861           NewArg = DAG.getMergeValues({NewArg, Copy.getValue(1)}, DL);
2862         } else {
2863           const SIMachineFunctionInfo *Info =
2864               MF.getInfo<SIMachineFunctionInfo>();
2865           MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
2866           const SmallVectorImpl<MCRegister> &PreloadRegs =
2867               Info->getArgInfo().PreloadKernArgs.find(i)->getSecond().Regs;
2868 
2869           SDValue Copy;
2870           if (PreloadRegs.size() == 1) {
2871             Register VReg = MRI.getLiveInVirtReg(PreloadRegs[0]);
2872             const TargetRegisterClass *RC = MRI.getRegClass(VReg);
2873             NewArg = DAG.getCopyFromReg(
2874                 Chain, DL, VReg,
2875                 EVT::getIntegerVT(*DAG.getContext(),
2876                                   TRI->getRegSizeInBits(*RC)));
2877 
2878           } else {
2879             // If the kernarg alignment does not match the alignment of the SGPR
2880             // tuple RC that can accommodate this argument, it will be built up
2881             // via copies from from the individual SGPRs that the argument was
2882             // preloaded to.
2883             SmallVector<SDValue, 4> Elts;
2884             for (auto Reg : PreloadRegs) {
2885               Register VReg = MRI.getLiveInVirtReg(Reg);
2886               Copy = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i32);
2887               Elts.push_back(Copy);
2888             }
2889             NewArg =
2890                 DAG.getBuildVector(EVT::getVectorVT(*DAG.getContext(), MVT::i32,
2891                                                     PreloadRegs.size()),
2892                                    DL, Elts);
2893           }
2894 
2895           SDValue CMemVT;
2896           if (VT.isScalarInteger() && VT.bitsLT(NewArg.getSimpleValueType()))
2897             CMemVT = DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewArg);
2898           else
2899             CMemVT = DAG.getBitcast(MemVT, NewArg);
2900           NewArg = convertArgType(DAG, VT, MemVT, DL, CMemVT,
2901                                   Ins[i].Flags.isSExt(), &Ins[i]);
2902           NewArg = DAG.getMergeValues({NewArg, Chain}, DL);
2903         }
2904       } else {
2905         NewArg =
2906             lowerKernargMemParameter(DAG, VT, MemVT, DL, Chain, Offset,
2907                                      Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2908       }
2909       Chains.push_back(NewArg.getValue(1));
2910 
2911       auto *ParamTy =
2912         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2913       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2914           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2915                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2916         // On SI local pointers are just offsets into LDS, so they are always
2917         // less than 16-bits.  On CI and newer they could potentially be
2918         // real pointers, so we can't guarantee their size.
2919         NewArg = DAG.getNode(ISD::AssertZext, DL, NewArg.getValueType(), NewArg,
2920                              DAG.getValueType(MVT::i16));
2921       }
2922 
2923       InVals.push_back(NewArg);
2924       continue;
2925     } else if (!IsEntryFunc && VA.isMemLoc()) {
2926       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2927       InVals.push_back(Val);
2928       if (!Arg.Flags.isByVal())
2929         Chains.push_back(Val.getValue(1));
2930       continue;
2931     }
2932 
2933     assert(VA.isRegLoc() && "Parameter must be in a register!");
2934 
2935     Register Reg = VA.getLocReg();
2936     const TargetRegisterClass *RC = nullptr;
2937     if (AMDGPU::VGPR_32RegClass.contains(Reg))
2938       RC = &AMDGPU::VGPR_32RegClass;
2939     else if (AMDGPU::SGPR_32RegClass.contains(Reg))
2940       RC = &AMDGPU::SGPR_32RegClass;
2941     else
2942       llvm_unreachable("Unexpected register class in LowerFormalArguments!");
2943     EVT ValVT = VA.getValVT();
2944 
2945     Reg = MF.addLiveIn(Reg, RC);
2946     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2947 
2948     if (Arg.Flags.isSRet()) {
2949       // The return object should be reasonably addressable.
2950 
2951       // FIXME: This helps when the return is a real sret. If it is a
2952       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2953       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2954       unsigned NumBits
2955         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2956       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2957         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2958     }
2959 
2960     // If this is an 8 or 16-bit value, it is really passed promoted
2961     // to 32 bits. Insert an assert[sz]ext to capture this, then
2962     // truncate to the right size.
2963     switch (VA.getLocInfo()) {
2964     case CCValAssign::Full:
2965       break;
2966     case CCValAssign::BCvt:
2967       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2968       break;
2969     case CCValAssign::SExt:
2970       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2971                         DAG.getValueType(ValVT));
2972       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2973       break;
2974     case CCValAssign::ZExt:
2975       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2976                         DAG.getValueType(ValVT));
2977       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2978       break;
2979     case CCValAssign::AExt:
2980       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2981       break;
2982     default:
2983       llvm_unreachable("Unknown loc info!");
2984     }
2985 
2986     InVals.push_back(Val);
2987   }
2988 
2989   // Start adding system SGPRs.
2990   if (IsEntryFunc) {
2991     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2992   } else {
2993     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2994     if (!IsGraphics)
2995       allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2996   }
2997 
2998   auto &ArgUsageInfo =
2999     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
3000   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
3001 
3002   unsigned StackArgSize = CCInfo.getStackSize();
3003   Info->setBytesInStackArgArea(StackArgSize);
3004 
3005   return Chains.empty() ? Chain :
3006     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
3007 }
3008 
3009 // TODO: If return values can't fit in registers, we should return as many as
3010 // possible in registers before passing on stack.
3011 bool SITargetLowering::CanLowerReturn(
3012   CallingConv::ID CallConv,
3013   MachineFunction &MF, bool IsVarArg,
3014   const SmallVectorImpl<ISD::OutputArg> &Outs,
3015   LLVMContext &Context) const {
3016   // Replacing returns with sret/stack usage doesn't make sense for shaders.
3017   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
3018   // for shaders. Vector types should be explicitly handled by CC.
3019   if (AMDGPU::isEntryFunctionCC(CallConv))
3020     return true;
3021 
3022   SmallVector<CCValAssign, 16> RVLocs;
3023   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3024   if (!CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)))
3025     return false;
3026 
3027   // We must use the stack if return would require unavailable registers.
3028   unsigned MaxNumVGPRs = Subtarget->getMaxNumVGPRs(MF);
3029   unsigned TotalNumVGPRs = AMDGPU::VGPR_32RegClass.getNumRegs();
3030   for (unsigned i = MaxNumVGPRs; i < TotalNumVGPRs; ++i)
3031     if (CCInfo.isAllocated(AMDGPU::VGPR_32RegClass.getRegister(i)))
3032       return false;
3033 
3034   return true;
3035 }
3036 
3037 SDValue
3038 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3039                               bool isVarArg,
3040                               const SmallVectorImpl<ISD::OutputArg> &Outs,
3041                               const SmallVectorImpl<SDValue> &OutVals,
3042                               const SDLoc &DL, SelectionDAG &DAG) const {
3043   MachineFunction &MF = DAG.getMachineFunction();
3044   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3045 
3046   if (AMDGPU::isKernel(CallConv)) {
3047     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
3048                                              OutVals, DL, DAG);
3049   }
3050 
3051   bool IsShader = AMDGPU::isShader(CallConv);
3052 
3053   Info->setIfReturnsVoid(Outs.empty());
3054   bool IsWaveEnd = Info->returnsVoid() && IsShader;
3055 
3056   // CCValAssign - represent the assignment of the return value to a location.
3057   SmallVector<CCValAssign, 48> RVLocs;
3058   SmallVector<ISD::OutputArg, 48> Splits;
3059 
3060   // CCState - Info about the registers and stack slots.
3061   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3062                  *DAG.getContext());
3063 
3064   // Analyze outgoing return values.
3065   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
3066 
3067   SDValue Glue;
3068   SmallVector<SDValue, 48> RetOps;
3069   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
3070 
3071   // Copy the result values into the output registers.
3072   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
3073        ++I, ++RealRVLocIdx) {
3074     CCValAssign &VA = RVLocs[I];
3075     assert(VA.isRegLoc() && "Can only return in registers!");
3076     // TODO: Partially return in registers if return values don't fit.
3077     SDValue Arg = OutVals[RealRVLocIdx];
3078 
3079     // Copied from other backends.
3080     switch (VA.getLocInfo()) {
3081     case CCValAssign::Full:
3082       break;
3083     case CCValAssign::BCvt:
3084       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3085       break;
3086     case CCValAssign::SExt:
3087       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3088       break;
3089     case CCValAssign::ZExt:
3090       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3091       break;
3092     case CCValAssign::AExt:
3093       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3094       break;
3095     default:
3096       llvm_unreachable("Unknown loc info!");
3097     }
3098 
3099     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Glue);
3100     Glue = Chain.getValue(1);
3101     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3102   }
3103 
3104   // FIXME: Does sret work properly?
3105   if (!Info->isEntryFunction()) {
3106     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
3107     const MCPhysReg *I =
3108       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3109     if (I) {
3110       for (; *I; ++I) {
3111         if (AMDGPU::SReg_64RegClass.contains(*I))
3112           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3113         else if (AMDGPU::SReg_32RegClass.contains(*I))
3114           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
3115         else
3116           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3117       }
3118     }
3119   }
3120 
3121   // Update chain and glue.
3122   RetOps[0] = Chain;
3123   if (Glue.getNode())
3124     RetOps.push_back(Glue);
3125 
3126   unsigned Opc = AMDGPUISD::ENDPGM;
3127   if (!IsWaveEnd)
3128     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_GLUE;
3129   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
3130 }
3131 
3132 SDValue SITargetLowering::LowerCallResult(
3133     SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool IsVarArg,
3134     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3135     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
3136     SDValue ThisVal) const {
3137   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
3138 
3139   // Assign locations to each value returned by this call.
3140   SmallVector<CCValAssign, 16> RVLocs;
3141   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
3142                  *DAG.getContext());
3143   CCInfo.AnalyzeCallResult(Ins, RetCC);
3144 
3145   // Copy all of the result registers out of their specified physreg.
3146   for (unsigned i = 0; i != RVLocs.size(); ++i) {
3147     CCValAssign VA = RVLocs[i];
3148     SDValue Val;
3149 
3150     if (VA.isRegLoc()) {
3151       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InGlue);
3152       Chain = Val.getValue(1);
3153       InGlue = Val.getValue(2);
3154     } else if (VA.isMemLoc()) {
3155       report_fatal_error("TODO: return values in memory");
3156     } else
3157       llvm_unreachable("unknown argument location type");
3158 
3159     switch (VA.getLocInfo()) {
3160     case CCValAssign::Full:
3161       break;
3162     case CCValAssign::BCvt:
3163       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3164       break;
3165     case CCValAssign::ZExt:
3166       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
3167                         DAG.getValueType(VA.getValVT()));
3168       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3169       break;
3170     case CCValAssign::SExt:
3171       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
3172                         DAG.getValueType(VA.getValVT()));
3173       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3174       break;
3175     case CCValAssign::AExt:
3176       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3177       break;
3178     default:
3179       llvm_unreachable("Unknown loc info!");
3180     }
3181 
3182     InVals.push_back(Val);
3183   }
3184 
3185   return Chain;
3186 }
3187 
3188 // Add code to pass special inputs required depending on used features separate
3189 // from the explicit user arguments present in the IR.
3190 void SITargetLowering::passSpecialInputs(
3191     CallLoweringInfo &CLI,
3192     CCState &CCInfo,
3193     const SIMachineFunctionInfo &Info,
3194     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
3195     SmallVectorImpl<SDValue> &MemOpChains,
3196     SDValue Chain) const {
3197   // If we don't have a call site, this was a call inserted by
3198   // legalization. These can never use special inputs.
3199   if (!CLI.CB)
3200     return;
3201 
3202   SelectionDAG &DAG = CLI.DAG;
3203   const SDLoc &DL = CLI.DL;
3204   const Function &F = DAG.getMachineFunction().getFunction();
3205 
3206   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
3207   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
3208 
3209   const AMDGPUFunctionArgInfo *CalleeArgInfo
3210     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
3211   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
3212     auto &ArgUsageInfo =
3213       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
3214     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
3215   }
3216 
3217   // TODO: Unify with private memory register handling. This is complicated by
3218   // the fact that at least in kernels, the input argument is not necessarily
3219   // in the same location as the input.
3220   static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
3221                              StringLiteral> ImplicitAttrs[] = {
3222     {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"},
3223     {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" },
3224     {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"},
3225     {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"},
3226     {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"},
3227     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"},
3228     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"},
3229     {AMDGPUFunctionArgInfo::LDS_KERNEL_ID,"amdgpu-no-lds-kernel-id"},
3230   };
3231 
3232   for (auto Attr : ImplicitAttrs) {
3233     const ArgDescriptor *OutgoingArg;
3234     const TargetRegisterClass *ArgRC;
3235     LLT ArgTy;
3236 
3237     AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first;
3238 
3239     // If the callee does not use the attribute value, skip copying the value.
3240     if (CLI.CB->hasFnAttr(Attr.second))
3241       continue;
3242 
3243     std::tie(OutgoingArg, ArgRC, ArgTy) =
3244         CalleeArgInfo->getPreloadedValue(InputID);
3245     if (!OutgoingArg)
3246       continue;
3247 
3248     const ArgDescriptor *IncomingArg;
3249     const TargetRegisterClass *IncomingArgRC;
3250     LLT Ty;
3251     std::tie(IncomingArg, IncomingArgRC, Ty) =
3252         CallerArgInfo.getPreloadedValue(InputID);
3253     assert(IncomingArgRC == ArgRC);
3254 
3255     // All special arguments are ints for now.
3256     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
3257     SDValue InputReg;
3258 
3259     if (IncomingArg) {
3260       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
3261     } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
3262       // The implicit arg ptr is special because it doesn't have a corresponding
3263       // input for kernels, and is computed from the kernarg segment pointer.
3264       InputReg = getImplicitArgPtr(DAG, DL);
3265     } else if (InputID == AMDGPUFunctionArgInfo::LDS_KERNEL_ID) {
3266       std::optional<uint32_t> Id =
3267           AMDGPUMachineFunction::getLDSKernelIdMetadata(F);
3268       if (Id.has_value()) {
3269         InputReg = DAG.getConstant(*Id, DL, ArgVT);
3270       } else {
3271         InputReg = DAG.getUNDEF(ArgVT);
3272       }
3273     } else {
3274       // We may have proven the input wasn't needed, although the ABI is
3275       // requiring it. We just need to allocate the register appropriately.
3276       InputReg = DAG.getUNDEF(ArgVT);
3277     }
3278 
3279     if (OutgoingArg->isRegister()) {
3280       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
3281       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
3282         report_fatal_error("failed to allocate implicit input argument");
3283     } else {
3284       unsigned SpecialArgOffset =
3285           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
3286       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
3287                                               SpecialArgOffset);
3288       MemOpChains.push_back(ArgStore);
3289     }
3290   }
3291 
3292   // Pack workitem IDs into a single register or pass it as is if already
3293   // packed.
3294   const ArgDescriptor *OutgoingArg;
3295   const TargetRegisterClass *ArgRC;
3296   LLT Ty;
3297 
3298   std::tie(OutgoingArg, ArgRC, Ty) =
3299       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
3300   if (!OutgoingArg)
3301     std::tie(OutgoingArg, ArgRC, Ty) =
3302         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
3303   if (!OutgoingArg)
3304     std::tie(OutgoingArg, ArgRC, Ty) =
3305         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
3306   if (!OutgoingArg)
3307     return;
3308 
3309   const ArgDescriptor *IncomingArgX = std::get<0>(
3310       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
3311   const ArgDescriptor *IncomingArgY = std::get<0>(
3312       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
3313   const ArgDescriptor *IncomingArgZ = std::get<0>(
3314       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
3315 
3316   SDValue InputReg;
3317   SDLoc SL;
3318 
3319   const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
3320   const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
3321   const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
3322 
3323   // If incoming ids are not packed we need to pack them.
3324   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
3325       NeedWorkItemIDX) {
3326     if (Subtarget->getMaxWorkitemID(F, 0) != 0) {
3327       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
3328     } else {
3329       InputReg = DAG.getConstant(0, DL, MVT::i32);
3330     }
3331   }
3332 
3333   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
3334       NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) {
3335     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
3336     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
3337                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
3338     InputReg = InputReg.getNode() ?
3339                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
3340   }
3341 
3342   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
3343       NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) {
3344     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
3345     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
3346                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
3347     InputReg = InputReg.getNode() ?
3348                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
3349   }
3350 
3351   if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
3352     if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) {
3353       // We're in a situation where the outgoing function requires the workitem
3354       // ID, but the calling function does not have it (e.g a graphics function
3355       // calling a C calling convention function). This is illegal, but we need
3356       // to produce something.
3357       InputReg = DAG.getUNDEF(MVT::i32);
3358     } else {
3359       // Workitem ids are already packed, any of present incoming arguments
3360       // will carry all required fields.
3361       ArgDescriptor IncomingArg = ArgDescriptor::createArg(
3362         IncomingArgX ? *IncomingArgX :
3363         IncomingArgY ? *IncomingArgY :
3364         *IncomingArgZ, ~0u);
3365       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
3366     }
3367   }
3368 
3369   if (OutgoingArg->isRegister()) {
3370     if (InputReg)
3371       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
3372 
3373     CCInfo.AllocateReg(OutgoingArg->getRegister());
3374   } else {
3375     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
3376     if (InputReg) {
3377       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
3378                                               SpecialArgOffset);
3379       MemOpChains.push_back(ArgStore);
3380     }
3381   }
3382 }
3383 
3384 static bool canGuaranteeTCO(CallingConv::ID CC) {
3385   return CC == CallingConv::Fast;
3386 }
3387 
3388 /// Return true if we might ever do TCO for calls with this calling convention.
3389 static bool mayTailCallThisCC(CallingConv::ID CC) {
3390   switch (CC) {
3391   case CallingConv::C:
3392   case CallingConv::AMDGPU_Gfx:
3393     return true;
3394   default:
3395     return canGuaranteeTCO(CC);
3396   }
3397 }
3398 
3399 bool SITargetLowering::isEligibleForTailCallOptimization(
3400     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
3401     const SmallVectorImpl<ISD::OutputArg> &Outs,
3402     const SmallVectorImpl<SDValue> &OutVals,
3403     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3404   if (AMDGPU::isChainCC(CalleeCC))
3405     return true;
3406 
3407   if (!mayTailCallThisCC(CalleeCC))
3408     return false;
3409 
3410   // For a divergent call target, we need to do a waterfall loop over the
3411   // possible callees which precludes us from using a simple jump.
3412   if (Callee->isDivergent())
3413     return false;
3414 
3415   MachineFunction &MF = DAG.getMachineFunction();
3416   const Function &CallerF = MF.getFunction();
3417   CallingConv::ID CallerCC = CallerF.getCallingConv();
3418   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3419   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3420 
3421   // Kernels aren't callable, and don't have a live in return address so it
3422   // doesn't make sense to do a tail call with entry functions.
3423   if (!CallerPreserved)
3424     return false;
3425 
3426   bool CCMatch = CallerCC == CalleeCC;
3427 
3428   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3429     if (canGuaranteeTCO(CalleeCC) && CCMatch)
3430       return true;
3431     return false;
3432   }
3433 
3434   // TODO: Can we handle var args?
3435   if (IsVarArg)
3436     return false;
3437 
3438   for (const Argument &Arg : CallerF.args()) {
3439     if (Arg.hasByValAttr())
3440       return false;
3441   }
3442 
3443   LLVMContext &Ctx = *DAG.getContext();
3444 
3445   // Check that the call results are passed in the same way.
3446   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
3447                                   CCAssignFnForCall(CalleeCC, IsVarArg),
3448                                   CCAssignFnForCall(CallerCC, IsVarArg)))
3449     return false;
3450 
3451   // The callee has to preserve all registers the caller needs to preserve.
3452   if (!CCMatch) {
3453     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3454     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3455       return false;
3456   }
3457 
3458   // Nothing more to check if the callee is taking no arguments.
3459   if (Outs.empty())
3460     return true;
3461 
3462   SmallVector<CCValAssign, 16> ArgLocs;
3463   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
3464 
3465   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
3466 
3467   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
3468   // If the stack arguments for this call do not fit into our own save area then
3469   // the call cannot be made tail.
3470   // TODO: Is this really necessary?
3471   if (CCInfo.getStackSize() > FuncInfo->getBytesInStackArgArea())
3472     return false;
3473 
3474   const MachineRegisterInfo &MRI = MF.getRegInfo();
3475   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
3476 }
3477 
3478 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3479   if (!CI->isTailCall())
3480     return false;
3481 
3482   const Function *ParentFn = CI->getParent()->getParent();
3483   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
3484     return false;
3485   return true;
3486 }
3487 
3488 // The wave scratch offset register is used as the global base pointer.
3489 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
3490                                     SmallVectorImpl<SDValue> &InVals) const {
3491   CallingConv::ID CallConv = CLI.CallConv;
3492   bool IsChainCallConv = AMDGPU::isChainCC(CallConv);
3493 
3494   SelectionDAG &DAG = CLI.DAG;
3495 
3496   TargetLowering::ArgListEntry RequestedExec;
3497   if (IsChainCallConv) {
3498     // The last argument should be the value that we need to put in EXEC.
3499     // Pop it out of CLI.Outs and CLI.OutVals before we do any processing so we
3500     // don't treat it like the rest of the arguments.
3501     RequestedExec = CLI.Args.back();
3502     assert(RequestedExec.Node && "No node for EXEC");
3503 
3504     if (!RequestedExec.Ty->isIntegerTy(Subtarget->getWavefrontSize()))
3505       return lowerUnhandledCall(CLI, InVals, "Invalid value for EXEC");
3506 
3507     assert(CLI.Outs.back().OrigArgIndex == 2 && "Unexpected last arg");
3508     CLI.Outs.pop_back();
3509     CLI.OutVals.pop_back();
3510 
3511     if (RequestedExec.Ty->isIntegerTy(64)) {
3512       assert(CLI.Outs.back().OrigArgIndex == 2 && "Exec wasn't split up");
3513       CLI.Outs.pop_back();
3514       CLI.OutVals.pop_back();
3515     }
3516 
3517     assert(CLI.Outs.back().OrigArgIndex != 2 &&
3518            "Haven't popped all the pieces of the EXEC mask");
3519   }
3520 
3521   const SDLoc &DL = CLI.DL;
3522   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3523   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3524   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3525   SDValue Chain = CLI.Chain;
3526   SDValue Callee = CLI.Callee;
3527   bool &IsTailCall = CLI.IsTailCall;
3528   bool IsVarArg = CLI.IsVarArg;
3529   bool IsSibCall = false;
3530   bool IsThisReturn = false;
3531   MachineFunction &MF = DAG.getMachineFunction();
3532 
3533   if (Callee.isUndef() || isNullConstant(Callee)) {
3534     if (!CLI.IsTailCall) {
3535       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
3536         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
3537     }
3538 
3539     return Chain;
3540   }
3541 
3542   if (IsVarArg) {
3543     return lowerUnhandledCall(CLI, InVals,
3544                               "unsupported call to variadic function ");
3545   }
3546 
3547   if (!CLI.CB)
3548     report_fatal_error("unsupported libcall legalization");
3549 
3550   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
3551     return lowerUnhandledCall(CLI, InVals,
3552                               "unsupported required tail call to function ");
3553   }
3554 
3555   if (IsTailCall) {
3556     IsTailCall = isEligibleForTailCallOptimization(
3557       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3558     if (!IsTailCall &&
3559         ((CLI.CB && CLI.CB->isMustTailCall()) || IsChainCallConv)) {
3560       report_fatal_error("failed to perform tail call elimination on a call "
3561                          "site marked musttail or on llvm.amdgcn.cs.chain");
3562     }
3563 
3564     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3565 
3566     // A sibling call is one where we're under the usual C ABI and not planning
3567     // to change that but can still do a tail call:
3568     if (!TailCallOpt && IsTailCall)
3569       IsSibCall = true;
3570 
3571     if (IsTailCall)
3572       ++NumTailCalls;
3573   }
3574 
3575   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3576   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3577   SmallVector<SDValue, 8> MemOpChains;
3578 
3579   // Analyze operands of the call, assigning locations to each operand.
3580   SmallVector<CCValAssign, 16> ArgLocs;
3581   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3582   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3583 
3584   if (CallConv != CallingConv::AMDGPU_Gfx && !AMDGPU::isChainCC(CallConv)) {
3585     // With a fixed ABI, allocate fixed registers before user arguments.
3586     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3587   }
3588 
3589   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3590 
3591   // Get a count of how many bytes are to be pushed on the stack.
3592   unsigned NumBytes = CCInfo.getStackSize();
3593 
3594   if (IsSibCall) {
3595     // Since we're not changing the ABI to make this a tail call, the memory
3596     // operands are already available in the caller's incoming argument space.
3597     NumBytes = 0;
3598   }
3599 
3600   // FPDiff is the byte offset of the call's argument area from the callee's.
3601   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3602   // by this amount for a tail call. In a sibling call it must be 0 because the
3603   // caller will deallocate the entire stack and the callee still expects its
3604   // arguments to begin at SP+0. Completely unused for non-tail calls.
3605   int32_t FPDiff = 0;
3606   MachineFrameInfo &MFI = MF.getFrameInfo();
3607 
3608   // Adjust the stack pointer for the new arguments...
3609   // These operations are automatically eliminated by the prolog/epilog pass
3610   if (!IsSibCall)
3611     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3612 
3613   if (!IsSibCall || IsChainCallConv) {
3614     if (!Subtarget->enableFlatScratch()) {
3615       SmallVector<SDValue, 4> CopyFromChains;
3616 
3617       // In the HSA case, this should be an identity copy.
3618       SDValue ScratchRSrcReg
3619         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3620       RegsToPass.emplace_back(IsChainCallConv
3621                                   ? AMDGPU::SGPR48_SGPR49_SGPR50_SGPR51
3622                                   : AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3,
3623                               ScratchRSrcReg);
3624       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3625       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3626     }
3627   }
3628 
3629   MVT PtrVT = MVT::i32;
3630 
3631   // Walk the register/memloc assignments, inserting copies/loads.
3632   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3633     CCValAssign &VA = ArgLocs[i];
3634     SDValue Arg = OutVals[i];
3635 
3636     // Promote the value if needed.
3637     switch (VA.getLocInfo()) {
3638     case CCValAssign::Full:
3639       break;
3640     case CCValAssign::BCvt:
3641       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3642       break;
3643     case CCValAssign::ZExt:
3644       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3645       break;
3646     case CCValAssign::SExt:
3647       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3648       break;
3649     case CCValAssign::AExt:
3650       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3651       break;
3652     case CCValAssign::FPExt:
3653       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3654       break;
3655     default:
3656       llvm_unreachable("Unknown loc info!");
3657     }
3658 
3659     if (VA.isRegLoc()) {
3660       RegsToPass.push_back(std::pair(VA.getLocReg(), Arg));
3661     } else {
3662       assert(VA.isMemLoc());
3663 
3664       SDValue DstAddr;
3665       MachinePointerInfo DstInfo;
3666 
3667       unsigned LocMemOffset = VA.getLocMemOffset();
3668       int32_t Offset = LocMemOffset;
3669 
3670       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3671       MaybeAlign Alignment;
3672 
3673       if (IsTailCall) {
3674         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3675         unsigned OpSize = Flags.isByVal() ?
3676           Flags.getByValSize() : VA.getValVT().getStoreSize();
3677 
3678         // FIXME: We can have better than the minimum byval required alignment.
3679         Alignment =
3680             Flags.isByVal()
3681                 ? Flags.getNonZeroByValAlign()
3682                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3683 
3684         Offset = Offset + FPDiff;
3685         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3686 
3687         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3688         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3689 
3690         // Make sure any stack arguments overlapping with where we're storing
3691         // are loaded before this eventual operation. Otherwise they'll be
3692         // clobbered.
3693 
3694         // FIXME: Why is this really necessary? This seems to just result in a
3695         // lot of code to copy the stack and write them back to the same
3696         // locations, which are supposed to be immutable?
3697         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3698       } else {
3699         // Stores to the argument stack area are relative to the stack pointer.
3700         SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3701                                         MVT::i32);
3702         DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3703         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3704         Alignment =
3705             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3706       }
3707 
3708       if (Outs[i].Flags.isByVal()) {
3709         SDValue SizeNode =
3710             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3711         SDValue Cpy =
3712             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3713                           Outs[i].Flags.getNonZeroByValAlign(),
3714                           /*isVol = */ false, /*AlwaysInline = */ true,
3715                           /*isTailCall = */ false, DstInfo,
3716                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3717 
3718         MemOpChains.push_back(Cpy);
3719       } else {
3720         SDValue Store =
3721             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3722         MemOpChains.push_back(Store);
3723       }
3724     }
3725   }
3726 
3727   if (!MemOpChains.empty())
3728     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3729 
3730   // Build a sequence of copy-to-reg nodes chained together with token chain
3731   // and flag operands which copy the outgoing args into the appropriate regs.
3732   SDValue InGlue;
3733   for (auto &RegToPass : RegsToPass) {
3734     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3735                              RegToPass.second, InGlue);
3736     InGlue = Chain.getValue(1);
3737   }
3738 
3739 
3740   // We don't usually want to end the call-sequence here because we would tidy
3741   // the frame up *after* the call, however in the ABI-changing tail-call case
3742   // we've carefully laid out the parameters so that when sp is reset they'll be
3743   // in the correct location.
3744   if (IsTailCall && !IsSibCall) {
3745     Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, InGlue, DL);
3746     InGlue = Chain.getValue(1);
3747   }
3748 
3749   std::vector<SDValue> Ops;
3750   Ops.push_back(Chain);
3751   Ops.push_back(Callee);
3752   // Add a redundant copy of the callee global which will not be legalized, as
3753   // we need direct access to the callee later.
3754   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3755     const GlobalValue *GV = GSD->getGlobal();
3756     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3757   } else {
3758     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3759   }
3760 
3761   if (IsTailCall) {
3762     // Each tail call may have to adjust the stack by a different amount, so
3763     // this information must travel along with the operation for eventual
3764     // consumption by emitEpilogue.
3765     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3766   }
3767 
3768   if (IsChainCallConv)
3769     Ops.push_back(RequestedExec.Node);
3770 
3771   // Add argument registers to the end of the list so that they are known live
3772   // into the call.
3773   for (auto &RegToPass : RegsToPass) {
3774     Ops.push_back(DAG.getRegister(RegToPass.first,
3775                                   RegToPass.second.getValueType()));
3776   }
3777 
3778   // Add a register mask operand representing the call-preserved registers.
3779   auto *TRI = static_cast<const SIRegisterInfo *>(Subtarget->getRegisterInfo());
3780   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3781   assert(Mask && "Missing call preserved mask for calling convention");
3782   Ops.push_back(DAG.getRegisterMask(Mask));
3783 
3784   if (InGlue.getNode())
3785     Ops.push_back(InGlue);
3786 
3787   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3788 
3789   // If we're doing a tall call, use a TC_RETURN here rather than an
3790   // actual call instruction.
3791   if (IsTailCall) {
3792     MFI.setHasTailCall();
3793     unsigned OPC = AMDGPUISD::TC_RETURN;
3794     switch (CallConv) {
3795     case CallingConv::AMDGPU_Gfx:
3796       OPC = AMDGPUISD::TC_RETURN_GFX;
3797       break;
3798     case CallingConv::AMDGPU_CS_Chain:
3799     case CallingConv::AMDGPU_CS_ChainPreserve:
3800       OPC = AMDGPUISD::TC_RETURN_CHAIN;
3801       break;
3802     }
3803 
3804     return DAG.getNode(OPC, DL, NodeTys, Ops);
3805   }
3806 
3807   // Returns a chain and a flag for retval copy to use.
3808   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3809   Chain = Call.getValue(0);
3810   InGlue = Call.getValue(1);
3811 
3812   uint64_t CalleePopBytes = NumBytes;
3813   Chain = DAG.getCALLSEQ_END(Chain, 0, CalleePopBytes, InGlue, DL);
3814   if (!Ins.empty())
3815     InGlue = Chain.getValue(1);
3816 
3817   // Handle result values, copying them out of physregs into vregs that we
3818   // return.
3819   return LowerCallResult(Chain, InGlue, CallConv, IsVarArg, Ins, DL, DAG,
3820                          InVals, IsThisReturn,
3821                          IsThisReturn ? OutVals[0] : SDValue());
3822 }
3823 
3824 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3825 // except for applying the wave size scale to the increment amount.
3826 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3827     SDValue Op, SelectionDAG &DAG) const {
3828   const MachineFunction &MF = DAG.getMachineFunction();
3829   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3830 
3831   SDLoc dl(Op);
3832   EVT VT = Op.getValueType();
3833   SDValue Tmp1 = Op;
3834   SDValue Tmp2 = Op.getValue(1);
3835   SDValue Tmp3 = Op.getOperand(2);
3836   SDValue Chain = Tmp1.getOperand(0);
3837 
3838   Register SPReg = Info->getStackPtrOffsetReg();
3839 
3840   // Chain the dynamic stack allocation so that it doesn't modify the stack
3841   // pointer when other instructions are using the stack.
3842   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3843 
3844   SDValue Size  = Tmp2.getOperand(1);
3845   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3846   Chain = SP.getValue(1);
3847   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3848   const TargetFrameLowering *TFL = Subtarget->getFrameLowering();
3849   unsigned Opc =
3850     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3851     ISD::ADD : ISD::SUB;
3852 
3853   SDValue ScaledSize = DAG.getNode(
3854       ISD::SHL, dl, VT, Size,
3855       DAG.getConstant(Subtarget->getWavefrontSizeLog2(), dl, MVT::i32));
3856 
3857   Align StackAlign = TFL->getStackAlign();
3858   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3859   if (Alignment && *Alignment > StackAlign) {
3860     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3861                        DAG.getConstant(-(uint64_t)Alignment->value()
3862                                            << Subtarget->getWavefrontSizeLog2(),
3863                                        dl, VT));
3864   }
3865 
3866   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3867   Tmp2 = DAG.getCALLSEQ_END(Chain, 0, 0, SDValue(), dl);
3868 
3869   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3870 }
3871 
3872 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3873                                                   SelectionDAG &DAG) const {
3874   // We only handle constant sizes here to allow non-entry block, static sized
3875   // allocas. A truly dynamic value is more difficult to support because we
3876   // don't know if the size value is uniform or not. If the size isn't uniform,
3877   // we would need to do a wave reduction to get the maximum size to know how
3878   // much to increment the uniform stack pointer.
3879   SDValue Size = Op.getOperand(1);
3880   if (isa<ConstantSDNode>(Size))
3881       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3882 
3883   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3884 }
3885 
3886 SDValue SITargetLowering::LowerSTACKSAVE(SDValue Op, SelectionDAG &DAG) const {
3887   if (Op.getValueType() != MVT::i32)
3888     return Op; // Defer to cannot select error.
3889 
3890   Register SP = getStackPointerRegisterToSaveRestore();
3891   SDLoc SL(Op);
3892 
3893   SDValue CopyFromSP = DAG.getCopyFromReg(Op->getOperand(0), SL, SP, MVT::i32);
3894 
3895   // Convert from wave uniform to swizzled vector address. This should protect
3896   // from any edge cases where the stacksave result isn't directly used with
3897   // stackrestore.
3898   SDValue VectorAddress =
3899       DAG.getNode(AMDGPUISD::WAVE_ADDRESS, SL, MVT::i32, CopyFromSP);
3900   return DAG.getMergeValues({VectorAddress, CopyFromSP.getValue(1)}, SL);
3901 }
3902 
3903 SDValue SITargetLowering::lowerGET_ROUNDING(SDValue Op,
3904                                             SelectionDAG &DAG) const {
3905   SDLoc SL(Op);
3906   assert(Op.getValueType() == MVT::i32);
3907 
3908   uint32_t BothRoundHwReg =
3909       AMDGPU::Hwreg::encodeHwreg(AMDGPU::Hwreg::ID_MODE, 0, 4);
3910   SDValue GetRoundBothImm = DAG.getTargetConstant(BothRoundHwReg, SL, MVT::i32);
3911 
3912   SDValue IntrinID =
3913       DAG.getTargetConstant(Intrinsic::amdgcn_s_getreg, SL, MVT::i32);
3914   SDValue GetReg = DAG.getNode(ISD::INTRINSIC_W_CHAIN, SL, Op->getVTList(),
3915                                Op.getOperand(0), IntrinID, GetRoundBothImm);
3916 
3917   // There are two rounding modes, one for f32 and one for f64/f16. We only
3918   // report in the standard value range if both are the same.
3919   //
3920   // The raw values also differ from the expected FLT_ROUNDS values. Nearest
3921   // ties away from zero is not supported, and the other values are rotated by
3922   // 1.
3923   //
3924   // If the two rounding modes are not the same, report a target defined value.
3925 
3926   // Mode register rounding mode fields:
3927   //
3928   // [1:0] Single-precision round mode.
3929   // [3:2] Double/Half-precision round mode.
3930   //
3931   // 0=nearest even; 1= +infinity; 2= -infinity, 3= toward zero.
3932   //
3933   //             Hardware   Spec
3934   // Toward-0        3        0
3935   // Nearest Even    0        1
3936   // +Inf            1        2
3937   // -Inf            2        3
3938   //  NearestAway0  N/A       4
3939   //
3940   // We have to handle 16 permutations of a 4-bit value, so we create a 64-bit
3941   // table we can index by the raw hardware mode.
3942   //
3943   // (trunc (FltRoundConversionTable >> MODE.fp_round)) & 0xf
3944 
3945   SDValue BitTable =
3946       DAG.getConstant(AMDGPU::FltRoundConversionTable, SL, MVT::i64);
3947 
3948   SDValue Two = DAG.getConstant(2, SL, MVT::i32);
3949   SDValue RoundModeTimesNumBits =
3950       DAG.getNode(ISD::SHL, SL, MVT::i32, GetReg, Two);
3951 
3952   // TODO: We could possibly avoid a 64-bit shift and use a simpler table if we
3953   // knew only one mode was demanded.
3954   SDValue TableValue =
3955       DAG.getNode(ISD::SRL, SL, MVT::i64, BitTable, RoundModeTimesNumBits);
3956   SDValue TruncTable = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, TableValue);
3957 
3958   SDValue EntryMask = DAG.getConstant(0xf, SL, MVT::i32);
3959   SDValue TableEntry =
3960       DAG.getNode(ISD::AND, SL, MVT::i32, TruncTable, EntryMask);
3961 
3962   // There's a gap in the 4-bit encoded table and actual enum values, so offset
3963   // if it's an extended value.
3964   SDValue Four = DAG.getConstant(4, SL, MVT::i32);
3965   SDValue IsStandardValue =
3966       DAG.getSetCC(SL, MVT::i1, TableEntry, Four, ISD::SETULT);
3967   SDValue EnumOffset = DAG.getNode(ISD::ADD, SL, MVT::i32, TableEntry, Four);
3968   SDValue Result = DAG.getNode(ISD::SELECT, SL, MVT::i32, IsStandardValue,
3969                                TableEntry, EnumOffset);
3970 
3971   return DAG.getMergeValues({Result, GetReg.getValue(1)}, SL);
3972 }
3973 
3974 SDValue SITargetLowering::lowerPREFETCH(SDValue Op, SelectionDAG &DAG) const {
3975   if (Op->isDivergent())
3976     return SDValue();
3977 
3978   switch (cast<MemSDNode>(Op)->getAddressSpace()) {
3979   case AMDGPUAS::FLAT_ADDRESS:
3980   case AMDGPUAS::GLOBAL_ADDRESS:
3981   case AMDGPUAS::CONSTANT_ADDRESS:
3982   case AMDGPUAS::CONSTANT_ADDRESS_32BIT:
3983     break;
3984   default:
3985     return SDValue();
3986   }
3987 
3988   return Op;
3989 }
3990 
3991 // Work around DAG legality rules only based on the result type.
3992 SDValue SITargetLowering::lowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
3993   bool IsStrict = Op.getOpcode() == ISD::STRICT_FP_EXTEND;
3994   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
3995   EVT SrcVT = Src.getValueType();
3996 
3997   if (SrcVT.getScalarType() != MVT::bf16)
3998     return Op;
3999 
4000   SDLoc SL(Op);
4001   SDValue BitCast =
4002       DAG.getNode(ISD::BITCAST, SL, SrcVT.changeTypeToInteger(), Src);
4003 
4004   EVT DstVT = Op.getValueType();
4005   if (IsStrict)
4006     llvm_unreachable("Need STRICT_BF16_TO_FP");
4007 
4008   return DAG.getNode(ISD::BF16_TO_FP, SL, DstVT, BitCast);
4009 }
4010 
4011 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
4012                                              const MachineFunction &MF) const {
4013   Register Reg = StringSwitch<Register>(RegName)
4014     .Case("m0", AMDGPU::M0)
4015     .Case("exec", AMDGPU::EXEC)
4016     .Case("exec_lo", AMDGPU::EXEC_LO)
4017     .Case("exec_hi", AMDGPU::EXEC_HI)
4018     .Case("flat_scratch", AMDGPU::FLAT_SCR)
4019     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
4020     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
4021     .Default(Register());
4022 
4023   if (Reg == AMDGPU::NoRegister) {
4024     report_fatal_error(Twine("invalid register name \""
4025                              + StringRef(RegName)  + "\"."));
4026 
4027   }
4028 
4029   if (!Subtarget->hasFlatScrRegister() &&
4030        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
4031     report_fatal_error(Twine("invalid register \""
4032                              + StringRef(RegName)  + "\" for subtarget."));
4033   }
4034 
4035   switch (Reg) {
4036   case AMDGPU::M0:
4037   case AMDGPU::EXEC_LO:
4038   case AMDGPU::EXEC_HI:
4039   case AMDGPU::FLAT_SCR_LO:
4040   case AMDGPU::FLAT_SCR_HI:
4041     if (VT.getSizeInBits() == 32)
4042       return Reg;
4043     break;
4044   case AMDGPU::EXEC:
4045   case AMDGPU::FLAT_SCR:
4046     if (VT.getSizeInBits() == 64)
4047       return Reg;
4048     break;
4049   default:
4050     llvm_unreachable("missing register type checking");
4051   }
4052 
4053   report_fatal_error(Twine("invalid type for register \""
4054                            + StringRef(RegName) + "\"."));
4055 }
4056 
4057 // If kill is not the last instruction, split the block so kill is always a
4058 // proper terminator.
4059 MachineBasicBlock *
4060 SITargetLowering::splitKillBlock(MachineInstr &MI,
4061                                  MachineBasicBlock *BB) const {
4062   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
4063   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4064   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
4065   return SplitBB;
4066 }
4067 
4068 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
4069 // \p MI will be the only instruction in the loop body block. Otherwise, it will
4070 // be the first instruction in the remainder block.
4071 //
4072 /// \returns { LoopBody, Remainder }
4073 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
4074 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
4075   MachineFunction *MF = MBB.getParent();
4076   MachineBasicBlock::iterator I(&MI);
4077 
4078   // To insert the loop we need to split the block. Move everything after this
4079   // point to a new block, and insert a new empty block between the two.
4080   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
4081   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
4082   MachineFunction::iterator MBBI(MBB);
4083   ++MBBI;
4084 
4085   MF->insert(MBBI, LoopBB);
4086   MF->insert(MBBI, RemainderBB);
4087 
4088   LoopBB->addSuccessor(LoopBB);
4089   LoopBB->addSuccessor(RemainderBB);
4090 
4091   // Move the rest of the block into a new block.
4092   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
4093 
4094   if (InstInLoop) {
4095     auto Next = std::next(I);
4096 
4097     // Move instruction to loop body.
4098     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
4099 
4100     // Move the rest of the block.
4101     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
4102   } else {
4103     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
4104   }
4105 
4106   MBB.addSuccessor(LoopBB);
4107 
4108   return std::pair(LoopBB, RemainderBB);
4109 }
4110 
4111 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
4112 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
4113   MachineBasicBlock *MBB = MI.getParent();
4114   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4115   auto I = MI.getIterator();
4116   auto E = std::next(I);
4117 
4118   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
4119     .addImm(0);
4120 
4121   MIBundleBuilder Bundler(*MBB, I, E);
4122   finalizeBundle(*MBB, Bundler.begin());
4123 }
4124 
4125 MachineBasicBlock *
4126 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
4127                                          MachineBasicBlock *BB) const {
4128   const DebugLoc &DL = MI.getDebugLoc();
4129 
4130   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4131 
4132   MachineBasicBlock *LoopBB;
4133   MachineBasicBlock *RemainderBB;
4134   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4135 
4136   // Apparently kill flags are only valid if the def is in the same block?
4137   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
4138     Src->setIsKill(false);
4139 
4140   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
4141 
4142   MachineBasicBlock::iterator I = LoopBB->end();
4143 
4144   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
4145     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
4146 
4147   // Clear TRAP_STS.MEM_VIOL
4148   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
4149     .addImm(0)
4150     .addImm(EncodedReg);
4151 
4152   bundleInstWithWaitcnt(MI);
4153 
4154   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
4155 
4156   // Load and check TRAP_STS.MEM_VIOL
4157   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
4158     .addImm(EncodedReg);
4159 
4160   // FIXME: Do we need to use an isel pseudo that may clobber scc?
4161   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4162     .addReg(Reg, RegState::Kill)
4163     .addImm(0);
4164   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4165     .addMBB(LoopBB);
4166 
4167   return RemainderBB;
4168 }
4169 
4170 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
4171 // wavefront. If the value is uniform and just happens to be in a VGPR, this
4172 // will only do one iteration. In the worst case, this will loop 64 times.
4173 //
4174 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
4175 static MachineBasicBlock::iterator
4176 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
4177                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
4178                        const DebugLoc &DL, const MachineOperand &Idx,
4179                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
4180                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
4181                        Register &SGPRIdxReg) {
4182 
4183   MachineFunction *MF = OrigBB.getParent();
4184   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4185   const SIRegisterInfo *TRI = ST.getRegisterInfo();
4186   MachineBasicBlock::iterator I = LoopBB.begin();
4187 
4188   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
4189   Register PhiExec = MRI.createVirtualRegister(BoolRC);
4190   Register NewExec = MRI.createVirtualRegister(BoolRC);
4191   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
4192   Register CondReg = MRI.createVirtualRegister(BoolRC);
4193 
4194   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
4195     .addReg(InitReg)
4196     .addMBB(&OrigBB)
4197     .addReg(ResultReg)
4198     .addMBB(&LoopBB);
4199 
4200   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
4201     .addReg(InitSaveExecReg)
4202     .addMBB(&OrigBB)
4203     .addReg(NewExec)
4204     .addMBB(&LoopBB);
4205 
4206   // Read the next variant <- also loop target.
4207   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
4208       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
4209 
4210   // Compare the just read M0 value to all possible Idx values.
4211   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
4212       .addReg(CurrentIdxReg)
4213       .addReg(Idx.getReg(), 0, Idx.getSubReg());
4214 
4215   // Update EXEC, save the original EXEC value to VCC.
4216   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
4217                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
4218           NewExec)
4219     .addReg(CondReg, RegState::Kill);
4220 
4221   MRI.setSimpleHint(NewExec, CondReg);
4222 
4223   if (UseGPRIdxMode) {
4224     if (Offset == 0) {
4225       SGPRIdxReg = CurrentIdxReg;
4226     } else {
4227       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
4228       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
4229           .addReg(CurrentIdxReg, RegState::Kill)
4230           .addImm(Offset);
4231     }
4232   } else {
4233     // Move index from VCC into M0
4234     if (Offset == 0) {
4235       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4236         .addReg(CurrentIdxReg, RegState::Kill);
4237     } else {
4238       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
4239         .addReg(CurrentIdxReg, RegState::Kill)
4240         .addImm(Offset);
4241     }
4242   }
4243 
4244   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
4245   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
4246   MachineInstr *InsertPt =
4247     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
4248                                                   : AMDGPU::S_XOR_B64_term), Exec)
4249       .addReg(Exec)
4250       .addReg(NewExec);
4251 
4252   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
4253   // s_cbranch_scc0?
4254 
4255   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
4256   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
4257     .addMBB(&LoopBB);
4258 
4259   return InsertPt->getIterator();
4260 }
4261 
4262 // This has slightly sub-optimal regalloc when the source vector is killed by
4263 // the read. The register allocator does not understand that the kill is
4264 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
4265 // subregister from it, using 1 more VGPR than necessary. This was saved when
4266 // this was expanded after register allocation.
4267 static MachineBasicBlock::iterator
4268 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
4269                unsigned InitResultReg, unsigned PhiReg, int Offset,
4270                bool UseGPRIdxMode, Register &SGPRIdxReg) {
4271   MachineFunction *MF = MBB.getParent();
4272   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4273   const SIRegisterInfo *TRI = ST.getRegisterInfo();
4274   MachineRegisterInfo &MRI = MF->getRegInfo();
4275   const DebugLoc &DL = MI.getDebugLoc();
4276   MachineBasicBlock::iterator I(&MI);
4277 
4278   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4279   Register DstReg = MI.getOperand(0).getReg();
4280   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
4281   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
4282   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
4283   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
4284 
4285   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
4286 
4287   // Save the EXEC mask
4288   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
4289     .addReg(Exec);
4290 
4291   MachineBasicBlock *LoopBB;
4292   MachineBasicBlock *RemainderBB;
4293   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
4294 
4295   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
4296 
4297   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
4298                                       InitResultReg, DstReg, PhiReg, TmpExec,
4299                                       Offset, UseGPRIdxMode, SGPRIdxReg);
4300 
4301   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
4302   MachineFunction::iterator MBBI(LoopBB);
4303   ++MBBI;
4304   MF->insert(MBBI, LandingPad);
4305   LoopBB->removeSuccessor(RemainderBB);
4306   LandingPad->addSuccessor(RemainderBB);
4307   LoopBB->addSuccessor(LandingPad);
4308   MachineBasicBlock::iterator First = LandingPad->begin();
4309   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
4310     .addReg(SaveExec);
4311 
4312   return InsPt;
4313 }
4314 
4315 // Returns subreg index, offset
4316 static std::pair<unsigned, int>
4317 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
4318                             const TargetRegisterClass *SuperRC,
4319                             unsigned VecReg,
4320                             int Offset) {
4321   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
4322 
4323   // Skip out of bounds offsets, or else we would end up using an undefined
4324   // register.
4325   if (Offset >= NumElts || Offset < 0)
4326     return std::pair(AMDGPU::sub0, Offset);
4327 
4328   return std::pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
4329 }
4330 
4331 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
4332                                  MachineRegisterInfo &MRI, MachineInstr &MI,
4333                                  int Offset) {
4334   MachineBasicBlock *MBB = MI.getParent();
4335   const DebugLoc &DL = MI.getDebugLoc();
4336   MachineBasicBlock::iterator I(&MI);
4337 
4338   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
4339 
4340   assert(Idx->getReg() != AMDGPU::NoRegister);
4341 
4342   if (Offset == 0) {
4343     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
4344   } else {
4345     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
4346         .add(*Idx)
4347         .addImm(Offset);
4348   }
4349 }
4350 
4351 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
4352                                    MachineRegisterInfo &MRI, MachineInstr &MI,
4353                                    int Offset) {
4354   MachineBasicBlock *MBB = MI.getParent();
4355   const DebugLoc &DL = MI.getDebugLoc();
4356   MachineBasicBlock::iterator I(&MI);
4357 
4358   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
4359 
4360   if (Offset == 0)
4361     return Idx->getReg();
4362 
4363   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
4364   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
4365       .add(*Idx)
4366       .addImm(Offset);
4367   return Tmp;
4368 }
4369 
4370 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
4371                                           MachineBasicBlock &MBB,
4372                                           const GCNSubtarget &ST) {
4373   const SIInstrInfo *TII = ST.getInstrInfo();
4374   const SIRegisterInfo &TRI = TII->getRegisterInfo();
4375   MachineFunction *MF = MBB.getParent();
4376   MachineRegisterInfo &MRI = MF->getRegInfo();
4377 
4378   Register Dst = MI.getOperand(0).getReg();
4379   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
4380   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
4381   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
4382 
4383   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
4384   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
4385 
4386   unsigned SubReg;
4387   std::tie(SubReg, Offset)
4388     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
4389 
4390   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
4391 
4392   // Check for a SGPR index.
4393   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
4394     MachineBasicBlock::iterator I(&MI);
4395     const DebugLoc &DL = MI.getDebugLoc();
4396 
4397     if (UseGPRIdxMode) {
4398       // TODO: Look at the uses to avoid the copy. This may require rescheduling
4399       // to avoid interfering with other uses, so probably requires a new
4400       // optimization pass.
4401       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
4402 
4403       const MCInstrDesc &GPRIDXDesc =
4404           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
4405       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
4406           .addReg(SrcReg)
4407           .addReg(Idx)
4408           .addImm(SubReg);
4409     } else {
4410       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
4411 
4412       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
4413         .addReg(SrcReg, 0, SubReg)
4414         .addReg(SrcReg, RegState::Implicit);
4415     }
4416 
4417     MI.eraseFromParent();
4418 
4419     return &MBB;
4420   }
4421 
4422   // Control flow needs to be inserted if indexing with a VGPR.
4423   const DebugLoc &DL = MI.getDebugLoc();
4424   MachineBasicBlock::iterator I(&MI);
4425 
4426   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4427   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4428 
4429   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
4430 
4431   Register SGPRIdxReg;
4432   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
4433                               UseGPRIdxMode, SGPRIdxReg);
4434 
4435   MachineBasicBlock *LoopBB = InsPt->getParent();
4436 
4437   if (UseGPRIdxMode) {
4438     const MCInstrDesc &GPRIDXDesc =
4439         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
4440 
4441     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
4442         .addReg(SrcReg)
4443         .addReg(SGPRIdxReg)
4444         .addImm(SubReg);
4445   } else {
4446     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
4447       .addReg(SrcReg, 0, SubReg)
4448       .addReg(SrcReg, RegState::Implicit);
4449   }
4450 
4451   MI.eraseFromParent();
4452 
4453   return LoopBB;
4454 }
4455 
4456 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
4457                                           MachineBasicBlock &MBB,
4458                                           const GCNSubtarget &ST) {
4459   const SIInstrInfo *TII = ST.getInstrInfo();
4460   const SIRegisterInfo &TRI = TII->getRegisterInfo();
4461   MachineFunction *MF = MBB.getParent();
4462   MachineRegisterInfo &MRI = MF->getRegInfo();
4463 
4464   Register Dst = MI.getOperand(0).getReg();
4465   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
4466   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
4467   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
4468   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
4469   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
4470   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
4471 
4472   // This can be an immediate, but will be folded later.
4473   assert(Val->getReg());
4474 
4475   unsigned SubReg;
4476   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
4477                                                          SrcVec->getReg(),
4478                                                          Offset);
4479   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
4480 
4481   if (Idx->getReg() == AMDGPU::NoRegister) {
4482     MachineBasicBlock::iterator I(&MI);
4483     const DebugLoc &DL = MI.getDebugLoc();
4484 
4485     assert(Offset == 0);
4486 
4487     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
4488         .add(*SrcVec)
4489         .add(*Val)
4490         .addImm(SubReg);
4491 
4492     MI.eraseFromParent();
4493     return &MBB;
4494   }
4495 
4496   // Check for a SGPR index.
4497   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
4498     MachineBasicBlock::iterator I(&MI);
4499     const DebugLoc &DL = MI.getDebugLoc();
4500 
4501     if (UseGPRIdxMode) {
4502       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
4503 
4504       const MCInstrDesc &GPRIDXDesc =
4505           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
4506       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
4507           .addReg(SrcVec->getReg())
4508           .add(*Val)
4509           .addReg(Idx)
4510           .addImm(SubReg);
4511     } else {
4512       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
4513 
4514       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
4515           TRI.getRegSizeInBits(*VecRC), 32, false);
4516       BuildMI(MBB, I, DL, MovRelDesc, Dst)
4517           .addReg(SrcVec->getReg())
4518           .add(*Val)
4519           .addImm(SubReg);
4520     }
4521     MI.eraseFromParent();
4522     return &MBB;
4523   }
4524 
4525   // Control flow needs to be inserted if indexing with a VGPR.
4526   if (Val->isReg())
4527     MRI.clearKillFlags(Val->getReg());
4528 
4529   const DebugLoc &DL = MI.getDebugLoc();
4530 
4531   Register PhiReg = MRI.createVirtualRegister(VecRC);
4532 
4533   Register SGPRIdxReg;
4534   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
4535                               UseGPRIdxMode, SGPRIdxReg);
4536   MachineBasicBlock *LoopBB = InsPt->getParent();
4537 
4538   if (UseGPRIdxMode) {
4539     const MCInstrDesc &GPRIDXDesc =
4540         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
4541 
4542     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
4543         .addReg(PhiReg)
4544         .add(*Val)
4545         .addReg(SGPRIdxReg)
4546         .addImm(AMDGPU::sub0);
4547   } else {
4548     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
4549         TRI.getRegSizeInBits(*VecRC), 32, false);
4550     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
4551         .addReg(PhiReg)
4552         .add(*Val)
4553         .addImm(AMDGPU::sub0);
4554   }
4555 
4556   MI.eraseFromParent();
4557   return LoopBB;
4558 }
4559 
4560 static MachineBasicBlock *lowerWaveReduce(MachineInstr &MI,
4561                                           MachineBasicBlock &BB,
4562                                           const GCNSubtarget &ST,
4563                                           unsigned Opc) {
4564   MachineRegisterInfo &MRI = BB.getParent()->getRegInfo();
4565   const SIRegisterInfo *TRI = ST.getRegisterInfo();
4566   const DebugLoc &DL = MI.getDebugLoc();
4567   const SIInstrInfo *TII = ST.getInstrInfo();
4568 
4569   // Reduction operations depend on whether the input operand is SGPR or VGPR.
4570   Register SrcReg = MI.getOperand(1).getReg();
4571   bool isSGPR = TRI->isSGPRClass(MRI.getRegClass(SrcReg));
4572   Register DstReg = MI.getOperand(0).getReg();
4573   MachineBasicBlock *RetBB = nullptr;
4574   if (isSGPR) {
4575     // These operations with a uniform value i.e. SGPR are idempotent.
4576     // Reduced value will be same as given sgpr.
4577     BuildMI(BB, MI, DL, TII->get(AMDGPU::S_MOV_B32), DstReg).addReg(SrcReg);
4578     RetBB = &BB;
4579   } else {
4580     // TODO: Implement DPP Strategy and switch based on immediate strategy
4581     // operand. For now, for all the cases (default, Iterative and DPP we use
4582     // iterative approach by default.)
4583 
4584     // To reduce the VGPR using iterative approach, we need to iterate
4585     // over all the active lanes. Lowering consists of ComputeLoop,
4586     // which iterate over only active lanes. We use copy of EXEC register
4587     // as induction variable and every active lane modifies it using bitset0
4588     // so that we will get the next active lane for next iteration.
4589     MachineBasicBlock::iterator I = BB.end();
4590     Register SrcReg = MI.getOperand(1).getReg();
4591 
4592     // Create Control flow for loop
4593     // Split MI's Machine Basic block into For loop
4594     auto [ComputeLoop, ComputeEnd] = splitBlockForLoop(MI, BB, true);
4595 
4596     // Create virtual registers required for lowering.
4597     const TargetRegisterClass *WaveMaskRegClass = TRI->getWaveMaskRegClass();
4598     const TargetRegisterClass *DstRegClass = MRI.getRegClass(DstReg);
4599     Register LoopIterator = MRI.createVirtualRegister(WaveMaskRegClass);
4600     Register InitalValReg = MRI.createVirtualRegister(DstRegClass);
4601 
4602     Register AccumulatorReg = MRI.createVirtualRegister(DstRegClass);
4603     Register ActiveBitsReg = MRI.createVirtualRegister(WaveMaskRegClass);
4604     Register NewActiveBitsReg = MRI.createVirtualRegister(WaveMaskRegClass);
4605 
4606     Register FF1Reg = MRI.createVirtualRegister(DstRegClass);
4607     Register LaneValueReg = MRI.createVirtualRegister(DstRegClass);
4608 
4609     bool IsWave32 = ST.isWave32();
4610     unsigned MovOpc = IsWave32 ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
4611     unsigned ExecReg = IsWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
4612 
4613     // Create initail values of induction variable from Exec, Accumulator and
4614     // insert branch instr to newly created ComputeBlockk
4615     uint32_t InitalValue =
4616         (Opc == AMDGPU::S_MIN_U32) ? std::numeric_limits<uint32_t>::max() : 0;
4617     auto TmpSReg =
4618         BuildMI(BB, I, DL, TII->get(MovOpc), LoopIterator).addReg(ExecReg);
4619     BuildMI(BB, I, DL, TII->get(AMDGPU::S_MOV_B32), InitalValReg)
4620         .addImm(InitalValue);
4621     BuildMI(BB, I, DL, TII->get(AMDGPU::S_BRANCH)).addMBB(ComputeLoop);
4622 
4623     // Start constructing ComputeLoop
4624     I = ComputeLoop->end();
4625     auto Accumulator =
4626         BuildMI(*ComputeLoop, I, DL, TII->get(AMDGPU::PHI), AccumulatorReg)
4627             .addReg(InitalValReg)
4628             .addMBB(&BB);
4629     auto ActiveBits =
4630         BuildMI(*ComputeLoop, I, DL, TII->get(AMDGPU::PHI), ActiveBitsReg)
4631             .addReg(TmpSReg->getOperand(0).getReg())
4632             .addMBB(&BB);
4633 
4634     // Perform the computations
4635     unsigned SFFOpc = IsWave32 ? AMDGPU::S_FF1_I32_B32 : AMDGPU::S_FF1_I32_B64;
4636     auto FF1 = BuildMI(*ComputeLoop, I, DL, TII->get(SFFOpc), FF1Reg)
4637                    .addReg(ActiveBits->getOperand(0).getReg());
4638     auto LaneValue = BuildMI(*ComputeLoop, I, DL,
4639                              TII->get(AMDGPU::V_READLANE_B32), LaneValueReg)
4640                          .addReg(SrcReg)
4641                          .addReg(FF1->getOperand(0).getReg());
4642     auto NewAccumulator = BuildMI(*ComputeLoop, I, DL, TII->get(Opc), DstReg)
4643                               .addReg(Accumulator->getOperand(0).getReg())
4644                               .addReg(LaneValue->getOperand(0).getReg());
4645 
4646     // Manipulate the iterator to get the next active lane
4647     unsigned BITSETOpc =
4648         IsWave32 ? AMDGPU::S_BITSET0_B32 : AMDGPU::S_BITSET0_B64;
4649     auto NewActiveBits =
4650         BuildMI(*ComputeLoop, I, DL, TII->get(BITSETOpc), NewActiveBitsReg)
4651             .addReg(FF1->getOperand(0).getReg())
4652             .addReg(ActiveBits->getOperand(0).getReg());
4653 
4654     // Add phi nodes
4655     Accumulator.addReg(NewAccumulator->getOperand(0).getReg())
4656         .addMBB(ComputeLoop);
4657     ActiveBits.addReg(NewActiveBits->getOperand(0).getReg())
4658         .addMBB(ComputeLoop);
4659 
4660     // Creating branching
4661     unsigned CMPOpc = IsWave32 ? AMDGPU::S_CMP_LG_U32 : AMDGPU::S_CMP_LG_U64;
4662     BuildMI(*ComputeLoop, I, DL, TII->get(CMPOpc))
4663         .addReg(NewActiveBits->getOperand(0).getReg())
4664         .addImm(0);
4665     BuildMI(*ComputeLoop, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4666         .addMBB(ComputeLoop);
4667 
4668     RetBB = ComputeEnd;
4669   }
4670   MI.eraseFromParent();
4671   return RetBB;
4672 }
4673 
4674 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
4675   MachineInstr &MI, MachineBasicBlock *BB) const {
4676 
4677   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4678   MachineFunction *MF = BB->getParent();
4679   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
4680 
4681   switch (MI.getOpcode()) {
4682   case AMDGPU::WAVE_REDUCE_UMIN_PSEUDO_U32:
4683     return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_MIN_U32);
4684   case AMDGPU::WAVE_REDUCE_UMAX_PSEUDO_U32:
4685     return lowerWaveReduce(MI, *BB, *getSubtarget(), AMDGPU::S_MAX_U32);
4686   case AMDGPU::S_UADDO_PSEUDO:
4687   case AMDGPU::S_USUBO_PSEUDO: {
4688     const DebugLoc &DL = MI.getDebugLoc();
4689     MachineOperand &Dest0 = MI.getOperand(0);
4690     MachineOperand &Dest1 = MI.getOperand(1);
4691     MachineOperand &Src0 = MI.getOperand(2);
4692     MachineOperand &Src1 = MI.getOperand(3);
4693 
4694     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
4695                        ? AMDGPU::S_ADD_I32
4696                        : AMDGPU::S_SUB_I32;
4697     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
4698 
4699     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
4700         .addImm(1)
4701         .addImm(0);
4702 
4703     MI.eraseFromParent();
4704     return BB;
4705   }
4706   case AMDGPU::S_ADD_U64_PSEUDO:
4707   case AMDGPU::S_SUB_U64_PSEUDO: {
4708     // For targets older than GFX12, we emit a sequence of 32-bit operations.
4709     // For GFX12, we emit s_add_u64 and s_sub_u64.
4710     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4711     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4712     const DebugLoc &DL = MI.getDebugLoc();
4713     MachineOperand &Dest = MI.getOperand(0);
4714     MachineOperand &Src0 = MI.getOperand(1);
4715     MachineOperand &Src1 = MI.getOperand(2);
4716     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
4717     if (Subtarget->hasScalarAddSub64()) {
4718       unsigned Opc = IsAdd ? AMDGPU::S_ADD_U64 : AMDGPU::S_SUB_U64;
4719       BuildMI(*BB, MI, DL, TII->get(Opc), Dest.getReg())
4720           .addReg(Src0.getReg())
4721           .addReg(Src1.getReg());
4722     } else {
4723       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4724       const TargetRegisterClass *BoolRC = TRI->getBoolRC();
4725 
4726       Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4727       Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4728 
4729       MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
4730           MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4731       MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
4732           MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4733 
4734       MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
4735           MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4736       MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
4737           MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4738 
4739       unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
4740       unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
4741       BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
4742           .add(Src0Sub0)
4743           .add(Src1Sub0);
4744       BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4745           .add(Src0Sub1)
4746           .add(Src1Sub1);
4747       BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4748           .addReg(DestSub0)
4749           .addImm(AMDGPU::sub0)
4750           .addReg(DestSub1)
4751           .addImm(AMDGPU::sub1);
4752     }
4753     MI.eraseFromParent();
4754     return BB;
4755   }
4756   case AMDGPU::V_ADD_U64_PSEUDO:
4757   case AMDGPU::V_SUB_U64_PSEUDO: {
4758     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4759     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4760     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4761     const DebugLoc &DL = MI.getDebugLoc();
4762 
4763     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
4764 
4765     MachineOperand &Dest = MI.getOperand(0);
4766     MachineOperand &Src0 = MI.getOperand(1);
4767     MachineOperand &Src1 = MI.getOperand(2);
4768 
4769     if (IsAdd && ST.hasLshlAddB64()) {
4770       auto Add = BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_LSHL_ADD_U64_e64),
4771                          Dest.getReg())
4772                      .add(Src0)
4773                      .addImm(0)
4774                      .add(Src1);
4775       TII->legalizeOperands(*Add);
4776       MI.eraseFromParent();
4777       return BB;
4778     }
4779 
4780     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4781 
4782     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4783     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4784 
4785     Register CarryReg = MRI.createVirtualRegister(CarryRC);
4786     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
4787 
4788     const TargetRegisterClass *Src0RC = Src0.isReg()
4789                                             ? MRI.getRegClass(Src0.getReg())
4790                                             : &AMDGPU::VReg_64RegClass;
4791     const TargetRegisterClass *Src1RC = Src1.isReg()
4792                                             ? MRI.getRegClass(Src1.getReg())
4793                                             : &AMDGPU::VReg_64RegClass;
4794 
4795     const TargetRegisterClass *Src0SubRC =
4796         TRI->getSubRegisterClass(Src0RC, AMDGPU::sub0);
4797     const TargetRegisterClass *Src1SubRC =
4798         TRI->getSubRegisterClass(Src1RC, AMDGPU::sub1);
4799 
4800     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
4801         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
4802     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
4803         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
4804 
4805     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
4806         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
4807     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
4808         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
4809 
4810     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
4811     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
4812                                .addReg(CarryReg, RegState::Define)
4813                                .add(SrcReg0Sub0)
4814                                .add(SrcReg1Sub0)
4815                                .addImm(0); // clamp bit
4816 
4817     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
4818     MachineInstr *HiHalf =
4819         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4820             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4821             .add(SrcReg0Sub1)
4822             .add(SrcReg1Sub1)
4823             .addReg(CarryReg, RegState::Kill)
4824             .addImm(0); // clamp bit
4825 
4826     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4827         .addReg(DestSub0)
4828         .addImm(AMDGPU::sub0)
4829         .addReg(DestSub1)
4830         .addImm(AMDGPU::sub1);
4831     TII->legalizeOperands(*LoHalf);
4832     TII->legalizeOperands(*HiHalf);
4833     MI.eraseFromParent();
4834     return BB;
4835   }
4836   case AMDGPU::S_ADD_CO_PSEUDO:
4837   case AMDGPU::S_SUB_CO_PSEUDO: {
4838     // This pseudo has a chance to be selected
4839     // only from uniform add/subcarry node. All the VGPR operands
4840     // therefore assumed to be splat vectors.
4841     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4842     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4843     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4844     MachineBasicBlock::iterator MII = MI;
4845     const DebugLoc &DL = MI.getDebugLoc();
4846     MachineOperand &Dest = MI.getOperand(0);
4847     MachineOperand &CarryDest = MI.getOperand(1);
4848     MachineOperand &Src0 = MI.getOperand(2);
4849     MachineOperand &Src1 = MI.getOperand(3);
4850     MachineOperand &Src2 = MI.getOperand(4);
4851     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4852                        ? AMDGPU::S_ADDC_U32
4853                        : AMDGPU::S_SUBB_U32;
4854     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4855       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4856       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4857           .addReg(Src0.getReg());
4858       Src0.setReg(RegOp0);
4859     }
4860     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4861       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4862       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4863           .addReg(Src1.getReg());
4864       Src1.setReg(RegOp1);
4865     }
4866     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4867     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4868       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4869           .addReg(Src2.getReg());
4870       Src2.setReg(RegOp2);
4871     }
4872 
4873     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4874     unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC);
4875     assert(WaveSize == 64 || WaveSize == 32);
4876 
4877     if (WaveSize == 64) {
4878       if (ST.hasScalarCompareEq64()) {
4879         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4880             .addReg(Src2.getReg())
4881             .addImm(0);
4882       } else {
4883         const TargetRegisterClass *SubRC =
4884             TRI->getSubRegisterClass(Src2RC, AMDGPU::sub0);
4885         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4886             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4887         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4888             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4889         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4890 
4891         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4892             .add(Src2Sub0)
4893             .add(Src2Sub1);
4894 
4895         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4896             .addReg(Src2_32, RegState::Kill)
4897             .addImm(0);
4898       }
4899     } else {
4900       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4901           .addReg(Src2.getReg())
4902           .addImm(0);
4903     }
4904 
4905     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4906 
4907     unsigned SelOpc =
4908         (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
4909 
4910     BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg())
4911         .addImm(-1)
4912         .addImm(0);
4913 
4914     MI.eraseFromParent();
4915     return BB;
4916   }
4917   case AMDGPU::SI_INIT_M0: {
4918     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4919             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4920         .add(MI.getOperand(0));
4921     MI.eraseFromParent();
4922     return BB;
4923   }
4924   case AMDGPU::GET_GROUPSTATICSIZE: {
4925     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4926            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4927     DebugLoc DL = MI.getDebugLoc();
4928     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4929         .add(MI.getOperand(0))
4930         .addImm(MFI->getLDSSize());
4931     MI.eraseFromParent();
4932     return BB;
4933   }
4934   case AMDGPU::GET_SHADERCYCLESHILO: {
4935     assert(MF->getSubtarget<GCNSubtarget>().hasShaderCyclesHiLoRegisters());
4936     MachineRegisterInfo &MRI = MF->getRegInfo();
4937     const DebugLoc &DL = MI.getDebugLoc();
4938     // The algorithm is:
4939     //
4940     // hi1 = getreg(SHADER_CYCLES_HI)
4941     // lo1 = getreg(SHADER_CYCLES_LO)
4942     // hi2 = getreg(SHADER_CYCLES_HI)
4943     //
4944     // If hi1 == hi2 then there was no overflow and the result is hi2:lo1.
4945     // Otherwise there was overflow and the result is hi2:0. In both cases the
4946     // result should represent the actual time at some point during the sequence
4947     // of three getregs.
4948     Register RegHi1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4949     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_GETREG_B32), RegHi1)
4950         .addImm(AMDGPU::Hwreg::encodeHwreg(AMDGPU::Hwreg::ID_SHADER_CYCLES_HI,
4951                                            0, 32));
4952     Register RegLo1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4953     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_GETREG_B32), RegLo1)
4954         .addImm(
4955             AMDGPU::Hwreg::encodeHwreg(AMDGPU::Hwreg::ID_SHADER_CYCLES, 0, 32));
4956     Register RegHi2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4957     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_GETREG_B32), RegHi2)
4958         .addImm(AMDGPU::Hwreg::encodeHwreg(AMDGPU::Hwreg::ID_SHADER_CYCLES_HI,
4959                                            0, 32));
4960     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CMP_EQ_U32))
4961         .addReg(RegHi1)
4962         .addReg(RegHi2);
4963     Register RegLo = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4964     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B32), RegLo)
4965         .addReg(RegLo1)
4966         .addImm(0);
4967     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE))
4968         .add(MI.getOperand(0))
4969         .addReg(RegLo)
4970         .addImm(AMDGPU::sub0)
4971         .addReg(RegHi2)
4972         .addImm(AMDGPU::sub1);
4973     MI.eraseFromParent();
4974     return BB;
4975   }
4976   case AMDGPU::SI_INDIRECT_SRC_V1:
4977   case AMDGPU::SI_INDIRECT_SRC_V2:
4978   case AMDGPU::SI_INDIRECT_SRC_V4:
4979   case AMDGPU::SI_INDIRECT_SRC_V8:
4980   case AMDGPU::SI_INDIRECT_SRC_V9:
4981   case AMDGPU::SI_INDIRECT_SRC_V10:
4982   case AMDGPU::SI_INDIRECT_SRC_V11:
4983   case AMDGPU::SI_INDIRECT_SRC_V12:
4984   case AMDGPU::SI_INDIRECT_SRC_V16:
4985   case AMDGPU::SI_INDIRECT_SRC_V32:
4986     return emitIndirectSrc(MI, *BB, *getSubtarget());
4987   case AMDGPU::SI_INDIRECT_DST_V1:
4988   case AMDGPU::SI_INDIRECT_DST_V2:
4989   case AMDGPU::SI_INDIRECT_DST_V4:
4990   case AMDGPU::SI_INDIRECT_DST_V8:
4991   case AMDGPU::SI_INDIRECT_DST_V9:
4992   case AMDGPU::SI_INDIRECT_DST_V10:
4993   case AMDGPU::SI_INDIRECT_DST_V11:
4994   case AMDGPU::SI_INDIRECT_DST_V12:
4995   case AMDGPU::SI_INDIRECT_DST_V16:
4996   case AMDGPU::SI_INDIRECT_DST_V32:
4997     return emitIndirectDst(MI, *BB, *getSubtarget());
4998   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4999   case AMDGPU::SI_KILL_I1_PSEUDO:
5000     return splitKillBlock(MI, BB);
5001   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
5002     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5003     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
5004     const SIRegisterInfo *TRI = ST.getRegisterInfo();
5005 
5006     Register Dst = MI.getOperand(0).getReg();
5007     const MachineOperand &Src0 = MI.getOperand(1);
5008     const MachineOperand &Src1 = MI.getOperand(2);
5009     const DebugLoc &DL = MI.getDebugLoc();
5010     Register SrcCond = MI.getOperand(3).getReg();
5011 
5012     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5013     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
5014     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
5015     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
5016 
5017     const TargetRegisterClass *Src0RC = Src0.isReg()
5018                                             ? MRI.getRegClass(Src0.getReg())
5019                                             : &AMDGPU::VReg_64RegClass;
5020     const TargetRegisterClass *Src1RC = Src1.isReg()
5021                                             ? MRI.getRegClass(Src1.getReg())
5022                                             : &AMDGPU::VReg_64RegClass;
5023 
5024     const TargetRegisterClass *Src0SubRC =
5025         TRI->getSubRegisterClass(Src0RC, AMDGPU::sub0);
5026     const TargetRegisterClass *Src1SubRC =
5027         TRI->getSubRegisterClass(Src1RC, AMDGPU::sub1);
5028 
5029     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
5030         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
5031     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
5032         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
5033 
5034     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
5035         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
5036     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
5037         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
5038 
5039     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
5040       .addReg(SrcCond);
5041     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
5042         .addImm(0)
5043         .add(Src0Sub0)
5044         .addImm(0)
5045         .add(Src1Sub0)
5046         .addReg(SrcCondCopy);
5047     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
5048         .addImm(0)
5049         .add(Src0Sub1)
5050         .addImm(0)
5051         .add(Src1Sub1)
5052         .addReg(SrcCondCopy);
5053 
5054     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
5055       .addReg(DstLo)
5056       .addImm(AMDGPU::sub0)
5057       .addReg(DstHi)
5058       .addImm(AMDGPU::sub1);
5059     MI.eraseFromParent();
5060     return BB;
5061   }
5062   case AMDGPU::SI_BR_UNDEF: {
5063     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
5064     const DebugLoc &DL = MI.getDebugLoc();
5065     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
5066                            .add(MI.getOperand(0));
5067     Br->getOperand(1).setIsUndef(); // read undef SCC
5068     MI.eraseFromParent();
5069     return BB;
5070   }
5071   case AMDGPU::ADJCALLSTACKUP:
5072   case AMDGPU::ADJCALLSTACKDOWN: {
5073     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
5074     MachineInstrBuilder MIB(*MF, &MI);
5075     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
5076        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
5077     return BB;
5078   }
5079   case AMDGPU::SI_CALL_ISEL: {
5080     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
5081     const DebugLoc &DL = MI.getDebugLoc();
5082 
5083     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
5084 
5085     MachineInstrBuilder MIB;
5086     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
5087 
5088     for (const MachineOperand &MO : MI.operands())
5089       MIB.add(MO);
5090 
5091     MIB.cloneMemRefs(MI);
5092     MI.eraseFromParent();
5093     return BB;
5094   }
5095   case AMDGPU::V_ADD_CO_U32_e32:
5096   case AMDGPU::V_SUB_CO_U32_e32:
5097   case AMDGPU::V_SUBREV_CO_U32_e32: {
5098     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
5099     const DebugLoc &DL = MI.getDebugLoc();
5100     unsigned Opc = MI.getOpcode();
5101 
5102     bool NeedClampOperand = false;
5103     if (TII->pseudoToMCOpcode(Opc) == -1) {
5104       Opc = AMDGPU::getVOPe64(Opc);
5105       NeedClampOperand = true;
5106     }
5107 
5108     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
5109     if (TII->isVOP3(*I)) {
5110       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
5111       const SIRegisterInfo *TRI = ST.getRegisterInfo();
5112       I.addReg(TRI->getVCC(), RegState::Define);
5113     }
5114     I.add(MI.getOperand(1))
5115      .add(MI.getOperand(2));
5116     if (NeedClampOperand)
5117       I.addImm(0); // clamp bit for e64 encoding
5118 
5119     TII->legalizeOperands(*I);
5120 
5121     MI.eraseFromParent();
5122     return BB;
5123   }
5124   case AMDGPU::V_ADDC_U32_e32:
5125   case AMDGPU::V_SUBB_U32_e32:
5126   case AMDGPU::V_SUBBREV_U32_e32:
5127     // These instructions have an implicit use of vcc which counts towards the
5128     // constant bus limit.
5129     TII->legalizeOperands(MI);
5130     return BB;
5131   case AMDGPU::DS_GWS_INIT:
5132   case AMDGPU::DS_GWS_SEMA_BR:
5133   case AMDGPU::DS_GWS_BARRIER:
5134     TII->enforceOperandRCAlignment(MI, AMDGPU::OpName::data0);
5135     [[fallthrough]];
5136   case AMDGPU::DS_GWS_SEMA_V:
5137   case AMDGPU::DS_GWS_SEMA_P:
5138   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
5139     // A s_waitcnt 0 is required to be the instruction immediately following.
5140     if (getSubtarget()->hasGWSAutoReplay()) {
5141       bundleInstWithWaitcnt(MI);
5142       return BB;
5143     }
5144 
5145     return emitGWSMemViolTestLoop(MI, BB);
5146   case AMDGPU::S_SETREG_B32: {
5147     // Try to optimize cases that only set the denormal mode or rounding mode.
5148     //
5149     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
5150     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
5151     // instead.
5152     //
5153     // FIXME: This could be predicates on the immediate, but tablegen doesn't
5154     // allow you to have a no side effect instruction in the output of a
5155     // sideeffecting pattern.
5156     unsigned ID, Offset, Width;
5157     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
5158     if (ID != AMDGPU::Hwreg::ID_MODE)
5159       return BB;
5160 
5161     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
5162     const unsigned SetMask = WidthMask << Offset;
5163 
5164     if (getSubtarget()->hasDenormModeInst()) {
5165       unsigned SetDenormOp = 0;
5166       unsigned SetRoundOp = 0;
5167 
5168       // The dedicated instructions can only set the whole denorm or round mode
5169       // at once, not a subset of bits in either.
5170       if (SetMask ==
5171           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
5172         // If this fully sets both the round and denorm mode, emit the two
5173         // dedicated instructions for these.
5174         SetRoundOp = AMDGPU::S_ROUND_MODE;
5175         SetDenormOp = AMDGPU::S_DENORM_MODE;
5176       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
5177         SetRoundOp = AMDGPU::S_ROUND_MODE;
5178       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
5179         SetDenormOp = AMDGPU::S_DENORM_MODE;
5180       }
5181 
5182       if (SetRoundOp || SetDenormOp) {
5183         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5184         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
5185         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
5186           unsigned ImmVal = Def->getOperand(1).getImm();
5187           if (SetRoundOp) {
5188             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
5189                 .addImm(ImmVal & 0xf);
5190 
5191             // If we also have the denorm mode, get just the denorm mode bits.
5192             ImmVal >>= 4;
5193           }
5194 
5195           if (SetDenormOp) {
5196             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
5197                 .addImm(ImmVal & 0xf);
5198           }
5199 
5200           MI.eraseFromParent();
5201           return BB;
5202         }
5203       }
5204     }
5205 
5206     // If only FP bits are touched, used the no side effects pseudo.
5207     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
5208                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
5209       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
5210 
5211     return BB;
5212   }
5213   case AMDGPU::S_INVERSE_BALLOT_U32:
5214   case AMDGPU::S_INVERSE_BALLOT_U64: {
5215     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5216     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
5217     const SIRegisterInfo *TRI = ST.getRegisterInfo();
5218     const DebugLoc &DL = MI.getDebugLoc();
5219     const Register DstReg = MI.getOperand(0).getReg();
5220     Register MaskReg = MI.getOperand(1).getReg();
5221 
5222     const bool IsVALU = TRI->isVectorRegister(MRI, MaskReg);
5223 
5224     if (IsVALU) {
5225       MaskReg = TII->readlaneVGPRToSGPR(MaskReg, MI, MRI);
5226     }
5227 
5228     BuildMI(*BB, &MI, DL, TII->get(AMDGPU::COPY), DstReg).addReg(MaskReg);
5229     MI.eraseFromParent();
5230     return BB;
5231   }
5232   case AMDGPU::ENDPGM_TRAP: {
5233     const DebugLoc &DL = MI.getDebugLoc();
5234     if (BB->succ_empty() && std::next(MI.getIterator()) == BB->end()) {
5235       MI.setDesc(TII->get(AMDGPU::S_ENDPGM));
5236       MI.addOperand(MachineOperand::CreateImm(0));
5237       return BB;
5238     }
5239 
5240     // We need a block split to make the real endpgm a terminator. We also don't
5241     // want to break phis in successor blocks, so we can't just delete to the
5242     // end of the block.
5243 
5244     MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
5245     MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
5246     MF->push_back(TrapBB);
5247     BuildMI(*TrapBB, TrapBB->end(), DL, TII->get(AMDGPU::S_ENDPGM))
5248       .addImm(0);
5249     BuildMI(*BB, &MI, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
5250       .addMBB(TrapBB);
5251 
5252     BB->addSuccessor(TrapBB);
5253     MI.eraseFromParent();
5254     return SplitBB;
5255   }
5256   default:
5257     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
5258   }
5259 }
5260 
5261 bool SITargetLowering::hasAtomicFaddRtnForTy(SDValue &Op) const {
5262   switch (Op.getValue(0).getSimpleValueType().SimpleTy) {
5263   case MVT::f32:
5264     return Subtarget->hasAtomicFaddRtnInsts();
5265   case MVT::v2f16:
5266   case MVT::f64:
5267     return Subtarget->hasGFX90AInsts();
5268   default:
5269     return false;
5270   }
5271 }
5272 
5273 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
5274   // This currently forces unfolding various combinations of fsub into fma with
5275   // free fneg'd operands. As long as we have fast FMA (controlled by
5276   // isFMAFasterThanFMulAndFAdd), we should perform these.
5277 
5278   // When fma is quarter rate, for f64 where add / sub are at best half rate,
5279   // most of these combines appear to be cycle neutral but save on instruction
5280   // count / code size.
5281   return true;
5282 }
5283 
5284 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; }
5285 
5286 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
5287                                          EVT VT) const {
5288   if (!VT.isVector()) {
5289     return MVT::i1;
5290   }
5291   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
5292 }
5293 
5294 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
5295   // TODO: Should i16 be used always if legal? For now it would force VALU
5296   // shifts.
5297   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
5298 }
5299 
5300 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
5301   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
5302              ? Ty.changeElementSize(16)
5303              : Ty.changeElementSize(32);
5304 }
5305 
5306 // Answering this is somewhat tricky and depends on the specific device which
5307 // have different rates for fma or all f64 operations.
5308 //
5309 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
5310 // regardless of which device (although the number of cycles differs between
5311 // devices), so it is always profitable for f64.
5312 //
5313 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
5314 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
5315 // which we can always do even without fused FP ops since it returns the same
5316 // result as the separate operations and since it is always full
5317 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
5318 // however does not support denormals, so we do report fma as faster if we have
5319 // a fast fma device and require denormals.
5320 //
5321 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
5322                                                   EVT VT) const {
5323   VT = VT.getScalarType();
5324 
5325   switch (VT.getSimpleVT().SimpleTy) {
5326   case MVT::f32: {
5327     // If mad is not available this depends only on if f32 fma is full rate.
5328     if (!Subtarget->hasMadMacF32Insts())
5329       return Subtarget->hasFastFMAF32();
5330 
5331     // Otherwise f32 mad is always full rate and returns the same result as
5332     // the separate operations so should be preferred over fma.
5333     // However does not support denormals.
5334     if (!denormalModeIsFlushAllF32(MF))
5335       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
5336 
5337     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
5338     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
5339   }
5340   case MVT::f64:
5341     return true;
5342   case MVT::f16:
5343     return Subtarget->has16BitInsts() && !denormalModeIsFlushAllF64F16(MF);
5344   default:
5345     break;
5346   }
5347 
5348   return false;
5349 }
5350 
5351 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
5352                                                   LLT Ty) const {
5353   switch (Ty.getScalarSizeInBits()) {
5354   case 16:
5355     return isFMAFasterThanFMulAndFAdd(MF, MVT::f16);
5356   case 32:
5357     return isFMAFasterThanFMulAndFAdd(MF, MVT::f32);
5358   case 64:
5359     return isFMAFasterThanFMulAndFAdd(MF, MVT::f64);
5360   default:
5361     break;
5362   }
5363 
5364   return false;
5365 }
5366 
5367 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const {
5368   if (!Ty.isScalar())
5369     return false;
5370 
5371   if (Ty.getScalarSizeInBits() == 16)
5372     return Subtarget->hasMadF16() && denormalModeIsFlushAllF64F16(*MI.getMF());
5373   if (Ty.getScalarSizeInBits() == 32)
5374     return Subtarget->hasMadMacF32Insts() &&
5375            denormalModeIsFlushAllF32(*MI.getMF());
5376 
5377   return false;
5378 }
5379 
5380 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
5381                                    const SDNode *N) const {
5382   // TODO: Check future ftz flag
5383   // v_mad_f32/v_mac_f32 do not support denormals.
5384   EVT VT = N->getValueType(0);
5385   if (VT == MVT::f32)
5386     return Subtarget->hasMadMacF32Insts() &&
5387            denormalModeIsFlushAllF32(DAG.getMachineFunction());
5388   if (VT == MVT::f16) {
5389     return Subtarget->hasMadF16() &&
5390            denormalModeIsFlushAllF64F16(DAG.getMachineFunction());
5391   }
5392 
5393   return false;
5394 }
5395 
5396 //===----------------------------------------------------------------------===//
5397 // Custom DAG Lowering Operations
5398 //===----------------------------------------------------------------------===//
5399 
5400 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
5401 // wider vector type is legal.
5402 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
5403                                              SelectionDAG &DAG) const {
5404   unsigned Opc = Op.getOpcode();
5405   EVT VT = Op.getValueType();
5406   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
5407          VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i16 ||
5408          VT == MVT::v16f16 || VT == MVT::v8f32 || VT == MVT::v16f32 ||
5409          VT == MVT::v32f32 || VT == MVT::v32i16 || VT == MVT::v32f16);
5410 
5411   SDValue Lo, Hi;
5412   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5413 
5414   SDLoc SL(Op);
5415   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
5416                              Op->getFlags());
5417   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
5418                              Op->getFlags());
5419 
5420   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
5421 }
5422 
5423 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
5424 // wider vector type is legal.
5425 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
5426                                               SelectionDAG &DAG) const {
5427   unsigned Opc = Op.getOpcode();
5428   EVT VT = Op.getValueType();
5429   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
5430          VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i16 ||
5431          VT == MVT::v16f16 || VT == MVT::v8f32 || VT == MVT::v16f32 ||
5432          VT == MVT::v32f32 || VT == MVT::v32i16 || VT == MVT::v32f16);
5433 
5434   SDValue Lo0, Hi0;
5435   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
5436   SDValue Lo1, Hi1;
5437   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
5438 
5439   SDLoc SL(Op);
5440 
5441   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
5442                              Op->getFlags());
5443   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
5444                              Op->getFlags());
5445 
5446   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
5447 }
5448 
5449 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
5450                                               SelectionDAG &DAG) const {
5451   unsigned Opc = Op.getOpcode();
5452   EVT VT = Op.getValueType();
5453   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 ||
5454          VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v16i16 ||
5455          VT == MVT::v16f16 || VT == MVT::v8f32 || VT == MVT::v16f32 ||
5456          VT == MVT::v32f32 || VT == MVT::v32f16 || VT == MVT::v32i16 ||
5457          VT == MVT::v4bf16 || VT == MVT::v8bf16 || VT == MVT::v16bf16 ||
5458          VT == MVT::v32bf16);
5459 
5460   SDValue Lo0, Hi0;
5461   SDValue Op0 = Op.getOperand(0);
5462   std::tie(Lo0, Hi0) = Op0.getValueType().isVector()
5463                            ? DAG.SplitVectorOperand(Op.getNode(), 0)
5464                            : std::pair(Op0, Op0);
5465   SDValue Lo1, Hi1;
5466   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
5467   SDValue Lo2, Hi2;
5468   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
5469 
5470   SDLoc SL(Op);
5471   auto ResVT = DAG.GetSplitDestVTs(VT);
5472 
5473   SDValue OpLo = DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2,
5474                              Op->getFlags());
5475   SDValue OpHi = DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2,
5476                              Op->getFlags());
5477 
5478   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
5479 }
5480 
5481 
5482 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5483   switch (Op.getOpcode()) {
5484   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
5485   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
5486   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5487   case ISD::LOAD: {
5488     SDValue Result = LowerLOAD(Op, DAG);
5489     assert((!Result.getNode() ||
5490             Result.getNode()->getNumValues() == 2) &&
5491            "Load should return a value and a chain");
5492     return Result;
5493   }
5494   case ISD::FSQRT: {
5495     EVT VT = Op.getValueType();
5496     if (VT == MVT::f32)
5497       return lowerFSQRTF32(Op, DAG);
5498     if (VT == MVT::f64)
5499       return lowerFSQRTF64(Op, DAG);
5500     return SDValue();
5501   }
5502   case ISD::FSIN:
5503   case ISD::FCOS:
5504     return LowerTrig(Op, DAG);
5505   case ISD::SELECT: return LowerSELECT(Op, DAG);
5506   case ISD::FDIV: return LowerFDIV(Op, DAG);
5507   case ISD::FFREXP: return LowerFFREXP(Op, DAG);
5508   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
5509   case ISD::STORE: return LowerSTORE(Op, DAG);
5510   case ISD::GlobalAddress: {
5511     MachineFunction &MF = DAG.getMachineFunction();
5512     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
5513     return LowerGlobalAddress(MFI, Op, DAG);
5514   }
5515   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5516   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
5517   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
5518   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
5519   case ISD::INSERT_SUBVECTOR:
5520     return lowerINSERT_SUBVECTOR(Op, DAG);
5521   case ISD::INSERT_VECTOR_ELT:
5522     return lowerINSERT_VECTOR_ELT(Op, DAG);
5523   case ISD::EXTRACT_VECTOR_ELT:
5524     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
5525   case ISD::VECTOR_SHUFFLE:
5526     return lowerVECTOR_SHUFFLE(Op, DAG);
5527   case ISD::SCALAR_TO_VECTOR:
5528     return lowerSCALAR_TO_VECTOR(Op, DAG);
5529   case ISD::BUILD_VECTOR:
5530     return lowerBUILD_VECTOR(Op, DAG);
5531   case ISD::FP_ROUND:
5532   case ISD::STRICT_FP_ROUND:
5533     return lowerFP_ROUND(Op, DAG);
5534   case ISD::FPTRUNC_ROUND: {
5535     unsigned Opc;
5536     SDLoc DL(Op);
5537 
5538     if (Op.getOperand(0)->getValueType(0) != MVT::f32)
5539       return SDValue();
5540 
5541     // Get the rounding mode from the last operand
5542     int RoundMode = Op.getConstantOperandVal(1);
5543     if (RoundMode == (int)RoundingMode::TowardPositive)
5544       Opc = AMDGPUISD::FPTRUNC_ROUND_UPWARD;
5545     else if (RoundMode == (int)RoundingMode::TowardNegative)
5546       Opc = AMDGPUISD::FPTRUNC_ROUND_DOWNWARD;
5547     else
5548       return SDValue();
5549 
5550     return DAG.getNode(Opc, DL, Op.getNode()->getVTList(), Op->getOperand(0));
5551   }
5552   case ISD::TRAP:
5553     return lowerTRAP(Op, DAG);
5554   case ISD::DEBUGTRAP:
5555     return lowerDEBUGTRAP(Op, DAG);
5556   case ISD::FABS:
5557   case ISD::FNEG:
5558   case ISD::FCANONICALIZE:
5559   case ISD::BSWAP:
5560     return splitUnaryVectorOp(Op, DAG);
5561   case ISD::FMINNUM:
5562   case ISD::FMAXNUM:
5563     return lowerFMINNUM_FMAXNUM(Op, DAG);
5564   case ISD::FLDEXP:
5565   case ISD::STRICT_FLDEXP:
5566     return lowerFLDEXP(Op, DAG);
5567   case ISD::FMA:
5568     return splitTernaryVectorOp(Op, DAG);
5569   case ISD::FP_TO_SINT:
5570   case ISD::FP_TO_UINT:
5571     return LowerFP_TO_INT(Op, DAG);
5572   case ISD::SHL:
5573   case ISD::SRA:
5574   case ISD::SRL:
5575   case ISD::ADD:
5576   case ISD::SUB:
5577   case ISD::SMIN:
5578   case ISD::SMAX:
5579   case ISD::UMIN:
5580   case ISD::UMAX:
5581   case ISD::FADD:
5582   case ISD::FMUL:
5583   case ISD::FMINNUM_IEEE:
5584   case ISD::FMAXNUM_IEEE:
5585   case ISD::UADDSAT:
5586   case ISD::USUBSAT:
5587   case ISD::SADDSAT:
5588   case ISD::SSUBSAT:
5589     return splitBinaryVectorOp(Op, DAG);
5590   case ISD::MUL:
5591     return lowerMUL(Op, DAG);
5592   case ISD::SMULO:
5593   case ISD::UMULO:
5594     return lowerXMULO(Op, DAG);
5595   case ISD::SMUL_LOHI:
5596   case ISD::UMUL_LOHI:
5597     return lowerXMUL_LOHI(Op, DAG);
5598   case ISD::DYNAMIC_STACKALLOC:
5599     return LowerDYNAMIC_STACKALLOC(Op, DAG);
5600   case ISD::STACKSAVE:
5601     return LowerSTACKSAVE(Op, DAG);
5602   case ISD::GET_ROUNDING:
5603     return lowerGET_ROUNDING(Op, DAG);
5604   case ISD::PREFETCH:
5605     return lowerPREFETCH(Op, DAG);
5606   case ISD::FP_EXTEND:
5607   case ISD::STRICT_FP_EXTEND:
5608     return lowerFP_EXTEND(Op, DAG);
5609   }
5610   return SDValue();
5611 }
5612 
5613 // Used for D16: Casts the result of an instruction into the right vector,
5614 // packs values if loads return unpacked values.
5615 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
5616                                        const SDLoc &DL,
5617                                        SelectionDAG &DAG, bool Unpacked) {
5618   if (!LoadVT.isVector())
5619     return Result;
5620 
5621   // Cast back to the original packed type or to a larger type that is a
5622   // multiple of 32 bit for D16. Widening the return type is a required for
5623   // legalization.
5624   EVT FittingLoadVT = LoadVT;
5625   if ((LoadVT.getVectorNumElements() % 2) == 1) {
5626     FittingLoadVT =
5627         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
5628                          LoadVT.getVectorNumElements() + 1);
5629   }
5630 
5631   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
5632     // Truncate to v2i16/v4i16.
5633     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
5634 
5635     // Workaround legalizer not scalarizing truncate after vector op
5636     // legalization but not creating intermediate vector trunc.
5637     SmallVector<SDValue, 4> Elts;
5638     DAG.ExtractVectorElements(Result, Elts);
5639     for (SDValue &Elt : Elts)
5640       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
5641 
5642     // Pad illegal v1i16/v3fi6 to v4i16
5643     if ((LoadVT.getVectorNumElements() % 2) == 1)
5644       Elts.push_back(DAG.getUNDEF(MVT::i16));
5645 
5646     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
5647 
5648     // Bitcast to original type (v2f16/v4f16).
5649     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
5650   }
5651 
5652   // Cast back to the original packed type.
5653   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
5654 }
5655 
5656 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
5657                                               MemSDNode *M,
5658                                               SelectionDAG &DAG,
5659                                               ArrayRef<SDValue> Ops,
5660                                               bool IsIntrinsic) const {
5661   SDLoc DL(M);
5662 
5663   bool Unpacked = Subtarget->hasUnpackedD16VMem();
5664   EVT LoadVT = M->getValueType(0);
5665 
5666   EVT EquivLoadVT = LoadVT;
5667   if (LoadVT.isVector()) {
5668     if (Unpacked) {
5669       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
5670                                      LoadVT.getVectorNumElements());
5671     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
5672       // Widen v3f16 to legal type
5673       EquivLoadVT =
5674           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
5675                            LoadVT.getVectorNumElements() + 1);
5676     }
5677   }
5678 
5679   // Change from v4f16/v2f16 to EquivLoadVT.
5680   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
5681 
5682   SDValue Load
5683     = DAG.getMemIntrinsicNode(
5684       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
5685       VTList, Ops, M->getMemoryVT(),
5686       M->getMemOperand());
5687 
5688   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
5689 
5690   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
5691 }
5692 
5693 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
5694                                              SelectionDAG &DAG,
5695                                              ArrayRef<SDValue> Ops) const {
5696   SDLoc DL(M);
5697   EVT LoadVT = M->getValueType(0);
5698   EVT EltType = LoadVT.getScalarType();
5699   EVT IntVT = LoadVT.changeTypeToInteger();
5700 
5701   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
5702 
5703   assert(M->getNumValues() == 2 || M->getNumValues() == 3);
5704   bool IsTFE = M->getNumValues() == 3;
5705 
5706   unsigned Opc;
5707   if (IsFormat) {
5708     Opc = IsTFE ? AMDGPUISD::BUFFER_LOAD_FORMAT_TFE
5709                 : AMDGPUISD::BUFFER_LOAD_FORMAT;
5710   } else {
5711     // TODO: Support non-format TFE loads.
5712     if (IsTFE)
5713       return SDValue();
5714     Opc = AMDGPUISD::BUFFER_LOAD;
5715   }
5716 
5717   if (IsD16) {
5718     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
5719   }
5720 
5721   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
5722   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
5723     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
5724 
5725   if (isTypeLegal(LoadVT)) {
5726     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
5727                                M->getMemOperand(), DAG);
5728   }
5729 
5730   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
5731   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
5732   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
5733                                         M->getMemOperand(), DAG);
5734   return DAG.getMergeValues(
5735       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
5736       DL);
5737 }
5738 
5739 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
5740                                   SDNode *N, SelectionDAG &DAG) {
5741   EVT VT = N->getValueType(0);
5742   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
5743   unsigned CondCode = CD->getZExtValue();
5744   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
5745     return DAG.getUNDEF(VT);
5746 
5747   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
5748 
5749   SDValue LHS = N->getOperand(1);
5750   SDValue RHS = N->getOperand(2);
5751 
5752   SDLoc DL(N);
5753 
5754   EVT CmpVT = LHS.getValueType();
5755   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
5756     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
5757       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5758     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
5759     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
5760   }
5761 
5762   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
5763 
5764   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
5765   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
5766 
5767   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
5768                               DAG.getCondCode(CCOpcode));
5769   if (VT.bitsEq(CCVT))
5770     return SetCC;
5771   return DAG.getZExtOrTrunc(SetCC, DL, VT);
5772 }
5773 
5774 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
5775                                   SDNode *N, SelectionDAG &DAG) {
5776   EVT VT = N->getValueType(0);
5777   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
5778 
5779   unsigned CondCode = CD->getZExtValue();
5780   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
5781     return DAG.getUNDEF(VT);
5782 
5783   SDValue Src0 = N->getOperand(1);
5784   SDValue Src1 = N->getOperand(2);
5785   EVT CmpVT = Src0.getValueType();
5786   SDLoc SL(N);
5787 
5788   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
5789     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
5790     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
5791   }
5792 
5793   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
5794   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
5795   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
5796   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
5797   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
5798                               Src1, DAG.getCondCode(CCOpcode));
5799   if (VT.bitsEq(CCVT))
5800     return SetCC;
5801   return DAG.getZExtOrTrunc(SetCC, SL, VT);
5802 }
5803 
5804 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
5805                                     SelectionDAG &DAG) {
5806   EVT VT = N->getValueType(0);
5807   SDValue Src = N->getOperand(1);
5808   SDLoc SL(N);
5809 
5810   if (Src.getOpcode() == ISD::SETCC) {
5811     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
5812     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
5813                        Src.getOperand(1), Src.getOperand(2));
5814   }
5815   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
5816     // (ballot 0) -> 0
5817     if (Arg->isZero())
5818       return DAG.getConstant(0, SL, VT);
5819 
5820     // (ballot 1) -> EXEC/EXEC_LO
5821     if (Arg->isOne()) {
5822       Register Exec;
5823       if (VT.getScalarSizeInBits() == 32)
5824         Exec = AMDGPU::EXEC_LO;
5825       else if (VT.getScalarSizeInBits() == 64)
5826         Exec = AMDGPU::EXEC;
5827       else
5828         return SDValue();
5829 
5830       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
5831     }
5832   }
5833 
5834   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
5835   // ISD::SETNE)
5836   return DAG.getNode(
5837       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
5838       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
5839 }
5840 
5841 void SITargetLowering::ReplaceNodeResults(SDNode *N,
5842                                           SmallVectorImpl<SDValue> &Results,
5843                                           SelectionDAG &DAG) const {
5844   switch (N->getOpcode()) {
5845   case ISD::INSERT_VECTOR_ELT: {
5846     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
5847       Results.push_back(Res);
5848     return;
5849   }
5850   case ISD::EXTRACT_VECTOR_ELT: {
5851     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
5852       Results.push_back(Res);
5853     return;
5854   }
5855   case ISD::INTRINSIC_WO_CHAIN: {
5856     unsigned IID = N->getConstantOperandVal(0);
5857     switch (IID) {
5858     case Intrinsic::amdgcn_make_buffer_rsrc:
5859       Results.push_back(lowerPointerAsRsrcIntrin(N, DAG));
5860       return;
5861     case Intrinsic::amdgcn_cvt_pkrtz: {
5862       SDValue Src0 = N->getOperand(1);
5863       SDValue Src1 = N->getOperand(2);
5864       SDLoc SL(N);
5865       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
5866                                 Src0, Src1);
5867       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
5868       return;
5869     }
5870     case Intrinsic::amdgcn_cvt_pknorm_i16:
5871     case Intrinsic::amdgcn_cvt_pknorm_u16:
5872     case Intrinsic::amdgcn_cvt_pk_i16:
5873     case Intrinsic::amdgcn_cvt_pk_u16: {
5874       SDValue Src0 = N->getOperand(1);
5875       SDValue Src1 = N->getOperand(2);
5876       SDLoc SL(N);
5877       unsigned Opcode;
5878 
5879       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
5880         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
5881       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
5882         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
5883       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
5884         Opcode = AMDGPUISD::CVT_PK_I16_I32;
5885       else
5886         Opcode = AMDGPUISD::CVT_PK_U16_U32;
5887 
5888       EVT VT = N->getValueType(0);
5889       if (isTypeLegal(VT))
5890         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
5891       else {
5892         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
5893         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
5894       }
5895       return;
5896     }
5897     }
5898     break;
5899   }
5900   case ISD::INTRINSIC_W_CHAIN: {
5901     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
5902       if (Res.getOpcode() == ISD::MERGE_VALUES) {
5903         // FIXME: Hacky
5904         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
5905           Results.push_back(Res.getOperand(I));
5906         }
5907       } else {
5908         Results.push_back(Res);
5909         Results.push_back(Res.getValue(1));
5910       }
5911       return;
5912     }
5913 
5914     break;
5915   }
5916   case ISD::SELECT: {
5917     SDLoc SL(N);
5918     EVT VT = N->getValueType(0);
5919     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
5920     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
5921     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
5922 
5923     EVT SelectVT = NewVT;
5924     if (NewVT.bitsLT(MVT::i32)) {
5925       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
5926       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
5927       SelectVT = MVT::i32;
5928     }
5929 
5930     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
5931                                     N->getOperand(0), LHS, RHS);
5932 
5933     if (NewVT != SelectVT)
5934       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
5935     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
5936     return;
5937   }
5938   case ISD::FNEG: {
5939     if (N->getValueType(0) != MVT::v2f16)
5940       break;
5941 
5942     SDLoc SL(N);
5943     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5944 
5945     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
5946                              BC,
5947                              DAG.getConstant(0x80008000, SL, MVT::i32));
5948     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5949     return;
5950   }
5951   case ISD::FABS: {
5952     if (N->getValueType(0) != MVT::v2f16)
5953       break;
5954 
5955     SDLoc SL(N);
5956     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5957 
5958     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
5959                              BC,
5960                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
5961     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5962     return;
5963   }
5964   case ISD::FSQRT: {
5965     if (N->getValueType(0) != MVT::f16)
5966       break;
5967     Results.push_back(lowerFSQRTF16(SDValue(N, 0), DAG));
5968     break;
5969   }
5970   default:
5971     AMDGPUTargetLowering::ReplaceNodeResults(N, Results, DAG);
5972     break;
5973   }
5974 }
5975 
5976 /// Helper function for LowerBRCOND
5977 static SDNode *findUser(SDValue Value, unsigned Opcode) {
5978 
5979   SDNode *Parent = Value.getNode();
5980   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
5981        I != E; ++I) {
5982 
5983     if (I.getUse().get() != Value)
5984       continue;
5985 
5986     if (I->getOpcode() == Opcode)
5987       return *I;
5988   }
5989   return nullptr;
5990 }
5991 
5992 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
5993   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
5994     switch (Intr->getConstantOperandVal(1)) {
5995     case Intrinsic::amdgcn_if:
5996       return AMDGPUISD::IF;
5997     case Intrinsic::amdgcn_else:
5998       return AMDGPUISD::ELSE;
5999     case Intrinsic::amdgcn_loop:
6000       return AMDGPUISD::LOOP;
6001     case Intrinsic::amdgcn_end_cf:
6002       llvm_unreachable("should not occur");
6003     default:
6004       return 0;
6005     }
6006   }
6007 
6008   // break, if_break, else_break are all only used as inputs to loop, not
6009   // directly as branch conditions.
6010   return 0;
6011 }
6012 
6013 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
6014   const Triple &TT = getTargetMachine().getTargetTriple();
6015   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
6016           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
6017          AMDGPU::shouldEmitConstantsToTextSection(TT);
6018 }
6019 
6020 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
6021   if (Subtarget->isAmdPalOS() || Subtarget->isMesa3DOS())
6022     return false;
6023 
6024   // FIXME: Either avoid relying on address space here or change the default
6025   // address space for functions to avoid the explicit check.
6026   return (GV->getValueType()->isFunctionTy() ||
6027           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
6028          !shouldEmitFixup(GV) &&
6029          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
6030 }
6031 
6032 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
6033   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
6034 }
6035 
6036 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
6037   if (!GV->hasExternalLinkage())
6038     return true;
6039 
6040   const auto OS = getTargetMachine().getTargetTriple().getOS();
6041   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
6042 }
6043 
6044 /// This transforms the control flow intrinsics to get the branch destination as
6045 /// last parameter, also switches branch target with BR if the need arise
6046 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
6047                                       SelectionDAG &DAG) const {
6048   SDLoc DL(BRCOND);
6049 
6050   SDNode *Intr = BRCOND.getOperand(1).getNode();
6051   SDValue Target = BRCOND.getOperand(2);
6052   SDNode *BR = nullptr;
6053   SDNode *SetCC = nullptr;
6054 
6055   if (Intr->getOpcode() == ISD::SETCC) {
6056     // As long as we negate the condition everything is fine
6057     SetCC = Intr;
6058     Intr = SetCC->getOperand(0).getNode();
6059 
6060   } else {
6061     // Get the target from BR if we don't negate the condition
6062     BR = findUser(BRCOND, ISD::BR);
6063     assert(BR && "brcond missing unconditional branch user");
6064     Target = BR->getOperand(1);
6065   }
6066 
6067   unsigned CFNode = isCFIntrinsic(Intr);
6068   if (CFNode == 0) {
6069     // This is a uniform branch so we don't need to legalize.
6070     return BRCOND;
6071   }
6072 
6073   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
6074                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
6075 
6076   assert(!SetCC ||
6077         (SetCC->getConstantOperandVal(1) == 1 &&
6078          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
6079                                                              ISD::SETNE));
6080 
6081   // operands of the new intrinsic call
6082   SmallVector<SDValue, 4> Ops;
6083   if (HaveChain)
6084     Ops.push_back(BRCOND.getOperand(0));
6085 
6086   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
6087   Ops.push_back(Target);
6088 
6089   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
6090 
6091   // build the new intrinsic call
6092   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
6093 
6094   if (!HaveChain) {
6095     SDValue Ops[] =  {
6096       SDValue(Result, 0),
6097       BRCOND.getOperand(0)
6098     };
6099 
6100     Result = DAG.getMergeValues(Ops, DL).getNode();
6101   }
6102 
6103   if (BR) {
6104     // Give the branch instruction our target
6105     SDValue Ops[] = {
6106       BR->getOperand(0),
6107       BRCOND.getOperand(2)
6108     };
6109     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
6110     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
6111   }
6112 
6113   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
6114 
6115   // Copy the intrinsic results to registers
6116   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
6117     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
6118     if (!CopyToReg)
6119       continue;
6120 
6121     Chain = DAG.getCopyToReg(
6122       Chain, DL,
6123       CopyToReg->getOperand(1),
6124       SDValue(Result, i - 1),
6125       SDValue());
6126 
6127     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
6128   }
6129 
6130   // Remove the old intrinsic from the chain
6131   DAG.ReplaceAllUsesOfValueWith(
6132     SDValue(Intr, Intr->getNumValues() - 1),
6133     Intr->getOperand(0));
6134 
6135   return Chain;
6136 }
6137 
6138 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
6139                                           SelectionDAG &DAG) const {
6140   MVT VT = Op.getSimpleValueType();
6141   SDLoc DL(Op);
6142   // Checking the depth
6143   if (Op.getConstantOperandVal(0) != 0)
6144     return DAG.getConstant(0, DL, VT);
6145 
6146   MachineFunction &MF = DAG.getMachineFunction();
6147   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
6148   // Check for kernel and shader functions
6149   if (Info->isEntryFunction())
6150     return DAG.getConstant(0, DL, VT);
6151 
6152   MachineFrameInfo &MFI = MF.getFrameInfo();
6153   // There is a call to @llvm.returnaddress in this function
6154   MFI.setReturnAddressIsTaken(true);
6155 
6156   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
6157   // Get the return address reg and mark it as an implicit live-in
6158   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
6159 
6160   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
6161 }
6162 
6163 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
6164                                             SDValue Op,
6165                                             const SDLoc &DL,
6166                                             EVT VT) const {
6167   return Op.getValueType().bitsLE(VT) ?
6168       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
6169     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
6170                 DAG.getTargetConstant(0, DL, MVT::i32));
6171 }
6172 
6173 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
6174   assert(Op.getValueType() == MVT::f16 &&
6175          "Do not know how to custom lower FP_ROUND for non-f16 type");
6176 
6177   SDValue Src = Op.getOperand(0);
6178   EVT SrcVT = Src.getValueType();
6179   if (SrcVT != MVT::f64)
6180     return Op;
6181 
6182   // TODO: Handle strictfp
6183   if (Op.getOpcode() != ISD::FP_ROUND)
6184     return Op;
6185 
6186   SDLoc DL(Op);
6187 
6188   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
6189   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
6190   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
6191 }
6192 
6193 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
6194                                                SelectionDAG &DAG) const {
6195   EVT VT = Op.getValueType();
6196   const MachineFunction &MF = DAG.getMachineFunction();
6197   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
6198   bool IsIEEEMode = Info->getMode().IEEE;
6199 
6200   // FIXME: Assert during selection that this is only selected for
6201   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
6202   // mode functions, but this happens to be OK since it's only done in cases
6203   // where there is known no sNaN.
6204   if (IsIEEEMode)
6205     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
6206 
6207   if (VT == MVT::v4f16 || VT == MVT::v8f16 || VT == MVT::v16f16 ||
6208       VT == MVT::v16f16)
6209     return splitBinaryVectorOp(Op, DAG);
6210   return Op;
6211 }
6212 
6213 SDValue SITargetLowering::lowerFLDEXP(SDValue Op, SelectionDAG &DAG) const {
6214   bool IsStrict = Op.getOpcode() == ISD::STRICT_FLDEXP;
6215   EVT VT = Op.getValueType();
6216   assert(VT == MVT::f16);
6217 
6218   SDValue Exp = Op.getOperand(IsStrict ? 2 : 1);
6219   EVT ExpVT = Exp.getValueType();
6220   if (ExpVT == MVT::i16)
6221     return Op;
6222 
6223   SDLoc DL(Op);
6224 
6225   // Correct the exponent type for f16 to i16.
6226   // Clamp the range of the exponent to the instruction's range.
6227 
6228   // TODO: This should be a generic narrowing legalization, and can easily be
6229   // for GlobalISel.
6230 
6231   SDValue MinExp = DAG.getConstant(minIntN(16), DL, ExpVT);
6232   SDValue ClampMin = DAG.getNode(ISD::SMAX, DL, ExpVT, Exp, MinExp);
6233 
6234   SDValue MaxExp = DAG.getConstant(maxIntN(16), DL, ExpVT);
6235   SDValue Clamp = DAG.getNode(ISD::SMIN, DL, ExpVT, ClampMin, MaxExp);
6236 
6237   SDValue TruncExp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Clamp);
6238 
6239   if (IsStrict) {
6240     return DAG.getNode(ISD::STRICT_FLDEXP, DL, {VT, MVT::Other},
6241                        {Op.getOperand(0), Op.getOperand(1), TruncExp});
6242   }
6243 
6244   return DAG.getNode(ISD::FLDEXP, DL, VT, Op.getOperand(0), TruncExp);
6245 }
6246 
6247 // Custom lowering for vector multiplications and s_mul_u64.
6248 SDValue SITargetLowering::lowerMUL(SDValue Op, SelectionDAG &DAG) const {
6249   EVT VT = Op.getValueType();
6250 
6251   // Split vector operands.
6252   if (VT.isVector())
6253     return splitBinaryVectorOp(Op, DAG);
6254 
6255   assert(VT == MVT::i64 && "The following code is a special for s_mul_u64");
6256 
6257   // There are four ways to lower s_mul_u64:
6258   //
6259   // 1. If all the operands are uniform, then we lower it as it is.
6260   //
6261   // 2. If the operands are divergent, then we have to split s_mul_u64 in 32-bit
6262   //    multiplications because there is not a vector equivalent of s_mul_u64.
6263   //
6264   // 3. If the cost model decides that it is more efficient to use vector
6265   //    registers, then we have to split s_mul_u64 in 32-bit multiplications.
6266   //    This happens in splitScalarSMULU64() in SIInstrInfo.cpp .
6267   //
6268   // 4. If the cost model decides to use vector registers and both of the
6269   //    operands are zero-extended/sign-extended from 32-bits, then we split the
6270   //    s_mul_u64 in two 32-bit multiplications. The problem is that it is not
6271   //    possible to check if the operands are zero-extended or sign-extended in
6272   //    SIInstrInfo.cpp. For this reason, here, we replace s_mul_u64 with
6273   //    s_mul_u64_u32_pseudo if both operands are zero-extended and we replace
6274   //    s_mul_u64 with s_mul_i64_i32_pseudo if both operands are sign-extended.
6275   //    If the cost model decides that we have to use vector registers, then
6276   //    splitScalarSMulPseudo() (in SIInstrInfo.cpp) split s_mul_u64_u32/
6277   //    s_mul_i64_i32_pseudo in two vector multiplications. If the cost model
6278   //    decides that we should use scalar registers, then s_mul_u64_u32_pseudo/
6279   //    s_mul_i64_i32_pseudo is lowered as s_mul_u64 in expandPostRAPseudo() in
6280   //    SIInstrInfo.cpp .
6281 
6282   if (Op->isDivergent())
6283     return SDValue();
6284 
6285   SDValue Op0 = Op.getOperand(0);
6286   SDValue Op1 = Op.getOperand(1);
6287   // If all the operands are zero-enteted to 32-bits, then we replace s_mul_u64
6288   // with s_mul_u64_u32_pseudo. If all the operands are sign-extended to
6289   // 32-bits, then we replace s_mul_u64 with s_mul_i64_i32_pseudo.
6290   KnownBits Op0KnownBits = DAG.computeKnownBits(Op0);
6291   unsigned Op0LeadingZeros = Op0KnownBits.countMinLeadingZeros();
6292   KnownBits Op1KnownBits = DAG.computeKnownBits(Op1);
6293   unsigned Op1LeadingZeros = Op1KnownBits.countMinLeadingZeros();
6294   SDLoc SL(Op);
6295   if (Op0LeadingZeros >= 32 && Op1LeadingZeros >= 32)
6296     return SDValue(
6297         DAG.getMachineNode(AMDGPU::S_MUL_U64_U32_PSEUDO, SL, VT, Op0, Op1), 0);
6298   unsigned Op0SignBits = DAG.ComputeNumSignBits(Op0);
6299   unsigned Op1SignBits = DAG.ComputeNumSignBits(Op1);
6300   if (Op0SignBits >= 33 && Op1SignBits >= 33)
6301     return SDValue(
6302         DAG.getMachineNode(AMDGPU::S_MUL_I64_I32_PSEUDO, SL, VT, Op0, Op1), 0);
6303   // If all the operands are uniform, then we lower s_mul_u64 as it is.
6304   return Op;
6305 }
6306 
6307 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
6308   EVT VT = Op.getValueType();
6309   SDLoc SL(Op);
6310   SDValue LHS = Op.getOperand(0);
6311   SDValue RHS = Op.getOperand(1);
6312   bool isSigned = Op.getOpcode() == ISD::SMULO;
6313 
6314   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
6315     const APInt &C = RHSC->getAPIntValue();
6316     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
6317     if (C.isPowerOf2()) {
6318       // smulo(x, signed_min) is same as umulo(x, signed_min).
6319       bool UseArithShift = isSigned && !C.isMinSignedValue();
6320       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
6321       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
6322       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
6323           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
6324                       SL, VT, Result, ShiftAmt),
6325           LHS, ISD::SETNE);
6326       return DAG.getMergeValues({ Result, Overflow }, SL);
6327     }
6328   }
6329 
6330   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
6331   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
6332                             SL, VT, LHS, RHS);
6333 
6334   SDValue Sign = isSigned
6335     ? DAG.getNode(ISD::SRA, SL, VT, Result,
6336                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
6337     : DAG.getConstant(0, SL, VT);
6338   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
6339 
6340   return DAG.getMergeValues({ Result, Overflow }, SL);
6341 }
6342 
6343 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const {
6344   if (Op->isDivergent()) {
6345     // Select to V_MAD_[IU]64_[IU]32.
6346     return Op;
6347   }
6348   if (Subtarget->hasSMulHi()) {
6349     // Expand to S_MUL_I32 + S_MUL_HI_[IU]32.
6350     return SDValue();
6351   }
6352   // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to
6353   // calculate the high part, so we might as well do the whole thing with
6354   // V_MAD_[IU]64_[IU]32.
6355   return Op;
6356 }
6357 
6358 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
6359   if (!Subtarget->isTrapHandlerEnabled() ||
6360       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
6361     return lowerTrapEndpgm(Op, DAG);
6362 
6363   return Subtarget->supportsGetDoorbellID() ? lowerTrapHsa(Op, DAG) :
6364          lowerTrapHsaQueuePtr(Op, DAG);
6365 }
6366 
6367 SDValue SITargetLowering::lowerTrapEndpgm(
6368     SDValue Op, SelectionDAG &DAG) const {
6369   SDLoc SL(Op);
6370   SDValue Chain = Op.getOperand(0);
6371   return DAG.getNode(AMDGPUISD::ENDPGM_TRAP, SL, MVT::Other, Chain);
6372 }
6373 
6374 SDValue SITargetLowering::loadImplicitKernelArgument(SelectionDAG &DAG, MVT VT,
6375     const SDLoc &DL, Align Alignment, ImplicitParameter Param) const {
6376   MachineFunction &MF = DAG.getMachineFunction();
6377   uint64_t Offset = getImplicitParameterOffset(MF, Param);
6378   SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), Offset);
6379   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
6380   return DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, PtrInfo, Alignment,
6381                      MachineMemOperand::MODereferenceable |
6382                          MachineMemOperand::MOInvariant);
6383 }
6384 
6385 SDValue SITargetLowering::lowerTrapHsaQueuePtr(
6386     SDValue Op, SelectionDAG &DAG) const {
6387   SDLoc SL(Op);
6388   SDValue Chain = Op.getOperand(0);
6389 
6390   SDValue QueuePtr;
6391   // For code object version 5, QueuePtr is passed through implicit kernarg.
6392   const Module *M = DAG.getMachineFunction().getFunction().getParent();
6393   if (AMDGPU::getCodeObjectVersion(*M) >= AMDGPU::AMDHSA_COV5) {
6394     QueuePtr =
6395         loadImplicitKernelArgument(DAG, MVT::i64, SL, Align(8), QUEUE_PTR);
6396   } else {
6397     MachineFunction &MF = DAG.getMachineFunction();
6398     SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
6399     Register UserSGPR = Info->getQueuePtrUserSGPR();
6400 
6401     if (UserSGPR == AMDGPU::NoRegister) {
6402       // We probably are in a function incorrectly marked with
6403       // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the
6404       // trap, so just use a null pointer.
6405       QueuePtr = DAG.getConstant(0, SL, MVT::i64);
6406     } else {
6407       QueuePtr = CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, UserSGPR,
6408                                       MVT::i64);
6409     }
6410   }
6411 
6412   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
6413   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
6414                                    QueuePtr, SDValue());
6415 
6416   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
6417   SDValue Ops[] = {
6418     ToReg,
6419     DAG.getTargetConstant(TrapID, SL, MVT::i16),
6420     SGPR01,
6421     ToReg.getValue(1)
6422   };
6423   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
6424 }
6425 
6426 SDValue SITargetLowering::lowerTrapHsa(
6427     SDValue Op, SelectionDAG &DAG) const {
6428   SDLoc SL(Op);
6429   SDValue Chain = Op.getOperand(0);
6430 
6431   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
6432   SDValue Ops[] = {
6433     Chain,
6434     DAG.getTargetConstant(TrapID, SL, MVT::i16)
6435   };
6436   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
6437 }
6438 
6439 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
6440   SDLoc SL(Op);
6441   SDValue Chain = Op.getOperand(0);
6442   MachineFunction &MF = DAG.getMachineFunction();
6443 
6444   if (!Subtarget->isTrapHandlerEnabled() ||
6445       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
6446     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
6447                                      "debugtrap handler not supported",
6448                                      Op.getDebugLoc(),
6449                                      DS_Warning);
6450     LLVMContext &Ctx = MF.getFunction().getContext();
6451     Ctx.diagnose(NoTrap);
6452     return Chain;
6453   }
6454 
6455   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
6456   SDValue Ops[] = {
6457     Chain,
6458     DAG.getTargetConstant(TrapID, SL, MVT::i16)
6459   };
6460   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
6461 }
6462 
6463 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
6464                                              SelectionDAG &DAG) const {
6465   if (Subtarget->hasApertureRegs()) {
6466     const unsigned ApertureRegNo = (AS == AMDGPUAS::LOCAL_ADDRESS)
6467                                        ? AMDGPU::SRC_SHARED_BASE
6468                                        : AMDGPU::SRC_PRIVATE_BASE;
6469     // Note: this feature (register) is broken. When used as a 32-bit operand,
6470     // it returns a wrong value (all zeroes?). The real value is in the upper 32
6471     // bits.
6472     //
6473     // To work around the issue, directly emit a 64 bit mov from this register
6474     // then extract the high bits. Note that this shouldn't even result in a
6475     // shift being emitted and simply become a pair of registers (e.g.):
6476     //    s_mov_b64 s[6:7], src_shared_base
6477     //    v_mov_b32_e32 v1, s7
6478     //
6479     // FIXME: It would be more natural to emit a CopyFromReg here, but then copy
6480     // coalescing would kick in and it would think it's okay to use the "HI"
6481     // subregister directly (instead of extracting the HI 32 bits) which is an
6482     // artificial (unusable) register.
6483     //  Register TableGen definitions would need an overhaul to get rid of the
6484     //  artificial "HI" aperture registers and prevent this kind of issue from
6485     //  happening.
6486     SDNode *Mov = DAG.getMachineNode(AMDGPU::S_MOV_B64, DL, MVT::i64,
6487                                      DAG.getRegister(ApertureRegNo, MVT::i64));
6488     return DAG.getNode(
6489         ISD::TRUNCATE, DL, MVT::i32,
6490         DAG.getNode(ISD::SRL, DL, MVT::i64,
6491                     {SDValue(Mov, 0), DAG.getConstant(32, DL, MVT::i64)}));
6492   }
6493 
6494   // For code object version 5, private_base and shared_base are passed through
6495   // implicit kernargs.
6496   const Module *M = DAG.getMachineFunction().getFunction().getParent();
6497   if (AMDGPU::getCodeObjectVersion(*M) >= AMDGPU::AMDHSA_COV5) {
6498     ImplicitParameter Param =
6499         (AS == AMDGPUAS::LOCAL_ADDRESS) ? SHARED_BASE : PRIVATE_BASE;
6500     return loadImplicitKernelArgument(DAG, MVT::i32, DL, Align(4), Param);
6501   }
6502 
6503   MachineFunction &MF = DAG.getMachineFunction();
6504   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
6505   Register UserSGPR = Info->getQueuePtrUserSGPR();
6506   if (UserSGPR == AMDGPU::NoRegister) {
6507     // We probably are in a function incorrectly marked with
6508     // amdgpu-no-queue-ptr. This is undefined.
6509     return DAG.getUNDEF(MVT::i32);
6510   }
6511 
6512   SDValue QueuePtr = CreateLiveInRegister(
6513     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
6514 
6515   // Offset into amd_queue_t for group_segment_aperture_base_hi /
6516   // private_segment_aperture_base_hi.
6517   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
6518 
6519   SDValue Ptr =
6520       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::getFixed(StructOffset));
6521 
6522   // TODO: Use custom target PseudoSourceValue.
6523   // TODO: We should use the value from the IR intrinsic call, but it might not
6524   // be available and how do we get it?
6525   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
6526   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
6527                      commonAlignment(Align(64), StructOffset),
6528                      MachineMemOperand::MODereferenceable |
6529                          MachineMemOperand::MOInvariant);
6530 }
6531 
6532 /// Return true if the value is a known valid address, such that a null check is
6533 /// not necessary.
6534 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG,
6535                            const AMDGPUTargetMachine &TM, unsigned AddrSpace) {
6536   if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) ||
6537       isa<BasicBlockSDNode>(Val))
6538     return true;
6539 
6540   if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val))
6541     return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace);
6542 
6543   // TODO: Search through arithmetic, handle arguments and loads
6544   // marked nonnull.
6545   return false;
6546 }
6547 
6548 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
6549                                              SelectionDAG &DAG) const {
6550   SDLoc SL(Op);
6551   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
6552 
6553   SDValue Src = ASC->getOperand(0);
6554   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
6555   unsigned SrcAS = ASC->getSrcAddressSpace();
6556 
6557   const AMDGPUTargetMachine &TM =
6558     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
6559 
6560   // flat -> local/private
6561   if (SrcAS == AMDGPUAS::FLAT_ADDRESS) {
6562     unsigned DestAS = ASC->getDestAddressSpace();
6563 
6564     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
6565         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
6566       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
6567 
6568       if (isKnownNonNull(Src, DAG, TM, SrcAS))
6569         return Ptr;
6570 
6571       unsigned NullVal = TM.getNullPointerValue(DestAS);
6572       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
6573       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
6574 
6575       return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr,
6576                          SegmentNullPtr);
6577     }
6578   }
6579 
6580   // local/private -> flat
6581   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
6582     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
6583         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
6584 
6585       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
6586       SDValue CvtPtr =
6587           DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
6588       CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr);
6589 
6590       if (isKnownNonNull(Src, DAG, TM, SrcAS))
6591         return CvtPtr;
6592 
6593       unsigned NullVal = TM.getNullPointerValue(SrcAS);
6594       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
6595 
6596       SDValue NonNull
6597         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
6598 
6599       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr,
6600                          FlatNullPtr);
6601     }
6602   }
6603 
6604   if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
6605       Op.getValueType() == MVT::i64) {
6606     const SIMachineFunctionInfo *Info =
6607         DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>();
6608     SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32);
6609     SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi);
6610     return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
6611   }
6612 
6613   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
6614       Src.getValueType() == MVT::i64)
6615     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
6616 
6617   // global <-> flat are no-ops and never emitted.
6618 
6619   const MachineFunction &MF = DAG.getMachineFunction();
6620   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
6621     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
6622   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
6623 
6624   return DAG.getUNDEF(ASC->getValueType(0));
6625 }
6626 
6627 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
6628 // the small vector and inserting them into the big vector. That is better than
6629 // the default expansion of doing it via a stack slot. Even though the use of
6630 // the stack slot would be optimized away afterwards, the stack slot itself
6631 // remains.
6632 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
6633                                                 SelectionDAG &DAG) const {
6634   SDValue Vec = Op.getOperand(0);
6635   SDValue Ins = Op.getOperand(1);
6636   SDValue Idx = Op.getOperand(2);
6637   EVT VecVT = Vec.getValueType();
6638   EVT InsVT = Ins.getValueType();
6639   EVT EltVT = VecVT.getVectorElementType();
6640   unsigned InsNumElts = InsVT.getVectorNumElements();
6641   unsigned IdxVal = Idx->getAsZExtVal();
6642   SDLoc SL(Op);
6643 
6644   if (EltVT.getScalarSizeInBits() == 16 && IdxVal % 2 == 0) {
6645     // Insert 32-bit registers at a time.
6646     assert(InsNumElts % 2 == 0 && "expect legal vector types");
6647 
6648     unsigned VecNumElts = VecVT.getVectorNumElements();
6649     EVT NewVecVT =
6650         EVT::getVectorVT(*DAG.getContext(), MVT::i32, VecNumElts / 2);
6651     EVT NewInsVT = InsNumElts == 2 ? MVT::i32
6652                                    : EVT::getVectorVT(*DAG.getContext(),
6653                                                       MVT::i32, InsNumElts / 2);
6654 
6655     Vec = DAG.getNode(ISD::BITCAST, SL, NewVecVT, Vec);
6656     Ins = DAG.getNode(ISD::BITCAST, SL, NewInsVT, Ins);
6657 
6658     for (unsigned I = 0; I != InsNumElts / 2; ++I) {
6659       SDValue Elt;
6660       if (InsNumElts == 2) {
6661         Elt = Ins;
6662       } else {
6663         Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Ins,
6664                           DAG.getConstant(I, SL, MVT::i32));
6665       }
6666       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, NewVecVT, Vec, Elt,
6667                         DAG.getConstant(IdxVal / 2 + I, SL, MVT::i32));
6668     }
6669 
6670     return DAG.getNode(ISD::BITCAST, SL, VecVT, Vec);
6671   }
6672 
6673   for (unsigned I = 0; I != InsNumElts; ++I) {
6674     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
6675                               DAG.getConstant(I, SL, MVT::i32));
6676     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
6677                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
6678   }
6679   return Vec;
6680 }
6681 
6682 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
6683                                                  SelectionDAG &DAG) const {
6684   SDValue Vec = Op.getOperand(0);
6685   SDValue InsVal = Op.getOperand(1);
6686   SDValue Idx = Op.getOperand(2);
6687   EVT VecVT = Vec.getValueType();
6688   EVT EltVT = VecVT.getVectorElementType();
6689   unsigned VecSize = VecVT.getSizeInBits();
6690   unsigned EltSize = EltVT.getSizeInBits();
6691   SDLoc SL(Op);
6692 
6693   // Specially handle the case of v4i16 with static indexing.
6694   unsigned NumElts = VecVT.getVectorNumElements();
6695   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
6696   if (NumElts == 4 && EltSize == 16 && KIdx) {
6697     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
6698 
6699     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
6700                                  DAG.getConstant(0, SL, MVT::i32));
6701     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
6702                                  DAG.getConstant(1, SL, MVT::i32));
6703 
6704     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
6705     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
6706 
6707     unsigned Idx = KIdx->getZExtValue();
6708     bool InsertLo = Idx < 2;
6709     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
6710       InsertLo ? LoVec : HiVec,
6711       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
6712       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
6713 
6714     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
6715 
6716     SDValue Concat = InsertLo ?
6717       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
6718       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
6719 
6720     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
6721   }
6722 
6723   // Static indexing does not lower to stack access, and hence there is no need
6724   // for special custom lowering to avoid stack access.
6725   if (isa<ConstantSDNode>(Idx))
6726     return SDValue();
6727 
6728   // Avoid stack access for dynamic indexing by custom lowering to
6729   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
6730 
6731   assert(VecSize <= 64 && "Expected target vector size to be <= 64 bits");
6732 
6733   MVT IntVT = MVT::getIntegerVT(VecSize);
6734 
6735   // Convert vector index to bit-index and get the required bit mask.
6736   assert(isPowerOf2_32(EltSize));
6737   const auto EltMask = maskTrailingOnes<uint64_t>(EltSize);
6738   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
6739   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
6740   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
6741                             DAG.getConstant(EltMask, SL, IntVT), ScaledIdx);
6742 
6743   // 1. Create a congruent vector with the target value in each element.
6744   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
6745                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
6746 
6747   // 2. Mask off all other indicies except the required index within (1).
6748   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
6749 
6750   // 3. Mask off the required index within the target vector.
6751   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
6752   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
6753                             DAG.getNOT(SL, BFM, IntVT), BCVec);
6754 
6755   // 4. Get (2) and (3) ORed into the target vector.
6756   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
6757 
6758   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
6759 }
6760 
6761 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
6762                                                   SelectionDAG &DAG) const {
6763   SDLoc SL(Op);
6764 
6765   EVT ResultVT = Op.getValueType();
6766   SDValue Vec = Op.getOperand(0);
6767   SDValue Idx = Op.getOperand(1);
6768   EVT VecVT = Vec.getValueType();
6769   unsigned VecSize = VecVT.getSizeInBits();
6770   EVT EltVT = VecVT.getVectorElementType();
6771 
6772   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
6773 
6774   // Make sure we do any optimizations that will make it easier to fold
6775   // source modifiers before obscuring it with bit operations.
6776 
6777   // XXX - Why doesn't this get called when vector_shuffle is expanded?
6778   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
6779     return Combined;
6780 
6781   if (VecSize == 128 || VecSize == 256 || VecSize == 512) {
6782     SDValue Lo, Hi;
6783     EVT LoVT, HiVT;
6784     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
6785 
6786     if (VecSize == 128) {
6787       SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec);
6788       Lo = DAG.getBitcast(LoVT,
6789                           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, V2,
6790                                       DAG.getConstant(0, SL, MVT::i32)));
6791       Hi = DAG.getBitcast(HiVT,
6792                           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, V2,
6793                                       DAG.getConstant(1, SL, MVT::i32)));
6794     } else if (VecSize == 256) {
6795       SDValue V2 = DAG.getBitcast(MVT::v4i64, Vec);
6796       SDValue Parts[4];
6797       for (unsigned P = 0; P < 4; ++P) {
6798         Parts[P] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, V2,
6799                                DAG.getConstant(P, SL, MVT::i32));
6800       }
6801 
6802       Lo = DAG.getBitcast(LoVT, DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i64,
6803                                             Parts[0], Parts[1]));
6804       Hi = DAG.getBitcast(HiVT, DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i64,
6805                                             Parts[2], Parts[3]));
6806     } else {
6807       assert(VecSize == 512);
6808 
6809       SDValue V2 = DAG.getBitcast(MVT::v8i64, Vec);
6810       SDValue Parts[8];
6811       for (unsigned P = 0; P < 8; ++P) {
6812         Parts[P] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, V2,
6813                                DAG.getConstant(P, SL, MVT::i32));
6814       }
6815 
6816       Lo = DAG.getBitcast(LoVT,
6817                           DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v4i64,
6818                                       Parts[0], Parts[1], Parts[2], Parts[3]));
6819       Hi = DAG.getBitcast(HiVT,
6820                           DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v4i64,
6821                                       Parts[4], Parts[5],Parts[6], Parts[7]));
6822     }
6823 
6824     EVT IdxVT = Idx.getValueType();
6825     unsigned NElem = VecVT.getVectorNumElements();
6826     assert(isPowerOf2_32(NElem));
6827     SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT);
6828     SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask);
6829     SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT);
6830     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx);
6831   }
6832 
6833   assert(VecSize <= 64);
6834 
6835   MVT IntVT = MVT::getIntegerVT(VecSize);
6836 
6837   // If Vec is just a SCALAR_TO_VECTOR, then use the scalar integer directly.
6838   SDValue VecBC = peekThroughBitcasts(Vec);
6839   if (VecBC.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6840     SDValue Src = VecBC.getOperand(0);
6841     Src = DAG.getBitcast(Src.getValueType().changeTypeToInteger(), Src);
6842     Vec = DAG.getAnyExtOrTrunc(Src, SL, IntVT);
6843   }
6844 
6845   unsigned EltSize = EltVT.getSizeInBits();
6846   assert(isPowerOf2_32(EltSize));
6847 
6848   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
6849 
6850   // Convert vector index to bit-index (* EltSize)
6851   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
6852 
6853   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
6854   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
6855 
6856   if (ResultVT == MVT::f16 || ResultVT == MVT::bf16) {
6857     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
6858     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
6859   }
6860 
6861   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
6862 }
6863 
6864 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
6865   assert(Elt % 2 == 0);
6866   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
6867 }
6868 
6869 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
6870                                               SelectionDAG &DAG) const {
6871   SDLoc SL(Op);
6872   EVT ResultVT = Op.getValueType();
6873   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
6874 
6875   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
6876   EVT EltVT = PackVT.getVectorElementType();
6877   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
6878 
6879   // vector_shuffle <0,1,6,7> lhs, rhs
6880   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
6881   //
6882   // vector_shuffle <6,7,2,3> lhs, rhs
6883   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
6884   //
6885   // vector_shuffle <6,7,0,1> lhs, rhs
6886   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
6887 
6888   // Avoid scalarizing when both halves are reading from consecutive elements.
6889   SmallVector<SDValue, 4> Pieces;
6890   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
6891     if (elementPairIsContiguous(SVN->getMask(), I)) {
6892       const int Idx = SVN->getMaskElt(I);
6893       int VecIdx = Idx < SrcNumElts ? 0 : 1;
6894       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
6895       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
6896                                     PackVT, SVN->getOperand(VecIdx),
6897                                     DAG.getConstant(EltIdx, SL, MVT::i32));
6898       Pieces.push_back(SubVec);
6899     } else {
6900       const int Idx0 = SVN->getMaskElt(I);
6901       const int Idx1 = SVN->getMaskElt(I + 1);
6902       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
6903       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
6904       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
6905       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
6906 
6907       SDValue Vec0 = SVN->getOperand(VecIdx0);
6908       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
6909                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
6910 
6911       SDValue Vec1 = SVN->getOperand(VecIdx1);
6912       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
6913                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
6914       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
6915     }
6916   }
6917 
6918   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
6919 }
6920 
6921 SDValue SITargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
6922                                                 SelectionDAG &DAG) const {
6923   SDValue SVal = Op.getOperand(0);
6924   EVT ResultVT = Op.getValueType();
6925   EVT SValVT = SVal.getValueType();
6926   SDValue UndefVal = DAG.getUNDEF(SValVT);
6927   SDLoc SL(Op);
6928 
6929   SmallVector<SDValue, 8> VElts;
6930   VElts.push_back(SVal);
6931   for (int I = 1, E = ResultVT.getVectorNumElements(); I < E; ++I)
6932     VElts.push_back(UndefVal);
6933 
6934   return DAG.getBuildVector(ResultVT, SL, VElts);
6935 }
6936 
6937 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
6938                                             SelectionDAG &DAG) const {
6939   SDLoc SL(Op);
6940   EVT VT = Op.getValueType();
6941 
6942   if (VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 ||
6943       VT == MVT::v8f16 || VT == MVT::v4bf16 || VT == MVT::v8bf16) {
6944     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(),
6945                                   VT.getVectorNumElements() / 2);
6946     MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits());
6947 
6948     // Turn into pair of packed build_vectors.
6949     // TODO: Special case for constants that can be materialized with s_mov_b64.
6950     SmallVector<SDValue, 4> LoOps, HiOps;
6951     for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) {
6952       LoOps.push_back(Op.getOperand(I));
6953       HiOps.push_back(Op.getOperand(I + E));
6954     }
6955     SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps);
6956     SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps);
6957 
6958     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo);
6959     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi);
6960 
6961     SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL,
6962                                        { CastLo, CastHi });
6963     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
6964   }
6965 
6966   if (VT == MVT::v16i16 || VT == MVT::v16f16 || VT == MVT::v16bf16) {
6967     EVT QuarterVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(),
6968                                      VT.getVectorNumElements() / 4);
6969     MVT QuarterIntVT = MVT::getIntegerVT(QuarterVT.getSizeInBits());
6970 
6971     SmallVector<SDValue, 4> Parts[4];
6972     for (unsigned I = 0, E = VT.getVectorNumElements() / 4; I != E; ++I) {
6973       for (unsigned P = 0; P < 4; ++P)
6974         Parts[P].push_back(Op.getOperand(I + P * E));
6975     }
6976     SDValue Casts[4];
6977     for (unsigned P = 0; P < 4; ++P) {
6978       SDValue Vec = DAG.getBuildVector(QuarterVT, SL, Parts[P]);
6979       Casts[P] = DAG.getNode(ISD::BITCAST, SL, QuarterIntVT, Vec);
6980     }
6981 
6982     SDValue Blend =
6983         DAG.getBuildVector(MVT::getVectorVT(QuarterIntVT, 4), SL, Casts);
6984     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
6985   }
6986 
6987   if (VT == MVT::v32i16 || VT == MVT::v32f16 || VT == MVT::v32bf16) {
6988     EVT QuarterVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(),
6989                                      VT.getVectorNumElements() / 8);
6990     MVT QuarterIntVT = MVT::getIntegerVT(QuarterVT.getSizeInBits());
6991 
6992     SmallVector<SDValue, 8> Parts[8];
6993     for (unsigned I = 0, E = VT.getVectorNumElements() / 8; I != E; ++I) {
6994       for (unsigned P = 0; P < 8; ++P)
6995         Parts[P].push_back(Op.getOperand(I + P * E));
6996     }
6997     SDValue Casts[8];
6998     for (unsigned P = 0; P < 8; ++P) {
6999       SDValue Vec = DAG.getBuildVector(QuarterVT, SL, Parts[P]);
7000       Casts[P] = DAG.getNode(ISD::BITCAST, SL, QuarterIntVT, Vec);
7001     }
7002 
7003     SDValue Blend =
7004         DAG.getBuildVector(MVT::getVectorVT(QuarterIntVT, 8), SL, Casts);
7005     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
7006   }
7007 
7008   assert(VT == MVT::v2f16 || VT == MVT::v2i16 || VT == MVT::v2bf16);
7009   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
7010 
7011   SDValue Lo = Op.getOperand(0);
7012   SDValue Hi = Op.getOperand(1);
7013 
7014   // Avoid adding defined bits with the zero_extend.
7015   if (Hi.isUndef()) {
7016     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
7017     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
7018     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
7019   }
7020 
7021   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
7022   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
7023 
7024   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
7025                               DAG.getConstant(16, SL, MVT::i32));
7026   if (Lo.isUndef())
7027     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
7028 
7029   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
7030   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
7031 
7032   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
7033   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
7034 }
7035 
7036 bool
7037 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
7038   // We can fold offsets for anything that doesn't require a GOT relocation.
7039   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
7040           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
7041           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
7042          !shouldEmitGOTReloc(GA->getGlobal());
7043 }
7044 
7045 static SDValue
7046 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
7047                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
7048                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
7049   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
7050   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
7051   // lowered to the following code sequence:
7052   //
7053   // For constant address space:
7054   //   s_getpc_b64 s[0:1]
7055   //   s_add_u32 s0, s0, $symbol
7056   //   s_addc_u32 s1, s1, 0
7057   //
7058   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
7059   //   a fixup or relocation is emitted to replace $symbol with a literal
7060   //   constant, which is a pc-relative offset from the encoding of the $symbol
7061   //   operand to the global variable.
7062   //
7063   // For global address space:
7064   //   s_getpc_b64 s[0:1]
7065   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
7066   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
7067   //
7068   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
7069   //   fixups or relocations are emitted to replace $symbol@*@lo and
7070   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
7071   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
7072   //   operand to the global variable.
7073   SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset, GAFlags);
7074   SDValue PtrHi;
7075   if (GAFlags == SIInstrInfo::MO_NONE)
7076     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
7077   else
7078     PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset, GAFlags + 1);
7079   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
7080 }
7081 
7082 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
7083                                              SDValue Op,
7084                                              SelectionDAG &DAG) const {
7085   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
7086   SDLoc DL(GSD);
7087   EVT PtrVT = Op.getValueType();
7088 
7089   const GlobalValue *GV = GSD->getGlobal();
7090   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
7091        shouldUseLDSConstAddress(GV)) ||
7092       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
7093       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
7094     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
7095         GV->hasExternalLinkage()) {
7096       Type *Ty = GV->getValueType();
7097       // HIP uses an unsized array `extern __shared__ T s[]` or similar
7098       // zero-sized type in other languages to declare the dynamic shared
7099       // memory which size is not known at the compile time. They will be
7100       // allocated by the runtime and placed directly after the static
7101       // allocated ones. They all share the same offset.
7102       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
7103         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
7104         // Adjust alignment for that dynamic shared memory array.
7105         Function &F = DAG.getMachineFunction().getFunction();
7106         MFI->setDynLDSAlign(F, *cast<GlobalVariable>(GV));
7107         MFI->setUsesDynamicLDS(true);
7108         return SDValue(
7109             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
7110       }
7111     }
7112     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
7113   }
7114 
7115   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
7116     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
7117                                             SIInstrInfo::MO_ABS32_LO);
7118     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
7119   }
7120 
7121   if (Subtarget->isAmdPalOS() || Subtarget->isMesa3DOS()) {
7122     SDValue AddrLo = DAG.getTargetGlobalAddress(
7123         GV, DL, MVT::i32, GSD->getOffset(), SIInstrInfo::MO_ABS32_LO);
7124     AddrLo = {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, AddrLo), 0};
7125 
7126     SDValue AddrHi = DAG.getTargetGlobalAddress(
7127         GV, DL, MVT::i32, GSD->getOffset(), SIInstrInfo::MO_ABS32_HI);
7128     AddrHi = {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, AddrHi), 0};
7129 
7130     return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, AddrLo, AddrHi);
7131   }
7132 
7133   if (shouldEmitFixup(GV))
7134     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
7135 
7136   if (shouldEmitPCReloc(GV))
7137     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
7138                                    SIInstrInfo::MO_REL32);
7139 
7140   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
7141                                             SIInstrInfo::MO_GOTPCREL32);
7142 
7143   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
7144   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
7145   const DataLayout &DataLayout = DAG.getDataLayout();
7146   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
7147   MachinePointerInfo PtrInfo
7148     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
7149 
7150   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
7151                      MachineMemOperand::MODereferenceable |
7152                          MachineMemOperand::MOInvariant);
7153 }
7154 
7155 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
7156                                    const SDLoc &DL, SDValue V) const {
7157   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
7158   // the destination register.
7159   //
7160   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
7161   // so we will end up with redundant moves to m0.
7162   //
7163   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
7164 
7165   // A Null SDValue creates a glue result.
7166   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
7167                                   V, Chain);
7168   return SDValue(M0, 0);
7169 }
7170 
7171 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
7172                                                  SDValue Op,
7173                                                  MVT VT,
7174                                                  unsigned Offset) const {
7175   SDLoc SL(Op);
7176   SDValue Param = lowerKernargMemParameter(
7177       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
7178   // The local size values will have the hi 16-bits as zero.
7179   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
7180                      DAG.getValueType(VT));
7181 }
7182 
7183 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
7184                                         EVT VT) {
7185   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
7186                                       "non-hsa intrinsic with hsa target",
7187                                       DL.getDebugLoc());
7188   DAG.getContext()->diagnose(BadIntrin);
7189   return DAG.getUNDEF(VT);
7190 }
7191 
7192 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
7193                                          EVT VT) {
7194   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
7195                                       "intrinsic not supported on subtarget",
7196                                       DL.getDebugLoc());
7197   DAG.getContext()->diagnose(BadIntrin);
7198   return DAG.getUNDEF(VT);
7199 }
7200 
7201 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
7202                                     ArrayRef<SDValue> Elts) {
7203   assert(!Elts.empty());
7204   MVT Type;
7205   unsigned NumElts = Elts.size();
7206 
7207   if (NumElts <= 12) {
7208     Type = MVT::getVectorVT(MVT::f32, NumElts);
7209   } else {
7210     assert(Elts.size() <= 16);
7211     Type = MVT::v16f32;
7212     NumElts = 16;
7213   }
7214 
7215   SmallVector<SDValue, 16> VecElts(NumElts);
7216   for (unsigned i = 0; i < Elts.size(); ++i) {
7217     SDValue Elt = Elts[i];
7218     if (Elt.getValueType() != MVT::f32)
7219       Elt = DAG.getBitcast(MVT::f32, Elt);
7220     VecElts[i] = Elt;
7221   }
7222   for (unsigned i = Elts.size(); i < NumElts; ++i)
7223     VecElts[i] = DAG.getUNDEF(MVT::f32);
7224 
7225   if (NumElts == 1)
7226     return VecElts[0];
7227   return DAG.getBuildVector(Type, DL, VecElts);
7228 }
7229 
7230 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
7231                               SDValue Src, int ExtraElts) {
7232   EVT SrcVT = Src.getValueType();
7233 
7234   SmallVector<SDValue, 8> Elts;
7235 
7236   if (SrcVT.isVector())
7237     DAG.ExtractVectorElements(Src, Elts);
7238   else
7239     Elts.push_back(Src);
7240 
7241   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
7242   while (ExtraElts--)
7243     Elts.push_back(Undef);
7244 
7245   return DAG.getBuildVector(CastVT, DL, Elts);
7246 }
7247 
7248 // Re-construct the required return value for a image load intrinsic.
7249 // This is more complicated due to the optional use TexFailCtrl which means the required
7250 // return type is an aggregate
7251 static SDValue constructRetValue(SelectionDAG &DAG,
7252                                  MachineSDNode *Result,
7253                                  ArrayRef<EVT> ResultTypes,
7254                                  bool IsTexFail, bool Unpacked, bool IsD16,
7255                                  int DMaskPop, int NumVDataDwords,
7256                                  const SDLoc &DL) {
7257   // Determine the required return type. This is the same regardless of IsTexFail flag
7258   EVT ReqRetVT = ResultTypes[0];
7259   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
7260   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
7261     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
7262 
7263   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
7264     DMaskPop : (DMaskPop + 1) / 2;
7265 
7266   MVT DataDwordVT = NumDataDwords == 1 ?
7267     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
7268 
7269   MVT MaskPopVT = MaskPopDwords == 1 ?
7270     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
7271 
7272   SDValue Data(Result, 0);
7273   SDValue TexFail;
7274 
7275   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
7276     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
7277     if (MaskPopVT.isVector()) {
7278       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
7279                          SDValue(Result, 0), ZeroIdx);
7280     } else {
7281       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
7282                          SDValue(Result, 0), ZeroIdx);
7283     }
7284   }
7285 
7286   if (DataDwordVT.isVector())
7287     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
7288                           NumDataDwords - MaskPopDwords);
7289 
7290   if (IsD16)
7291     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
7292 
7293   EVT LegalReqRetVT = ReqRetVT;
7294   if (!ReqRetVT.isVector()) {
7295     if (!Data.getValueType().isInteger())
7296       Data = DAG.getNode(ISD::BITCAST, DL,
7297                          Data.getValueType().changeTypeToInteger(), Data);
7298     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
7299   } else {
7300     // We need to widen the return vector to a legal type
7301     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
7302         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
7303       LegalReqRetVT =
7304           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
7305                            ReqRetVT.getVectorNumElements() + 1);
7306     }
7307   }
7308   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
7309 
7310   if (IsTexFail) {
7311     TexFail =
7312         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
7313                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
7314 
7315     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
7316   }
7317 
7318   if (Result->getNumValues() == 1)
7319     return Data;
7320 
7321   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
7322 }
7323 
7324 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
7325                          SDValue *LWE, bool &IsTexFail) {
7326   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
7327 
7328   uint64_t Value = TexFailCtrlConst->getZExtValue();
7329   if (Value) {
7330     IsTexFail = true;
7331   }
7332 
7333   SDLoc DL(TexFailCtrlConst);
7334   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
7335   Value &= ~(uint64_t)0x1;
7336   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
7337   Value &= ~(uint64_t)0x2;
7338 
7339   return Value == 0;
7340 }
7341 
7342 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
7343                                       MVT PackVectorVT,
7344                                       SmallVectorImpl<SDValue> &PackedAddrs,
7345                                       unsigned DimIdx, unsigned EndIdx,
7346                                       unsigned NumGradients) {
7347   SDLoc DL(Op);
7348   for (unsigned I = DimIdx; I < EndIdx; I++) {
7349     SDValue Addr = Op.getOperand(I);
7350 
7351     // Gradients are packed with undef for each coordinate.
7352     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
7353     // 1D: undef,dx/dh; undef,dx/dv
7354     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
7355     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
7356     if (((I + 1) >= EndIdx) ||
7357         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
7358                                          I == DimIdx + NumGradients - 1))) {
7359       if (Addr.getValueType() != MVT::i16)
7360         Addr = DAG.getBitcast(MVT::i16, Addr);
7361       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
7362     } else {
7363       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
7364       I++;
7365     }
7366     Addr = DAG.getBitcast(MVT::f32, Addr);
7367     PackedAddrs.push_back(Addr);
7368   }
7369 }
7370 
7371 SDValue SITargetLowering::lowerImage(SDValue Op,
7372                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
7373                                      SelectionDAG &DAG, bool WithChain) const {
7374   SDLoc DL(Op);
7375   MachineFunction &MF = DAG.getMachineFunction();
7376   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
7377   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
7378       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
7379   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
7380   unsigned IntrOpcode = Intr->BaseOpcode;
7381   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
7382   bool IsGFX11Plus = AMDGPU::isGFX11Plus(*Subtarget);
7383   bool IsGFX12Plus = AMDGPU::isGFX12Plus(*Subtarget);
7384 
7385   SmallVector<EVT, 3> ResultTypes(Op->values());
7386   SmallVector<EVT, 3> OrigResultTypes(Op->values());
7387   bool IsD16 = false;
7388   bool IsG16 = false;
7389   bool IsA16 = false;
7390   SDValue VData;
7391   int NumVDataDwords;
7392   bool AdjustRetType = false;
7393 
7394   // Offset of intrinsic arguments
7395   const unsigned ArgOffset = WithChain ? 2 : 1;
7396 
7397   unsigned DMask;
7398   unsigned DMaskLanes = 0;
7399 
7400   if (BaseOpcode->Atomic) {
7401     VData = Op.getOperand(2);
7402 
7403     bool Is64Bit = VData.getValueSizeInBits() == 64;
7404     if (BaseOpcode->AtomicX2) {
7405       SDValue VData2 = Op.getOperand(3);
7406       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
7407                                  {VData, VData2});
7408       if (Is64Bit)
7409         VData = DAG.getBitcast(MVT::v4i32, VData);
7410 
7411       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
7412       DMask = Is64Bit ? 0xf : 0x3;
7413       NumVDataDwords = Is64Bit ? 4 : 2;
7414     } else {
7415       DMask = Is64Bit ? 0x3 : 0x1;
7416       NumVDataDwords = Is64Bit ? 2 : 1;
7417     }
7418   } else {
7419     auto *DMaskConst =
7420         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
7421     DMask = DMaskConst->getZExtValue();
7422     DMaskLanes = BaseOpcode->Gather4 ? 4 : llvm::popcount(DMask);
7423 
7424     if (BaseOpcode->Store) {
7425       VData = Op.getOperand(2);
7426 
7427       MVT StoreVT = VData.getSimpleValueType();
7428       if (StoreVT.getScalarType() == MVT::f16) {
7429         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
7430           return Op; // D16 is unsupported for this instruction
7431 
7432         IsD16 = true;
7433         VData = handleD16VData(VData, DAG, true);
7434       }
7435 
7436       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
7437     } else {
7438       // Work out the num dwords based on the dmask popcount and underlying type
7439       // and whether packing is supported.
7440       MVT LoadVT = ResultTypes[0].getSimpleVT();
7441       if (LoadVT.getScalarType() == MVT::f16) {
7442         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
7443           return Op; // D16 is unsupported for this instruction
7444 
7445         IsD16 = true;
7446       }
7447 
7448       // Confirm that the return type is large enough for the dmask specified
7449       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
7450           (!LoadVT.isVector() && DMaskLanes > 1))
7451           return Op;
7452 
7453       // The sq block of gfx8 and gfx9 do not estimate register use correctly
7454       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
7455       // instructions.
7456       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
7457           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
7458         NumVDataDwords = (DMaskLanes + 1) / 2;
7459       else
7460         NumVDataDwords = DMaskLanes;
7461 
7462       AdjustRetType = true;
7463     }
7464   }
7465 
7466   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
7467   SmallVector<SDValue, 4> VAddrs;
7468 
7469   // Check for 16 bit addresses or derivatives and pack if true.
7470   MVT VAddrVT =
7471       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
7472   MVT VAddrScalarVT = VAddrVT.getScalarType();
7473   MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
7474   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
7475 
7476   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
7477   VAddrScalarVT = VAddrVT.getScalarType();
7478   MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
7479   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
7480 
7481   // Push back extra arguments.
7482   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) {
7483     if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) {
7484       assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument");
7485       // Special handling of bias when A16 is on. Bias is of type half but
7486       // occupies full 32-bit.
7487       SDValue Bias = DAG.getBuildVector(
7488           MVT::v2f16, DL,
7489           {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)});
7490       VAddrs.push_back(Bias);
7491     } else {
7492       assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) &&
7493              "Bias needs to be converted to 16 bit in A16 mode");
7494       VAddrs.push_back(Op.getOperand(ArgOffset + I));
7495     }
7496   }
7497 
7498   if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
7499     // 16 bit gradients are supported, but are tied to the A16 control
7500     // so both gradients and addresses must be 16 bit
7501     LLVM_DEBUG(
7502         dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
7503                   "require 16 bit args for both gradients and addresses");
7504     return Op;
7505   }
7506 
7507   if (IsA16) {
7508     if (!ST->hasA16()) {
7509       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
7510                            "support 16 bit addresses\n");
7511       return Op;
7512     }
7513   }
7514 
7515   // We've dealt with incorrect input so we know that if IsA16, IsG16
7516   // are set then we have to compress/pack operands (either address,
7517   // gradient or both)
7518   // In the case where a16 and gradients are tied (no G16 support) then we
7519   // have already verified that both IsA16 and IsG16 are true
7520   if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
7521     // Activate g16
7522     const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
7523         AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
7524     IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
7525   }
7526 
7527   // Add gradients (packed or unpacked)
7528   if (IsG16) {
7529     // Pack the gradients
7530     // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
7531     packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
7532                               ArgOffset + Intr->GradientStart,
7533                               ArgOffset + Intr->CoordStart, Intr->NumGradients);
7534   } else {
7535     for (unsigned I = ArgOffset + Intr->GradientStart;
7536          I < ArgOffset + Intr->CoordStart; I++)
7537       VAddrs.push_back(Op.getOperand(I));
7538   }
7539 
7540   // Add addresses (packed or unpacked)
7541   if (IsA16) {
7542     packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
7543                               ArgOffset + Intr->CoordStart, VAddrEnd,
7544                               0 /* No gradients */);
7545   } else {
7546     // Add uncompressed address
7547     for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
7548       VAddrs.push_back(Op.getOperand(I));
7549   }
7550 
7551   // If the register allocator cannot place the address registers contiguously
7552   // without introducing moves, then using the non-sequential address encoding
7553   // is always preferable, since it saves VALU instructions and is usually a
7554   // wash in terms of code size or even better.
7555   //
7556   // However, we currently have no way of hinting to the register allocator that
7557   // MIMG addresses should be placed contiguously when it is possible to do so,
7558   // so force non-NSA for the common 2-address case as a heuristic.
7559   //
7560   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
7561   // allocation when possible.
7562   //
7563   // Partial NSA is allowed on GFX11+ where the final register is a contiguous
7564   // set of the remaining addresses.
7565   const unsigned NSAMaxSize = ST->getNSAMaxSize(BaseOpcode->Sampler);
7566   const bool HasPartialNSAEncoding = ST->hasPartialNSAEncoding();
7567   const bool UseNSA = ST->hasNSAEncoding() &&
7568                       VAddrs.size() >= ST->getNSAThreshold(MF) &&
7569                       (VAddrs.size() <= NSAMaxSize || HasPartialNSAEncoding);
7570   const bool UsePartialNSA =
7571       UseNSA && HasPartialNSAEncoding && VAddrs.size() > NSAMaxSize;
7572 
7573   SDValue VAddr;
7574   if (UsePartialNSA) {
7575     VAddr = getBuildDwordsVector(DAG, DL,
7576                                  ArrayRef(VAddrs).drop_front(NSAMaxSize - 1));
7577   }
7578   else if (!UseNSA) {
7579     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
7580   }
7581 
7582   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
7583   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
7584   SDValue Unorm;
7585   if (!BaseOpcode->Sampler) {
7586     Unorm = True;
7587   } else {
7588     auto UnormConst =
7589         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
7590 
7591     Unorm = UnormConst->getZExtValue() ? True : False;
7592   }
7593 
7594   SDValue TFE;
7595   SDValue LWE;
7596   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
7597   bool IsTexFail = false;
7598   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
7599     return Op;
7600 
7601   if (IsTexFail) {
7602     if (!DMaskLanes) {
7603       // Expecting to get an error flag since TFC is on - and dmask is 0
7604       // Force dmask to be at least 1 otherwise the instruction will fail
7605       DMask = 0x1;
7606       DMaskLanes = 1;
7607       NumVDataDwords = 1;
7608     }
7609     NumVDataDwords += 1;
7610     AdjustRetType = true;
7611   }
7612 
7613   // Has something earlier tagged that the return type needs adjusting
7614   // This happens if the instruction is a load or has set TexFailCtrl flags
7615   if (AdjustRetType) {
7616     // NumVDataDwords reflects the true number of dwords required in the return type
7617     if (DMaskLanes == 0 && !BaseOpcode->Store) {
7618       // This is a no-op load. This can be eliminated
7619       SDValue Undef = DAG.getUNDEF(Op.getValueType());
7620       if (isa<MemSDNode>(Op))
7621         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
7622       return Undef;
7623     }
7624 
7625     EVT NewVT = NumVDataDwords > 1 ?
7626                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
7627                 : MVT::i32;
7628 
7629     ResultTypes[0] = NewVT;
7630     if (ResultTypes.size() == 3) {
7631       // Original result was aggregate type used for TexFailCtrl results
7632       // The actual instruction returns as a vector type which has now been
7633       // created. Remove the aggregate result.
7634       ResultTypes.erase(&ResultTypes[1]);
7635     }
7636   }
7637 
7638   unsigned CPol = cast<ConstantSDNode>(
7639       Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
7640   if (BaseOpcode->Atomic)
7641     CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
7642   if (CPol & ~(IsGFX12Plus ? AMDGPU::CPol::ALL : AMDGPU::CPol::ALL_pregfx12))
7643     return Op;
7644 
7645   SmallVector<SDValue, 26> Ops;
7646   if (BaseOpcode->Store || BaseOpcode->Atomic)
7647     Ops.push_back(VData); // vdata
7648   if (UsePartialNSA) {
7649     append_range(Ops, ArrayRef(VAddrs).take_front(NSAMaxSize - 1));
7650     Ops.push_back(VAddr);
7651   }
7652   else if (UseNSA)
7653     append_range(Ops, VAddrs);
7654   else
7655     Ops.push_back(VAddr);
7656   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
7657   if (BaseOpcode->Sampler)
7658     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
7659   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
7660   if (IsGFX10Plus)
7661     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
7662   if (!IsGFX12Plus || BaseOpcode->Sampler || BaseOpcode->MSAA)
7663     Ops.push_back(Unorm);
7664   Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
7665   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
7666                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
7667   if (IsGFX10Plus)
7668     Ops.push_back(IsA16 ? True : False);
7669   if (!Subtarget->hasGFX90AInsts()) {
7670     Ops.push_back(TFE); //tfe
7671   } else if (TFE->getAsZExtVal()) {
7672     report_fatal_error("TFE is not supported on this GPU");
7673   }
7674   if (!IsGFX12Plus || BaseOpcode->Sampler || BaseOpcode->MSAA)
7675     Ops.push_back(LWE); // lwe
7676   if (!IsGFX10Plus)
7677     Ops.push_back(DimInfo->DA ? True : False);
7678   if (BaseOpcode->HasD16)
7679     Ops.push_back(IsD16 ? True : False);
7680   if (isa<MemSDNode>(Op))
7681     Ops.push_back(Op.getOperand(0)); // chain
7682 
7683   int NumVAddrDwords =
7684       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
7685   int Opcode = -1;
7686 
7687   if (IsGFX12Plus) {
7688     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx12,
7689                                    NumVDataDwords, NumVAddrDwords);
7690   } else if (IsGFX11Plus) {
7691     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
7692                                    UseNSA ? AMDGPU::MIMGEncGfx11NSA
7693                                           : AMDGPU::MIMGEncGfx11Default,
7694                                    NumVDataDwords, NumVAddrDwords);
7695   } else if (IsGFX10Plus) {
7696     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
7697                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
7698                                           : AMDGPU::MIMGEncGfx10Default,
7699                                    NumVDataDwords, NumVAddrDwords);
7700   } else {
7701     if (Subtarget->hasGFX90AInsts()) {
7702       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
7703                                      NumVDataDwords, NumVAddrDwords);
7704       if (Opcode == -1)
7705         report_fatal_error(
7706             "requested image instruction is not supported on this GPU");
7707     }
7708     if (Opcode == -1 &&
7709         Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
7710       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
7711                                      NumVDataDwords, NumVAddrDwords);
7712     if (Opcode == -1)
7713       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
7714                                      NumVDataDwords, NumVAddrDwords);
7715   }
7716   if (Opcode == -1)
7717     return Op;
7718 
7719   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
7720   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
7721     MachineMemOperand *MemRef = MemOp->getMemOperand();
7722     DAG.setNodeMemRefs(NewNode, {MemRef});
7723   }
7724 
7725   if (BaseOpcode->AtomicX2) {
7726     SmallVector<SDValue, 1> Elt;
7727     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
7728     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
7729   }
7730   if (BaseOpcode->Store)
7731     return SDValue(NewNode, 0);
7732   return constructRetValue(DAG, NewNode,
7733                            OrigResultTypes, IsTexFail,
7734                            Subtarget->hasUnpackedD16VMem(), IsD16,
7735                            DMaskLanes, NumVDataDwords, DL);
7736 }
7737 
7738 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
7739                                        SDValue Offset, SDValue CachePolicy,
7740                                        SelectionDAG &DAG) const {
7741   MachineFunction &MF = DAG.getMachineFunction();
7742 
7743   const DataLayout &DataLayout = DAG.getDataLayout();
7744   Align Alignment =
7745       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
7746 
7747   MachineMemOperand *MMO = MF.getMachineMemOperand(
7748       MachinePointerInfo(),
7749       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
7750           MachineMemOperand::MOInvariant,
7751       VT.getStoreSize(), Alignment);
7752 
7753   if (!Offset->isDivergent()) {
7754     SDValue Ops[] = {
7755         Rsrc,
7756         Offset, // Offset
7757         CachePolicy
7758     };
7759 
7760     // Widen vec3 load to vec4.
7761     if (VT.isVector() && VT.getVectorNumElements() == 3 &&
7762         !Subtarget->hasScalarDwordx3Loads()) {
7763       EVT WidenedVT =
7764           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
7765       auto WidenedOp = DAG.getMemIntrinsicNode(
7766           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
7767           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
7768       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
7769                                    DAG.getVectorIdxConstant(0, DL));
7770       return Subvector;
7771     }
7772 
7773     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
7774                                    DAG.getVTList(VT), Ops, VT, MMO);
7775   }
7776 
7777   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
7778   // assume that the buffer is unswizzled.
7779   SmallVector<SDValue, 4> Loads;
7780   unsigned NumLoads = 1;
7781   MVT LoadVT = VT.getSimpleVT();
7782   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
7783   assert((LoadVT.getScalarType() == MVT::i32 ||
7784           LoadVT.getScalarType() == MVT::f32));
7785 
7786   if (NumElts == 8 || NumElts == 16) {
7787     NumLoads = NumElts / 4;
7788     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
7789   }
7790 
7791   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
7792   SDValue Ops[] = {
7793       DAG.getEntryNode(),                               // Chain
7794       Rsrc,                                             // rsrc
7795       DAG.getConstant(0, DL, MVT::i32),                 // vindex
7796       {},                                               // voffset
7797       {},                                               // soffset
7798       {},                                               // offset
7799       CachePolicy,                                      // cachepolicy
7800       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
7801   };
7802 
7803   // Use the alignment to ensure that the required offsets will fit into the
7804   // immediate offsets.
7805   setBufferOffsets(Offset, DAG, &Ops[3],
7806                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
7807 
7808   uint64_t InstOffset = Ops[5]->getAsZExtVal();
7809   for (unsigned i = 0; i < NumLoads; ++i) {
7810     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
7811     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
7812                                         LoadVT, MMO, DAG));
7813   }
7814 
7815   if (NumElts == 8 || NumElts == 16)
7816     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
7817 
7818   return Loads[0];
7819 }
7820 
7821 SDValue SITargetLowering::lowerWorkitemID(SelectionDAG &DAG, SDValue Op,
7822                                           unsigned Dim,
7823                                           const ArgDescriptor &Arg) const {
7824   SDLoc SL(Op);
7825   MachineFunction &MF = DAG.getMachineFunction();
7826   unsigned MaxID = Subtarget->getMaxWorkitemID(MF.getFunction(), Dim);
7827   if (MaxID == 0)
7828     return DAG.getConstant(0, SL, MVT::i32);
7829 
7830   SDValue Val = loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
7831                                SDLoc(DAG.getEntryNode()), Arg);
7832 
7833   // Don't bother inserting AssertZext for packed IDs since we're emitting the
7834   // masking operations anyway.
7835   //
7836   // TODO: We could assert the top bit is 0 for the source copy.
7837   if (Arg.isMasked())
7838     return Val;
7839 
7840   // Preserve the known bits after expansion to a copy.
7841   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), llvm::bit_width(MaxID));
7842   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Val,
7843                      DAG.getValueType(SmallVT));
7844 }
7845 
7846 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
7847                                                   SelectionDAG &DAG) const {
7848   MachineFunction &MF = DAG.getMachineFunction();
7849   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
7850 
7851   EVT VT = Op.getValueType();
7852   SDLoc DL(Op);
7853   unsigned IntrinsicID = Op.getConstantOperandVal(0);
7854 
7855   // TODO: Should this propagate fast-math-flags?
7856 
7857   switch (IntrinsicID) {
7858   case Intrinsic::amdgcn_implicit_buffer_ptr: {
7859     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
7860       return emitNonHSAIntrinsicError(DAG, DL, VT);
7861     return getPreloadedValue(DAG, *MFI, VT,
7862                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
7863   }
7864   case Intrinsic::amdgcn_dispatch_ptr:
7865   case Intrinsic::amdgcn_queue_ptr: {
7866     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
7867       DiagnosticInfoUnsupported BadIntrin(
7868           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
7869           DL.getDebugLoc());
7870       DAG.getContext()->diagnose(BadIntrin);
7871       return DAG.getUNDEF(VT);
7872     }
7873 
7874     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
7875       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
7876     return getPreloadedValue(DAG, *MFI, VT, RegID);
7877   }
7878   case Intrinsic::amdgcn_implicitarg_ptr: {
7879     if (MFI->isEntryFunction())
7880       return getImplicitArgPtr(DAG, DL);
7881     return getPreloadedValue(DAG, *MFI, VT,
7882                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
7883   }
7884   case Intrinsic::amdgcn_kernarg_segment_ptr: {
7885     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
7886       // This only makes sense to call in a kernel, so just lower to null.
7887       return DAG.getConstant(0, DL, VT);
7888     }
7889 
7890     return getPreloadedValue(DAG, *MFI, VT,
7891                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
7892   }
7893   case Intrinsic::amdgcn_dispatch_id: {
7894     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
7895   }
7896   case Intrinsic::amdgcn_rcp:
7897     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
7898   case Intrinsic::amdgcn_rsq:
7899     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
7900   case Intrinsic::amdgcn_rsq_legacy:
7901     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
7902       return emitRemovedIntrinsicError(DAG, DL, VT);
7903     return SDValue();
7904   case Intrinsic::amdgcn_rcp_legacy:
7905     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
7906       return emitRemovedIntrinsicError(DAG, DL, VT);
7907     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
7908   case Intrinsic::amdgcn_rsq_clamp: {
7909     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
7910       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
7911 
7912     Type *Type = VT.getTypeForEVT(*DAG.getContext());
7913     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
7914     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
7915 
7916     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
7917     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
7918                               DAG.getConstantFP(Max, DL, VT));
7919     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
7920                        DAG.getConstantFP(Min, DL, VT));
7921   }
7922   case Intrinsic::r600_read_ngroups_x:
7923     if (Subtarget->isAmdHsaOS())
7924       return emitNonHSAIntrinsicError(DAG, DL, VT);
7925 
7926     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
7927                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
7928                                     false);
7929   case Intrinsic::r600_read_ngroups_y:
7930     if (Subtarget->isAmdHsaOS())
7931       return emitNonHSAIntrinsicError(DAG, DL, VT);
7932 
7933     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
7934                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
7935                                     false);
7936   case Intrinsic::r600_read_ngroups_z:
7937     if (Subtarget->isAmdHsaOS())
7938       return emitNonHSAIntrinsicError(DAG, DL, VT);
7939 
7940     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
7941                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
7942                                     false);
7943   case Intrinsic::r600_read_global_size_x:
7944     if (Subtarget->isAmdHsaOS())
7945       return emitNonHSAIntrinsicError(DAG, DL, VT);
7946 
7947     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
7948                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
7949                                     Align(4), false);
7950   case Intrinsic::r600_read_global_size_y:
7951     if (Subtarget->isAmdHsaOS())
7952       return emitNonHSAIntrinsicError(DAG, DL, VT);
7953 
7954     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
7955                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
7956                                     Align(4), false);
7957   case Intrinsic::r600_read_global_size_z:
7958     if (Subtarget->isAmdHsaOS())
7959       return emitNonHSAIntrinsicError(DAG, DL, VT);
7960 
7961     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
7962                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
7963                                     Align(4), false);
7964   case Intrinsic::r600_read_local_size_x:
7965     if (Subtarget->isAmdHsaOS())
7966       return emitNonHSAIntrinsicError(DAG, DL, VT);
7967 
7968     return lowerImplicitZextParam(DAG, Op, MVT::i16,
7969                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
7970   case Intrinsic::r600_read_local_size_y:
7971     if (Subtarget->isAmdHsaOS())
7972       return emitNonHSAIntrinsicError(DAG, DL, VT);
7973 
7974     return lowerImplicitZextParam(DAG, Op, MVT::i16,
7975                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
7976   case Intrinsic::r600_read_local_size_z:
7977     if (Subtarget->isAmdHsaOS())
7978       return emitNonHSAIntrinsicError(DAG, DL, VT);
7979 
7980     return lowerImplicitZextParam(DAG, Op, MVT::i16,
7981                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
7982   case Intrinsic::amdgcn_workgroup_id_x:
7983     return getPreloadedValue(DAG, *MFI, VT,
7984                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
7985   case Intrinsic::amdgcn_workgroup_id_y:
7986     return getPreloadedValue(DAG, *MFI, VT,
7987                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
7988   case Intrinsic::amdgcn_workgroup_id_z:
7989     return getPreloadedValue(DAG, *MFI, VT,
7990                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
7991   case Intrinsic::amdgcn_lds_kernel_id: {
7992     if (MFI->isEntryFunction())
7993       return getLDSKernelId(DAG, DL);
7994     return getPreloadedValue(DAG, *MFI, VT,
7995                              AMDGPUFunctionArgInfo::LDS_KERNEL_ID);
7996   }
7997   case Intrinsic::amdgcn_workitem_id_x:
7998     return lowerWorkitemID(DAG, Op, 0, MFI->getArgInfo().WorkItemIDX);
7999   case Intrinsic::amdgcn_workitem_id_y:
8000     return lowerWorkitemID(DAG, Op, 1, MFI->getArgInfo().WorkItemIDY);
8001   case Intrinsic::amdgcn_workitem_id_z:
8002     return lowerWorkitemID(DAG, Op, 2, MFI->getArgInfo().WorkItemIDZ);
8003   case Intrinsic::amdgcn_wavefrontsize:
8004     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
8005                            SDLoc(Op), MVT::i32);
8006   case Intrinsic::amdgcn_s_buffer_load: {
8007     unsigned CPol = Op.getConstantOperandVal(3);
8008     if (CPol & ~((Subtarget->getGeneration() >= AMDGPUSubtarget::GFX12)
8009                      ? AMDGPU::CPol::ALL
8010                      : AMDGPU::CPol::ALL_pregfx12))
8011       return Op;
8012     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
8013                         DAG);
8014   }
8015   case Intrinsic::amdgcn_fdiv_fast:
8016     return lowerFDIV_FAST(Op, DAG);
8017   case Intrinsic::amdgcn_sin:
8018     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
8019 
8020   case Intrinsic::amdgcn_cos:
8021     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
8022 
8023   case Intrinsic::amdgcn_mul_u24:
8024     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
8025   case Intrinsic::amdgcn_mul_i24:
8026     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
8027 
8028   case Intrinsic::amdgcn_log_clamp: {
8029     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
8030       return SDValue();
8031 
8032     return emitRemovedIntrinsicError(DAG, DL, VT);
8033   }
8034   case Intrinsic::amdgcn_fract:
8035     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
8036 
8037   case Intrinsic::amdgcn_class:
8038     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
8039                        Op.getOperand(1), Op.getOperand(2));
8040   case Intrinsic::amdgcn_div_fmas:
8041     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
8042                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
8043                        Op.getOperand(4));
8044 
8045   case Intrinsic::amdgcn_div_fixup:
8046     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
8047                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
8048 
8049   case Intrinsic::amdgcn_div_scale: {
8050     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
8051 
8052     // Translate to the operands expected by the machine instruction. The
8053     // first parameter must be the same as the first instruction.
8054     SDValue Numerator = Op.getOperand(1);
8055     SDValue Denominator = Op.getOperand(2);
8056 
8057     // Note this order is opposite of the machine instruction's operations,
8058     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
8059     // intrinsic has the numerator as the first operand to match a normal
8060     // division operation.
8061 
8062     SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator;
8063 
8064     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
8065                        Denominator, Numerator);
8066   }
8067   case Intrinsic::amdgcn_icmp: {
8068     // There is a Pat that handles this variant, so return it as-is.
8069     if (Op.getOperand(1).getValueType() == MVT::i1 &&
8070         Op.getConstantOperandVal(2) == 0 &&
8071         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
8072       return Op;
8073     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
8074   }
8075   case Intrinsic::amdgcn_fcmp: {
8076     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
8077   }
8078   case Intrinsic::amdgcn_ballot:
8079     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
8080   case Intrinsic::amdgcn_fmed3:
8081     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
8082                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
8083   case Intrinsic::amdgcn_fdot2:
8084     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
8085                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
8086                        Op.getOperand(4));
8087   case Intrinsic::amdgcn_fmul_legacy:
8088     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
8089                        Op.getOperand(1), Op.getOperand(2));
8090   case Intrinsic::amdgcn_sffbh:
8091     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
8092   case Intrinsic::amdgcn_sbfe:
8093     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
8094                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
8095   case Intrinsic::amdgcn_ubfe:
8096     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
8097                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
8098   case Intrinsic::amdgcn_cvt_pkrtz:
8099   case Intrinsic::amdgcn_cvt_pknorm_i16:
8100   case Intrinsic::amdgcn_cvt_pknorm_u16:
8101   case Intrinsic::amdgcn_cvt_pk_i16:
8102   case Intrinsic::amdgcn_cvt_pk_u16: {
8103     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
8104     EVT VT = Op.getValueType();
8105     unsigned Opcode;
8106 
8107     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
8108       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
8109     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
8110       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
8111     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
8112       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
8113     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
8114       Opcode = AMDGPUISD::CVT_PK_I16_I32;
8115     else
8116       Opcode = AMDGPUISD::CVT_PK_U16_U32;
8117 
8118     if (isTypeLegal(VT))
8119       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
8120 
8121     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
8122                                Op.getOperand(1), Op.getOperand(2));
8123     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
8124   }
8125   case Intrinsic::amdgcn_fmad_ftz:
8126     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
8127                        Op.getOperand(2), Op.getOperand(3));
8128 
8129   case Intrinsic::amdgcn_if_break:
8130     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
8131                                       Op->getOperand(1), Op->getOperand(2)), 0);
8132 
8133   case Intrinsic::amdgcn_groupstaticsize: {
8134     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
8135     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
8136       return Op;
8137 
8138     const Module *M = MF.getFunction().getParent();
8139     const GlobalValue *GV =
8140         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
8141     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
8142                                             SIInstrInfo::MO_ABS32_LO);
8143     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
8144   }
8145   case Intrinsic::amdgcn_is_shared:
8146   case Intrinsic::amdgcn_is_private: {
8147     SDLoc SL(Op);
8148     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
8149       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
8150     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
8151     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
8152                                  Op.getOperand(1));
8153 
8154     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
8155                                 DAG.getConstant(1, SL, MVT::i32));
8156     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
8157   }
8158   case Intrinsic::amdgcn_perm:
8159     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
8160                        Op.getOperand(2), Op.getOperand(3));
8161   case Intrinsic::amdgcn_reloc_constant: {
8162     Module *M = const_cast<Module *>(MF.getFunction().getParent());
8163     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
8164     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
8165     auto RelocSymbol = cast<GlobalVariable>(
8166         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
8167     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
8168                                             SIInstrInfo::MO_ABS32_LO);
8169     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
8170   }
8171   default:
8172     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
8173             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
8174       return lowerImage(Op, ImageDimIntr, DAG, false);
8175 
8176     return Op;
8177   }
8178 }
8179 
8180 // On targets not supporting constant in soffset field, turn zero to
8181 // SGPR_NULL to avoid generating an extra s_mov with zero.
8182 static SDValue selectSOffset(SDValue SOffset, SelectionDAG &DAG,
8183                              const GCNSubtarget *Subtarget) {
8184   if (Subtarget->hasRestrictedSOffset() && isNullConstant(SOffset))
8185     return DAG.getRegister(AMDGPU::SGPR_NULL, MVT::i32);
8186   return SOffset;
8187 }
8188 
8189 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
8190                                                      SelectionDAG &DAG,
8191                                                      unsigned NewOpcode) const {
8192   SDLoc DL(Op);
8193 
8194   SDValue VData = Op.getOperand(2);
8195   SDValue Rsrc = bufferRsrcPtrToVector(Op.getOperand(3), DAG);
8196   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
8197   auto SOffset = selectSOffset(Op.getOperand(5), DAG, Subtarget);
8198   SDValue Ops[] = {
8199       Op.getOperand(0),                      // Chain
8200       VData,                                 // vdata
8201       Rsrc,                                  // rsrc
8202       DAG.getConstant(0, DL, MVT::i32),      // vindex
8203       Offsets.first,                         // voffset
8204       SOffset,                               // soffset
8205       Offsets.second,                        // offset
8206       Op.getOperand(6),                      // cachepolicy
8207       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8208   };
8209 
8210   auto *M = cast<MemSDNode>(Op);
8211 
8212   EVT MemVT = VData.getValueType();
8213   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
8214                                  M->getMemOperand());
8215 }
8216 
8217 // Return a value to use for the idxen operand by examining the vindex operand.
8218 static unsigned getIdxEn(SDValue VIndex) {
8219   // No need to set idxen if vindex is known to be zero.
8220   return isNullConstant(VIndex) ? 0 : 1;
8221 }
8222 
8223 SDValue
8224 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
8225                                                 unsigned NewOpcode) const {
8226   SDLoc DL(Op);
8227 
8228   SDValue VData = Op.getOperand(2);
8229   SDValue Rsrc = bufferRsrcPtrToVector(Op.getOperand(3), DAG);
8230   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
8231   auto SOffset = selectSOffset(Op.getOperand(6), DAG, Subtarget);
8232   SDValue Ops[] = {
8233       Op.getOperand(0),                      // Chain
8234       VData,                                 // vdata
8235       Rsrc,                                  // rsrc
8236       Op.getOperand(4),                      // vindex
8237       Offsets.first,                         // voffset
8238       SOffset,                               // soffset
8239       Offsets.second,                        // offset
8240       Op.getOperand(7),                      // cachepolicy
8241       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8242   };
8243 
8244   auto *M = cast<MemSDNode>(Op);
8245 
8246   EVT MemVT = VData.getValueType();
8247   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
8248                                  M->getMemOperand());
8249 }
8250 
8251 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
8252                                                  SelectionDAG &DAG) const {
8253   unsigned IntrID = Op.getConstantOperandVal(1);
8254   SDLoc DL(Op);
8255 
8256   switch (IntrID) {
8257   case Intrinsic::amdgcn_ds_ordered_add:
8258   case Intrinsic::amdgcn_ds_ordered_swap: {
8259     MemSDNode *M = cast<MemSDNode>(Op);
8260     SDValue Chain = M->getOperand(0);
8261     SDValue M0 = M->getOperand(2);
8262     SDValue Value = M->getOperand(3);
8263     unsigned IndexOperand = M->getConstantOperandVal(7);
8264     unsigned WaveRelease = M->getConstantOperandVal(8);
8265     unsigned WaveDone = M->getConstantOperandVal(9);
8266 
8267     unsigned OrderedCountIndex = IndexOperand & 0x3f;
8268     IndexOperand &= ~0x3f;
8269     unsigned CountDw = 0;
8270 
8271     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
8272       CountDw = (IndexOperand >> 24) & 0xf;
8273       IndexOperand &= ~(0xf << 24);
8274 
8275       if (CountDw < 1 || CountDw > 4) {
8276         report_fatal_error(
8277             "ds_ordered_count: dword count must be between 1 and 4");
8278       }
8279     }
8280 
8281     if (IndexOperand)
8282       report_fatal_error("ds_ordered_count: bad index operand");
8283 
8284     if (WaveDone && !WaveRelease)
8285       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
8286 
8287     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
8288     unsigned ShaderType =
8289         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
8290     unsigned Offset0 = OrderedCountIndex << 2;
8291     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (Instruction << 4);
8292 
8293     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
8294       Offset1 |= (CountDw - 1) << 6;
8295 
8296     if (Subtarget->getGeneration() < AMDGPUSubtarget::GFX11)
8297       Offset1 |= ShaderType << 2;
8298 
8299     unsigned Offset = Offset0 | (Offset1 << 8);
8300 
8301     SDValue Ops[] = {
8302       Chain,
8303       Value,
8304       DAG.getTargetConstant(Offset, DL, MVT::i16),
8305       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
8306     };
8307     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
8308                                    M->getVTList(), Ops, M->getMemoryVT(),
8309                                    M->getMemOperand());
8310   }
8311   case Intrinsic::amdgcn_ds_fadd: {
8312     MemSDNode *M = cast<MemSDNode>(Op);
8313     unsigned Opc;
8314     switch (IntrID) {
8315     case Intrinsic::amdgcn_ds_fadd:
8316       Opc = ISD::ATOMIC_LOAD_FADD;
8317       break;
8318     }
8319 
8320     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
8321                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
8322                          M->getMemOperand());
8323   }
8324   case Intrinsic::amdgcn_ds_fmin:
8325   case Intrinsic::amdgcn_ds_fmax: {
8326     MemSDNode *M = cast<MemSDNode>(Op);
8327     unsigned Opc;
8328     switch (IntrID) {
8329     case Intrinsic::amdgcn_ds_fmin:
8330       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
8331       break;
8332     case Intrinsic::amdgcn_ds_fmax:
8333       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
8334       break;
8335     default:
8336       llvm_unreachable("Unknown intrinsic!");
8337     }
8338     SDValue Ops[] = {
8339       M->getOperand(0), // Chain
8340       M->getOperand(2), // Ptr
8341       M->getOperand(3)  // Value
8342     };
8343 
8344     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
8345                                    M->getMemoryVT(), M->getMemOperand());
8346   }
8347   case Intrinsic::amdgcn_buffer_load:
8348   case Intrinsic::amdgcn_buffer_load_format: {
8349     unsigned Glc = Op.getConstantOperandVal(5);
8350     unsigned Slc = Op.getConstantOperandVal(6);
8351     unsigned IdxEn = getIdxEn(Op.getOperand(3));
8352     SDValue Ops[] = {
8353       Op.getOperand(0), // Chain
8354       Op.getOperand(2), // rsrc
8355       Op.getOperand(3), // vindex
8356       SDValue(),        // voffset -- will be set by setBufferOffsets
8357       SDValue(),        // soffset -- will be set by setBufferOffsets
8358       SDValue(),        // offset -- will be set by setBufferOffsets
8359       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
8360       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
8361     };
8362     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
8363 
8364     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
8365         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
8366 
8367     EVT VT = Op.getValueType();
8368     EVT IntVT = VT.changeTypeToInteger();
8369     auto *M = cast<MemSDNode>(Op);
8370     EVT LoadVT = Op.getValueType();
8371 
8372     if (LoadVT.getScalarType() == MVT::f16)
8373       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
8374                                  M, DAG, Ops);
8375 
8376     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
8377     if (LoadVT.getScalarType() == MVT::i8 ||
8378         LoadVT.getScalarType() == MVT::i16)
8379       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
8380 
8381     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
8382                                M->getMemOperand(), DAG);
8383   }
8384   case Intrinsic::amdgcn_raw_buffer_load:
8385   case Intrinsic::amdgcn_raw_ptr_buffer_load:
8386   case Intrinsic::amdgcn_raw_buffer_load_format:
8387   case Intrinsic::amdgcn_raw_ptr_buffer_load_format: {
8388     const bool IsFormat =
8389         IntrID == Intrinsic::amdgcn_raw_buffer_load_format ||
8390         IntrID == Intrinsic::amdgcn_raw_ptr_buffer_load_format;
8391 
8392     SDValue Rsrc = bufferRsrcPtrToVector(Op.getOperand(2), DAG);
8393     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
8394     auto SOffset = selectSOffset(Op.getOperand(4), DAG, Subtarget);
8395     SDValue Ops[] = {
8396         Op.getOperand(0),                      // Chain
8397         Rsrc,                                  // rsrc
8398         DAG.getConstant(0, DL, MVT::i32),      // vindex
8399         Offsets.first,                         // voffset
8400         SOffset,                               // soffset
8401         Offsets.second,                        // offset
8402         Op.getOperand(5),                      // cachepolicy, swizzled buffer
8403         DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8404     };
8405 
8406     auto *M = cast<MemSDNode>(Op);
8407     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
8408   }
8409   case Intrinsic::amdgcn_struct_buffer_load:
8410   case Intrinsic::amdgcn_struct_ptr_buffer_load:
8411   case Intrinsic::amdgcn_struct_buffer_load_format:
8412   case Intrinsic::amdgcn_struct_ptr_buffer_load_format: {
8413     const bool IsFormat =
8414         IntrID == Intrinsic::amdgcn_struct_buffer_load_format ||
8415         IntrID == Intrinsic::amdgcn_struct_ptr_buffer_load_format;
8416 
8417     SDValue Rsrc = bufferRsrcPtrToVector(Op.getOperand(2), DAG);
8418     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
8419     auto SOffset = selectSOffset(Op.getOperand(5), DAG, Subtarget);
8420     SDValue Ops[] = {
8421         Op.getOperand(0),                      // Chain
8422         Rsrc,                                  // rsrc
8423         Op.getOperand(3),                      // vindex
8424         Offsets.first,                         // voffset
8425         SOffset,                               // soffset
8426         Offsets.second,                        // offset
8427         Op.getOperand(6),                      // cachepolicy, swizzled buffer
8428         DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8429     };
8430 
8431     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
8432   }
8433   case Intrinsic::amdgcn_tbuffer_load: {
8434     MemSDNode *M = cast<MemSDNode>(Op);
8435     EVT LoadVT = Op.getValueType();
8436 
8437     auto SOffset = selectSOffset(Op.getOperand(5), DAG, Subtarget);
8438     unsigned Dfmt = Op.getConstantOperandVal(7);
8439     unsigned Nfmt = Op.getConstantOperandVal(8);
8440     unsigned Glc = Op.getConstantOperandVal(9);
8441     unsigned Slc = Op.getConstantOperandVal(10);
8442     unsigned IdxEn = getIdxEn(Op.getOperand(3));
8443     SDValue Ops[] = {
8444         Op.getOperand(0),                                        // Chain
8445         Op.getOperand(2),                                        // rsrc
8446         Op.getOperand(3),                                        // vindex
8447         Op.getOperand(4),                                        // voffset
8448         SOffset,                                                 // soffset
8449         Op.getOperand(6),                                        // offset
8450         DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
8451         DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32),   // cachepolicy
8452         DAG.getTargetConstant(IdxEn, DL, MVT::i1)                // idxen
8453     };
8454 
8455     if (LoadVT.getScalarType() == MVT::f16)
8456       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
8457                                  M, DAG, Ops);
8458     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
8459                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
8460                                DAG);
8461   }
8462   case Intrinsic::amdgcn_raw_tbuffer_load:
8463   case Intrinsic::amdgcn_raw_ptr_tbuffer_load: {
8464     MemSDNode *M = cast<MemSDNode>(Op);
8465     EVT LoadVT = Op.getValueType();
8466     SDValue Rsrc = bufferRsrcPtrToVector(Op.getOperand(2), DAG);
8467     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
8468     auto SOffset = selectSOffset(Op.getOperand(4), DAG, Subtarget);
8469 
8470     SDValue Ops[] = {
8471         Op.getOperand(0),                      // Chain
8472         Rsrc,                                  // rsrc
8473         DAG.getConstant(0, DL, MVT::i32),      // vindex
8474         Offsets.first,                         // voffset
8475         SOffset,                               // soffset
8476         Offsets.second,                        // offset
8477         Op.getOperand(5),                      // format
8478         Op.getOperand(6),                      // cachepolicy, swizzled buffer
8479         DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8480     };
8481 
8482     if (LoadVT.getScalarType() == MVT::f16)
8483       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
8484                                  M, DAG, Ops);
8485     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
8486                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
8487                                DAG);
8488   }
8489   case Intrinsic::amdgcn_struct_tbuffer_load:
8490   case Intrinsic::amdgcn_struct_ptr_tbuffer_load: {
8491     MemSDNode *M = cast<MemSDNode>(Op);
8492     EVT LoadVT = Op.getValueType();
8493     SDValue Rsrc = bufferRsrcPtrToVector(Op.getOperand(2), DAG);
8494     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
8495     auto SOffset = selectSOffset(Op.getOperand(5), DAG, Subtarget);
8496 
8497     SDValue Ops[] = {
8498         Op.getOperand(0),                      // Chain
8499         Rsrc,                                  // rsrc
8500         Op.getOperand(3),                      // vindex
8501         Offsets.first,                         // voffset
8502         SOffset,                               // soffset
8503         Offsets.second,                        // offset
8504         Op.getOperand(6),                      // format
8505         Op.getOperand(7),                      // cachepolicy, swizzled buffer
8506         DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8507     };
8508 
8509     if (LoadVT.getScalarType() == MVT::f16)
8510       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
8511                                  M, DAG, Ops);
8512     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
8513                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
8514                                DAG);
8515   }
8516   case Intrinsic::amdgcn_buffer_atomic_swap:
8517   case Intrinsic::amdgcn_buffer_atomic_add:
8518   case Intrinsic::amdgcn_buffer_atomic_sub:
8519   case Intrinsic::amdgcn_buffer_atomic_csub:
8520   case Intrinsic::amdgcn_buffer_atomic_smin:
8521   case Intrinsic::amdgcn_buffer_atomic_umin:
8522   case Intrinsic::amdgcn_buffer_atomic_smax:
8523   case Intrinsic::amdgcn_buffer_atomic_umax:
8524   case Intrinsic::amdgcn_buffer_atomic_and:
8525   case Intrinsic::amdgcn_buffer_atomic_or:
8526   case Intrinsic::amdgcn_buffer_atomic_xor:
8527   case Intrinsic::amdgcn_buffer_atomic_fadd: {
8528     unsigned Slc = Op.getConstantOperandVal(6);
8529     unsigned IdxEn = getIdxEn(Op.getOperand(4));
8530     SDValue Ops[] = {
8531       Op.getOperand(0), // Chain
8532       Op.getOperand(2), // vdata
8533       Op.getOperand(3), // rsrc
8534       Op.getOperand(4), // vindex
8535       SDValue(),        // voffset -- will be set by setBufferOffsets
8536       SDValue(),        // soffset -- will be set by setBufferOffsets
8537       SDValue(),        // offset -- will be set by setBufferOffsets
8538       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
8539       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
8540     };
8541     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
8542 
8543     EVT VT = Op.getValueType();
8544 
8545     auto *M = cast<MemSDNode>(Op);
8546     unsigned Opcode = 0;
8547 
8548     switch (IntrID) {
8549     case Intrinsic::amdgcn_buffer_atomic_swap:
8550       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
8551       break;
8552     case Intrinsic::amdgcn_buffer_atomic_add:
8553       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
8554       break;
8555     case Intrinsic::amdgcn_buffer_atomic_sub:
8556       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
8557       break;
8558     case Intrinsic::amdgcn_buffer_atomic_csub:
8559       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
8560       break;
8561     case Intrinsic::amdgcn_buffer_atomic_smin:
8562       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
8563       break;
8564     case Intrinsic::amdgcn_buffer_atomic_umin:
8565       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
8566       break;
8567     case Intrinsic::amdgcn_buffer_atomic_smax:
8568       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
8569       break;
8570     case Intrinsic::amdgcn_buffer_atomic_umax:
8571       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
8572       break;
8573     case Intrinsic::amdgcn_buffer_atomic_and:
8574       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
8575       break;
8576     case Intrinsic::amdgcn_buffer_atomic_or:
8577       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
8578       break;
8579     case Intrinsic::amdgcn_buffer_atomic_xor:
8580       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
8581       break;
8582     case Intrinsic::amdgcn_buffer_atomic_fadd:
8583       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
8584       break;
8585     default:
8586       llvm_unreachable("unhandled atomic opcode");
8587     }
8588 
8589     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
8590                                    M->getMemOperand());
8591   }
8592   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
8593   case Intrinsic::amdgcn_raw_ptr_buffer_atomic_fadd:
8594     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
8595   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
8596   case Intrinsic::amdgcn_struct_ptr_buffer_atomic_fadd:
8597     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
8598   case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
8599   case Intrinsic::amdgcn_raw_ptr_buffer_atomic_fmin:
8600     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
8601   case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
8602   case Intrinsic::amdgcn_struct_ptr_buffer_atomic_fmin:
8603     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
8604   case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
8605   case Intrinsic::amdgcn_raw_ptr_buffer_atomic_fmax:
8606     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
8607   case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
8608   case Intrinsic::amdgcn_struct_ptr_buffer_atomic_fmax:
8609     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
8610   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
8611   case Intrinsic::amdgcn_raw_ptr_buffer_atomic_swap:
8612     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
8613   case Intrinsic::amdgcn_raw_buffer_atomic_add:
8614   case Intrinsic::amdgcn_raw_ptr_buffer_atomic_add:
8615     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
8616   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
8617   case Intrinsic::amdgcn_raw_ptr_buffer_atomic_sub:
8618     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
8619   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
8620   case Intrinsic::amdgcn_raw_ptr_buffer_atomic_smin:
8621     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
8622   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
8623   case Intrinsic::amdgcn_raw_ptr_buffer_atomic_umin:
8624     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
8625   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
8626   case Intrinsic::amdgcn_raw_ptr_buffer_atomic_smax:
8627     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
8628   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
8629   case Intrinsic::amdgcn_raw_ptr_buffer_atomic_umax:
8630     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
8631   case Intrinsic::amdgcn_raw_buffer_atomic_and:
8632   case Intrinsic::amdgcn_raw_ptr_buffer_atomic_and:
8633     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
8634   case Intrinsic::amdgcn_raw_buffer_atomic_or:
8635   case Intrinsic::amdgcn_raw_ptr_buffer_atomic_or:
8636     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
8637   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
8638   case Intrinsic::amdgcn_raw_ptr_buffer_atomic_xor:
8639     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
8640   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
8641   case Intrinsic::amdgcn_raw_ptr_buffer_atomic_inc:
8642     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
8643   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
8644   case Intrinsic::amdgcn_raw_ptr_buffer_atomic_dec:
8645     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
8646   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
8647   case Intrinsic::amdgcn_struct_ptr_buffer_atomic_swap:
8648     return lowerStructBufferAtomicIntrin(Op, DAG,
8649                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
8650   case Intrinsic::amdgcn_struct_buffer_atomic_add:
8651   case Intrinsic::amdgcn_struct_ptr_buffer_atomic_add:
8652     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
8653   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
8654   case Intrinsic::amdgcn_struct_ptr_buffer_atomic_sub:
8655     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
8656   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
8657   case Intrinsic::amdgcn_struct_ptr_buffer_atomic_smin:
8658     return lowerStructBufferAtomicIntrin(Op, DAG,
8659                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
8660   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
8661   case Intrinsic::amdgcn_struct_ptr_buffer_atomic_umin:
8662     return lowerStructBufferAtomicIntrin(Op, DAG,
8663                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
8664   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
8665   case Intrinsic::amdgcn_struct_ptr_buffer_atomic_smax:
8666     return lowerStructBufferAtomicIntrin(Op, DAG,
8667                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
8668   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
8669   case Intrinsic::amdgcn_struct_ptr_buffer_atomic_umax:
8670     return lowerStructBufferAtomicIntrin(Op, DAG,
8671                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
8672   case Intrinsic::amdgcn_struct_buffer_atomic_and:
8673   case Intrinsic::amdgcn_struct_ptr_buffer_atomic_and:
8674     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
8675   case Intrinsic::amdgcn_struct_buffer_atomic_or:
8676   case Intrinsic::amdgcn_struct_ptr_buffer_atomic_or:
8677     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
8678   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
8679   case Intrinsic::amdgcn_struct_ptr_buffer_atomic_xor:
8680     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
8681   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
8682   case Intrinsic::amdgcn_struct_ptr_buffer_atomic_inc:
8683     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
8684   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
8685   case Intrinsic::amdgcn_struct_ptr_buffer_atomic_dec:
8686     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
8687 
8688   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
8689     unsigned Slc = Op.getConstantOperandVal(7);
8690     unsigned IdxEn = getIdxEn(Op.getOperand(5));
8691     SDValue Ops[] = {
8692       Op.getOperand(0), // Chain
8693       Op.getOperand(2), // src
8694       Op.getOperand(3), // cmp
8695       Op.getOperand(4), // rsrc
8696       Op.getOperand(5), // vindex
8697       SDValue(),        // voffset -- will be set by setBufferOffsets
8698       SDValue(),        // soffset -- will be set by setBufferOffsets
8699       SDValue(),        // offset -- will be set by setBufferOffsets
8700       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
8701       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
8702     };
8703     setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
8704 
8705     EVT VT = Op.getValueType();
8706     auto *M = cast<MemSDNode>(Op);
8707 
8708     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
8709                                    Op->getVTList(), Ops, VT, M->getMemOperand());
8710   }
8711   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap:
8712   case Intrinsic::amdgcn_raw_ptr_buffer_atomic_cmpswap: {
8713     SDValue Rsrc = bufferRsrcPtrToVector(Op.getOperand(4), DAG);
8714     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
8715     auto SOffset = selectSOffset(Op.getOperand(6), DAG, Subtarget);
8716     SDValue Ops[] = {
8717         Op.getOperand(0),                      // Chain
8718         Op.getOperand(2),                      // src
8719         Op.getOperand(3),                      // cmp
8720         Rsrc,                                  // rsrc
8721         DAG.getConstant(0, DL, MVT::i32),      // vindex
8722         Offsets.first,                         // voffset
8723         SOffset,                               // soffset
8724         Offsets.second,                        // offset
8725         Op.getOperand(7),                      // cachepolicy
8726         DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8727     };
8728     EVT VT = Op.getValueType();
8729     auto *M = cast<MemSDNode>(Op);
8730 
8731     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
8732                                    Op->getVTList(), Ops, VT, M->getMemOperand());
8733   }
8734   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap:
8735   case Intrinsic::amdgcn_struct_ptr_buffer_atomic_cmpswap: {
8736     SDValue Rsrc = bufferRsrcPtrToVector(Op->getOperand(4), DAG);
8737     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
8738     auto SOffset = selectSOffset(Op.getOperand(7), DAG, Subtarget);
8739     SDValue Ops[] = {
8740         Op.getOperand(0),                      // Chain
8741         Op.getOperand(2),                      // src
8742         Op.getOperand(3),                      // cmp
8743         Rsrc,                                  // rsrc
8744         Op.getOperand(5),                      // vindex
8745         Offsets.first,                         // voffset
8746         SOffset,                               // soffset
8747         Offsets.second,                        // offset
8748         Op.getOperand(8),                      // cachepolicy
8749         DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8750     };
8751     EVT VT = Op.getValueType();
8752     auto *M = cast<MemSDNode>(Op);
8753 
8754     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
8755                                    Op->getVTList(), Ops, VT, M->getMemOperand());
8756   }
8757   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
8758     MemSDNode *M = cast<MemSDNode>(Op);
8759     SDValue NodePtr = M->getOperand(2);
8760     SDValue RayExtent = M->getOperand(3);
8761     SDValue RayOrigin = M->getOperand(4);
8762     SDValue RayDir = M->getOperand(5);
8763     SDValue RayInvDir = M->getOperand(6);
8764     SDValue TDescr = M->getOperand(7);
8765 
8766     assert(NodePtr.getValueType() == MVT::i32 ||
8767            NodePtr.getValueType() == MVT::i64);
8768     assert(RayDir.getValueType() == MVT::v3f16 ||
8769            RayDir.getValueType() == MVT::v3f32);
8770 
8771     if (!Subtarget->hasGFX10_AEncoding()) {
8772       emitRemovedIntrinsicError(DAG, DL, Op.getValueType());
8773       return SDValue();
8774     }
8775 
8776     const bool IsGFX11 = AMDGPU::isGFX11(*Subtarget);
8777     const bool IsGFX11Plus = AMDGPU::isGFX11Plus(*Subtarget);
8778     const bool IsGFX12Plus = AMDGPU::isGFX12Plus(*Subtarget);
8779     const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
8780     const bool Is64 = NodePtr.getValueType() == MVT::i64;
8781     const unsigned NumVDataDwords = 4;
8782     const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
8783     const unsigned NumVAddrs = IsGFX11Plus ? (IsA16 ? 4 : 5) : NumVAddrDwords;
8784     const bool UseNSA = (Subtarget->hasNSAEncoding() &&
8785                          NumVAddrs <= Subtarget->getNSAMaxSize()) ||
8786                         IsGFX12Plus;
8787     const unsigned BaseOpcodes[2][2] = {
8788         {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
8789         {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
8790          AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
8791     int Opcode;
8792     if (UseNSA) {
8793       Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
8794                                      IsGFX12Plus ? AMDGPU::MIMGEncGfx12
8795                                      : IsGFX11   ? AMDGPU::MIMGEncGfx11NSA
8796                                                  : AMDGPU::MIMGEncGfx10NSA,
8797                                      NumVDataDwords, NumVAddrDwords);
8798     } else {
8799       assert(!IsGFX12Plus);
8800       Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
8801                                      IsGFX11 ? AMDGPU::MIMGEncGfx11Default
8802                                              : AMDGPU::MIMGEncGfx10Default,
8803                                      NumVDataDwords, NumVAddrDwords);
8804     }
8805     assert(Opcode != -1);
8806 
8807     SmallVector<SDValue, 16> Ops;
8808 
8809     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
8810       SmallVector<SDValue, 3> Lanes;
8811       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
8812       if (Lanes[0].getValueSizeInBits() == 32) {
8813         for (unsigned I = 0; I < 3; ++I)
8814           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
8815       } else {
8816         if (IsAligned) {
8817           Ops.push_back(
8818             DAG.getBitcast(MVT::i32,
8819                            DAG.getBuildVector(MVT::v2f16, DL,
8820                                               { Lanes[0], Lanes[1] })));
8821           Ops.push_back(Lanes[2]);
8822         } else {
8823           SDValue Elt0 = Ops.pop_back_val();
8824           Ops.push_back(
8825             DAG.getBitcast(MVT::i32,
8826                            DAG.getBuildVector(MVT::v2f16, DL,
8827                                               { Elt0, Lanes[0] })));
8828           Ops.push_back(
8829             DAG.getBitcast(MVT::i32,
8830                            DAG.getBuildVector(MVT::v2f16, DL,
8831                                               { Lanes[1], Lanes[2] })));
8832         }
8833       }
8834     };
8835 
8836     if (UseNSA && IsGFX11Plus) {
8837       Ops.push_back(NodePtr);
8838       Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
8839       Ops.push_back(RayOrigin);
8840       if (IsA16) {
8841         SmallVector<SDValue, 3> DirLanes, InvDirLanes, MergedLanes;
8842         DAG.ExtractVectorElements(RayDir, DirLanes, 0, 3);
8843         DAG.ExtractVectorElements(RayInvDir, InvDirLanes, 0, 3);
8844         for (unsigned I = 0; I < 3; ++I) {
8845           MergedLanes.push_back(DAG.getBitcast(
8846               MVT::i32, DAG.getBuildVector(MVT::v2f16, DL,
8847                                            {DirLanes[I], InvDirLanes[I]})));
8848         }
8849         Ops.push_back(DAG.getBuildVector(MVT::v3i32, DL, MergedLanes));
8850       } else {
8851         Ops.push_back(RayDir);
8852         Ops.push_back(RayInvDir);
8853       }
8854     } else {
8855       if (Is64)
8856         DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0,
8857                                   2);
8858       else
8859         Ops.push_back(NodePtr);
8860 
8861       Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
8862       packLanes(RayOrigin, true);
8863       packLanes(RayDir, true);
8864       packLanes(RayInvDir, false);
8865     }
8866 
8867     if (!UseNSA) {
8868       // Build a single vector containing all the operands so far prepared.
8869       if (NumVAddrDwords > 12) {
8870         SDValue Undef = DAG.getUNDEF(MVT::i32);
8871         Ops.append(16 - Ops.size(), Undef);
8872       }
8873       assert(Ops.size() >= 8 && Ops.size() <= 12);
8874       SDValue MergedOps = DAG.getBuildVector(
8875           MVT::getVectorVT(MVT::i32, Ops.size()), DL, Ops);
8876       Ops.clear();
8877       Ops.push_back(MergedOps);
8878     }
8879 
8880     Ops.push_back(TDescr);
8881     Ops.push_back(DAG.getTargetConstant(IsA16, DL, MVT::i1));
8882     Ops.push_back(M->getChain());
8883 
8884     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
8885     MachineMemOperand *MemRef = M->getMemOperand();
8886     DAG.setNodeMemRefs(NewNode, {MemRef});
8887     return SDValue(NewNode, 0);
8888   }
8889   case Intrinsic::amdgcn_global_atomic_fmin:
8890   case Intrinsic::amdgcn_global_atomic_fmax:
8891   case Intrinsic::amdgcn_global_atomic_fmin_num:
8892   case Intrinsic::amdgcn_global_atomic_fmax_num:
8893   case Intrinsic::amdgcn_flat_atomic_fmin:
8894   case Intrinsic::amdgcn_flat_atomic_fmax:
8895   case Intrinsic::amdgcn_flat_atomic_fmin_num:
8896   case Intrinsic::amdgcn_flat_atomic_fmax_num: {
8897     MemSDNode *M = cast<MemSDNode>(Op);
8898     SDValue Ops[] = {
8899       M->getOperand(0), // Chain
8900       M->getOperand(2), // Ptr
8901       M->getOperand(3)  // Value
8902     };
8903     unsigned Opcode = 0;
8904     switch (IntrID) {
8905     case Intrinsic::amdgcn_global_atomic_fmin:
8906     case Intrinsic::amdgcn_global_atomic_fmin_num:
8907     case Intrinsic::amdgcn_flat_atomic_fmin:
8908     case Intrinsic::amdgcn_flat_atomic_fmin_num: {
8909       Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
8910       break;
8911     }
8912     case Intrinsic::amdgcn_global_atomic_fmax:
8913     case Intrinsic::amdgcn_global_atomic_fmax_num:
8914     case Intrinsic::amdgcn_flat_atomic_fmax:
8915     case Intrinsic::amdgcn_flat_atomic_fmax_num: {
8916       Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
8917       break;
8918     }
8919     default:
8920       llvm_unreachable("unhandled atomic opcode");
8921     }
8922     return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
8923                                    M->getVTList(), Ops, M->getMemoryVT(),
8924                                    M->getMemOperand());
8925   }
8926   case Intrinsic::amdgcn_s_get_barrier_state: {
8927     SDValue Chain = Op->getOperand(0);
8928     SmallVector<SDValue, 2> Ops;
8929     unsigned Opc;
8930     bool IsInlinableBarID = false;
8931     int64_t BarID;
8932 
8933     if (isa<ConstantSDNode>(Op->getOperand(2))) {
8934       BarID = cast<ConstantSDNode>(Op->getOperand(2))->getSExtValue();
8935       IsInlinableBarID = AMDGPU::isInlinableIntLiteral(BarID);
8936     }
8937 
8938     if (IsInlinableBarID) {
8939       Opc = AMDGPU::S_GET_BARRIER_STATE_IMM;
8940       SDValue K = DAG.getTargetConstant(BarID, DL, MVT::i32);
8941       Ops.push_back(K);
8942     } else {
8943       Opc = AMDGPU::S_GET_BARRIER_STATE_M0;
8944       SDValue M0Val = copyToM0(DAG, Chain, DL, Op.getOperand(2));
8945       Ops.push_back(M0Val.getValue(0));
8946     }
8947 
8948     auto NewMI = DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops);
8949     return SDValue(NewMI, 0);
8950   }
8951   default:
8952 
8953     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
8954             AMDGPU::getImageDimIntrinsicInfo(IntrID))
8955       return lowerImage(Op, ImageDimIntr, DAG, true);
8956 
8957     return SDValue();
8958   }
8959 }
8960 
8961 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
8962 // dwordx4 if on SI and handle TFE loads.
8963 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
8964                                               SDVTList VTList,
8965                                               ArrayRef<SDValue> Ops, EVT MemVT,
8966                                               MachineMemOperand *MMO,
8967                                               SelectionDAG &DAG) const {
8968   LLVMContext &C = *DAG.getContext();
8969   MachineFunction &MF = DAG.getMachineFunction();
8970   EVT VT = VTList.VTs[0];
8971 
8972   assert(VTList.NumVTs == 2 || VTList.NumVTs == 3);
8973   bool IsTFE = VTList.NumVTs == 3;
8974   if (IsTFE) {
8975     unsigned NumValueDWords = divideCeil(VT.getSizeInBits(), 32);
8976     unsigned NumOpDWords = NumValueDWords + 1;
8977     EVT OpDWordsVT = EVT::getVectorVT(C, MVT::i32, NumOpDWords);
8978     SDVTList OpDWordsVTList = DAG.getVTList(OpDWordsVT, VTList.VTs[2]);
8979     MachineMemOperand *OpDWordsMMO =
8980         MF.getMachineMemOperand(MMO, 0, NumOpDWords * 4);
8981     SDValue Op = getMemIntrinsicNode(Opcode, DL, OpDWordsVTList, Ops,
8982                                      OpDWordsVT, OpDWordsMMO, DAG);
8983     SDValue Status = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, Op,
8984                                  DAG.getVectorIdxConstant(NumValueDWords, DL));
8985     SDValue ZeroIdx = DAG.getVectorIdxConstant(0, DL);
8986     SDValue ValueDWords =
8987         NumValueDWords == 1
8988             ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, Op, ZeroIdx)
8989             : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
8990                           EVT::getVectorVT(C, MVT::i32, NumValueDWords), Op,
8991                           ZeroIdx);
8992     SDValue Value = DAG.getNode(ISD::BITCAST, DL, VT, ValueDWords);
8993     return DAG.getMergeValues({Value, Status, SDValue(Op.getNode(), 1)}, DL);
8994   }
8995 
8996   if (!Subtarget->hasDwordx3LoadStores() &&
8997       (VT == MVT::v3i32 || VT == MVT::v3f32)) {
8998     EVT WidenedVT = EVT::getVectorVT(C, VT.getVectorElementType(), 4);
8999     EVT WidenedMemVT = EVT::getVectorVT(C, MemVT.getVectorElementType(), 4);
9000     MachineMemOperand *WidenedMMO = MF.getMachineMemOperand(MMO, 0, 16);
9001     SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
9002     SDValue Op = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
9003                                          WidenedMemVT, WidenedMMO);
9004     SDValue Value = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Op,
9005                                 DAG.getVectorIdxConstant(0, DL));
9006     return DAG.getMergeValues({Value, SDValue(Op.getNode(), 1)}, DL);
9007   }
9008 
9009   return DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops, MemVT, MMO);
9010 }
9011 
9012 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
9013                                          bool ImageStore) const {
9014   EVT StoreVT = VData.getValueType();
9015 
9016   // No change for f16 and legal vector D16 types.
9017   if (!StoreVT.isVector())
9018     return VData;
9019 
9020   SDLoc DL(VData);
9021   unsigned NumElements = StoreVT.getVectorNumElements();
9022 
9023   if (Subtarget->hasUnpackedD16VMem()) {
9024     // We need to unpack the packed data to store.
9025     EVT IntStoreVT = StoreVT.changeTypeToInteger();
9026     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
9027 
9028     EVT EquivStoreVT =
9029         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
9030     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
9031     return DAG.UnrollVectorOp(ZExt.getNode());
9032   }
9033 
9034   // The sq block of gfx8.1 does not estimate register use correctly for d16
9035   // image store instructions. The data operand is computed as if it were not a
9036   // d16 image instruction.
9037   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
9038     // Bitcast to i16
9039     EVT IntStoreVT = StoreVT.changeTypeToInteger();
9040     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
9041 
9042     // Decompose into scalars
9043     SmallVector<SDValue, 4> Elts;
9044     DAG.ExtractVectorElements(IntVData, Elts);
9045 
9046     // Group pairs of i16 into v2i16 and bitcast to i32
9047     SmallVector<SDValue, 4> PackedElts;
9048     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
9049       SDValue Pair =
9050           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
9051       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
9052       PackedElts.push_back(IntPair);
9053     }
9054     if ((NumElements % 2) == 1) {
9055       // Handle v3i16
9056       unsigned I = Elts.size() / 2;
9057       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
9058                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
9059       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
9060       PackedElts.push_back(IntPair);
9061     }
9062 
9063     // Pad using UNDEF
9064     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
9065 
9066     // Build final vector
9067     EVT VecVT =
9068         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
9069     return DAG.getBuildVector(VecVT, DL, PackedElts);
9070   }
9071 
9072   if (NumElements == 3) {
9073     EVT IntStoreVT =
9074         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
9075     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
9076 
9077     EVT WidenedStoreVT = EVT::getVectorVT(
9078         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
9079     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
9080                                          WidenedStoreVT.getStoreSizeInBits());
9081     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
9082     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
9083   }
9084 
9085   assert(isTypeLegal(StoreVT));
9086   return VData;
9087 }
9088 
9089 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
9090                                               SelectionDAG &DAG) const {
9091   SDLoc DL(Op);
9092   SDValue Chain = Op.getOperand(0);
9093   unsigned IntrinsicID = Op.getConstantOperandVal(1);
9094   MachineFunction &MF = DAG.getMachineFunction();
9095 
9096   switch (IntrinsicID) {
9097   case Intrinsic::amdgcn_exp_compr: {
9098     if (!Subtarget->hasCompressedExport()) {
9099       DiagnosticInfoUnsupported BadIntrin(
9100           DAG.getMachineFunction().getFunction(),
9101           "intrinsic not supported on subtarget", DL.getDebugLoc());
9102       DAG.getContext()->diagnose(BadIntrin);
9103     }
9104     SDValue Src0 = Op.getOperand(4);
9105     SDValue Src1 = Op.getOperand(5);
9106     // Hack around illegal type on SI by directly selecting it.
9107     if (isTypeLegal(Src0.getValueType()))
9108       return SDValue();
9109 
9110     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
9111     SDValue Undef = DAG.getUNDEF(MVT::f32);
9112     const SDValue Ops[] = {
9113       Op.getOperand(2), // tgt
9114       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
9115       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
9116       Undef, // src2
9117       Undef, // src3
9118       Op.getOperand(7), // vm
9119       DAG.getTargetConstant(1, DL, MVT::i1), // compr
9120       Op.getOperand(3), // en
9121       Op.getOperand(0) // Chain
9122     };
9123 
9124     unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
9125     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
9126   }
9127   case Intrinsic::amdgcn_s_barrier: {
9128     const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
9129     if (getTargetMachine().getOptLevel() > CodeGenOptLevel::None) {
9130       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
9131       if (WGSize <= ST.getWavefrontSize())
9132         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
9133                                           Op.getOperand(0)), 0);
9134     }
9135 
9136     // On GFX12 lower s_barrier into s_barrier_signal_imm and s_barrier_wait
9137     if (ST.hasSplitBarriers()) {
9138       SDValue K =
9139           DAG.getTargetConstant(AMDGPU::Barrier::WORKGROUP, DL, MVT::i32);
9140       SDValue BarSignal =
9141           SDValue(DAG.getMachineNode(AMDGPU::S_BARRIER_SIGNAL_IMM, DL,
9142                                      MVT::Other, K, Op.getOperand(0)),
9143                   0);
9144       SDValue BarWait =
9145           SDValue(DAG.getMachineNode(AMDGPU::S_BARRIER_WAIT, DL, MVT::Other, K,
9146                                      BarSignal.getValue(0)),
9147                   0);
9148       return BarWait;
9149     }
9150 
9151     return SDValue();
9152   };
9153   case Intrinsic::amdgcn_tbuffer_store: {
9154     SDValue VData = Op.getOperand(2);
9155     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
9156     if (IsD16)
9157       VData = handleD16VData(VData, DAG);
9158     unsigned Dfmt = Op.getConstantOperandVal(8);
9159     unsigned Nfmt = Op.getConstantOperandVal(9);
9160     unsigned Glc = Op.getConstantOperandVal(10);
9161     unsigned Slc = Op.getConstantOperandVal(11);
9162     unsigned IdxEn = getIdxEn(Op.getOperand(4));
9163     SDValue Ops[] = {
9164       Chain,
9165       VData,             // vdata
9166       Op.getOperand(3),  // rsrc
9167       Op.getOperand(4),  // vindex
9168       Op.getOperand(5),  // voffset
9169       Op.getOperand(6),  // soffset
9170       Op.getOperand(7),  // offset
9171       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
9172       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
9173       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
9174     };
9175     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
9176                            AMDGPUISD::TBUFFER_STORE_FORMAT;
9177     MemSDNode *M = cast<MemSDNode>(Op);
9178     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
9179                                    M->getMemoryVT(), M->getMemOperand());
9180   }
9181 
9182   case Intrinsic::amdgcn_struct_tbuffer_store:
9183   case Intrinsic::amdgcn_struct_ptr_tbuffer_store: {
9184     SDValue VData = Op.getOperand(2);
9185     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
9186     if (IsD16)
9187       VData = handleD16VData(VData, DAG);
9188     SDValue Rsrc = bufferRsrcPtrToVector(Op.getOperand(3), DAG);
9189     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
9190     auto SOffset = selectSOffset(Op.getOperand(6), DAG, Subtarget);
9191     SDValue Ops[] = {
9192         Chain,
9193         VData,                                 // vdata
9194         Rsrc,                                  // rsrc
9195         Op.getOperand(4),                      // vindex
9196         Offsets.first,                         // voffset
9197         SOffset,                               // soffset
9198         Offsets.second,                        // offset
9199         Op.getOperand(7),                      // format
9200         Op.getOperand(8),                      // cachepolicy, swizzled buffer
9201         DAG.getTargetConstant(1, DL, MVT::i1), // idxen
9202     };
9203     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
9204                            AMDGPUISD::TBUFFER_STORE_FORMAT;
9205     MemSDNode *M = cast<MemSDNode>(Op);
9206     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
9207                                    M->getMemoryVT(), M->getMemOperand());
9208   }
9209 
9210   case Intrinsic::amdgcn_raw_tbuffer_store:
9211   case Intrinsic::amdgcn_raw_ptr_tbuffer_store: {
9212     SDValue VData = Op.getOperand(2);
9213     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
9214     if (IsD16)
9215       VData = handleD16VData(VData, DAG);
9216     SDValue Rsrc = bufferRsrcPtrToVector(Op.getOperand(3), DAG);
9217     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
9218     auto SOffset = selectSOffset(Op.getOperand(5), DAG, Subtarget);
9219     SDValue Ops[] = {
9220         Chain,
9221         VData,                                 // vdata
9222         Rsrc,                                  // rsrc
9223         DAG.getConstant(0, DL, MVT::i32),      // vindex
9224         Offsets.first,                         // voffset
9225         SOffset,                               // soffset
9226         Offsets.second,                        // offset
9227         Op.getOperand(6),                      // format
9228         Op.getOperand(7),                      // cachepolicy, swizzled buffer
9229         DAG.getTargetConstant(0, DL, MVT::i1), // idxen
9230     };
9231     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
9232                            AMDGPUISD::TBUFFER_STORE_FORMAT;
9233     MemSDNode *M = cast<MemSDNode>(Op);
9234     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
9235                                    M->getMemoryVT(), M->getMemOperand());
9236   }
9237 
9238   case Intrinsic::amdgcn_buffer_store:
9239   case Intrinsic::amdgcn_buffer_store_format: {
9240     SDValue VData = Op.getOperand(2);
9241     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
9242     if (IsD16)
9243       VData = handleD16VData(VData, DAG);
9244     unsigned Glc = Op.getConstantOperandVal(6);
9245     unsigned Slc = Op.getConstantOperandVal(7);
9246     unsigned IdxEn = getIdxEn(Op.getOperand(4));
9247     SDValue Ops[] = {
9248       Chain,
9249       VData,
9250       Op.getOperand(3), // rsrc
9251       Op.getOperand(4), // vindex
9252       SDValue(), // voffset -- will be set by setBufferOffsets
9253       SDValue(), // soffset -- will be set by setBufferOffsets
9254       SDValue(), // offset -- will be set by setBufferOffsets
9255       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
9256       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
9257     };
9258     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
9259 
9260     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
9261                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
9262     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
9263     MemSDNode *M = cast<MemSDNode>(Op);
9264 
9265     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
9266     EVT VDataType = VData.getValueType().getScalarType();
9267     if (VDataType == MVT::i8 || VDataType == MVT::i16)
9268       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
9269 
9270     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
9271                                    M->getMemoryVT(), M->getMemOperand());
9272   }
9273 
9274   case Intrinsic::amdgcn_raw_buffer_store:
9275   case Intrinsic::amdgcn_raw_ptr_buffer_store:
9276   case Intrinsic::amdgcn_raw_buffer_store_format:
9277   case Intrinsic::amdgcn_raw_ptr_buffer_store_format: {
9278     const bool IsFormat =
9279         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format ||
9280         IntrinsicID == Intrinsic::amdgcn_raw_ptr_buffer_store_format;
9281 
9282     SDValue VData = Op.getOperand(2);
9283     EVT VDataVT = VData.getValueType();
9284     EVT EltType = VDataVT.getScalarType();
9285     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
9286     if (IsD16) {
9287       VData = handleD16VData(VData, DAG);
9288       VDataVT = VData.getValueType();
9289     }
9290 
9291     if (!isTypeLegal(VDataVT)) {
9292       VData =
9293           DAG.getNode(ISD::BITCAST, DL,
9294                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
9295     }
9296 
9297     SDValue Rsrc = bufferRsrcPtrToVector(Op.getOperand(3), DAG);
9298     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
9299     auto SOffset = selectSOffset(Op.getOperand(5), DAG, Subtarget);
9300     SDValue Ops[] = {
9301         Chain,
9302         VData,
9303         Rsrc,
9304         DAG.getConstant(0, DL, MVT::i32),      // vindex
9305         Offsets.first,                         // voffset
9306         SOffset,                               // soffset
9307         Offsets.second,                        // offset
9308         Op.getOperand(6),                      // cachepolicy, swizzled buffer
9309         DAG.getTargetConstant(0, DL, MVT::i1), // idxen
9310     };
9311     unsigned Opc =
9312         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
9313     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
9314     MemSDNode *M = cast<MemSDNode>(Op);
9315 
9316     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
9317     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
9318       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
9319 
9320     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
9321                                    M->getMemoryVT(), M->getMemOperand());
9322   }
9323 
9324   case Intrinsic::amdgcn_struct_buffer_store:
9325   case Intrinsic::amdgcn_struct_ptr_buffer_store:
9326   case Intrinsic::amdgcn_struct_buffer_store_format:
9327   case Intrinsic::amdgcn_struct_ptr_buffer_store_format: {
9328     const bool IsFormat =
9329         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format ||
9330         IntrinsicID == Intrinsic::amdgcn_struct_ptr_buffer_store_format;
9331 
9332     SDValue VData = Op.getOperand(2);
9333     EVT VDataVT = VData.getValueType();
9334     EVT EltType = VDataVT.getScalarType();
9335     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
9336 
9337     if (IsD16) {
9338       VData = handleD16VData(VData, DAG);
9339       VDataVT = VData.getValueType();
9340     }
9341 
9342     if (!isTypeLegal(VDataVT)) {
9343       VData =
9344           DAG.getNode(ISD::BITCAST, DL,
9345                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
9346     }
9347 
9348     auto Rsrc = bufferRsrcPtrToVector(Op.getOperand(3), DAG);
9349     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
9350     auto SOffset = selectSOffset(Op.getOperand(6), DAG, Subtarget);
9351     SDValue Ops[] = {
9352         Chain,
9353         VData,
9354         Rsrc,
9355         Op.getOperand(4),                      // vindex
9356         Offsets.first,                         // voffset
9357         SOffset,                               // soffset
9358         Offsets.second,                        // offset
9359         Op.getOperand(7),                      // cachepolicy, swizzled buffer
9360         DAG.getTargetConstant(1, DL, MVT::i1), // idxen
9361     };
9362     unsigned Opc =
9363         !IsFormat ? AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
9364     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
9365     MemSDNode *M = cast<MemSDNode>(Op);
9366 
9367     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
9368     EVT VDataType = VData.getValueType().getScalarType();
9369     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
9370       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
9371 
9372     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
9373                                    M->getMemoryVT(), M->getMemOperand());
9374   }
9375   case Intrinsic::amdgcn_raw_buffer_load_lds:
9376   case Intrinsic::amdgcn_raw_ptr_buffer_load_lds:
9377   case Intrinsic::amdgcn_struct_buffer_load_lds:
9378   case Intrinsic::amdgcn_struct_ptr_buffer_load_lds: {
9379     unsigned Opc;
9380     bool HasVIndex =
9381         IntrinsicID == Intrinsic::amdgcn_struct_buffer_load_lds ||
9382         IntrinsicID == Intrinsic::amdgcn_struct_ptr_buffer_load_lds;
9383     unsigned OpOffset = HasVIndex ? 1 : 0;
9384     SDValue VOffset = Op.getOperand(5 + OpOffset);
9385     bool HasVOffset = !isNullConstant(VOffset);
9386     unsigned Size = Op->getConstantOperandVal(4);
9387 
9388     switch (Size) {
9389     default:
9390       return SDValue();
9391     case 1:
9392       Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_BOTHEN
9393                                    : AMDGPU::BUFFER_LOAD_UBYTE_LDS_IDXEN
9394                       : HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFEN
9395                                    : AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFSET;
9396       break;
9397     case 2:
9398       Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_BOTHEN
9399                                    : AMDGPU::BUFFER_LOAD_USHORT_LDS_IDXEN
9400                       : HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFEN
9401                                    : AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFSET;
9402       break;
9403     case 4:
9404       Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_BOTHEN
9405                                    : AMDGPU::BUFFER_LOAD_DWORD_LDS_IDXEN
9406                       : HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFEN
9407                                    : AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFSET;
9408       break;
9409     }
9410 
9411     SDValue M0Val = copyToM0(DAG, Chain, DL, Op.getOperand(3));
9412 
9413     SmallVector<SDValue, 8> Ops;
9414 
9415     if (HasVIndex && HasVOffset)
9416       Ops.push_back(DAG.getBuildVector(MVT::v2i32, DL,
9417                                        { Op.getOperand(5), // VIndex
9418                                          VOffset }));
9419     else if (HasVIndex)
9420       Ops.push_back(Op.getOperand(5));
9421     else if (HasVOffset)
9422       Ops.push_back(VOffset);
9423 
9424     SDValue Rsrc = bufferRsrcPtrToVector(Op.getOperand(2), DAG);
9425     Ops.push_back(Rsrc);
9426     Ops.push_back(Op.getOperand(6 + OpOffset)); // soffset
9427     Ops.push_back(Op.getOperand(7 + OpOffset)); // imm offset
9428     unsigned Aux = Op.getConstantOperandVal(8 + OpOffset);
9429     Ops.push_back(
9430       DAG.getTargetConstant(Aux & AMDGPU::CPol::ALL, DL, MVT::i8)); // cpol
9431     Ops.push_back(
9432       DAG.getTargetConstant((Aux >> 3) & 1, DL, MVT::i8));          // swz
9433     Ops.push_back(M0Val.getValue(0)); // Chain
9434     Ops.push_back(M0Val.getValue(1)); // Glue
9435 
9436     auto *M = cast<MemSDNode>(Op);
9437     MachineMemOperand *LoadMMO = M->getMemOperand();
9438     // Don't set the offset value here because the pointer points to the base of
9439     // the buffer.
9440     MachinePointerInfo LoadPtrI = LoadMMO->getPointerInfo();
9441 
9442     MachinePointerInfo StorePtrI = LoadPtrI;
9443     LoadPtrI.V = PoisonValue::get(
9444         PointerType::get(*DAG.getContext(), AMDGPUAS::GLOBAL_ADDRESS));
9445     LoadPtrI.AddrSpace = AMDGPUAS::GLOBAL_ADDRESS;
9446     StorePtrI.AddrSpace = AMDGPUAS::LOCAL_ADDRESS;
9447 
9448     auto F = LoadMMO->getFlags() &
9449              ~(MachineMemOperand::MOStore | MachineMemOperand::MOLoad);
9450     LoadMMO =
9451         MF.getMachineMemOperand(LoadPtrI, F | MachineMemOperand::MOLoad, Size,
9452                                 LoadMMO->getBaseAlign(), LoadMMO->getAAInfo());
9453 
9454     MachineMemOperand *StoreMMO = MF.getMachineMemOperand(
9455         StorePtrI, F | MachineMemOperand::MOStore, sizeof(int32_t),
9456         LoadMMO->getBaseAlign(), LoadMMO->getAAInfo());
9457 
9458     auto Load = DAG.getMachineNode(Opc, DL, M->getVTList(), Ops);
9459     DAG.setNodeMemRefs(Load, {LoadMMO, StoreMMO});
9460 
9461     return SDValue(Load, 0);
9462   }
9463   case Intrinsic::amdgcn_global_load_lds: {
9464     unsigned Opc;
9465     unsigned Size = Op->getConstantOperandVal(4);
9466     switch (Size) {
9467     default:
9468       return SDValue();
9469     case 1:
9470       Opc = AMDGPU::GLOBAL_LOAD_LDS_UBYTE;
9471       break;
9472     case 2:
9473       Opc = AMDGPU::GLOBAL_LOAD_LDS_USHORT;
9474       break;
9475     case 4:
9476       Opc = AMDGPU::GLOBAL_LOAD_LDS_DWORD;
9477       break;
9478     }
9479 
9480     auto *M = cast<MemSDNode>(Op);
9481     SDValue M0Val = copyToM0(DAG, Chain, DL, Op.getOperand(3));
9482 
9483     SmallVector<SDValue, 6> Ops;
9484 
9485     SDValue Addr = Op.getOperand(2); // Global ptr
9486     SDValue VOffset;
9487     // Try to split SAddr and VOffset. Global and LDS pointers share the same
9488     // immediate offset, so we cannot use a regular SelectGlobalSAddr().
9489     if (Addr->isDivergent() && Addr.getOpcode() == ISD::ADD) {
9490       SDValue LHS = Addr.getOperand(0);
9491       SDValue RHS = Addr.getOperand(1);
9492 
9493       if (LHS->isDivergent())
9494         std::swap(LHS, RHS);
9495 
9496       if (!LHS->isDivergent() && RHS.getOpcode() == ISD::ZERO_EXTEND &&
9497           RHS.getOperand(0).getValueType() == MVT::i32) {
9498         // add (i64 sgpr), (zero_extend (i32 vgpr))
9499         Addr = LHS;
9500         VOffset = RHS.getOperand(0);
9501       }
9502     }
9503 
9504     Ops.push_back(Addr);
9505     if (!Addr->isDivergent()) {
9506       Opc = AMDGPU::getGlobalSaddrOp(Opc);
9507       if (!VOffset)
9508         VOffset = SDValue(
9509             DAG.getMachineNode(AMDGPU::V_MOV_B32_e32, DL, MVT::i32,
9510                                DAG.getTargetConstant(0, DL, MVT::i32)), 0);
9511       Ops.push_back(VOffset);
9512     }
9513 
9514     Ops.push_back(Op.getOperand(5));  // Offset
9515     Ops.push_back(Op.getOperand(6));  // CPol
9516     Ops.push_back(M0Val.getValue(0)); // Chain
9517     Ops.push_back(M0Val.getValue(1)); // Glue
9518 
9519     MachineMemOperand *LoadMMO = M->getMemOperand();
9520     MachinePointerInfo LoadPtrI = LoadMMO->getPointerInfo();
9521     LoadPtrI.Offset = Op->getConstantOperandVal(5);
9522     MachinePointerInfo StorePtrI = LoadPtrI;
9523     LoadPtrI.V = PoisonValue::get(
9524         PointerType::get(*DAG.getContext(), AMDGPUAS::GLOBAL_ADDRESS));
9525     LoadPtrI.AddrSpace = AMDGPUAS::GLOBAL_ADDRESS;
9526     StorePtrI.AddrSpace = AMDGPUAS::LOCAL_ADDRESS;
9527     auto F = LoadMMO->getFlags() &
9528              ~(MachineMemOperand::MOStore | MachineMemOperand::MOLoad);
9529     LoadMMO =
9530         MF.getMachineMemOperand(LoadPtrI, F | MachineMemOperand::MOLoad, Size,
9531                                 LoadMMO->getBaseAlign(), LoadMMO->getAAInfo());
9532     MachineMemOperand *StoreMMO = MF.getMachineMemOperand(
9533         StorePtrI, F | MachineMemOperand::MOStore, sizeof(int32_t), Align(4),
9534         LoadMMO->getAAInfo());
9535 
9536     auto Load = DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops);
9537     DAG.setNodeMemRefs(Load, {LoadMMO, StoreMMO});
9538 
9539     return SDValue(Load, 0);
9540   }
9541   case Intrinsic::amdgcn_end_cf:
9542     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
9543                                       Op->getOperand(2), Chain), 0);
9544   case Intrinsic::amdgcn_s_barrier_init:
9545   case Intrinsic::amdgcn_s_barrier_join:
9546   case Intrinsic::amdgcn_s_wakeup_barrier: {
9547     SDValue Chain = Op->getOperand(0);
9548     SmallVector<SDValue, 2> Ops;
9549     SDValue BarOp = Op->getOperand(2);
9550     unsigned Opc;
9551     bool IsInlinableBarID = false;
9552     int64_t BarVal;
9553 
9554     if (isa<ConstantSDNode>(BarOp)) {
9555       BarVal = cast<ConstantSDNode>(BarOp)->getSExtValue();
9556       IsInlinableBarID = AMDGPU::isInlinableIntLiteral(BarVal);
9557     }
9558 
9559     if (IsInlinableBarID) {
9560       switch (IntrinsicID) {
9561       default:
9562         return SDValue();
9563       case Intrinsic::amdgcn_s_barrier_init:
9564         Opc = AMDGPU::S_BARRIER_INIT_IMM;
9565         break;
9566       case Intrinsic::amdgcn_s_barrier_join:
9567         Opc = AMDGPU::S_BARRIER_JOIN_IMM;
9568         break;
9569       case Intrinsic::amdgcn_s_wakeup_barrier:
9570         Opc = AMDGPU::S_WAKEUP_BARRIER_IMM;
9571         break;
9572       }
9573 
9574       SDValue K = DAG.getTargetConstant(BarVal, DL, MVT::i32);
9575       Ops.push_back(K);
9576     } else {
9577       switch (IntrinsicID) {
9578       default:
9579         return SDValue();
9580       case Intrinsic::amdgcn_s_barrier_init:
9581         Opc = AMDGPU::S_BARRIER_INIT_M0;
9582         break;
9583       case Intrinsic::amdgcn_s_barrier_join:
9584         Opc = AMDGPU::S_BARRIER_JOIN_M0;
9585         break;
9586       case Intrinsic::amdgcn_s_wakeup_barrier:
9587         Opc = AMDGPU::S_WAKEUP_BARRIER_M0;
9588         break;
9589       }
9590     }
9591 
9592     if (IntrinsicID == Intrinsic::amdgcn_s_barrier_init) {
9593       SDValue M0Val;
9594       // Member count will be read from M0[16:22]
9595       M0Val = DAG.getNode(ISD::SHL, DL, MVT::i32, Op.getOperand(3),
9596                           DAG.getShiftAmountConstant(16, MVT::i32, DL));
9597 
9598       if (!IsInlinableBarID) {
9599         // If reference to barrier id is not an inline constant then it must be
9600         // referenced with M0[4:0]. Perform an OR with the member count to
9601         // include it in M0.
9602         M0Val = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32,
9603                                            Op.getOperand(2), M0Val),
9604                         0);
9605       }
9606       Ops.push_back(copyToM0(DAG, Chain, DL, M0Val).getValue(0));
9607     } else if (!IsInlinableBarID) {
9608       Ops.push_back(copyToM0(DAG, Chain, DL, BarOp).getValue(0));
9609     }
9610 
9611     auto NewMI = DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops);
9612     return SDValue(NewMI, 0);
9613   }
9614   default: {
9615     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
9616             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
9617       return lowerImage(Op, ImageDimIntr, DAG, true);
9618 
9619     return Op;
9620   }
9621   }
9622 }
9623 
9624 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
9625 // offset (the offset that is included in bounds checking and swizzling, to be
9626 // split between the instruction's voffset and immoffset fields) and soffset
9627 // (the offset that is excluded from bounds checking and swizzling, to go in
9628 // the instruction's soffset field).  This function takes the first kind of
9629 // offset and figures out how to split it between voffset and immoffset.
9630 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
9631     SDValue Offset, SelectionDAG &DAG) const {
9632   SDLoc DL(Offset);
9633   const unsigned MaxImm = SIInstrInfo::getMaxMUBUFImmOffset(*Subtarget);
9634   SDValue N0 = Offset;
9635   ConstantSDNode *C1 = nullptr;
9636 
9637   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
9638     N0 = SDValue();
9639   else if (DAG.isBaseWithConstantOffset(N0)) {
9640     C1 = cast<ConstantSDNode>(N0.getOperand(1));
9641     N0 = N0.getOperand(0);
9642   }
9643 
9644   if (C1) {
9645     unsigned ImmOffset = C1->getZExtValue();
9646     // If the immediate value is too big for the immoffset field, put only bits
9647     // that would normally fit in the immoffset field. The remaining value that
9648     // is copied/added for the voffset field is a large power of 2, and it
9649     // stands more chance of being CSEd with the copy/add for another similar
9650     // load/store.
9651     // However, do not do that rounding down if that is a negative
9652     // number, as it appears to be illegal to have a negative offset in the
9653     // vgpr, even if adding the immediate offset makes it positive.
9654     unsigned Overflow = ImmOffset & ~MaxImm;
9655     ImmOffset -= Overflow;
9656     if ((int32_t)Overflow < 0) {
9657       Overflow += ImmOffset;
9658       ImmOffset = 0;
9659     }
9660     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
9661     if (Overflow) {
9662       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
9663       if (!N0)
9664         N0 = OverflowVal;
9665       else {
9666         SDValue Ops[] = { N0, OverflowVal };
9667         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
9668       }
9669     }
9670   }
9671   if (!N0)
9672     N0 = DAG.getConstant(0, DL, MVT::i32);
9673   if (!C1)
9674     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
9675   return {N0, SDValue(C1, 0)};
9676 }
9677 
9678 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
9679 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
9680 // pointed to by Offsets.
9681 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
9682                                         SelectionDAG &DAG, SDValue *Offsets,
9683                                         Align Alignment) const {
9684   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9685   SDLoc DL(CombinedOffset);
9686   if (auto *C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
9687     uint32_t Imm = C->getZExtValue();
9688     uint32_t SOffset, ImmOffset;
9689     if (TII->splitMUBUFOffset(Imm, SOffset, ImmOffset, Alignment)) {
9690       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
9691       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
9692       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
9693       return;
9694     }
9695   }
9696   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
9697     SDValue N0 = CombinedOffset.getOperand(0);
9698     SDValue N1 = CombinedOffset.getOperand(1);
9699     uint32_t SOffset, ImmOffset;
9700     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
9701     if (Offset >= 0 &&
9702         TII->splitMUBUFOffset(Offset, SOffset, ImmOffset, Alignment)) {
9703       Offsets[0] = N0;
9704       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
9705       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
9706       return;
9707     }
9708   }
9709 
9710   SDValue SOffsetZero = Subtarget->hasRestrictedSOffset()
9711                             ? DAG.getRegister(AMDGPU::SGPR_NULL, MVT::i32)
9712                             : DAG.getConstant(0, DL, MVT::i32);
9713 
9714   Offsets[0] = CombinedOffset;
9715   Offsets[1] = SOffsetZero;
9716   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
9717 }
9718 
9719 SDValue SITargetLowering::bufferRsrcPtrToVector(SDValue MaybePointer,
9720                                                 SelectionDAG &DAG) const {
9721   if (!MaybePointer.getValueType().isScalarInteger())
9722     return MaybePointer;
9723 
9724   SDLoc DL(MaybePointer);
9725 
9726   SDValue Rsrc = DAG.getBitcast(MVT::v4i32, MaybePointer);
9727   return Rsrc;
9728 }
9729 
9730 // Wrap a global or flat pointer into a buffer intrinsic using the flags
9731 // specified in the intrinsic.
9732 SDValue SITargetLowering::lowerPointerAsRsrcIntrin(SDNode *Op,
9733                                                    SelectionDAG &DAG) const {
9734   SDLoc Loc(Op);
9735 
9736   SDValue Pointer = Op->getOperand(1);
9737   SDValue Stride = Op->getOperand(2);
9738   SDValue NumRecords = Op->getOperand(3);
9739   SDValue Flags = Op->getOperand(4);
9740 
9741   auto [LowHalf, HighHalf] = DAG.SplitScalar(Pointer, Loc, MVT::i32, MVT::i32);
9742   SDValue Mask = DAG.getConstant(0x0000ffff, Loc, MVT::i32);
9743   SDValue Masked = DAG.getNode(ISD::AND, Loc, MVT::i32, HighHalf, Mask);
9744   std::optional<uint32_t> ConstStride = std::nullopt;
9745   if (auto *ConstNode = dyn_cast<ConstantSDNode>(Stride))
9746     ConstStride = ConstNode->getZExtValue();
9747 
9748   SDValue NewHighHalf = Masked;
9749   if (!ConstStride || *ConstStride != 0) {
9750     SDValue ShiftedStride;
9751     if (ConstStride) {
9752       ShiftedStride = DAG.getConstant(*ConstStride << 16, Loc, MVT::i32);
9753     } else {
9754       SDValue ExtStride = DAG.getAnyExtOrTrunc(Stride, Loc, MVT::i32);
9755       ShiftedStride =
9756           DAG.getNode(ISD::SHL, Loc, MVT::i32, ExtStride,
9757                       DAG.getShiftAmountConstant(16, MVT::i32, Loc));
9758     }
9759     NewHighHalf = DAG.getNode(ISD::OR, Loc, MVT::i32, Masked, ShiftedStride);
9760   }
9761 
9762   SDValue Rsrc = DAG.getNode(ISD::BUILD_VECTOR, Loc, MVT::v4i32, LowHalf,
9763                              NewHighHalf, NumRecords, Flags);
9764   SDValue RsrcPtr = DAG.getNode(ISD::BITCAST, Loc, MVT::i128, Rsrc);
9765   return RsrcPtr;
9766 }
9767 
9768 // Handle 8 bit and 16 bit buffer loads
9769 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
9770                                                      EVT LoadVT, SDLoc DL,
9771                                                      ArrayRef<SDValue> Ops,
9772                                                      MemSDNode *M) const {
9773   EVT IntVT = LoadVT.changeTypeToInteger();
9774   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
9775          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
9776 
9777   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
9778   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
9779                                                Ops, IntVT,
9780                                                M->getMemOperand());
9781   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
9782   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
9783 
9784   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
9785 }
9786 
9787 // Handle 8 bit and 16 bit buffer stores
9788 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
9789                                                       EVT VDataType, SDLoc DL,
9790                                                       SDValue Ops[],
9791                                                       MemSDNode *M) const {
9792   if (VDataType == MVT::f16)
9793     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
9794 
9795   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
9796   Ops[1] = BufferStoreExt;
9797   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
9798                                  AMDGPUISD::BUFFER_STORE_SHORT;
9799   ArrayRef<SDValue> OpsRef = ArrayRef(&Ops[0], 9);
9800   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
9801                                      M->getMemOperand());
9802 }
9803 
9804 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
9805                                  ISD::LoadExtType ExtType, SDValue Op,
9806                                  const SDLoc &SL, EVT VT) {
9807   if (VT.bitsLT(Op.getValueType()))
9808     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
9809 
9810   switch (ExtType) {
9811   case ISD::SEXTLOAD:
9812     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
9813   case ISD::ZEXTLOAD:
9814     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
9815   case ISD::EXTLOAD:
9816     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
9817   case ISD::NON_EXTLOAD:
9818     return Op;
9819   }
9820 
9821   llvm_unreachable("invalid ext type");
9822 }
9823 
9824 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
9825   SelectionDAG &DAG = DCI.DAG;
9826   if (Ld->getAlign() < Align(4) || Ld->isDivergent())
9827     return SDValue();
9828 
9829   // FIXME: Constant loads should all be marked invariant.
9830   unsigned AS = Ld->getAddressSpace();
9831   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
9832       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
9833       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
9834     return SDValue();
9835 
9836   // Don't do this early, since it may interfere with adjacent load merging for
9837   // illegal types. We can avoid losing alignment information for exotic types
9838   // pre-legalize.
9839   EVT MemVT = Ld->getMemoryVT();
9840   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
9841       MemVT.getSizeInBits() >= 32)
9842     return SDValue();
9843 
9844   SDLoc SL(Ld);
9845 
9846   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
9847          "unexpected vector extload");
9848 
9849   // TODO: Drop only high part of range.
9850   SDValue Ptr = Ld->getBasePtr();
9851   SDValue NewLoad = DAG.getLoad(
9852       ISD::UNINDEXED, ISD::NON_EXTLOAD, MVT::i32, SL, Ld->getChain(), Ptr,
9853       Ld->getOffset(), Ld->getPointerInfo(), MVT::i32, Ld->getAlign(),
9854       Ld->getMemOperand()->getFlags(), Ld->getAAInfo(),
9855       nullptr); // Drop ranges
9856 
9857   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
9858   if (MemVT.isFloatingPoint()) {
9859     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
9860            "unexpected fp extload");
9861     TruncVT = MemVT.changeTypeToInteger();
9862   }
9863 
9864   SDValue Cvt = NewLoad;
9865   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
9866     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
9867                       DAG.getValueType(TruncVT));
9868   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
9869              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
9870     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
9871   } else {
9872     assert(Ld->getExtensionType() == ISD::EXTLOAD);
9873   }
9874 
9875   EVT VT = Ld->getValueType(0);
9876   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9877 
9878   DCI.AddToWorklist(Cvt.getNode());
9879 
9880   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
9881   // the appropriate extension from the 32-bit load.
9882   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
9883   DCI.AddToWorklist(Cvt.getNode());
9884 
9885   // Handle conversion back to floating point if necessary.
9886   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
9887 
9888   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
9889 }
9890 
9891 static bool addressMayBeAccessedAsPrivate(const MachineMemOperand *MMO,
9892                                           const SIMachineFunctionInfo &Info) {
9893   // TODO: Should check if the address can definitely not access stack.
9894   if (Info.isEntryFunction())
9895     return Info.getUserSGPRInfo().hasFlatScratchInit();
9896   return true;
9897 }
9898 
9899 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
9900   SDLoc DL(Op);
9901   LoadSDNode *Load = cast<LoadSDNode>(Op);
9902   ISD::LoadExtType ExtType = Load->getExtensionType();
9903   EVT MemVT = Load->getMemoryVT();
9904 
9905   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
9906     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
9907       return SDValue();
9908 
9909     // FIXME: Copied from PPC
9910     // First, load into 32 bits, then truncate to 1 bit.
9911 
9912     SDValue Chain = Load->getChain();
9913     SDValue BasePtr = Load->getBasePtr();
9914     MachineMemOperand *MMO = Load->getMemOperand();
9915 
9916     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
9917 
9918     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
9919                                    BasePtr, RealMemVT, MMO);
9920 
9921     if (!MemVT.isVector()) {
9922       SDValue Ops[] = {
9923         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
9924         NewLD.getValue(1)
9925       };
9926 
9927       return DAG.getMergeValues(Ops, DL);
9928     }
9929 
9930     SmallVector<SDValue, 3> Elts;
9931     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
9932       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
9933                                 DAG.getConstant(I, DL, MVT::i32));
9934 
9935       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
9936     }
9937 
9938     SDValue Ops[] = {
9939       DAG.getBuildVector(MemVT, DL, Elts),
9940       NewLD.getValue(1)
9941     };
9942 
9943     return DAG.getMergeValues(Ops, DL);
9944   }
9945 
9946   if (!MemVT.isVector())
9947     return SDValue();
9948 
9949   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
9950          "Custom lowering for non-i32 vectors hasn't been implemented.");
9951 
9952   Align Alignment = Load->getAlign();
9953   unsigned AS = Load->getAddressSpace();
9954   if (Subtarget->hasLDSMisalignedBug() && AS == AMDGPUAS::FLAT_ADDRESS &&
9955       Alignment.value() < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
9956     return SplitVectorLoad(Op, DAG);
9957   }
9958 
9959   MachineFunction &MF = DAG.getMachineFunction();
9960   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
9961   // If there is a possibility that flat instruction access scratch memory
9962   // then we need to use the same legalization rules we use for private.
9963   if (AS == AMDGPUAS::FLAT_ADDRESS &&
9964       !Subtarget->hasMultiDwordFlatScratchAddressing())
9965     AS = addressMayBeAccessedAsPrivate(Load->getMemOperand(), *MFI) ?
9966          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
9967 
9968   unsigned NumElements = MemVT.getVectorNumElements();
9969 
9970   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
9971       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
9972     if (!Op->isDivergent() && Alignment >= Align(4) && NumElements < 32) {
9973       if (MemVT.isPow2VectorType() ||
9974           (Subtarget->hasScalarDwordx3Loads() && NumElements == 3))
9975         return SDValue();
9976       return WidenOrSplitVectorLoad(Op, DAG);
9977     }
9978     // Non-uniform loads will be selected to MUBUF instructions, so they
9979     // have the same legalization requirements as global and private
9980     // loads.
9981     //
9982   }
9983 
9984   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
9985       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
9986       AS == AMDGPUAS::GLOBAL_ADDRESS) {
9987     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
9988         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
9989         Alignment >= Align(4) && NumElements < 32) {
9990       if (MemVT.isPow2VectorType() ||
9991           (Subtarget->hasScalarDwordx3Loads() && NumElements == 3))
9992         return SDValue();
9993       return WidenOrSplitVectorLoad(Op, DAG);
9994     }
9995     // Non-uniform loads will be selected to MUBUF instructions, so they
9996     // have the same legalization requirements as global and private
9997     // loads.
9998     //
9999   }
10000   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
10001       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
10002       AS == AMDGPUAS::GLOBAL_ADDRESS ||
10003       AS == AMDGPUAS::FLAT_ADDRESS) {
10004     if (NumElements > 4)
10005       return SplitVectorLoad(Op, DAG);
10006     // v3 loads not supported on SI.
10007     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
10008       return WidenOrSplitVectorLoad(Op, DAG);
10009 
10010     // v3 and v4 loads are supported for private and global memory.
10011     return SDValue();
10012   }
10013   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
10014     // Depending on the setting of the private_element_size field in the
10015     // resource descriptor, we can only make private accesses up to a certain
10016     // size.
10017     switch (Subtarget->getMaxPrivateElementSize()) {
10018     case 4: {
10019       SDValue Ops[2];
10020       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
10021       return DAG.getMergeValues(Ops, DL);
10022     }
10023     case 8:
10024       if (NumElements > 2)
10025         return SplitVectorLoad(Op, DAG);
10026       return SDValue();
10027     case 16:
10028       // Same as global/flat
10029       if (NumElements > 4)
10030         return SplitVectorLoad(Op, DAG);
10031       // v3 loads not supported on SI.
10032       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
10033         return WidenOrSplitVectorLoad(Op, DAG);
10034 
10035       return SDValue();
10036     default:
10037       llvm_unreachable("unsupported private_element_size");
10038     }
10039   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
10040     unsigned Fast = 0;
10041     auto Flags = Load->getMemOperand()->getFlags();
10042     if (allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
10043                                            Load->getAlign(), Flags, &Fast) &&
10044         Fast > 1)
10045       return SDValue();
10046 
10047     if (MemVT.isVector())
10048       return SplitVectorLoad(Op, DAG);
10049   }
10050 
10051   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
10052                                       MemVT, *Load->getMemOperand())) {
10053     SDValue Ops[2];
10054     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
10055     return DAG.getMergeValues(Ops, DL);
10056   }
10057 
10058   return SDValue();
10059 }
10060 
10061 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10062   EVT VT = Op.getValueType();
10063   if (VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256 ||
10064       VT.getSizeInBits() == 512)
10065     return splitTernaryVectorOp(Op, DAG);
10066 
10067   assert(VT.getSizeInBits() == 64);
10068 
10069   SDLoc DL(Op);
10070   SDValue Cond = Op.getOperand(0);
10071 
10072   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
10073   SDValue One = DAG.getConstant(1, DL, MVT::i32);
10074 
10075   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
10076   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
10077 
10078   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
10079   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
10080 
10081   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
10082 
10083   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
10084   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
10085 
10086   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
10087 
10088   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
10089   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
10090 }
10091 
10092 // Catch division cases where we can use shortcuts with rcp and rsq
10093 // instructions.
10094 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
10095                                               SelectionDAG &DAG) const {
10096   SDLoc SL(Op);
10097   SDValue LHS = Op.getOperand(0);
10098   SDValue RHS = Op.getOperand(1);
10099   EVT VT = Op.getValueType();
10100   const SDNodeFlags Flags = Op->getFlags();
10101 
10102   bool AllowInaccurateRcp = Flags.hasApproximateFuncs() ||
10103                             DAG.getTarget().Options.UnsafeFPMath;
10104 
10105   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
10106     // Without !fpmath accuracy information, we can't do more because we don't
10107     // know exactly whether rcp is accurate enough to meet !fpmath requirement.
10108     // f16 is always accurate enough
10109     if (!AllowInaccurateRcp && VT != MVT::f16)
10110       return SDValue();
10111 
10112     if (CLHS->isExactlyValue(1.0)) {
10113       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
10114       // the CI documentation has a worst case error of 1 ulp.
10115       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
10116       // use it as long as we aren't trying to use denormals.
10117       //
10118       // v_rcp_f16 and v_rsq_f16 DO support denormals and 0.51ulp.
10119 
10120       // 1.0 / sqrt(x) -> rsq(x)
10121 
10122       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
10123       // error seems really high at 2^29 ULP.
10124       // 1.0 / x -> rcp(x)
10125       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
10126     }
10127 
10128     // Same as for 1.0, but expand the sign out of the constant.
10129     if (CLHS->isExactlyValue(-1.0)) {
10130       // -1.0 / x -> rcp (fneg x)
10131       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10132       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
10133     }
10134   }
10135 
10136   // For f16 require afn or arcp.
10137   // For f32 require afn.
10138   if (!AllowInaccurateRcp && (VT != MVT::f16 || !Flags.hasAllowReciprocal()))
10139     return SDValue();
10140 
10141   // Turn into multiply by the reciprocal.
10142   // x / y -> x * (1.0 / y)
10143   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
10144   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
10145 }
10146 
10147 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
10148                                                 SelectionDAG &DAG) const {
10149   SDLoc SL(Op);
10150   SDValue X = Op.getOperand(0);
10151   SDValue Y = Op.getOperand(1);
10152   EVT VT = Op.getValueType();
10153   const SDNodeFlags Flags = Op->getFlags();
10154 
10155   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
10156                             DAG.getTarget().Options.UnsafeFPMath;
10157   if (!AllowInaccurateDiv)
10158     return SDValue();
10159 
10160   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
10161   SDValue One = DAG.getConstantFP(1.0, SL, VT);
10162 
10163   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
10164   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
10165 
10166   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
10167   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
10168   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
10169   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
10170   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
10171   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
10172 }
10173 
10174 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
10175                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
10176                           SDNodeFlags Flags) {
10177   if (GlueChain->getNumValues() <= 1) {
10178     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
10179   }
10180 
10181   assert(GlueChain->getNumValues() == 3);
10182 
10183   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
10184   switch (Opcode) {
10185   default: llvm_unreachable("no chain equivalent for opcode");
10186   case ISD::FMUL:
10187     Opcode = AMDGPUISD::FMUL_W_CHAIN;
10188     break;
10189   }
10190 
10191   return DAG.getNode(Opcode, SL, VTList,
10192                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
10193                      Flags);
10194 }
10195 
10196 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
10197                            EVT VT, SDValue A, SDValue B, SDValue C,
10198                            SDValue GlueChain, SDNodeFlags Flags) {
10199   if (GlueChain->getNumValues() <= 1) {
10200     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
10201   }
10202 
10203   assert(GlueChain->getNumValues() == 3);
10204 
10205   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
10206   switch (Opcode) {
10207   default: llvm_unreachable("no chain equivalent for opcode");
10208   case ISD::FMA:
10209     Opcode = AMDGPUISD::FMA_W_CHAIN;
10210     break;
10211   }
10212 
10213   return DAG.getNode(Opcode, SL, VTList,
10214                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
10215                      Flags);
10216 }
10217 
10218 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
10219   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
10220     return FastLowered;
10221 
10222   SDLoc SL(Op);
10223   SDValue Src0 = Op.getOperand(0);
10224   SDValue Src1 = Op.getOperand(1);
10225 
10226   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
10227   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
10228 
10229   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
10230   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
10231 
10232   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
10233   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
10234 
10235   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
10236 }
10237 
10238 // Faster 2.5 ULP division that does not support denormals.
10239 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
10240   SDNodeFlags Flags = Op->getFlags();
10241   SDLoc SL(Op);
10242   SDValue LHS = Op.getOperand(1);
10243   SDValue RHS = Op.getOperand(2);
10244 
10245   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS, Flags);
10246 
10247   const APFloat K0Val(0x1p+96f);
10248   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
10249 
10250   const APFloat K1Val(0x1p-32f);
10251   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
10252 
10253   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
10254 
10255   EVT SetCCVT =
10256     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
10257 
10258   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
10259 
10260   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One, Flags);
10261 
10262   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3, Flags);
10263 
10264   // rcp does not support denormals.
10265   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1, Flags);
10266 
10267   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0, Flags);
10268 
10269   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul, Flags);
10270 }
10271 
10272 // Returns immediate value for setting the F32 denorm mode when using the
10273 // S_DENORM_MODE instruction.
10274 static SDValue getSPDenormModeValue(uint32_t SPDenormMode, SelectionDAG &DAG,
10275                                     const SIMachineFunctionInfo *Info,
10276                                     const GCNSubtarget *ST) {
10277   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
10278   uint32_t DPDenormModeDefault = Info->getMode().fpDenormModeDPValue();
10279   uint32_t Mode = SPDenormMode | (DPDenormModeDefault << 2);
10280   return DAG.getTargetConstant(Mode, SDLoc(), MVT::i32);
10281 }
10282 
10283 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
10284   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
10285     return FastLowered;
10286 
10287   // The selection matcher assumes anything with a chain selecting to a
10288   // mayRaiseFPException machine instruction. Since we're introducing a chain
10289   // here, we need to explicitly report nofpexcept for the regular fdiv
10290   // lowering.
10291   SDNodeFlags Flags = Op->getFlags();
10292   Flags.setNoFPExcept(true);
10293 
10294   SDLoc SL(Op);
10295   SDValue LHS = Op.getOperand(0);
10296   SDValue RHS = Op.getOperand(1);
10297 
10298   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
10299 
10300   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
10301 
10302   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
10303                                           {RHS, RHS, LHS}, Flags);
10304   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
10305                                         {LHS, RHS, LHS}, Flags);
10306 
10307   // Denominator is scaled to not be denormal, so using rcp is ok.
10308   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
10309                                   DenominatorScaled, Flags);
10310   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
10311                                      DenominatorScaled, Flags);
10312 
10313   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
10314                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
10315                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
10316   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
10317 
10318   const MachineFunction &MF = DAG.getMachineFunction();
10319   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10320   const DenormalMode DenormMode = Info->getMode().FP32Denormals;
10321 
10322   const bool PreservesDenormals = DenormMode == DenormalMode::getIEEE();
10323   const bool HasDynamicDenormals =
10324       (DenormMode.Input == DenormalMode::Dynamic) ||
10325       (DenormMode.Output == DenormalMode::Dynamic);
10326 
10327   SDValue SavedDenormMode;
10328 
10329   if (!PreservesDenormals) {
10330     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
10331     // lowering. The chain dependence is insufficient, and we need glue. We do
10332     // not need the glue variants in a strictfp function.
10333 
10334     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
10335 
10336     SDValue Glue = DAG.getEntryNode();
10337     if (HasDynamicDenormals) {
10338       SDNode *GetReg = DAG.getMachineNode(AMDGPU::S_GETREG_B32, SL,
10339                                           DAG.getVTList(MVT::i32, MVT::Glue),
10340                                           {BitField, Glue});
10341       SavedDenormMode = SDValue(GetReg, 0);
10342 
10343       Glue = DAG.getMergeValues(
10344           {DAG.getEntryNode(), SDValue(GetReg, 0), SDValue(GetReg, 1)}, SL);
10345     }
10346 
10347     SDNode *EnableDenorm;
10348     if (Subtarget->hasDenormModeInst()) {
10349       const SDValue EnableDenormValue =
10350           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, Info, Subtarget);
10351 
10352       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, Glue,
10353                                  EnableDenormValue)
10354                          .getNode();
10355     } else {
10356       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
10357                                                         SL, MVT::i32);
10358       EnableDenorm = DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
10359                                         {EnableDenormValue, BitField, Glue});
10360     }
10361 
10362     SDValue Ops[3] = {
10363       NegDivScale0,
10364       SDValue(EnableDenorm, 0),
10365       SDValue(EnableDenorm, 1)
10366     };
10367 
10368     NegDivScale0 = DAG.getMergeValues(Ops, SL);
10369   }
10370 
10371   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
10372                              ApproxRcp, One, NegDivScale0, Flags);
10373 
10374   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
10375                              ApproxRcp, Fma0, Flags);
10376 
10377   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
10378                            Fma1, Fma1, Flags);
10379 
10380   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
10381                              NumeratorScaled, Mul, Flags);
10382 
10383   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
10384                              Fma2, Fma1, Mul, Fma2, Flags);
10385 
10386   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
10387                              NumeratorScaled, Fma3, Flags);
10388 
10389   if (!PreservesDenormals) {
10390     SDNode *DisableDenorm;
10391     if (!HasDynamicDenormals && Subtarget->hasDenormModeInst()) {
10392       const SDValue DisableDenormValue = getSPDenormModeValue(
10393           FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, Info, Subtarget);
10394 
10395       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
10396                                   Fma4.getValue(1), DisableDenormValue,
10397                                   Fma4.getValue(2)).getNode();
10398     } else {
10399       assert(HasDynamicDenormals == (bool)SavedDenormMode);
10400       const SDValue DisableDenormValue =
10401           HasDynamicDenormals
10402               ? SavedDenormMode
10403               : DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
10404 
10405       DisableDenorm = DAG.getMachineNode(
10406           AMDGPU::S_SETREG_B32, SL, MVT::Other,
10407           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
10408     }
10409 
10410     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
10411                                       SDValue(DisableDenorm, 0), DAG.getRoot());
10412     DAG.setRoot(OutputChain);
10413   }
10414 
10415   SDValue Scale = NumeratorScaled.getValue(1);
10416   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
10417                              {Fma4, Fma1, Fma3, Scale}, Flags);
10418 
10419   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
10420 }
10421 
10422 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
10423   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
10424     return FastLowered;
10425 
10426   SDLoc SL(Op);
10427   SDValue X = Op.getOperand(0);
10428   SDValue Y = Op.getOperand(1);
10429 
10430   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
10431 
10432   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
10433 
10434   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
10435 
10436   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
10437 
10438   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
10439 
10440   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
10441 
10442   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
10443 
10444   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
10445 
10446   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
10447 
10448   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
10449   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
10450 
10451   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
10452                              NegDivScale0, Mul, DivScale1);
10453 
10454   SDValue Scale;
10455 
10456   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
10457     // Workaround a hardware bug on SI where the condition output from div_scale
10458     // is not usable.
10459 
10460     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
10461 
10462     // Figure out if the scale to use for div_fmas.
10463     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
10464     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
10465     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
10466     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
10467 
10468     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
10469     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
10470 
10471     SDValue Scale0Hi
10472       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
10473     SDValue Scale1Hi
10474       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
10475 
10476     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
10477     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
10478     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
10479   } else {
10480     Scale = DivScale1.getValue(1);
10481   }
10482 
10483   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
10484                              Fma4, Fma3, Mul, Scale);
10485 
10486   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
10487 }
10488 
10489 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
10490   EVT VT = Op.getValueType();
10491 
10492   if (VT == MVT::f32)
10493     return LowerFDIV32(Op, DAG);
10494 
10495   if (VT == MVT::f64)
10496     return LowerFDIV64(Op, DAG);
10497 
10498   if (VT == MVT::f16)
10499     return LowerFDIV16(Op, DAG);
10500 
10501   llvm_unreachable("Unexpected type for fdiv");
10502 }
10503 
10504 SDValue SITargetLowering::LowerFFREXP(SDValue Op, SelectionDAG &DAG) const {
10505   SDLoc dl(Op);
10506   SDValue Val = Op.getOperand(0);
10507   EVT VT = Val.getValueType();
10508   EVT ResultExpVT = Op->getValueType(1);
10509   EVT InstrExpVT = VT == MVT::f16 ? MVT::i16 : MVT::i32;
10510 
10511   SDValue Mant = DAG.getNode(
10512       ISD::INTRINSIC_WO_CHAIN, dl, VT,
10513       DAG.getTargetConstant(Intrinsic::amdgcn_frexp_mant, dl, MVT::i32), Val);
10514 
10515   SDValue Exp = DAG.getNode(
10516       ISD::INTRINSIC_WO_CHAIN, dl, InstrExpVT,
10517       DAG.getTargetConstant(Intrinsic::amdgcn_frexp_exp, dl, MVT::i32), Val);
10518 
10519   if (Subtarget->hasFractBug()) {
10520     SDValue Fabs = DAG.getNode(ISD::FABS, dl, VT, Val);
10521     SDValue Inf = DAG.getConstantFP(
10522         APFloat::getInf(SelectionDAG::EVTToAPFloatSemantics(VT)), dl, VT);
10523 
10524     SDValue IsFinite = DAG.getSetCC(dl, MVT::i1, Fabs, Inf, ISD::SETOLT);
10525     SDValue Zero = DAG.getConstant(0, dl, InstrExpVT);
10526     Exp = DAG.getNode(ISD::SELECT, dl, InstrExpVT, IsFinite, Exp, Zero);
10527     Mant = DAG.getNode(ISD::SELECT, dl, VT, IsFinite, Mant, Val);
10528   }
10529 
10530   SDValue CastExp = DAG.getSExtOrTrunc(Exp, dl, ResultExpVT);
10531   return DAG.getMergeValues({Mant, CastExp}, dl);
10532 }
10533 
10534 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
10535   SDLoc DL(Op);
10536   StoreSDNode *Store = cast<StoreSDNode>(Op);
10537   EVT VT = Store->getMemoryVT();
10538 
10539   if (VT == MVT::i1) {
10540     return DAG.getTruncStore(Store->getChain(), DL,
10541        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
10542        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
10543   }
10544 
10545   assert(VT.isVector() &&
10546          Store->getValue().getValueType().getScalarType() == MVT::i32);
10547 
10548   unsigned AS = Store->getAddressSpace();
10549   if (Subtarget->hasLDSMisalignedBug() &&
10550       AS == AMDGPUAS::FLAT_ADDRESS &&
10551       Store->getAlign().value() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
10552     return SplitVectorStore(Op, DAG);
10553   }
10554 
10555   MachineFunction &MF = DAG.getMachineFunction();
10556   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
10557   // If there is a possibility that flat instruction access scratch memory
10558   // then we need to use the same legalization rules we use for private.
10559   if (AS == AMDGPUAS::FLAT_ADDRESS &&
10560       !Subtarget->hasMultiDwordFlatScratchAddressing())
10561     AS = addressMayBeAccessedAsPrivate(Store->getMemOperand(), *MFI) ?
10562          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
10563 
10564   unsigned NumElements = VT.getVectorNumElements();
10565   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
10566       AS == AMDGPUAS::FLAT_ADDRESS) {
10567     if (NumElements > 4)
10568       return SplitVectorStore(Op, DAG);
10569     // v3 stores not supported on SI.
10570     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
10571       return SplitVectorStore(Op, DAG);
10572 
10573     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
10574                                         VT, *Store->getMemOperand()))
10575       return expandUnalignedStore(Store, DAG);
10576 
10577     return SDValue();
10578   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
10579     switch (Subtarget->getMaxPrivateElementSize()) {
10580     case 4:
10581       return scalarizeVectorStore(Store, DAG);
10582     case 8:
10583       if (NumElements > 2)
10584         return SplitVectorStore(Op, DAG);
10585       return SDValue();
10586     case 16:
10587       if (NumElements > 4 ||
10588           (NumElements == 3 && !Subtarget->enableFlatScratch()))
10589         return SplitVectorStore(Op, DAG);
10590       return SDValue();
10591     default:
10592       llvm_unreachable("unsupported private_element_size");
10593     }
10594   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
10595     unsigned Fast = 0;
10596     auto Flags = Store->getMemOperand()->getFlags();
10597     if (allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
10598                                            Store->getAlign(), Flags, &Fast) &&
10599         Fast > 1)
10600       return SDValue();
10601 
10602     if (VT.isVector())
10603       return SplitVectorStore(Op, DAG);
10604 
10605     return expandUnalignedStore(Store, DAG);
10606   }
10607 
10608   // Probably an invalid store. If so we'll end up emitting a selection error.
10609   return SDValue();
10610 }
10611 
10612 // Avoid the full correct expansion for f32 sqrt when promoting from f16.
10613 SDValue SITargetLowering::lowerFSQRTF16(SDValue Op, SelectionDAG &DAG) const {
10614   SDLoc SL(Op);
10615   assert(!Subtarget->has16BitInsts());
10616   SDNodeFlags Flags = Op->getFlags();
10617   SDValue Ext =
10618       DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Op.getOperand(0), Flags);
10619 
10620   SDValue SqrtID = DAG.getTargetConstant(Intrinsic::amdgcn_sqrt, SL, MVT::i32);
10621   SDValue Sqrt =
10622       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, MVT::f32, SqrtID, Ext, Flags);
10623 
10624   return DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Sqrt,
10625                      DAG.getTargetConstant(0, SL, MVT::i32), Flags);
10626 }
10627 
10628 SDValue SITargetLowering::lowerFSQRTF32(SDValue Op, SelectionDAG &DAG) const {
10629   SDLoc DL(Op);
10630   SDNodeFlags Flags = Op->getFlags();
10631   MVT VT = Op.getValueType().getSimpleVT();
10632   const SDValue X = Op.getOperand(0);
10633 
10634   if (allowApproxFunc(DAG, Flags)) {
10635     // Instruction is 1ulp but ignores denormals.
10636     return DAG.getNode(
10637         ISD::INTRINSIC_WO_CHAIN, DL, VT,
10638         DAG.getTargetConstant(Intrinsic::amdgcn_sqrt, DL, MVT::i32), X, Flags);
10639   }
10640 
10641   SDValue ScaleThreshold = DAG.getConstantFP(0x1.0p-96f, DL, VT);
10642   SDValue NeedScale = DAG.getSetCC(DL, MVT::i1, X, ScaleThreshold, ISD::SETOLT);
10643 
10644   SDValue ScaleUpFactor = DAG.getConstantFP(0x1.0p+32f, DL, VT);
10645 
10646   SDValue ScaledX = DAG.getNode(ISD::FMUL, DL, VT, X, ScaleUpFactor, Flags);
10647 
10648   SDValue SqrtX =
10649       DAG.getNode(ISD::SELECT, DL, VT, NeedScale, ScaledX, X, Flags);
10650 
10651   SDValue SqrtS;
10652   if (needsDenormHandlingF32(DAG, X, Flags)) {
10653     SDValue SqrtID =
10654         DAG.getTargetConstant(Intrinsic::amdgcn_sqrt, DL, MVT::i32);
10655     SqrtS = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, SqrtID, SqrtX, Flags);
10656 
10657     SDValue SqrtSAsInt = DAG.getNode(ISD::BITCAST, DL, MVT::i32, SqrtS);
10658     SDValue SqrtSNextDownInt = DAG.getNode(ISD::ADD, DL, MVT::i32, SqrtSAsInt,
10659                                            DAG.getConstant(-1, DL, MVT::i32));
10660     SDValue SqrtSNextDown = DAG.getNode(ISD::BITCAST, DL, VT, SqrtSNextDownInt);
10661 
10662     SDValue NegSqrtSNextDown =
10663         DAG.getNode(ISD::FNEG, DL, VT, SqrtSNextDown, Flags);
10664 
10665     SDValue SqrtVP =
10666         DAG.getNode(ISD::FMA, DL, VT, NegSqrtSNextDown, SqrtS, SqrtX, Flags);
10667 
10668     SDValue SqrtSNextUpInt = DAG.getNode(ISD::ADD, DL, MVT::i32, SqrtSAsInt,
10669                                          DAG.getConstant(1, DL, MVT::i32));
10670     SDValue SqrtSNextUp = DAG.getNode(ISD::BITCAST, DL, VT, SqrtSNextUpInt);
10671 
10672     SDValue NegSqrtSNextUp = DAG.getNode(ISD::FNEG, DL, VT, SqrtSNextUp, Flags);
10673     SDValue SqrtVS =
10674         DAG.getNode(ISD::FMA, DL, VT, NegSqrtSNextUp, SqrtS, SqrtX, Flags);
10675 
10676     SDValue Zero = DAG.getConstantFP(0.0f, DL, VT);
10677     SDValue SqrtVPLE0 = DAG.getSetCC(DL, MVT::i1, SqrtVP, Zero, ISD::SETOLE);
10678 
10679     SqrtS = DAG.getNode(ISD::SELECT, DL, VT, SqrtVPLE0, SqrtSNextDown, SqrtS,
10680                         Flags);
10681 
10682     SDValue SqrtVPVSGT0 = DAG.getSetCC(DL, MVT::i1, SqrtVS, Zero, ISD::SETOGT);
10683     SqrtS = DAG.getNode(ISD::SELECT, DL, VT, SqrtVPVSGT0, SqrtSNextUp, SqrtS,
10684                         Flags);
10685   } else {
10686     SDValue SqrtR = DAG.getNode(AMDGPUISD::RSQ, DL, VT, SqrtX, Flags);
10687 
10688     SqrtS = DAG.getNode(ISD::FMUL, DL, VT, SqrtX, SqrtR, Flags);
10689 
10690     SDValue Half = DAG.getConstantFP(0.5f, DL, VT);
10691     SDValue SqrtH = DAG.getNode(ISD::FMUL, DL, VT, SqrtR, Half, Flags);
10692     SDValue NegSqrtH = DAG.getNode(ISD::FNEG, DL, VT, SqrtH, Flags);
10693 
10694     SDValue SqrtE = DAG.getNode(ISD::FMA, DL, VT, NegSqrtH, SqrtS, Half, Flags);
10695     SqrtH = DAG.getNode(ISD::FMA, DL, VT, SqrtH, SqrtE, SqrtH, Flags);
10696     SqrtS = DAG.getNode(ISD::FMA, DL, VT, SqrtS, SqrtE, SqrtS, Flags);
10697 
10698     SDValue NegSqrtS = DAG.getNode(ISD::FNEG, DL, VT, SqrtS, Flags);
10699     SDValue SqrtD =
10700         DAG.getNode(ISD::FMA, DL, VT, NegSqrtS, SqrtS, SqrtX, Flags);
10701     SqrtS = DAG.getNode(ISD::FMA, DL, VT, SqrtD, SqrtH, SqrtS, Flags);
10702   }
10703 
10704   SDValue ScaleDownFactor = DAG.getConstantFP(0x1.0p-16f, DL, VT);
10705 
10706   SDValue ScaledDown =
10707       DAG.getNode(ISD::FMUL, DL, VT, SqrtS, ScaleDownFactor, Flags);
10708 
10709   SqrtS = DAG.getNode(ISD::SELECT, DL, VT, NeedScale, ScaledDown, SqrtS, Flags);
10710   SDValue IsZeroOrInf =
10711       DAG.getNode(ISD::IS_FPCLASS, DL, MVT::i1, SqrtX,
10712                   DAG.getTargetConstant(fcZero | fcPosInf, DL, MVT::i32));
10713 
10714   return DAG.getNode(ISD::SELECT, DL, VT, IsZeroOrInf, SqrtX, SqrtS, Flags);
10715 }
10716 
10717 SDValue SITargetLowering::lowerFSQRTF64(SDValue Op, SelectionDAG &DAG) const {
10718   // For double type, the SQRT and RSQ instructions don't have required
10719   // precision, we apply Goldschmidt's algorithm to improve the result:
10720   //
10721   //   y0 = rsq(x)
10722   //   g0 = x * y0
10723   //   h0 = 0.5 * y0
10724   //
10725   //   r0 = 0.5 - h0 * g0
10726   //   g1 = g0 * r0 + g0
10727   //   h1 = h0 * r0 + h0
10728   //
10729   //   r1 = 0.5 - h1 * g1 => d0 = x - g1 * g1
10730   //   g2 = g1 * r1 + g1     g2 = d0 * h1 + g1
10731   //   h2 = h1 * r1 + h1
10732   //
10733   //   r2 = 0.5 - h2 * g2 => d1 = x - g2 * g2
10734   //   g3 = g2 * r2 + g2     g3 = d1 * h1 + g2
10735   //
10736   //   sqrt(x) = g3
10737 
10738   SDNodeFlags Flags = Op->getFlags();
10739 
10740   SDLoc DL(Op);
10741 
10742   SDValue X = Op.getOperand(0);
10743   SDValue ScaleConstant = DAG.getConstantFP(0x1.0p-767, DL, MVT::f64);
10744 
10745   SDValue Scaling = DAG.getSetCC(DL, MVT::i1, X, ScaleConstant, ISD::SETOLT);
10746 
10747   SDValue ZeroInt = DAG.getConstant(0, DL, MVT::i32);
10748 
10749   // Scale up input if it is too small.
10750   SDValue ScaleUpFactor = DAG.getConstant(256, DL, MVT::i32);
10751   SDValue ScaleUp =
10752       DAG.getNode(ISD::SELECT, DL, MVT::i32, Scaling, ScaleUpFactor, ZeroInt);
10753   SDValue SqrtX = DAG.getNode(ISD::FLDEXP, DL, MVT::f64, X, ScaleUp, Flags);
10754 
10755   SDValue SqrtY = DAG.getNode(AMDGPUISD::RSQ, DL, MVT::f64, SqrtX);
10756 
10757   SDValue SqrtS0 = DAG.getNode(ISD::FMUL, DL, MVT::f64, SqrtX, SqrtY);
10758 
10759   SDValue Half = DAG.getConstantFP(0.5, DL, MVT::f64);
10760   SDValue SqrtH0 = DAG.getNode(ISD::FMUL, DL, MVT::f64, SqrtY, Half);
10761 
10762   SDValue NegSqrtH0 = DAG.getNode(ISD::FNEG, DL, MVT::f64, SqrtH0);
10763   SDValue SqrtR0 = DAG.getNode(ISD::FMA, DL, MVT::f64, NegSqrtH0, SqrtS0, Half);
10764 
10765   SDValue SqrtH1 = DAG.getNode(ISD::FMA, DL, MVT::f64, SqrtH0, SqrtR0, SqrtH0);
10766 
10767   SDValue SqrtS1 = DAG.getNode(ISD::FMA, DL, MVT::f64, SqrtS0, SqrtR0, SqrtS0);
10768 
10769   SDValue NegSqrtS1 = DAG.getNode(ISD::FNEG, DL, MVT::f64, SqrtS1);
10770   SDValue SqrtD0 = DAG.getNode(ISD::FMA, DL, MVT::f64, NegSqrtS1, SqrtS1, SqrtX);
10771 
10772   SDValue SqrtS2 = DAG.getNode(ISD::FMA, DL, MVT::f64, SqrtD0, SqrtH1, SqrtS1);
10773 
10774   SDValue NegSqrtS2 = DAG.getNode(ISD::FNEG, DL, MVT::f64, SqrtS2);
10775   SDValue SqrtD1 =
10776       DAG.getNode(ISD::FMA, DL, MVT::f64, NegSqrtS2, SqrtS2, SqrtX);
10777 
10778   SDValue SqrtRet = DAG.getNode(ISD::FMA, DL, MVT::f64, SqrtD1, SqrtH1, SqrtS2);
10779 
10780   SDValue ScaleDownFactor = DAG.getConstant(-128, DL, MVT::i32);
10781   SDValue ScaleDown =
10782       DAG.getNode(ISD::SELECT, DL, MVT::i32, Scaling, ScaleDownFactor, ZeroInt);
10783   SqrtRet = DAG.getNode(ISD::FLDEXP, DL, MVT::f64, SqrtRet, ScaleDown, Flags);
10784 
10785   // TODO: Switch to fcmp oeq 0 for finite only. Can't fully remove this check
10786   // with finite only or nsz because rsq(+/-0) = +/-inf
10787 
10788   // TODO: Check for DAZ and expand to subnormals
10789   SDValue IsZeroOrInf =
10790       DAG.getNode(ISD::IS_FPCLASS, DL, MVT::i1, SqrtX,
10791                   DAG.getTargetConstant(fcZero | fcPosInf, DL, MVT::i32));
10792 
10793   // If x is +INF, +0, or -0, use its original value
10794   return DAG.getNode(ISD::SELECT, DL, MVT::f64, IsZeroOrInf, SqrtX, SqrtRet,
10795                      Flags);
10796 }
10797 
10798 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
10799   SDLoc DL(Op);
10800   EVT VT = Op.getValueType();
10801   SDValue Arg = Op.getOperand(0);
10802   SDValue TrigVal;
10803 
10804   // Propagate fast-math flags so that the multiply we introduce can be folded
10805   // if Arg is already the result of a multiply by constant.
10806   auto Flags = Op->getFlags();
10807 
10808   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
10809 
10810   if (Subtarget->hasTrigReducedRange()) {
10811     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
10812     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
10813   } else {
10814     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
10815   }
10816 
10817   switch (Op.getOpcode()) {
10818   case ISD::FCOS:
10819     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
10820   case ISD::FSIN:
10821     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
10822   default:
10823     llvm_unreachable("Wrong trig opcode");
10824   }
10825 }
10826 
10827 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10828   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
10829   assert(AtomicNode->isCompareAndSwap());
10830   unsigned AS = AtomicNode->getAddressSpace();
10831 
10832   // No custom lowering required for local address space
10833   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
10834     return Op;
10835 
10836   // Non-local address space requires custom lowering for atomic compare
10837   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
10838   SDLoc DL(Op);
10839   SDValue ChainIn = Op.getOperand(0);
10840   SDValue Addr = Op.getOperand(1);
10841   SDValue Old = Op.getOperand(2);
10842   SDValue New = Op.getOperand(3);
10843   EVT VT = Op.getValueType();
10844   MVT SimpleVT = VT.getSimpleVT();
10845   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
10846 
10847   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
10848   SDValue Ops[] = { ChainIn, Addr, NewOld };
10849 
10850   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
10851                                  Ops, VT, AtomicNode->getMemOperand());
10852 }
10853 
10854 //===----------------------------------------------------------------------===//
10855 // Custom DAG optimizations
10856 //===----------------------------------------------------------------------===//
10857 
10858 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
10859                                                      DAGCombinerInfo &DCI) const {
10860   EVT VT = N->getValueType(0);
10861   EVT ScalarVT = VT.getScalarType();
10862   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
10863     return SDValue();
10864 
10865   SelectionDAG &DAG = DCI.DAG;
10866   SDLoc DL(N);
10867 
10868   SDValue Src = N->getOperand(0);
10869   EVT SrcVT = Src.getValueType();
10870 
10871   // TODO: We could try to match extracting the higher bytes, which would be
10872   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
10873   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
10874   // about in practice.
10875   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
10876     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
10877       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
10878       DCI.AddToWorklist(Cvt.getNode());
10879 
10880       // For the f16 case, fold to a cast to f32 and then cast back to f16.
10881       if (ScalarVT != MVT::f32) {
10882         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
10883                           DAG.getTargetConstant(0, DL, MVT::i32));
10884       }
10885       return Cvt;
10886     }
10887   }
10888 
10889   return SDValue();
10890 }
10891 
10892 SDValue SITargetLowering::performFCopySignCombine(SDNode *N,
10893                                                   DAGCombinerInfo &DCI) const {
10894   SDValue MagnitudeOp = N->getOperand(0);
10895   SDValue SignOp = N->getOperand(1);
10896   SelectionDAG &DAG = DCI.DAG;
10897   SDLoc DL(N);
10898 
10899   // f64 fcopysign is really an f32 copysign on the high bits, so replace the
10900   // lower half with a copy.
10901   // fcopysign f64:x, _:y -> x.lo32, (fcopysign (f32 x.hi32), _:y)
10902   if (MagnitudeOp.getValueType() == MVT::f64) {
10903     SDValue MagAsVector = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, MagnitudeOp);
10904     SDValue MagLo =
10905       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, MagAsVector,
10906                   DAG.getConstant(0, DL, MVT::i32));
10907     SDValue MagHi =
10908       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, MagAsVector,
10909                   DAG.getConstant(1, DL, MVT::i32));
10910 
10911     SDValue HiOp =
10912       DAG.getNode(ISD::FCOPYSIGN, DL, MVT::f32, MagHi, SignOp);
10913 
10914     SDValue Vector = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v2f32, MagLo, HiOp);
10915 
10916     return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Vector);
10917   }
10918 
10919   if (SignOp.getValueType() != MVT::f64)
10920     return SDValue();
10921 
10922   // Reduce width of sign operand, we only need the highest bit.
10923   //
10924   // fcopysign f64:x, f64:y ->
10925   //   fcopysign f64:x, (extract_vector_elt (bitcast f64:y to v2f32), 1)
10926   // TODO: In some cases it might make sense to go all the way to f16.
10927   SDValue SignAsVector = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32, SignOp);
10928   SDValue SignAsF32 =
10929       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, SignAsVector,
10930                   DAG.getConstant(1, DL, MVT::i32));
10931 
10932   return DAG.getNode(ISD::FCOPYSIGN, DL, N->getValueType(0), N->getOperand(0),
10933                      SignAsF32);
10934 }
10935 
10936 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
10937 // (shl (or x, c1), c2) -> add (shl x, c2), (shl c1, c2) iff x and c1 share no
10938 // bits
10939 
10940 // This is a variant of
10941 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
10942 //
10943 // The normal DAG combiner will do this, but only if the add has one use since
10944 // that would increase the number of instructions.
10945 //
10946 // This prevents us from seeing a constant offset that can be folded into a
10947 // memory instruction's addressing mode. If we know the resulting add offset of
10948 // a pointer can be folded into an addressing offset, we can replace the pointer
10949 // operand with the add of new constant offset. This eliminates one of the uses,
10950 // and may allow the remaining use to also be simplified.
10951 //
10952 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
10953                                                unsigned AddrSpace,
10954                                                EVT MemVT,
10955                                                DAGCombinerInfo &DCI) const {
10956   SDValue N0 = N->getOperand(0);
10957   SDValue N1 = N->getOperand(1);
10958 
10959   // We only do this to handle cases where it's profitable when there are
10960   // multiple uses of the add, so defer to the standard combine.
10961   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
10962       N0->hasOneUse())
10963     return SDValue();
10964 
10965   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
10966   if (!CN1)
10967     return SDValue();
10968 
10969   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
10970   if (!CAdd)
10971     return SDValue();
10972 
10973   SelectionDAG &DAG = DCI.DAG;
10974 
10975   if (N0->getOpcode() == ISD::OR &&
10976       !DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1)))
10977     return SDValue();
10978 
10979   // If the resulting offset is too large, we can't fold it into the
10980   // addressing mode offset.
10981   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
10982   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
10983 
10984   AddrMode AM;
10985   AM.HasBaseReg = true;
10986   AM.BaseOffs = Offset.getSExtValue();
10987   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
10988     return SDValue();
10989 
10990   SDLoc SL(N);
10991   EVT VT = N->getValueType(0);
10992 
10993   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
10994   SDValue COffset = DAG.getConstant(Offset, SL, VT);
10995 
10996   SDNodeFlags Flags;
10997   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
10998                           (N0.getOpcode() == ISD::OR ||
10999                            N0->getFlags().hasNoUnsignedWrap()));
11000 
11001   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
11002 }
11003 
11004 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
11005 /// by the chain and intrinsic ID. Theoretically we would also need to check the
11006 /// specific intrinsic, but they all place the pointer operand first.
11007 static unsigned getBasePtrIndex(const MemSDNode *N) {
11008   switch (N->getOpcode()) {
11009   case ISD::STORE:
11010   case ISD::INTRINSIC_W_CHAIN:
11011   case ISD::INTRINSIC_VOID:
11012     return 2;
11013   default:
11014     return 1;
11015   }
11016 }
11017 
11018 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
11019                                                   DAGCombinerInfo &DCI) const {
11020   SelectionDAG &DAG = DCI.DAG;
11021   SDLoc SL(N);
11022 
11023   unsigned PtrIdx = getBasePtrIndex(N);
11024   SDValue Ptr = N->getOperand(PtrIdx);
11025 
11026   // TODO: We could also do this for multiplies.
11027   if (Ptr.getOpcode() == ISD::SHL) {
11028     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
11029                                           N->getMemoryVT(), DCI);
11030     if (NewPtr) {
11031       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
11032 
11033       NewOps[PtrIdx] = NewPtr;
11034       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
11035     }
11036   }
11037 
11038   return SDValue();
11039 }
11040 
11041 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
11042   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
11043          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
11044          (Opc == ISD::XOR && Val == 0);
11045 }
11046 
11047 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
11048 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
11049 // integer combine opportunities since most 64-bit operations are decomposed
11050 // this way.  TODO: We won't want this for SALU especially if it is an inline
11051 // immediate.
11052 SDValue SITargetLowering::splitBinaryBitConstantOp(
11053   DAGCombinerInfo &DCI,
11054   const SDLoc &SL,
11055   unsigned Opc, SDValue LHS,
11056   const ConstantSDNode *CRHS) const {
11057   uint64_t Val = CRHS->getZExtValue();
11058   uint32_t ValLo = Lo_32(Val);
11059   uint32_t ValHi = Hi_32(Val);
11060   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11061 
11062     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
11063          bitOpWithConstantIsReducible(Opc, ValHi)) ||
11064         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
11065     // If we need to materialize a 64-bit immediate, it will be split up later
11066     // anyway. Avoid creating the harder to understand 64-bit immediate
11067     // materialization.
11068     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
11069   }
11070 
11071   return SDValue();
11072 }
11073 
11074 bool llvm::isBoolSGPR(SDValue V) {
11075   if (V.getValueType() != MVT::i1)
11076     return false;
11077   switch (V.getOpcode()) {
11078   default:
11079     break;
11080   case ISD::SETCC:
11081   case AMDGPUISD::FP_CLASS:
11082     return true;
11083   case ISD::AND:
11084   case ISD::OR:
11085   case ISD::XOR:
11086     return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
11087   }
11088   return false;
11089 }
11090 
11091 // If a constant has all zeroes or all ones within each byte return it.
11092 // Otherwise return 0.
11093 static uint32_t getConstantPermuteMask(uint32_t C) {
11094   // 0xff for any zero byte in the mask
11095   uint32_t ZeroByteMask = 0;
11096   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
11097   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
11098   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
11099   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
11100   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
11101   if ((NonZeroByteMask & C) != NonZeroByteMask)
11102     return 0; // Partial bytes selected.
11103   return C;
11104 }
11105 
11106 // Check if a node selects whole bytes from its operand 0 starting at a byte
11107 // boundary while masking the rest. Returns select mask as in the v_perm_b32
11108 // or -1 if not succeeded.
11109 // Note byte select encoding:
11110 // value 0-3 selects corresponding source byte;
11111 // value 0xc selects zero;
11112 // value 0xff selects 0xff.
11113 static uint32_t getPermuteMask(SDValue V) {
11114   assert(V.getValueSizeInBits() == 32);
11115 
11116   if (V.getNumOperands() != 2)
11117     return ~0;
11118 
11119   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
11120   if (!N1)
11121     return ~0;
11122 
11123   uint32_t C = N1->getZExtValue();
11124 
11125   switch (V.getOpcode()) {
11126   default:
11127     break;
11128   case ISD::AND:
11129     if (uint32_t ConstMask = getConstantPermuteMask(C))
11130       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
11131     break;
11132 
11133   case ISD::OR:
11134     if (uint32_t ConstMask = getConstantPermuteMask(C))
11135       return (0x03020100 & ~ConstMask) | ConstMask;
11136     break;
11137 
11138   case ISD::SHL:
11139     if (C % 8)
11140       return ~0;
11141 
11142     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
11143 
11144   case ISD::SRL:
11145     if (C % 8)
11146       return ~0;
11147 
11148     return uint32_t(0x0c0c0c0c03020100ull >> C);
11149   }
11150 
11151   return ~0;
11152 }
11153 
11154 SDValue SITargetLowering::performAndCombine(SDNode *N,
11155                                             DAGCombinerInfo &DCI) const {
11156   if (DCI.isBeforeLegalize())
11157     return SDValue();
11158 
11159   SelectionDAG &DAG = DCI.DAG;
11160   EVT VT = N->getValueType(0);
11161   SDValue LHS = N->getOperand(0);
11162   SDValue RHS = N->getOperand(1);
11163 
11164 
11165   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
11166   if (VT == MVT::i64 && CRHS) {
11167     if (SDValue Split
11168         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
11169       return Split;
11170   }
11171 
11172   if (CRHS && VT == MVT::i32) {
11173     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
11174     // nb = number of trailing zeroes in mask
11175     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
11176     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
11177     uint64_t Mask = CRHS->getZExtValue();
11178     unsigned Bits = llvm::popcount(Mask);
11179     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
11180         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
11181       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
11182         unsigned Shift = CShift->getZExtValue();
11183         unsigned NB = CRHS->getAPIntValue().countr_zero();
11184         unsigned Offset = NB + Shift;
11185         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
11186           SDLoc SL(N);
11187           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
11188                                     LHS->getOperand(0),
11189                                     DAG.getConstant(Offset, SL, MVT::i32),
11190                                     DAG.getConstant(Bits, SL, MVT::i32));
11191           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
11192           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
11193                                     DAG.getValueType(NarrowVT));
11194           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
11195                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
11196           return Shl;
11197         }
11198       }
11199     }
11200 
11201     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
11202     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
11203         isa<ConstantSDNode>(LHS.getOperand(2))) {
11204       uint32_t Sel = getConstantPermuteMask(Mask);
11205       if (!Sel)
11206         return SDValue();
11207 
11208       // Select 0xc for all zero bytes
11209       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
11210       SDLoc DL(N);
11211       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
11212                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
11213     }
11214   }
11215 
11216   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
11217   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
11218   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
11219     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
11220     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
11221 
11222     SDValue X = LHS.getOperand(0);
11223     SDValue Y = RHS.getOperand(0);
11224     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X ||
11225         !isTypeLegal(X.getValueType()))
11226       return SDValue();
11227 
11228     if (LCC == ISD::SETO) {
11229       if (X != LHS.getOperand(1))
11230         return SDValue();
11231 
11232       if (RCC == ISD::SETUNE) {
11233         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
11234         if (!C1 || !C1->isInfinity() || C1->isNegative())
11235           return SDValue();
11236 
11237         const uint32_t Mask = SIInstrFlags::N_NORMAL |
11238                               SIInstrFlags::N_SUBNORMAL |
11239                               SIInstrFlags::N_ZERO |
11240                               SIInstrFlags::P_ZERO |
11241                               SIInstrFlags::P_SUBNORMAL |
11242                               SIInstrFlags::P_NORMAL;
11243 
11244         static_assert(((~(SIInstrFlags::S_NAN |
11245                           SIInstrFlags::Q_NAN |
11246                           SIInstrFlags::N_INFINITY |
11247                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
11248                       "mask not equal");
11249 
11250         SDLoc DL(N);
11251         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
11252                            X, DAG.getConstant(Mask, DL, MVT::i32));
11253       }
11254     }
11255   }
11256 
11257   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
11258     std::swap(LHS, RHS);
11259 
11260   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
11261       RHS.hasOneUse()) {
11262     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
11263     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
11264     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
11265     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
11266     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
11267         (RHS.getOperand(0) == LHS.getOperand(0) &&
11268          LHS.getOperand(0) == LHS.getOperand(1))) {
11269       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
11270       unsigned NewMask = LCC == ISD::SETO ?
11271         Mask->getZExtValue() & ~OrdMask :
11272         Mask->getZExtValue() & OrdMask;
11273 
11274       SDLoc DL(N);
11275       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
11276                          DAG.getConstant(NewMask, DL, MVT::i32));
11277     }
11278   }
11279 
11280   if (VT == MVT::i32 &&
11281       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
11282     // and x, (sext cc from i1) => select cc, x, 0
11283     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
11284       std::swap(LHS, RHS);
11285     if (isBoolSGPR(RHS.getOperand(0)))
11286       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
11287                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
11288   }
11289 
11290   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
11291   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11292   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
11293       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
11294     uint32_t LHSMask = getPermuteMask(LHS);
11295     uint32_t RHSMask = getPermuteMask(RHS);
11296     if (LHSMask != ~0u && RHSMask != ~0u) {
11297       // Canonicalize the expression in an attempt to have fewer unique masks
11298       // and therefore fewer registers used to hold the masks.
11299       if (LHSMask > RHSMask) {
11300         std::swap(LHSMask, RHSMask);
11301         std::swap(LHS, RHS);
11302       }
11303 
11304       // Select 0xc for each lane used from source operand. Zero has 0xc mask
11305       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
11306       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
11307       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
11308 
11309       // Check of we need to combine values from two sources within a byte.
11310       if (!(LHSUsedLanes & RHSUsedLanes) &&
11311           // If we select high and lower word keep it for SDWA.
11312           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
11313           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
11314         // Each byte in each mask is either selector mask 0-3, or has higher
11315         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
11316         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
11317         // mask which is not 0xff wins. By anding both masks we have a correct
11318         // result except that 0x0c shall be corrected to give 0x0c only.
11319         uint32_t Mask = LHSMask & RHSMask;
11320         for (unsigned I = 0; I < 32; I += 8) {
11321           uint32_t ByteSel = 0xff << I;
11322           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
11323             Mask &= (0x0c << I) & 0xffffffff;
11324         }
11325 
11326         // Add 4 to each active LHS lane. It will not affect any existing 0xff
11327         // or 0x0c.
11328         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
11329         SDLoc DL(N);
11330 
11331         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
11332                            LHS.getOperand(0), RHS.getOperand(0),
11333                            DAG.getConstant(Sel, DL, MVT::i32));
11334       }
11335     }
11336   }
11337 
11338   return SDValue();
11339 }
11340 
11341 // A key component of v_perm is a mapping between byte position of the src
11342 // operands, and the byte position of the dest. To provide such, we need: 1. the
11343 // node that provides x byte of the dest of the OR, and 2. the byte of the node
11344 // used to provide that x byte. calculateByteProvider finds which node provides
11345 // a certain byte of the dest of the OR, and calculateSrcByte takes that node,
11346 // and finds an ultimate src and byte position For example: The supported
11347 // LoadCombine pattern for vector loads is as follows
11348 //                                t1
11349 //                                or
11350 //                      /                  \
11351 //                      t2                 t3
11352 //                     zext                shl
11353 //                      |                   |     \
11354 //                     t4                  t5     16
11355 //                     or                 anyext
11356 //                 /        \               |
11357 //                t6        t7             t8
11358 //               srl        shl             or
11359 //            /    |      /     \         /     \
11360 //           t9   t10    t11   t12      t13    t14
11361 //         trunc*  8    trunc*  8      and     and
11362 //           |            |          /    |     |    \
11363 //          t15          t16        t17  t18   t19   t20
11364 //                                trunc*  255   srl   -256
11365 //                                   |         /   \
11366 //                                  t15       t15  16
11367 //
11368 // *In this example, the truncs are from i32->i16
11369 //
11370 // calculateByteProvider would find t6, t7, t13, and t14 for bytes 0-3
11371 // respectively. calculateSrcByte would find (given node) -> ultimate src &
11372 // byteposition: t6 -> t15 & 1, t7 -> t16 & 0, t13 -> t15 & 0, t14 -> t15 & 3.
11373 // After finding the mapping, we can combine the tree into vperm t15, t16,
11374 // 0x05000407
11375 
11376 // Find the source and byte position from a node.
11377 // \p DestByte is the byte position of the dest of the or that the src
11378 // ultimately provides. \p SrcIndex is the byte of the src that maps to this
11379 // dest of the or byte. \p Depth tracks how many recursive iterations we have
11380 // performed.
11381 static const std::optional<ByteProvider<SDValue>>
11382 calculateSrcByte(const SDValue Op, uint64_t DestByte, uint64_t SrcIndex = 0,
11383                  unsigned Depth = 0) {
11384   // We may need to recursively traverse a series of SRLs
11385   if (Depth >= 6)
11386     return std::nullopt;
11387 
11388   auto ValueSize = Op.getValueSizeInBits();
11389   if (ValueSize != 8 && ValueSize != 16 && ValueSize != 32)
11390     return std::nullopt;
11391 
11392   switch (Op->getOpcode()) {
11393   case ISD::TRUNCATE: {
11394     return calculateSrcByte(Op->getOperand(0), DestByte, SrcIndex, Depth + 1);
11395   }
11396 
11397   case ISD::SIGN_EXTEND:
11398   case ISD::ZERO_EXTEND:
11399   case ISD::SIGN_EXTEND_INREG: {
11400     SDValue NarrowOp = Op->getOperand(0);
11401     auto NarrowVT = NarrowOp.getValueType();
11402     if (Op->getOpcode() == ISD::SIGN_EXTEND_INREG) {
11403       auto *VTSign = cast<VTSDNode>(Op->getOperand(1));
11404       NarrowVT = VTSign->getVT();
11405     }
11406     if (!NarrowVT.isByteSized())
11407       return std::nullopt;
11408     uint64_t NarrowByteWidth = NarrowVT.getStoreSize();
11409 
11410     if (SrcIndex >= NarrowByteWidth)
11411       return std::nullopt;
11412     return calculateSrcByte(Op->getOperand(0), DestByte, SrcIndex, Depth + 1);
11413   }
11414 
11415   case ISD::SRA:
11416   case ISD::SRL: {
11417     auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
11418     if (!ShiftOp)
11419       return std::nullopt;
11420 
11421     uint64_t BitShift = ShiftOp->getZExtValue();
11422 
11423     if (BitShift % 8 != 0)
11424       return std::nullopt;
11425 
11426     SrcIndex += BitShift / 8;
11427 
11428     return calculateSrcByte(Op->getOperand(0), DestByte, SrcIndex, Depth + 1);
11429   }
11430 
11431   default: {
11432     return ByteProvider<SDValue>::getSrc(Op, DestByte, SrcIndex);
11433   }
11434   }
11435   llvm_unreachable("fully handled switch");
11436 }
11437 
11438 // For a byte position in the result of an Or, traverse the tree and find the
11439 // node (and the byte of the node) which ultimately provides this {Or,
11440 // BytePosition}. \p Op is the operand we are currently examining. \p Index is
11441 // the byte position of the Op that corresponds with the originally requested
11442 // byte of the Or \p Depth tracks how many recursive iterations we have
11443 // performed. \p StartingIndex is the originally requested byte of the Or
11444 static const std::optional<ByteProvider<SDValue>>
11445 calculateByteProvider(const SDValue &Op, unsigned Index, unsigned Depth,
11446                       unsigned StartingIndex = 0) {
11447   // Finding Src tree of RHS of or typically requires at least 1 additional
11448   // depth
11449   if (Depth > 6)
11450     return std::nullopt;
11451 
11452   unsigned BitWidth = Op.getScalarValueSizeInBits();
11453   if (BitWidth % 8 != 0)
11454     return std::nullopt;
11455   if (Index > BitWidth / 8 - 1)
11456     return std::nullopt;
11457 
11458   switch (Op.getOpcode()) {
11459   case ISD::OR: {
11460     auto RHS = calculateByteProvider(Op.getOperand(1), Index, Depth + 1,
11461                                      StartingIndex);
11462     if (!RHS)
11463       return std::nullopt;
11464     auto LHS = calculateByteProvider(Op.getOperand(0), Index, Depth + 1,
11465                                      StartingIndex);
11466     if (!LHS)
11467       return std::nullopt;
11468     // A well formed Or will have two ByteProviders for each byte, one of which
11469     // is constant zero
11470     if (!LHS->isConstantZero() && !RHS->isConstantZero())
11471       return std::nullopt;
11472     if (!LHS || LHS->isConstantZero())
11473       return RHS;
11474     if (!RHS || RHS->isConstantZero())
11475       return LHS;
11476     return std::nullopt;
11477   }
11478 
11479   case ISD::AND: {
11480     auto BitMaskOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
11481     if (!BitMaskOp)
11482       return std::nullopt;
11483 
11484     uint32_t BitMask = BitMaskOp->getZExtValue();
11485     // Bits we expect for our StartingIndex
11486     uint32_t IndexMask = 0xFF << (Index * 8);
11487 
11488     if ((IndexMask & BitMask) != IndexMask) {
11489       // If the result of the and partially provides the byte, then it
11490       // is not well formatted
11491       if (IndexMask & BitMask)
11492         return std::nullopt;
11493       return ByteProvider<SDValue>::getConstantZero();
11494     }
11495 
11496     return calculateSrcByte(Op->getOperand(0), StartingIndex, Index);
11497   }
11498 
11499   case ISD::FSHR: {
11500     // fshr(X,Y,Z): (X << (BW - (Z % BW))) | (Y >> (Z % BW))
11501     auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(2));
11502     if (!ShiftOp || Op.getValueType().isVector())
11503       return std::nullopt;
11504 
11505     uint64_t BitsProvided = Op.getValueSizeInBits();
11506     if (BitsProvided % 8 != 0)
11507       return std::nullopt;
11508 
11509     uint64_t BitShift = ShiftOp->getAPIntValue().urem(BitsProvided);
11510     if (BitShift % 8)
11511       return std::nullopt;
11512 
11513     uint64_t ConcatSizeInBytes = BitsProvided / 4;
11514     uint64_t ByteShift = BitShift / 8;
11515 
11516     uint64_t NewIndex = (Index + ByteShift) % ConcatSizeInBytes;
11517     uint64_t BytesProvided = BitsProvided / 8;
11518     SDValue NextOp = Op.getOperand(NewIndex >= BytesProvided ? 0 : 1);
11519     NewIndex %= BytesProvided;
11520     return calculateByteProvider(NextOp, NewIndex, Depth + 1, StartingIndex);
11521   }
11522 
11523   case ISD::SRA:
11524   case ISD::SRL: {
11525     auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
11526     if (!ShiftOp)
11527       return std::nullopt;
11528 
11529     uint64_t BitShift = ShiftOp->getZExtValue();
11530     if (BitShift % 8)
11531       return std::nullopt;
11532 
11533     auto BitsProvided = Op.getScalarValueSizeInBits();
11534     if (BitsProvided % 8 != 0)
11535       return std::nullopt;
11536 
11537     uint64_t BytesProvided = BitsProvided / 8;
11538     uint64_t ByteShift = BitShift / 8;
11539     // The dest of shift will have good [0 : (BytesProvided - ByteShift)] bytes.
11540     // If the byte we are trying to provide (as tracked by index) falls in this
11541     // range, then the SRL provides the byte. The byte of interest of the src of
11542     // the SRL is Index + ByteShift
11543     return BytesProvided - ByteShift > Index
11544                ? calculateSrcByte(Op->getOperand(0), StartingIndex,
11545                                   Index + ByteShift)
11546                : ByteProvider<SDValue>::getConstantZero();
11547   }
11548 
11549   case ISD::SHL: {
11550     auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
11551     if (!ShiftOp)
11552       return std::nullopt;
11553 
11554     uint64_t BitShift = ShiftOp->getZExtValue();
11555     if (BitShift % 8 != 0)
11556       return std::nullopt;
11557     uint64_t ByteShift = BitShift / 8;
11558 
11559     // If we are shifting by an amount greater than (or equal to)
11560     // the index we are trying to provide, then it provides 0s. If not,
11561     // then this bytes are not definitively 0s, and the corresponding byte
11562     // of interest is Index - ByteShift of the src
11563     return Index < ByteShift
11564                ? ByteProvider<SDValue>::getConstantZero()
11565                : calculateByteProvider(Op.getOperand(0), Index - ByteShift,
11566                                        Depth + 1, StartingIndex);
11567   }
11568   case ISD::ANY_EXTEND:
11569   case ISD::SIGN_EXTEND:
11570   case ISD::ZERO_EXTEND:
11571   case ISD::SIGN_EXTEND_INREG:
11572   case ISD::AssertZext:
11573   case ISD::AssertSext: {
11574     SDValue NarrowOp = Op->getOperand(0);
11575     unsigned NarrowBitWidth = NarrowOp.getValueSizeInBits();
11576     if (Op->getOpcode() == ISD::SIGN_EXTEND_INREG ||
11577         Op->getOpcode() == ISD::AssertZext ||
11578         Op->getOpcode() == ISD::AssertSext) {
11579       auto *VTSign = cast<VTSDNode>(Op->getOperand(1));
11580       NarrowBitWidth = VTSign->getVT().getSizeInBits();
11581     }
11582     if (NarrowBitWidth % 8 != 0)
11583       return std::nullopt;
11584     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
11585 
11586     if (Index >= NarrowByteWidth)
11587       return Op.getOpcode() == ISD::ZERO_EXTEND
11588                  ? std::optional<ByteProvider<SDValue>>(
11589                        ByteProvider<SDValue>::getConstantZero())
11590                  : std::nullopt;
11591     return calculateByteProvider(NarrowOp, Index, Depth + 1, StartingIndex);
11592   }
11593 
11594   case ISD::TRUNCATE: {
11595     uint64_t NarrowByteWidth = BitWidth / 8;
11596 
11597     if (NarrowByteWidth >= Index) {
11598       return calculateByteProvider(Op.getOperand(0), Index, Depth + 1,
11599                                    StartingIndex);
11600     }
11601 
11602     return std::nullopt;
11603   }
11604 
11605   case ISD::CopyFromReg: {
11606     if (BitWidth / 8 > Index)
11607       return calculateSrcByte(Op, StartingIndex, Index);
11608 
11609     return std::nullopt;
11610   }
11611 
11612   case ISD::LOAD: {
11613     auto L = cast<LoadSDNode>(Op.getNode());
11614 
11615     unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
11616     if (NarrowBitWidth % 8 != 0)
11617       return std::nullopt;
11618     uint64_t NarrowByteWidth = NarrowBitWidth / 8;
11619 
11620     // If the width of the load does not reach byte we are trying to provide for
11621     // and it is not a ZEXTLOAD, then the load does not provide for the byte in
11622     // question
11623     if (Index >= NarrowByteWidth) {
11624       return L->getExtensionType() == ISD::ZEXTLOAD
11625                  ? std::optional<ByteProvider<SDValue>>(
11626                        ByteProvider<SDValue>::getConstantZero())
11627                  : std::nullopt;
11628     }
11629 
11630     if (NarrowByteWidth > Index) {
11631       return calculateSrcByte(Op, StartingIndex, Index);
11632     }
11633 
11634     return std::nullopt;
11635   }
11636 
11637   case ISD::BSWAP:
11638     return calculateByteProvider(Op->getOperand(0), BitWidth / 8 - Index - 1,
11639                                  Depth + 1, StartingIndex);
11640 
11641   case ISD::EXTRACT_VECTOR_ELT: {
11642     auto IdxOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
11643     if (!IdxOp)
11644       return std::nullopt;
11645     auto VecIdx = IdxOp->getZExtValue();
11646     auto ScalarSize = Op.getScalarValueSizeInBits();
11647     if (ScalarSize != 32) {
11648       if ((VecIdx + 1) * ScalarSize > 32)
11649         return std::nullopt;
11650       Index = ScalarSize == 8 ? VecIdx : VecIdx * 2 + Index;
11651     }
11652 
11653     return calculateSrcByte(ScalarSize == 32 ? Op : Op.getOperand(0),
11654                             StartingIndex, Index);
11655   }
11656 
11657   case AMDGPUISD::PERM: {
11658     auto PermMask = dyn_cast<ConstantSDNode>(Op->getOperand(2));
11659     if (!PermMask)
11660       return std::nullopt;
11661 
11662     auto IdxMask =
11663         (PermMask->getZExtValue() & (0xFF << (Index * 8))) >> (Index * 8);
11664     if (IdxMask > 0x07 && IdxMask != 0x0c)
11665       return std::nullopt;
11666 
11667     auto NextOp = Op.getOperand(IdxMask > 0x03 ? 0 : 1);
11668     auto NextIndex = IdxMask > 0x03 ? IdxMask % 4 : IdxMask;
11669 
11670     return IdxMask != 0x0c ? calculateSrcByte(NextOp, StartingIndex, NextIndex)
11671                            : ByteProvider<SDValue>(
11672                                  ByteProvider<SDValue>::getConstantZero());
11673   }
11674 
11675   default: {
11676     return std::nullopt;
11677   }
11678   }
11679 
11680   llvm_unreachable("fully handled switch");
11681 }
11682 
11683 // Returns true if the Operand is a scalar and is 16 bits
11684 static bool isExtendedFrom16Bits(SDValue &Operand) {
11685 
11686   switch (Operand.getOpcode()) {
11687   case ISD::ANY_EXTEND:
11688   case ISD::SIGN_EXTEND:
11689   case ISD::ZERO_EXTEND: {
11690     auto OpVT = Operand.getOperand(0).getValueType();
11691     return !OpVT.isVector() && OpVT.getSizeInBits() == 16;
11692   }
11693   case ISD::LOAD: {
11694     LoadSDNode *L = cast<LoadSDNode>(Operand.getNode());
11695     auto ExtType = cast<LoadSDNode>(L)->getExtensionType();
11696     if (ExtType == ISD::ZEXTLOAD || ExtType == ISD::SEXTLOAD ||
11697         ExtType == ISD::EXTLOAD) {
11698       auto MemVT = L->getMemoryVT();
11699       return !MemVT.isVector() && MemVT.getSizeInBits() == 16;
11700     }
11701     return L->getMemoryVT().getSizeInBits() == 16;
11702   }
11703   default:
11704     return false;
11705   }
11706 }
11707 
11708 // Returns true if the mask matches consecutive bytes, and the first byte
11709 // begins at a power of 2 byte offset from 0th byte
11710 static bool addresses16Bits(int Mask) {
11711   int Low8 = Mask & 0xff;
11712   int Hi8 = (Mask & 0xff00) >> 8;
11713 
11714   assert(Low8 < 8 && Hi8 < 8);
11715   // Are the bytes contiguous in the order of increasing addresses.
11716   bool IsConsecutive = (Hi8 - Low8 == 1);
11717   // Is the first byte at location that is aligned for 16 bit instructions.
11718   // A counter example is taking 2 consecutive bytes starting at the 8th bit.
11719   // In this case, we still need code to extract the 16 bit operand, so it
11720   // is better to use i8 v_perm
11721   bool Is16Aligned = !(Low8 % 2);
11722 
11723   return IsConsecutive && Is16Aligned;
11724 }
11725 
11726 // Do not lower into v_perm if the operands are actually 16 bit
11727 // and the selected bits (based on PermMask) correspond with two
11728 // easily addressable 16 bit operands.
11729 static bool hasNon16BitAccesses(uint64_t PermMask, SDValue &Op,
11730                                 SDValue &OtherOp) {
11731   int Low16 = PermMask & 0xffff;
11732   int Hi16 = (PermMask & 0xffff0000) >> 16;
11733 
11734   assert(Op.getValueType().isByteSized());
11735   assert(OtherOp.getValueType().isByteSized());
11736 
11737   auto TempOp = peekThroughBitcasts(Op);
11738   auto TempOtherOp = peekThroughBitcasts(OtherOp);
11739 
11740   auto OpIs16Bit =
11741       TempOtherOp.getValueSizeInBits() == 16 || isExtendedFrom16Bits(TempOp);
11742   if (!OpIs16Bit)
11743     return true;
11744 
11745   auto OtherOpIs16Bit = TempOtherOp.getValueSizeInBits() == 16 ||
11746                         isExtendedFrom16Bits(TempOtherOp);
11747   if (!OtherOpIs16Bit)
11748     return true;
11749 
11750   // Do we cleanly address both
11751   return !addresses16Bits(Low16) || !addresses16Bits(Hi16);
11752 }
11753 
11754 static SDValue matchPERM(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
11755   SelectionDAG &DAG = DCI.DAG;
11756   EVT VT = N->getValueType(0);
11757 
11758   if (VT != MVT::i32)
11759     return SDValue();
11760 
11761   // VT is known to be MVT::i32, so we need to provide 4 bytes.
11762   SmallVector<ByteProvider<SDValue>, 8> PermNodes;
11763   for (int i = 0; i < 4; i++) {
11764     // Find the ByteProvider that provides the ith byte of the result of OR
11765     std::optional<ByteProvider<SDValue>> P =
11766         calculateByteProvider(SDValue(N, 0), i, 0, /*StartingIndex = */ i);
11767     // TODO support constantZero
11768     if (!P || P->isConstantZero())
11769       return SDValue();
11770 
11771     PermNodes.push_back(*P);
11772   }
11773   if (PermNodes.size() != 4)
11774     return SDValue();
11775 
11776   int FirstSrc = 0;
11777   std::optional<int> SecondSrc;
11778   uint64_t PermMask = 0x00000000;
11779   for (size_t i = 0; i < PermNodes.size(); i++) {
11780     auto PermOp = PermNodes[i];
11781     // Since the mask is applied to Src1:Src2, Src1 bytes must be offset
11782     // by sizeof(Src2) = 4
11783     int SrcByteAdjust = 4;
11784 
11785     if (!PermOp.hasSameSrc(PermNodes[FirstSrc])) {
11786       if (SecondSrc.has_value())
11787         if (!PermOp.hasSameSrc(PermNodes[*SecondSrc]))
11788           return SDValue();
11789 
11790       // Set the index of the second distinct Src node
11791       SecondSrc = i;
11792       assert(!(PermNodes[*SecondSrc].Src->getValueSizeInBits() % 8));
11793       SrcByteAdjust = 0;
11794     }
11795     assert(PermOp.SrcOffset + SrcByteAdjust < 8);
11796     assert(!DAG.getDataLayout().isBigEndian());
11797     PermMask |= (PermOp.SrcOffset + SrcByteAdjust) << (i * 8);
11798   }
11799 
11800   SDValue Op = *PermNodes[FirstSrc].Src;
11801   SDValue OtherOp = SecondSrc.has_value() ? *PermNodes[*SecondSrc].Src
11802                                           : *PermNodes[FirstSrc].Src;
11803 
11804   // Check that we haven't just recreated the same FSHR node.
11805   if (N->getOpcode() == ISD::FSHR &&
11806       (N->getOperand(0) == Op || N->getOperand(0) == OtherOp) &&
11807       (N->getOperand(1) == Op || N->getOperand(1) == OtherOp))
11808     return SDValue();
11809 
11810   // Check that we are not just extracting the bytes in order from an op
11811   if (Op == OtherOp && Op.getValueSizeInBits() == 32) {
11812     int Low16 = PermMask & 0xffff;
11813     int Hi16 = (PermMask & 0xffff0000) >> 16;
11814 
11815     bool WellFormedLow = (Low16 == 0x0504) || (Low16 == 0x0100);
11816     bool WellFormedHi = (Hi16 == 0x0706) || (Hi16 == 0x0302);
11817 
11818     // The perm op would really just produce Op. So combine into Op
11819     if (WellFormedLow && WellFormedHi)
11820       return DAG.getBitcast(MVT::getIntegerVT(32), Op);
11821   }
11822 
11823   if (hasNon16BitAccesses(PermMask, Op, OtherOp)) {
11824     SDLoc DL(N);
11825     assert(Op.getValueType().isByteSized() &&
11826            OtherOp.getValueType().isByteSized());
11827 
11828     // If the ultimate src is less than 32 bits, then we will only be
11829     // using bytes 0: Op.getValueSizeInBytes() - 1 in the or.
11830     // CalculateByteProvider would not have returned Op as source if we
11831     // used a byte that is outside its ValueType. Thus, we are free to
11832     // ANY_EXTEND as the extended bits are dont-cares.
11833     Op = DAG.getBitcastedAnyExtOrTrunc(Op, DL, MVT::i32);
11834     OtherOp = DAG.getBitcastedAnyExtOrTrunc(OtherOp, DL, MVT::i32);
11835 
11836     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op, OtherOp,
11837                        DAG.getConstant(PermMask, DL, MVT::i32));
11838   }
11839 
11840   return SDValue();
11841 }
11842 
11843 SDValue SITargetLowering::performOrCombine(SDNode *N,
11844                                            DAGCombinerInfo &DCI) const {
11845   SelectionDAG &DAG = DCI.DAG;
11846   SDValue LHS = N->getOperand(0);
11847   SDValue RHS = N->getOperand(1);
11848 
11849   EVT VT = N->getValueType(0);
11850   if (VT == MVT::i1) {
11851     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
11852     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
11853         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
11854       SDValue Src = LHS.getOperand(0);
11855       if (Src != RHS.getOperand(0))
11856         return SDValue();
11857 
11858       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
11859       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
11860       if (!CLHS || !CRHS)
11861         return SDValue();
11862 
11863       // Only 10 bits are used.
11864       static const uint32_t MaxMask = 0x3ff;
11865 
11866       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
11867       SDLoc DL(N);
11868       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
11869                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
11870     }
11871 
11872     return SDValue();
11873   }
11874 
11875   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
11876   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
11877       LHS.getOpcode() == AMDGPUISD::PERM &&
11878       isa<ConstantSDNode>(LHS.getOperand(2))) {
11879     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
11880     if (!Sel)
11881       return SDValue();
11882 
11883     Sel |= LHS.getConstantOperandVal(2);
11884     SDLoc DL(N);
11885     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
11886                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
11887   }
11888 
11889   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
11890   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11891   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
11892       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
11893 
11894     // If all the uses of an or need to extract the individual elements, do not
11895     // attempt to lower into v_perm
11896     auto usesCombinedOperand = [](SDNode *OrUse) {
11897       // If we have any non-vectorized use, then it is a candidate for v_perm
11898       if (OrUse->getOpcode() != ISD::BITCAST ||
11899           !OrUse->getValueType(0).isVector())
11900         return true;
11901 
11902       // If we have any non-vectorized use, then it is a candidate for v_perm
11903       for (auto VUse : OrUse->uses()) {
11904         if (!VUse->getValueType(0).isVector())
11905           return true;
11906 
11907         // If the use of a vector is a store, then combining via a v_perm
11908         // is beneficial.
11909         // TODO -- whitelist more uses
11910         for (auto VectorwiseOp : {ISD::STORE, ISD::CopyToReg, ISD::CopyFromReg})
11911           if (VUse->getOpcode() == VectorwiseOp)
11912             return true;
11913       }
11914       return false;
11915     };
11916 
11917     if (!any_of(N->uses(), usesCombinedOperand))
11918       return SDValue();
11919 
11920     uint32_t LHSMask = getPermuteMask(LHS);
11921     uint32_t RHSMask = getPermuteMask(RHS);
11922 
11923     if (LHSMask != ~0u && RHSMask != ~0u) {
11924       // Canonicalize the expression in an attempt to have fewer unique masks
11925       // and therefore fewer registers used to hold the masks.
11926       if (LHSMask > RHSMask) {
11927         std::swap(LHSMask, RHSMask);
11928         std::swap(LHS, RHS);
11929       }
11930 
11931       // Select 0xc for each lane used from source operand. Zero has 0xc mask
11932       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
11933       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
11934       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
11935 
11936       // Check of we need to combine values from two sources within a byte.
11937       if (!(LHSUsedLanes & RHSUsedLanes) &&
11938           // If we select high and lower word keep it for SDWA.
11939           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
11940           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
11941         // Kill zero bytes selected by other mask. Zero value is 0xc.
11942         LHSMask &= ~RHSUsedLanes;
11943         RHSMask &= ~LHSUsedLanes;
11944         // Add 4 to each active LHS lane
11945         LHSMask |= LHSUsedLanes & 0x04040404;
11946         // Combine masks
11947         uint32_t Sel = LHSMask | RHSMask;
11948         SDLoc DL(N);
11949 
11950         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
11951                            LHS.getOperand(0), RHS.getOperand(0),
11952                            DAG.getConstant(Sel, DL, MVT::i32));
11953       }
11954     }
11955     if (LHSMask == ~0u || RHSMask == ~0u) {
11956       if (SDValue Perm = matchPERM(N, DCI))
11957         return Perm;
11958     }
11959   }
11960 
11961   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
11962     return SDValue();
11963 
11964   // TODO: This could be a generic combine with a predicate for extracting the
11965   // high half of an integer being free.
11966 
11967   // (or i64:x, (zero_extend i32:y)) ->
11968   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
11969   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
11970       RHS.getOpcode() != ISD::ZERO_EXTEND)
11971     std::swap(LHS, RHS);
11972 
11973   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
11974     SDValue ExtSrc = RHS.getOperand(0);
11975     EVT SrcVT = ExtSrc.getValueType();
11976     if (SrcVT == MVT::i32) {
11977       SDLoc SL(N);
11978       SDValue LowLHS, HiBits;
11979       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
11980       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
11981 
11982       DCI.AddToWorklist(LowOr.getNode());
11983       DCI.AddToWorklist(HiBits.getNode());
11984 
11985       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
11986                                 LowOr, HiBits);
11987       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
11988     }
11989   }
11990 
11991   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
11992   if (CRHS) {
11993     if (SDValue Split
11994           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR,
11995                                      N->getOperand(0), CRHS))
11996       return Split;
11997   }
11998 
11999   return SDValue();
12000 }
12001 
12002 SDValue SITargetLowering::performXorCombine(SDNode *N,
12003                                             DAGCombinerInfo &DCI) const {
12004   if (SDValue RV = reassociateScalarOps(N, DCI.DAG))
12005     return RV;
12006 
12007   SDValue LHS = N->getOperand(0);
12008   SDValue RHS = N->getOperand(1);
12009 
12010   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
12011   SelectionDAG &DAG = DCI.DAG;
12012 
12013   EVT VT = N->getValueType(0);
12014   if (CRHS && VT == MVT::i64) {
12015     if (SDValue Split
12016           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
12017       return Split;
12018   }
12019 
12020   // Make sure to apply the 64-bit constant splitting fold before trying to fold
12021   // fneg-like xors into 64-bit select.
12022   if (LHS.getOpcode() == ISD::SELECT && VT == MVT::i32) {
12023     // This looks like an fneg, try to fold as a source modifier.
12024     if (CRHS && CRHS->getAPIntValue().isSignMask() &&
12025         shouldFoldFNegIntoSrc(N, LHS)) {
12026       // xor (select c, a, b), 0x80000000 ->
12027       //   bitcast (select c, (fneg (bitcast a)), (fneg (bitcast b)))
12028       SDLoc DL(N);
12029       SDValue CastLHS =
12030           DAG.getNode(ISD::BITCAST, DL, MVT::f32, LHS->getOperand(1));
12031       SDValue CastRHS =
12032           DAG.getNode(ISD::BITCAST, DL, MVT::f32, LHS->getOperand(2));
12033       SDValue FNegLHS = DAG.getNode(ISD::FNEG, DL, MVT::f32, CastLHS);
12034       SDValue FNegRHS = DAG.getNode(ISD::FNEG, DL, MVT::f32, CastRHS);
12035       SDValue NewSelect = DAG.getNode(ISD::SELECT, DL, MVT::f32,
12036                                       LHS->getOperand(0), FNegLHS, FNegRHS);
12037       return DAG.getNode(ISD::BITCAST, DL, VT, NewSelect);
12038     }
12039   }
12040 
12041   return SDValue();
12042 }
12043 
12044 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
12045                                                    DAGCombinerInfo &DCI) const {
12046   if (!Subtarget->has16BitInsts() ||
12047       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
12048     return SDValue();
12049 
12050   EVT VT = N->getValueType(0);
12051   if (VT != MVT::i32)
12052     return SDValue();
12053 
12054   SDValue Src = N->getOperand(0);
12055   if (Src.getValueType() != MVT::i16)
12056     return SDValue();
12057 
12058   return SDValue();
12059 }
12060 
12061 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
12062                                                         DAGCombinerInfo &DCI)
12063                                                         const {
12064   SDValue Src = N->getOperand(0);
12065   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
12066 
12067   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
12068       VTSign->getVT() == MVT::i8) ||
12069       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
12070       VTSign->getVT() == MVT::i16)) &&
12071       Src.hasOneUse()) {
12072     auto *M = cast<MemSDNode>(Src);
12073     SDValue Ops[] = {
12074       Src.getOperand(0), // Chain
12075       Src.getOperand(1), // rsrc
12076       Src.getOperand(2), // vindex
12077       Src.getOperand(3), // voffset
12078       Src.getOperand(4), // soffset
12079       Src.getOperand(5), // offset
12080       Src.getOperand(6),
12081       Src.getOperand(7)
12082     };
12083     // replace with BUFFER_LOAD_BYTE/SHORT
12084     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
12085                                          Src.getOperand(0).getValueType());
12086     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
12087                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
12088     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
12089                                                           ResList,
12090                                                           Ops, M->getMemoryVT(),
12091                                                           M->getMemOperand());
12092     return DCI.DAG.getMergeValues({BufferLoadSignExt,
12093                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
12094   }
12095   return SDValue();
12096 }
12097 
12098 SDValue SITargetLowering::performClassCombine(SDNode *N,
12099                                               DAGCombinerInfo &DCI) const {
12100   SelectionDAG &DAG = DCI.DAG;
12101   SDValue Mask = N->getOperand(1);
12102 
12103   // fp_class x, 0 -> false
12104   if (isNullConstant(Mask))
12105     return DAG.getConstant(0, SDLoc(N), MVT::i1);
12106 
12107   if (N->getOperand(0).isUndef())
12108     return DAG.getUNDEF(MVT::i1);
12109 
12110   return SDValue();
12111 }
12112 
12113 SDValue SITargetLowering::performRcpCombine(SDNode *N,
12114                                             DAGCombinerInfo &DCI) const {
12115   EVT VT = N->getValueType(0);
12116   SDValue N0 = N->getOperand(0);
12117 
12118   if (N0.isUndef()) {
12119     return DCI.DAG.getConstantFP(
12120         APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)), SDLoc(N),
12121         VT);
12122   }
12123 
12124   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
12125                          N0.getOpcode() == ISD::SINT_TO_FP)) {
12126     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
12127                            N->getFlags());
12128   }
12129 
12130   // TODO: Could handle f32 + amdgcn.sqrt but probably never reaches here.
12131   if ((VT == MVT::f16 && N0.getOpcode() == ISD::FSQRT) &&
12132       N->getFlags().hasAllowContract() && N0->getFlags().hasAllowContract()) {
12133     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
12134                            N0.getOperand(0), N->getFlags());
12135   }
12136 
12137   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
12138 }
12139 
12140 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
12141                                        unsigned MaxDepth) const {
12142   unsigned Opcode = Op.getOpcode();
12143   if (Opcode == ISD::FCANONICALIZE)
12144     return true;
12145 
12146   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
12147     const auto &F = CFP->getValueAPF();
12148     if (F.isNaN() && F.isSignaling())
12149       return false;
12150     if (!F.isDenormal())
12151       return true;
12152 
12153     DenormalMode Mode =
12154         DAG.getMachineFunction().getDenormalMode(F.getSemantics());
12155     return Mode == DenormalMode::getIEEE();
12156   }
12157 
12158   // If source is a result of another standard FP operation it is already in
12159   // canonical form.
12160   if (MaxDepth == 0)
12161     return false;
12162 
12163   switch (Opcode) {
12164   // These will flush denorms if required.
12165   case ISD::FADD:
12166   case ISD::FSUB:
12167   case ISD::FMUL:
12168   case ISD::FCEIL:
12169   case ISD::FFLOOR:
12170   case ISD::FMA:
12171   case ISD::FMAD:
12172   case ISD::FSQRT:
12173   case ISD::FDIV:
12174   case ISD::FREM:
12175   case ISD::FP_ROUND:
12176   case ISD::FP_EXTEND:
12177   case ISD::FLDEXP:
12178   case AMDGPUISD::FMUL_LEGACY:
12179   case AMDGPUISD::FMAD_FTZ:
12180   case AMDGPUISD::RCP:
12181   case AMDGPUISD::RSQ:
12182   case AMDGPUISD::RSQ_CLAMP:
12183   case AMDGPUISD::RCP_LEGACY:
12184   case AMDGPUISD::RCP_IFLAG:
12185   case AMDGPUISD::LOG:
12186   case AMDGPUISD::EXP:
12187   case AMDGPUISD::DIV_SCALE:
12188   case AMDGPUISD::DIV_FMAS:
12189   case AMDGPUISD::DIV_FIXUP:
12190   case AMDGPUISD::FRACT:
12191   case AMDGPUISD::CVT_PKRTZ_F16_F32:
12192   case AMDGPUISD::CVT_F32_UBYTE0:
12193   case AMDGPUISD::CVT_F32_UBYTE1:
12194   case AMDGPUISD::CVT_F32_UBYTE2:
12195   case AMDGPUISD::CVT_F32_UBYTE3:
12196     return true;
12197 
12198   // It can/will be lowered or combined as a bit operation.
12199   // Need to check their input recursively to handle.
12200   case ISD::FNEG:
12201   case ISD::FABS:
12202   case ISD::FCOPYSIGN:
12203     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
12204 
12205   case ISD::FSIN:
12206   case ISD::FCOS:
12207   case ISD::FSINCOS:
12208     return Op.getValueType().getScalarType() != MVT::f16;
12209 
12210   case ISD::FMINNUM:
12211   case ISD::FMAXNUM:
12212   case ISD::FMINNUM_IEEE:
12213   case ISD::FMAXNUM_IEEE:
12214   case ISD::FMINIMUM:
12215   case ISD::FMAXIMUM:
12216   case AMDGPUISD::CLAMP:
12217   case AMDGPUISD::FMED3:
12218   case AMDGPUISD::FMAX3:
12219   case AMDGPUISD::FMIN3:
12220   case AMDGPUISD::FMAXIMUM3:
12221   case AMDGPUISD::FMINIMUM3: {
12222     // FIXME: Shouldn't treat the generic operations different based these.
12223     // However, we aren't really required to flush the result from
12224     // minnum/maxnum..
12225 
12226     // snans will be quieted, so we only need to worry about denormals.
12227     if (Subtarget->supportsMinMaxDenormModes() ||
12228         // FIXME: denormalsEnabledForType is broken for dynamic
12229         denormalsEnabledForType(DAG, Op.getValueType()))
12230       return true;
12231 
12232     // Flushing may be required.
12233     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
12234     // targets need to check their input recursively.
12235 
12236     // FIXME: Does this apply with clamp? It's implemented with max.
12237     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
12238       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
12239         return false;
12240     }
12241 
12242     return true;
12243   }
12244   case ISD::SELECT: {
12245     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
12246            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
12247   }
12248   case ISD::BUILD_VECTOR: {
12249     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
12250       SDValue SrcOp = Op.getOperand(i);
12251       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
12252         return false;
12253     }
12254 
12255     return true;
12256   }
12257   case ISD::EXTRACT_VECTOR_ELT:
12258   case ISD::EXTRACT_SUBVECTOR: {
12259     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
12260   }
12261   case ISD::INSERT_VECTOR_ELT: {
12262     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
12263            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
12264   }
12265   case ISD::UNDEF:
12266     // Could be anything.
12267     return false;
12268 
12269   case ISD::BITCAST:
12270     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
12271   case ISD::TRUNCATE: {
12272     // Hack round the mess we make when legalizing extract_vector_elt
12273     if (Op.getValueType() == MVT::i16) {
12274       SDValue TruncSrc = Op.getOperand(0);
12275       if (TruncSrc.getValueType() == MVT::i32 &&
12276           TruncSrc.getOpcode() == ISD::BITCAST &&
12277           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
12278         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
12279       }
12280     }
12281     return false;
12282   }
12283   case ISD::INTRINSIC_WO_CHAIN: {
12284     unsigned IntrinsicID = Op.getConstantOperandVal(0);
12285     // TODO: Handle more intrinsics
12286     switch (IntrinsicID) {
12287     case Intrinsic::amdgcn_cvt_pkrtz:
12288     case Intrinsic::amdgcn_cubeid:
12289     case Intrinsic::amdgcn_frexp_mant:
12290     case Intrinsic::amdgcn_fdot2:
12291     case Intrinsic::amdgcn_rcp:
12292     case Intrinsic::amdgcn_rsq:
12293     case Intrinsic::amdgcn_rsq_clamp:
12294     case Intrinsic::amdgcn_rcp_legacy:
12295     case Intrinsic::amdgcn_rsq_legacy:
12296     case Intrinsic::amdgcn_trig_preop:
12297     case Intrinsic::amdgcn_log:
12298     case Intrinsic::amdgcn_exp2:
12299       return true;
12300     default:
12301       break;
12302     }
12303 
12304     [[fallthrough]];
12305   }
12306   default:
12307     // FIXME: denormalsEnabledForType is broken for dynamic
12308     return denormalsEnabledForType(DAG, Op.getValueType()) &&
12309            DAG.isKnownNeverSNaN(Op);
12310   }
12311 
12312   llvm_unreachable("invalid operation");
12313 }
12314 
12315 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
12316                                        unsigned MaxDepth) const {
12317   MachineRegisterInfo &MRI = MF.getRegInfo();
12318   MachineInstr *MI = MRI.getVRegDef(Reg);
12319   unsigned Opcode = MI->getOpcode();
12320 
12321   if (Opcode == AMDGPU::G_FCANONICALIZE)
12322     return true;
12323 
12324   std::optional<FPValueAndVReg> FCR;
12325   // Constant splat (can be padded with undef) or scalar constant.
12326   if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) {
12327     if (FCR->Value.isSignaling())
12328       return false;
12329     if (!FCR->Value.isDenormal())
12330       return true;
12331 
12332     DenormalMode Mode = MF.getDenormalMode(FCR->Value.getSemantics());
12333     return Mode == DenormalMode::getIEEE();
12334   }
12335 
12336   if (MaxDepth == 0)
12337     return false;
12338 
12339   switch (Opcode) {
12340   case AMDGPU::G_FADD:
12341   case AMDGPU::G_FSUB:
12342   case AMDGPU::G_FMUL:
12343   case AMDGPU::G_FCEIL:
12344   case AMDGPU::G_FFLOOR:
12345   case AMDGPU::G_FRINT:
12346   case AMDGPU::G_FNEARBYINT:
12347   case AMDGPU::G_INTRINSIC_FPTRUNC_ROUND:
12348   case AMDGPU::G_INTRINSIC_TRUNC:
12349   case AMDGPU::G_INTRINSIC_ROUNDEVEN:
12350   case AMDGPU::G_FMA:
12351   case AMDGPU::G_FMAD:
12352   case AMDGPU::G_FSQRT:
12353   case AMDGPU::G_FDIV:
12354   case AMDGPU::G_FREM:
12355   case AMDGPU::G_FPOW:
12356   case AMDGPU::G_FPEXT:
12357   case AMDGPU::G_FLOG:
12358   case AMDGPU::G_FLOG2:
12359   case AMDGPU::G_FLOG10:
12360   case AMDGPU::G_FPTRUNC:
12361   case AMDGPU::G_AMDGPU_RCP_IFLAG:
12362   case AMDGPU::G_AMDGPU_CVT_F32_UBYTE0:
12363   case AMDGPU::G_AMDGPU_CVT_F32_UBYTE1:
12364   case AMDGPU::G_AMDGPU_CVT_F32_UBYTE2:
12365   case AMDGPU::G_AMDGPU_CVT_F32_UBYTE3:
12366     return true;
12367   case AMDGPU::G_FNEG:
12368   case AMDGPU::G_FABS:
12369   case AMDGPU::G_FCOPYSIGN:
12370     return isCanonicalized(MI->getOperand(1).getReg(), MF, MaxDepth - 1);
12371   case AMDGPU::G_FMINNUM:
12372   case AMDGPU::G_FMAXNUM:
12373   case AMDGPU::G_FMINNUM_IEEE:
12374   case AMDGPU::G_FMAXNUM_IEEE:
12375   case AMDGPU::G_FMINIMUM:
12376   case AMDGPU::G_FMAXIMUM: {
12377     if (Subtarget->supportsMinMaxDenormModes() ||
12378         // FIXME: denormalsEnabledForType is broken for dynamic
12379         denormalsEnabledForType(MRI.getType(Reg), MF))
12380       return true;
12381 
12382     [[fallthrough]];
12383   }
12384   case AMDGPU::G_BUILD_VECTOR:
12385     for (const MachineOperand &MO : llvm::drop_begin(MI->operands()))
12386       if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1))
12387         return false;
12388     return true;
12389   case AMDGPU::G_INTRINSIC:
12390   case AMDGPU::G_INTRINSIC_CONVERGENT:
12391     switch (cast<GIntrinsic>(MI)->getIntrinsicID()) {
12392     case Intrinsic::amdgcn_fmul_legacy:
12393     case Intrinsic::amdgcn_fmad_ftz:
12394     case Intrinsic::amdgcn_sqrt:
12395     case Intrinsic::amdgcn_fmed3:
12396     case Intrinsic::amdgcn_sin:
12397     case Intrinsic::amdgcn_cos:
12398     case Intrinsic::amdgcn_log:
12399     case Intrinsic::amdgcn_exp2:
12400     case Intrinsic::amdgcn_log_clamp:
12401     case Intrinsic::amdgcn_rcp:
12402     case Intrinsic::amdgcn_rcp_legacy:
12403     case Intrinsic::amdgcn_rsq:
12404     case Intrinsic::amdgcn_rsq_clamp:
12405     case Intrinsic::amdgcn_rsq_legacy:
12406     case Intrinsic::amdgcn_div_scale:
12407     case Intrinsic::amdgcn_div_fmas:
12408     case Intrinsic::amdgcn_div_fixup:
12409     case Intrinsic::amdgcn_fract:
12410     case Intrinsic::amdgcn_cvt_pkrtz:
12411     case Intrinsic::amdgcn_cubeid:
12412     case Intrinsic::amdgcn_cubema:
12413     case Intrinsic::amdgcn_cubesc:
12414     case Intrinsic::amdgcn_cubetc:
12415     case Intrinsic::amdgcn_frexp_mant:
12416     case Intrinsic::amdgcn_fdot2:
12417     case Intrinsic::amdgcn_trig_preop:
12418       return true;
12419     default:
12420       break;
12421     }
12422 
12423     [[fallthrough]];
12424   default:
12425     return false;
12426   }
12427 
12428   llvm_unreachable("invalid operation");
12429 }
12430 
12431 // Constant fold canonicalize.
12432 SDValue SITargetLowering::getCanonicalConstantFP(
12433   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
12434   // Flush denormals to 0 if not enabled.
12435   if (C.isDenormal()) {
12436     DenormalMode Mode =
12437         DAG.getMachineFunction().getDenormalMode(C.getSemantics());
12438     if (Mode == DenormalMode::getPreserveSign()) {
12439       return DAG.getConstantFP(
12440           APFloat::getZero(C.getSemantics(), C.isNegative()), SL, VT);
12441     }
12442 
12443     if (Mode != DenormalMode::getIEEE())
12444       return SDValue();
12445   }
12446 
12447   if (C.isNaN()) {
12448     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
12449     if (C.isSignaling()) {
12450       // Quiet a signaling NaN.
12451       // FIXME: Is this supposed to preserve payload bits?
12452       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
12453     }
12454 
12455     // Make sure it is the canonical NaN bitpattern.
12456     //
12457     // TODO: Can we use -1 as the canonical NaN value since it's an inline
12458     // immediate?
12459     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
12460       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
12461   }
12462 
12463   // Already canonical.
12464   return DAG.getConstantFP(C, SL, VT);
12465 }
12466 
12467 static bool vectorEltWillFoldAway(SDValue Op) {
12468   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
12469 }
12470 
12471 SDValue SITargetLowering::performFCanonicalizeCombine(
12472   SDNode *N,
12473   DAGCombinerInfo &DCI) const {
12474   SelectionDAG &DAG = DCI.DAG;
12475   SDValue N0 = N->getOperand(0);
12476   EVT VT = N->getValueType(0);
12477 
12478   // fcanonicalize undef -> qnan
12479   if (N0.isUndef()) {
12480     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
12481     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
12482   }
12483 
12484   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
12485     EVT VT = N->getValueType(0);
12486     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
12487   }
12488 
12489   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
12490   //                                                   (fcanonicalize k)
12491   //
12492   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
12493 
12494   // TODO: This could be better with wider vectors that will be split to v2f16,
12495   // and to consider uses since there aren't that many packed operations.
12496   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
12497       isTypeLegal(MVT::v2f16)) {
12498     SDLoc SL(N);
12499     SDValue NewElts[2];
12500     SDValue Lo = N0.getOperand(0);
12501     SDValue Hi = N0.getOperand(1);
12502     EVT EltVT = Lo.getValueType();
12503 
12504     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
12505       for (unsigned I = 0; I != 2; ++I) {
12506         SDValue Op = N0.getOperand(I);
12507         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
12508           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
12509                                               CFP->getValueAPF());
12510         } else if (Op.isUndef()) {
12511           // Handled below based on what the other operand is.
12512           NewElts[I] = Op;
12513         } else {
12514           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
12515         }
12516       }
12517 
12518       // If one half is undef, and one is constant, prefer a splat vector rather
12519       // than the normal qNaN. If it's a register, prefer 0.0 since that's
12520       // cheaper to use and may be free with a packed operation.
12521       if (NewElts[0].isUndef()) {
12522         if (isa<ConstantFPSDNode>(NewElts[1]))
12523           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
12524             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
12525       }
12526 
12527       if (NewElts[1].isUndef()) {
12528         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
12529           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
12530       }
12531 
12532       return DAG.getBuildVector(VT, SL, NewElts);
12533     }
12534   }
12535 
12536   unsigned SrcOpc = N0.getOpcode();
12537 
12538   // If it's free to do so, push canonicalizes further up the source, which may
12539   // find a canonical source.
12540   //
12541   // TODO: More opcodes. Note this is unsafe for the _ieee minnum/maxnum for
12542   // sNaNs.
12543   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
12544     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
12545     if (CRHS && N0.hasOneUse()) {
12546       SDLoc SL(N);
12547       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
12548                                    N0.getOperand(0));
12549       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
12550       DCI.AddToWorklist(Canon0.getNode());
12551 
12552       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
12553     }
12554   }
12555 
12556   return isCanonicalized(DAG, N0) ? N0 : SDValue();
12557 }
12558 
12559 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
12560   switch (Opc) {
12561   case ISD::FMAXNUM:
12562   case ISD::FMAXNUM_IEEE:
12563     return AMDGPUISD::FMAX3;
12564   case ISD::FMAXIMUM:
12565     return AMDGPUISD::FMAXIMUM3;
12566   case ISD::SMAX:
12567     return AMDGPUISD::SMAX3;
12568   case ISD::UMAX:
12569     return AMDGPUISD::UMAX3;
12570   case ISD::FMINNUM:
12571   case ISD::FMINNUM_IEEE:
12572     return AMDGPUISD::FMIN3;
12573   case ISD::FMINIMUM:
12574     return AMDGPUISD::FMINIMUM3;
12575   case ISD::SMIN:
12576     return AMDGPUISD::SMIN3;
12577   case ISD::UMIN:
12578     return AMDGPUISD::UMIN3;
12579   default:
12580     llvm_unreachable("Not a min/max opcode");
12581   }
12582 }
12583 
12584 SDValue SITargetLowering::performIntMed3ImmCombine(SelectionDAG &DAG,
12585                                                    const SDLoc &SL, SDValue Src,
12586                                                    SDValue MinVal,
12587                                                    SDValue MaxVal,
12588                                                    bool Signed) const {
12589 
12590   // med3 comes from
12591   //    min(max(x, K0), K1), K0 < K1
12592   //    max(min(x, K0), K1), K1 < K0
12593   //
12594   // "MinVal" and "MaxVal" respectively refer to the rhs of the
12595   // min/max op.
12596   ConstantSDNode *MinK = dyn_cast<ConstantSDNode>(MinVal);
12597   ConstantSDNode *MaxK = dyn_cast<ConstantSDNode>(MaxVal);
12598 
12599   if (!MinK || !MaxK)
12600     return SDValue();
12601 
12602   if (Signed) {
12603     if (MaxK->getAPIntValue().sge(MinK->getAPIntValue()))
12604       return SDValue();
12605   } else {
12606     if (MaxK->getAPIntValue().uge(MinK->getAPIntValue()))
12607       return SDValue();
12608   }
12609 
12610   EVT VT = MinK->getValueType(0);
12611   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
12612   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16()))
12613     return DAG.getNode(Med3Opc, SL, VT, Src, MaxVal, MinVal);
12614 
12615   // Note: we could also extend to i32 and use i32 med3 if i16 med3 is
12616   // not available, but this is unlikely to be profitable as constants
12617   // will often need to be materialized & extended, especially on
12618   // pre-GFX10 where VOP3 instructions couldn't take literal operands.
12619   return SDValue();
12620 }
12621 
12622 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
12623   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
12624     return C;
12625 
12626   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
12627     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
12628       return C;
12629   }
12630 
12631   return nullptr;
12632 }
12633 
12634 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
12635                                                   const SDLoc &SL,
12636                                                   SDValue Op0,
12637                                                   SDValue Op1) const {
12638   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
12639   if (!K1)
12640     return SDValue();
12641 
12642   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
12643   if (!K0)
12644     return SDValue();
12645 
12646   // Ordered >= (although NaN inputs should have folded away by now).
12647   if (K0->getValueAPF() > K1->getValueAPF())
12648     return SDValue();
12649 
12650   const MachineFunction &MF = DAG.getMachineFunction();
12651   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12652 
12653   // TODO: Check IEEE bit enabled?
12654   EVT VT = Op0.getValueType();
12655   if (Info->getMode().DX10Clamp) {
12656     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
12657     // hardware fmed3 behavior converting to a min.
12658     // FIXME: Should this be allowing -0.0?
12659     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
12660       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
12661   }
12662 
12663   // med3 for f16 is only available on gfx9+, and not available for v2f16.
12664   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
12665     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
12666     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
12667     // then give the other result, which is different from med3 with a NaN
12668     // input.
12669     SDValue Var = Op0.getOperand(0);
12670     if (!DAG.isKnownNeverSNaN(Var))
12671       return SDValue();
12672 
12673     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12674 
12675     if ((!K0->hasOneUse() ||
12676          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
12677         (!K1->hasOneUse() ||
12678          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
12679       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
12680                          Var, SDValue(K0, 0), SDValue(K1, 0));
12681     }
12682   }
12683 
12684   return SDValue();
12685 }
12686 
12687 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
12688                                                DAGCombinerInfo &DCI) const {
12689   SelectionDAG &DAG = DCI.DAG;
12690 
12691   EVT VT = N->getValueType(0);
12692   unsigned Opc = N->getOpcode();
12693   SDValue Op0 = N->getOperand(0);
12694   SDValue Op1 = N->getOperand(1);
12695 
12696   // Only do this if the inner op has one use since this will just increases
12697   // register pressure for no benefit.
12698 
12699   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
12700       !VT.isVector() &&
12701       (VT == MVT::i32 || VT == MVT::f32 ||
12702        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
12703     // max(max(a, b), c) -> max3(a, b, c)
12704     // min(min(a, b), c) -> min3(a, b, c)
12705     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
12706       SDLoc DL(N);
12707       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
12708                          DL,
12709                          N->getValueType(0),
12710                          Op0.getOperand(0),
12711                          Op0.getOperand(1),
12712                          Op1);
12713     }
12714 
12715     // Try commuted.
12716     // max(a, max(b, c)) -> max3(a, b, c)
12717     // min(a, min(b, c)) -> min3(a, b, c)
12718     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
12719       SDLoc DL(N);
12720       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
12721                          DL,
12722                          N->getValueType(0),
12723                          Op0,
12724                          Op1.getOperand(0),
12725                          Op1.getOperand(1));
12726     }
12727   }
12728 
12729   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
12730   // max(min(x, K0), K1), K1 < K0 -> med3(x, K1, K0)
12731   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
12732     if (SDValue Med3 = performIntMed3ImmCombine(
12733             DAG, SDLoc(N), Op0->getOperand(0), Op1, Op0->getOperand(1), true))
12734       return Med3;
12735   }
12736   if (Opc == ISD::SMAX && Op0.getOpcode() == ISD::SMIN && Op0.hasOneUse()) {
12737     if (SDValue Med3 = performIntMed3ImmCombine(
12738             DAG, SDLoc(N), Op0->getOperand(0), Op0->getOperand(1), Op1, true))
12739       return Med3;
12740   }
12741 
12742   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
12743     if (SDValue Med3 = performIntMed3ImmCombine(
12744             DAG, SDLoc(N), Op0->getOperand(0), Op1, Op0->getOperand(1), false))
12745       return Med3;
12746   }
12747   if (Opc == ISD::UMAX && Op0.getOpcode() == ISD::UMIN && Op0.hasOneUse()) {
12748     if (SDValue Med3 = performIntMed3ImmCombine(
12749             DAG, SDLoc(N), Op0->getOperand(0), Op0->getOperand(1), Op1, false))
12750       return Med3;
12751   }
12752 
12753   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
12754   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
12755        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
12756        (Opc == AMDGPUISD::FMIN_LEGACY &&
12757         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
12758       (VT == MVT::f32 || VT == MVT::f64 ||
12759        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
12760        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
12761       Op0.hasOneUse()) {
12762     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
12763       return Res;
12764   }
12765 
12766   return SDValue();
12767 }
12768 
12769 static bool isClampZeroToOne(SDValue A, SDValue B) {
12770   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
12771     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
12772       // FIXME: Should this be allowing -0.0?
12773       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
12774              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
12775     }
12776   }
12777 
12778   return false;
12779 }
12780 
12781 // FIXME: Should only worry about snans for version with chain.
12782 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
12783                                               DAGCombinerInfo &DCI) const {
12784   EVT VT = N->getValueType(0);
12785   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
12786   // NaNs. With a NaN input, the order of the operands may change the result.
12787 
12788   SelectionDAG &DAG = DCI.DAG;
12789   SDLoc SL(N);
12790 
12791   SDValue Src0 = N->getOperand(0);
12792   SDValue Src1 = N->getOperand(1);
12793   SDValue Src2 = N->getOperand(2);
12794 
12795   if (isClampZeroToOne(Src0, Src1)) {
12796     // const_a, const_b, x -> clamp is safe in all cases including signaling
12797     // nans.
12798     // FIXME: Should this be allowing -0.0?
12799     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
12800   }
12801 
12802   const MachineFunction &MF = DAG.getMachineFunction();
12803   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12804 
12805   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
12806   // handling no dx10-clamp?
12807   if (Info->getMode().DX10Clamp) {
12808     // If NaNs is clamped to 0, we are free to reorder the inputs.
12809 
12810     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
12811       std::swap(Src0, Src1);
12812 
12813     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
12814       std::swap(Src1, Src2);
12815 
12816     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
12817       std::swap(Src0, Src1);
12818 
12819     if (isClampZeroToOne(Src1, Src2))
12820       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
12821   }
12822 
12823   return SDValue();
12824 }
12825 
12826 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
12827                                                  DAGCombinerInfo &DCI) const {
12828   SDValue Src0 = N->getOperand(0);
12829   SDValue Src1 = N->getOperand(1);
12830   if (Src0.isUndef() && Src1.isUndef())
12831     return DCI.DAG.getUNDEF(N->getValueType(0));
12832   return SDValue();
12833 }
12834 
12835 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
12836 // expanded into a set of cmp/select instructions.
12837 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
12838                                                 unsigned NumElem,
12839                                                 bool IsDivergentIdx,
12840                                                 const GCNSubtarget *Subtarget) {
12841   if (UseDivergentRegisterIndexing)
12842     return false;
12843 
12844   unsigned VecSize = EltSize * NumElem;
12845 
12846   // Sub-dword vectors of size 2 dword or less have better implementation.
12847   if (VecSize <= 64 && EltSize < 32)
12848     return false;
12849 
12850   // Always expand the rest of sub-dword instructions, otherwise it will be
12851   // lowered via memory.
12852   if (EltSize < 32)
12853     return true;
12854 
12855   // Always do this if var-idx is divergent, otherwise it will become a loop.
12856   if (IsDivergentIdx)
12857     return true;
12858 
12859   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
12860   unsigned NumInsts = NumElem /* Number of compares */ +
12861                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
12862 
12863   // On some architectures (GFX9) movrel is not available and it's better
12864   // to expand.
12865   if (!Subtarget->hasMovrel())
12866     return NumInsts <= 16;
12867 
12868   // If movrel is available, use it instead of expanding for vector of 8
12869   // elements.
12870   return NumInsts <= 15;
12871 }
12872 
12873 bool SITargetLowering::shouldExpandVectorDynExt(SDNode *N) const {
12874   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
12875   if (isa<ConstantSDNode>(Idx))
12876     return false;
12877 
12878   SDValue Vec = N->getOperand(0);
12879   EVT VecVT = Vec.getValueType();
12880   EVT EltVT = VecVT.getVectorElementType();
12881   unsigned EltSize = EltVT.getSizeInBits();
12882   unsigned NumElem = VecVT.getVectorNumElements();
12883 
12884   return SITargetLowering::shouldExpandVectorDynExt(
12885       EltSize, NumElem, Idx->isDivergent(), getSubtarget());
12886 }
12887 
12888 SDValue SITargetLowering::performExtractVectorEltCombine(
12889   SDNode *N, DAGCombinerInfo &DCI) const {
12890   SDValue Vec = N->getOperand(0);
12891   SelectionDAG &DAG = DCI.DAG;
12892 
12893   EVT VecVT = Vec.getValueType();
12894   EVT VecEltVT = VecVT.getVectorElementType();
12895   EVT ResVT = N->getValueType(0);
12896 
12897   unsigned VecSize = VecVT.getSizeInBits();
12898   unsigned VecEltSize = VecEltVT.getSizeInBits();
12899 
12900   if ((Vec.getOpcode() == ISD::FNEG ||
12901        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
12902     SDLoc SL(N);
12903     SDValue Idx = N->getOperand(1);
12904     SDValue Elt =
12905         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, ResVT, Vec.getOperand(0), Idx);
12906     return DAG.getNode(Vec.getOpcode(), SL, ResVT, Elt);
12907   }
12908 
12909   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
12910   //    =>
12911   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
12912   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
12913   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
12914   if (Vec.hasOneUse() && DCI.isBeforeLegalize() && VecEltVT == ResVT) {
12915     SDLoc SL(N);
12916     SDValue Idx = N->getOperand(1);
12917     unsigned Opc = Vec.getOpcode();
12918 
12919     switch(Opc) {
12920     default:
12921       break;
12922       // TODO: Support other binary operations.
12923     case ISD::FADD:
12924     case ISD::FSUB:
12925     case ISD::FMUL:
12926     case ISD::ADD:
12927     case ISD::UMIN:
12928     case ISD::UMAX:
12929     case ISD::SMIN:
12930     case ISD::SMAX:
12931     case ISD::FMAXNUM:
12932     case ISD::FMINNUM:
12933     case ISD::FMAXNUM_IEEE:
12934     case ISD::FMINNUM_IEEE:
12935     case ISD::FMAXIMUM:
12936     case ISD::FMINIMUM: {
12937       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, ResVT,
12938                                  Vec.getOperand(0), Idx);
12939       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, ResVT,
12940                                  Vec.getOperand(1), Idx);
12941 
12942       DCI.AddToWorklist(Elt0.getNode());
12943       DCI.AddToWorklist(Elt1.getNode());
12944       return DAG.getNode(Opc, SL, ResVT, Elt0, Elt1, Vec->getFlags());
12945     }
12946     }
12947   }
12948 
12949   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
12950   if (shouldExpandVectorDynExt(N)) {
12951     SDLoc SL(N);
12952     SDValue Idx = N->getOperand(1);
12953     SDValue V;
12954     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
12955       SDValue IC = DAG.getVectorIdxConstant(I, SL);
12956       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, ResVT, Vec, IC);
12957       if (I == 0)
12958         V = Elt;
12959       else
12960         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
12961     }
12962     return V;
12963   }
12964 
12965   if (!DCI.isBeforeLegalize())
12966     return SDValue();
12967 
12968   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
12969   // elements. This exposes more load reduction opportunities by replacing
12970   // multiple small extract_vector_elements with a single 32-bit extract.
12971   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12972   if (isa<MemSDNode>(Vec) && VecEltSize <= 16 && VecEltVT.isByteSized() &&
12973       VecSize > 32 && VecSize % 32 == 0 && Idx) {
12974     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
12975 
12976     unsigned BitIndex = Idx->getZExtValue() * VecEltSize;
12977     unsigned EltIdx = BitIndex / 32;
12978     unsigned LeftoverBitIdx = BitIndex % 32;
12979     SDLoc SL(N);
12980 
12981     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
12982     DCI.AddToWorklist(Cast.getNode());
12983 
12984     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
12985                               DAG.getConstant(EltIdx, SL, MVT::i32));
12986     DCI.AddToWorklist(Elt.getNode());
12987     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
12988                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
12989     DCI.AddToWorklist(Srl.getNode());
12990 
12991     EVT VecEltAsIntVT = VecEltVT.changeTypeToInteger();
12992     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VecEltAsIntVT, Srl);
12993     DCI.AddToWorklist(Trunc.getNode());
12994 
12995     if (VecEltVT == ResVT) {
12996       return DAG.getNode(ISD::BITCAST, SL, VecEltVT, Trunc);
12997     }
12998 
12999     assert(ResVT.isScalarInteger());
13000     return DAG.getAnyExtOrTrunc(Trunc, SL, ResVT);
13001   }
13002 
13003   return SDValue();
13004 }
13005 
13006 SDValue
13007 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
13008                                                 DAGCombinerInfo &DCI) const {
13009   SDValue Vec = N->getOperand(0);
13010   SDValue Idx = N->getOperand(2);
13011   EVT VecVT = Vec.getValueType();
13012   EVT EltVT = VecVT.getVectorElementType();
13013 
13014   // INSERT_VECTOR_ELT (<n x e>, var-idx)
13015   // => BUILD_VECTOR n x select (e, const-idx)
13016   if (!shouldExpandVectorDynExt(N))
13017     return SDValue();
13018 
13019   SelectionDAG &DAG = DCI.DAG;
13020   SDLoc SL(N);
13021   SDValue Ins = N->getOperand(1);
13022   EVT IdxVT = Idx.getValueType();
13023 
13024   SmallVector<SDValue, 16> Ops;
13025   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
13026     SDValue IC = DAG.getConstant(I, SL, IdxVT);
13027     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
13028     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
13029     Ops.push_back(V);
13030   }
13031 
13032   return DAG.getBuildVector(VecVT, SL, Ops);
13033 }
13034 
13035 /// Return the source of an fp_extend from f16 to f32, or a converted FP
13036 /// constant.
13037 static SDValue strictFPExtFromF16(SelectionDAG &DAG, SDValue Src) {
13038   if (Src.getOpcode() == ISD::FP_EXTEND &&
13039       Src.getOperand(0).getValueType() == MVT::f16) {
13040     return Src.getOperand(0);
13041   }
13042 
13043   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Src)) {
13044     APFloat Val = CFP->getValueAPF();
13045     bool LosesInfo = true;
13046     Val.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &LosesInfo);
13047     if (!LosesInfo)
13048       return DAG.getConstantFP(Val, SDLoc(Src), MVT::f16);
13049   }
13050 
13051   return SDValue();
13052 }
13053 
13054 SDValue SITargetLowering::performFPRoundCombine(SDNode *N,
13055                                                 DAGCombinerInfo &DCI) const {
13056   assert(Subtarget->has16BitInsts() && !Subtarget->hasMed3_16() &&
13057          "combine only useful on gfx8");
13058 
13059   SDValue TruncSrc = N->getOperand(0);
13060   EVT VT = N->getValueType(0);
13061   if (VT != MVT::f16)
13062     return SDValue();
13063 
13064   if (TruncSrc.getOpcode() != AMDGPUISD::FMED3 ||
13065       TruncSrc.getValueType() != MVT::f32 || !TruncSrc.hasOneUse())
13066     return SDValue();
13067 
13068   SelectionDAG &DAG = DCI.DAG;
13069   SDLoc SL(N);
13070 
13071   // Optimize f16 fmed3 pattern performed on f32. On gfx8 there is no f16 fmed3,
13072   // and expanding it with min/max saves 1 instruction vs. casting to f32 and
13073   // casting back.
13074 
13075   // fptrunc (f32 (fmed3 (fpext f16:a, fpext f16:b, fpext f16:c))) =>
13076   // fmin(fmax(a, b), fmax(fmin(a, b), c))
13077   SDValue A = strictFPExtFromF16(DAG, TruncSrc.getOperand(0));
13078   if (!A)
13079     return SDValue();
13080 
13081   SDValue B = strictFPExtFromF16(DAG, TruncSrc.getOperand(1));
13082   if (!B)
13083     return SDValue();
13084 
13085   SDValue C = strictFPExtFromF16(DAG, TruncSrc.getOperand(2));
13086   if (!C)
13087     return SDValue();
13088 
13089   // This changes signaling nan behavior. If an input is a signaling nan, it
13090   // would have been quieted by the fpext originally. We don't care because
13091   // these are unconstrained ops. If we needed to insert quieting canonicalizes
13092   // we would be worse off than just doing the promotion.
13093   SDValue A1 = DAG.getNode(ISD::FMINNUM_IEEE, SL, VT, A, B);
13094   SDValue B1 = DAG.getNode(ISD::FMAXNUM_IEEE, SL, VT, A, B);
13095   SDValue C1 = DAG.getNode(ISD::FMAXNUM_IEEE, SL, VT, A1, C);
13096   return DAG.getNode(ISD::FMINNUM_IEEE, SL, VT, B1, C1);
13097 }
13098 
13099 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
13100                                           const SDNode *N0,
13101                                           const SDNode *N1) const {
13102   EVT VT = N0->getValueType(0);
13103 
13104   // Only do this if we are not trying to support denormals. v_mad_f32 does not
13105   // support denormals ever.
13106   if (((VT == MVT::f32 &&
13107         denormalModeIsFlushAllF32(DAG.getMachineFunction())) ||
13108        (VT == MVT::f16 && Subtarget->hasMadF16() &&
13109         denormalModeIsFlushAllF64F16(DAG.getMachineFunction()))) &&
13110       isOperationLegal(ISD::FMAD, VT))
13111     return ISD::FMAD;
13112 
13113   const TargetOptions &Options = DAG.getTarget().Options;
13114   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
13115        (N0->getFlags().hasAllowContract() &&
13116         N1->getFlags().hasAllowContract())) &&
13117       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
13118     return ISD::FMA;
13119   }
13120 
13121   return 0;
13122 }
13123 
13124 // For a reassociatable opcode perform:
13125 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
13126 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
13127                                                SelectionDAG &DAG) const {
13128   EVT VT = N->getValueType(0);
13129   if (VT != MVT::i32 && VT != MVT::i64)
13130     return SDValue();
13131 
13132   if (DAG.isBaseWithConstantOffset(SDValue(N, 0)))
13133     return SDValue();
13134 
13135   unsigned Opc = N->getOpcode();
13136   SDValue Op0 = N->getOperand(0);
13137   SDValue Op1 = N->getOperand(1);
13138 
13139   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
13140     return SDValue();
13141 
13142   if (Op0->isDivergent())
13143     std::swap(Op0, Op1);
13144 
13145   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
13146     return SDValue();
13147 
13148   SDValue Op2 = Op1.getOperand(1);
13149   Op1 = Op1.getOperand(0);
13150   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
13151     return SDValue();
13152 
13153   if (Op1->isDivergent())
13154     std::swap(Op1, Op2);
13155 
13156   SDLoc SL(N);
13157   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
13158   return DAG.getNode(Opc, SL, VT, Add1, Op2);
13159 }
13160 
13161 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
13162                            EVT VT,
13163                            SDValue N0, SDValue N1, SDValue N2,
13164                            bool Signed) {
13165   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
13166   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
13167   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
13168   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
13169 }
13170 
13171 // Fold (add (mul x, y), z) --> (mad_[iu]64_[iu]32 x, y, z) plus high
13172 // multiplies, if any.
13173 //
13174 // Full 64-bit multiplies that feed into an addition are lowered here instead
13175 // of using the generic expansion. The generic expansion ends up with
13176 // a tree of ADD nodes that prevents us from using the "add" part of the
13177 // MAD instruction. The expansion produced here results in a chain of ADDs
13178 // instead of a tree.
13179 SDValue SITargetLowering::tryFoldToMad64_32(SDNode *N,
13180                                             DAGCombinerInfo &DCI) const {
13181   assert(N->getOpcode() == ISD::ADD);
13182 
13183   SelectionDAG &DAG = DCI.DAG;
13184   EVT VT = N->getValueType(0);
13185   SDLoc SL(N);
13186   SDValue LHS = N->getOperand(0);
13187   SDValue RHS = N->getOperand(1);
13188 
13189   if (VT.isVector())
13190     return SDValue();
13191 
13192   // S_MUL_HI_[IU]32 was added in gfx9, which allows us to keep the overall
13193   // result in scalar registers for uniform values.
13194   if (!N->isDivergent() && Subtarget->hasSMulHi())
13195     return SDValue();
13196 
13197   unsigned NumBits = VT.getScalarSizeInBits();
13198   if (NumBits <= 32 || NumBits > 64)
13199     return SDValue();
13200 
13201   if (LHS.getOpcode() != ISD::MUL) {
13202     assert(RHS.getOpcode() == ISD::MUL);
13203     std::swap(LHS, RHS);
13204   }
13205 
13206   // Avoid the fold if it would unduly increase the number of multiplies due to
13207   // multiple uses, except on hardware with full-rate multiply-add (which is
13208   // part of full-rate 64-bit ops).
13209   if (!Subtarget->hasFullRate64Ops()) {
13210     unsigned NumUsers = 0;
13211     for (SDNode *Use : LHS->uses()) {
13212       // There is a use that does not feed into addition, so the multiply can't
13213       // be removed. We prefer MUL + ADD + ADDC over MAD + MUL.
13214       if (Use->getOpcode() != ISD::ADD)
13215         return SDValue();
13216 
13217       // We prefer 2xMAD over MUL + 2xADD + 2xADDC (code density), and prefer
13218       // MUL + 3xADD + 3xADDC over 3xMAD.
13219       ++NumUsers;
13220       if (NumUsers >= 3)
13221         return SDValue();
13222     }
13223   }
13224 
13225   SDValue MulLHS = LHS.getOperand(0);
13226   SDValue MulRHS = LHS.getOperand(1);
13227   SDValue AddRHS = RHS;
13228 
13229   // Always check whether operands are small unsigned values, since that
13230   // knowledge is useful in more cases. Check for small signed values only if
13231   // doing so can unlock a shorter code sequence.
13232   bool MulLHSUnsigned32 = numBitsUnsigned(MulLHS, DAG) <= 32;
13233   bool MulRHSUnsigned32 = numBitsUnsigned(MulRHS, DAG) <= 32;
13234 
13235   bool MulSignedLo = false;
13236   if (!MulLHSUnsigned32 || !MulRHSUnsigned32) {
13237     MulSignedLo = numBitsSigned(MulLHS, DAG) <= 32 &&
13238                   numBitsSigned(MulRHS, DAG) <= 32;
13239   }
13240 
13241   // The operands and final result all have the same number of bits. If
13242   // operands need to be extended, they can be extended with garbage. The
13243   // resulting garbage in the high bits of the mad_[iu]64_[iu]32 result is
13244   // truncated away in the end.
13245   if (VT != MVT::i64) {
13246     MulLHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulLHS);
13247     MulRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulRHS);
13248     AddRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, AddRHS);
13249   }
13250 
13251   // The basic code generated is conceptually straightforward. Pseudo code:
13252   //
13253   //   accum = mad_64_32 lhs.lo, rhs.lo, accum
13254   //   accum.hi = add (mul lhs.hi, rhs.lo), accum.hi
13255   //   accum.hi = add (mul lhs.lo, rhs.hi), accum.hi
13256   //
13257   // The second and third lines are optional, depending on whether the factors
13258   // are {sign,zero}-extended or not.
13259   //
13260   // The actual DAG is noisier than the pseudo code, but only due to
13261   // instructions that disassemble values into low and high parts, and
13262   // assemble the final result.
13263   SDValue One = DAG.getConstant(1, SL, MVT::i32);
13264 
13265   auto MulLHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulLHS);
13266   auto MulRHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulRHS);
13267   SDValue Accum =
13268       getMad64_32(DAG, SL, MVT::i64, MulLHSLo, MulRHSLo, AddRHS, MulSignedLo);
13269 
13270   if (!MulSignedLo && (!MulLHSUnsigned32 || !MulRHSUnsigned32)) {
13271     SDValue AccumLo, AccumHi;
13272     std::tie(AccumLo, AccumHi) = DAG.SplitScalar(Accum, SL, MVT::i32, MVT::i32);
13273 
13274     if (!MulLHSUnsigned32) {
13275       auto MulLHSHi =
13276           DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulLHS, One);
13277       SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSHi, MulRHSLo);
13278       AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi);
13279     }
13280 
13281     if (!MulRHSUnsigned32) {
13282       auto MulRHSHi =
13283           DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulRHS, One);
13284       SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSLo, MulRHSHi);
13285       AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi);
13286     }
13287 
13288     Accum = DAG.getBuildVector(MVT::v2i32, SL, {AccumLo, AccumHi});
13289     Accum = DAG.getBitcast(MVT::i64, Accum);
13290   }
13291 
13292   if (VT != MVT::i64)
13293     Accum = DAG.getNode(ISD::TRUNCATE, SL, VT, Accum);
13294   return Accum;
13295 }
13296 
13297 // Collect the ultimate src of each of the mul node's operands, and confirm
13298 // each operand is 8 bytes.
13299 static std::optional<ByteProvider<SDValue>>
13300 handleMulOperand(const SDValue &MulOperand) {
13301   auto Byte0 = calculateByteProvider(MulOperand, 0, 0);
13302   if (!Byte0 || Byte0->isConstantZero()) {
13303     return std::nullopt;
13304   }
13305   auto Byte1 = calculateByteProvider(MulOperand, 1, 0);
13306   if (Byte1 && !Byte1->isConstantZero()) {
13307     return std::nullopt;
13308   }
13309   return Byte0;
13310 }
13311 
13312 static unsigned addPermMasks(unsigned First, unsigned Second) {
13313   unsigned FirstCs = First & 0x0c0c0c0c;
13314   unsigned SecondCs = Second & 0x0c0c0c0c;
13315   unsigned FirstNoCs = First & ~0x0c0c0c0c;
13316   unsigned SecondNoCs = Second & ~0x0c0c0c0c;
13317 
13318   assert((FirstCs & 0xFF) | (SecondCs & 0xFF));
13319   assert((FirstCs & 0xFF00) | (SecondCs & 0xFF00));
13320   assert((FirstCs & 0xFF0000) | (SecondCs & 0xFF0000));
13321   assert((FirstCs & 0xFF000000) | (SecondCs & 0xFF000000));
13322 
13323   return (FirstNoCs | SecondNoCs) | (FirstCs & SecondCs);
13324 }
13325 
13326 static void placeSources(ByteProvider<SDValue> &Src0,
13327                          ByteProvider<SDValue> &Src1,
13328                          SmallVectorImpl<std::pair<SDValue, unsigned>> &Src0s,
13329                          SmallVectorImpl<std::pair<SDValue, unsigned>> &Src1s,
13330                          int Step) {
13331 
13332   assert(Src0.Src.has_value() && Src1.Src.has_value());
13333   // Src0s and Src1s are empty, just place arbitrarily.
13334   if (Step == 0) {
13335     Src0s.push_back({*Src0.Src, (Src0.SrcOffset << 24) + 0x0c0c0c});
13336     Src1s.push_back({*Src1.Src, (Src1.SrcOffset << 24) + 0x0c0c0c});
13337     return;
13338   }
13339 
13340   for (int BPI = 0; BPI < 2; BPI++) {
13341     std::pair<ByteProvider<SDValue>, ByteProvider<SDValue>> BPP = {Src0, Src1};
13342     if (BPI == 1) {
13343       BPP = {Src1, Src0};
13344     }
13345     unsigned ZeroMask = 0x0c0c0c0c;
13346     unsigned FMask = 0xFF << (8 * (3 - Step));
13347 
13348     unsigned FirstMask =
13349         BPP.first.SrcOffset << (8 * (3 - Step)) | (ZeroMask & ~FMask);
13350     unsigned SecondMask =
13351         BPP.second.SrcOffset << (8 * (3 - Step)) | (ZeroMask & ~FMask);
13352     // Attempt to find Src vector which contains our SDValue, if so, add our
13353     // perm mask to the existing one. If we are unable to find a match for the
13354     // first SDValue, attempt to find match for the second.
13355     int FirstGroup = -1;
13356     for (int I = 0; I < 2; I++) {
13357       SmallVectorImpl<std::pair<SDValue, unsigned>> &Srcs =
13358           I == 0 ? Src0s : Src1s;
13359       auto MatchesFirst = [&BPP](std::pair<SDValue, unsigned> IterElt) {
13360         return IterElt.first == *BPP.first.Src;
13361       };
13362 
13363       auto Match = llvm::find_if(Srcs, MatchesFirst);
13364       if (Match != Srcs.end()) {
13365         Match->second = addPermMasks(FirstMask, Match->second);
13366         FirstGroup = I;
13367         break;
13368       }
13369     }
13370     if (FirstGroup != -1) {
13371       SmallVectorImpl<std::pair<SDValue, unsigned>> &Srcs =
13372           FirstGroup == 1 ? Src0s : Src1s;
13373       auto MatchesSecond = [&BPP](std::pair<SDValue, unsigned> IterElt) {
13374         return IterElt.first == *BPP.second.Src;
13375       };
13376       auto Match = llvm::find_if(Srcs, MatchesSecond);
13377       if (Match != Srcs.end()) {
13378         Match->second = addPermMasks(SecondMask, Match->second);
13379       } else
13380         Srcs.push_back({*BPP.second.Src, SecondMask});
13381       return;
13382     }
13383   }
13384 
13385   // If we have made it here, then we could not find a match in Src0s or Src1s
13386   // for either Src0 or Src1, so just place them arbitrarily.
13387 
13388   unsigned ZeroMask = 0x0c0c0c0c;
13389   unsigned FMask = 0xFF << (8 * (3 - Step));
13390 
13391   Src0s.push_back(
13392       {*Src0.Src, (Src0.SrcOffset << (8 * (3 - Step)) | (ZeroMask & ~FMask))});
13393   Src1s.push_back(
13394       {*Src1.Src, (Src1.SrcOffset << (8 * (3 - Step)) | (ZeroMask & ~FMask))});
13395 
13396   return;
13397 }
13398 
13399 static SDValue
13400 resolveSources(SelectionDAG &DAG, SDLoc SL,
13401                SmallVectorImpl<std::pair<SDValue, unsigned>> &Srcs,
13402                bool IsSigned, bool IsAny) {
13403 
13404   // If we just have one source, just permute it accordingly.
13405   if (Srcs.size() == 1) {
13406     auto Elt = Srcs.begin();
13407     auto EltVal = DAG.getBitcastedAnyExtOrTrunc(Elt->first, SL, MVT::i32);
13408 
13409     // v_perm will produce the original value.
13410     if (Elt->second == 0x3020100)
13411       return EltVal;
13412 
13413     return DAG.getNode(AMDGPUISD::PERM, SL, MVT::i32, EltVal, EltVal,
13414                        DAG.getConstant(Elt->second, SL, MVT::i32));
13415   }
13416 
13417   auto FirstElt = Srcs.begin();
13418   auto SecondElt = std::next(FirstElt);
13419 
13420   SmallVector<SDValue, 2> Perms;
13421 
13422   // If we have multiple sources in the chain, combine them via perms (using
13423   // calculated perm mask) and Ors.
13424   while (true) {
13425     auto FirstMask = FirstElt->second;
13426     auto SecondMask = SecondElt->second;
13427 
13428     unsigned FirstCs = FirstMask & 0x0c0c0c0c;
13429     unsigned FirstPlusFour = FirstMask | 0x04040404;
13430     // 0x0c + 0x04 = 0x10, so anding with 0x0F will produced 0x00 for any
13431     // original 0x0C.
13432     FirstMask = (FirstPlusFour & 0x0F0F0F0F) | FirstCs;
13433 
13434     auto PermMask = addPermMasks(FirstMask, SecondMask);
13435     auto FirstVal =
13436         DAG.getBitcastedAnyExtOrTrunc(FirstElt->first, SL, MVT::i32);
13437     auto SecondVal =
13438         DAG.getBitcastedAnyExtOrTrunc(SecondElt->first, SL, MVT::i32);
13439 
13440     Perms.push_back(DAG.getNode(AMDGPUISD::PERM, SL, MVT::i32, FirstVal,
13441                                 SecondVal,
13442                                 DAG.getConstant(PermMask, SL, MVT::i32)));
13443 
13444     FirstElt = std::next(SecondElt);
13445     if (FirstElt == Srcs.end())
13446       break;
13447 
13448     SecondElt = std::next(FirstElt);
13449     // If we only have a FirstElt, then just combine that into the cumulative
13450     // source node.
13451     if (SecondElt == Srcs.end()) {
13452       auto EltVal =
13453           DAG.getBitcastedAnyExtOrTrunc(FirstElt->first, SL, MVT::i32);
13454 
13455       Perms.push_back(
13456           DAG.getNode(AMDGPUISD::PERM, SL, MVT::i32, EltVal, EltVal,
13457                       DAG.getConstant(FirstElt->second, SL, MVT::i32)));
13458       break;
13459     }
13460   }
13461 
13462   assert(Perms.size() == 1 || Perms.size() == 2);
13463   return Perms.size() == 2
13464              ? DAG.getNode(ISD::OR, SL, MVT::i32, Perms[0], Perms[1])
13465              : Perms[0];
13466 }
13467 
13468 static void fixMasks(SmallVectorImpl<std::pair<SDValue, unsigned>> &Srcs,
13469                      unsigned ChainLength) {
13470   for (auto &[EntryVal, EntryMask] : Srcs) {
13471     EntryMask = EntryMask >> ((4 - ChainLength) * 8);
13472     auto ZeroMask = ChainLength == 2 ? 0x0c0c0000 : 0x0c000000;
13473     EntryMask += ZeroMask;
13474   }
13475 }
13476 
13477 static bool isMul(const SDValue Op) {
13478   auto Opcode = Op.getOpcode();
13479 
13480   return (Opcode == ISD::MUL || Opcode == AMDGPUISD::MUL_U24 ||
13481           Opcode == AMDGPUISD::MUL_I24);
13482 }
13483 
13484 static std::optional<bool>
13485 checkDot4MulSignedness(const SDValue &N, ByteProvider<SDValue> &Src0,
13486                        ByteProvider<SDValue> &Src1, const SDValue &S0Op,
13487                        const SDValue &S1Op, const SelectionDAG &DAG) {
13488   // If we both ops are i8s (pre legalize-dag), then the signedness semantics
13489   // of the dot4 is irrelevant.
13490   if (S0Op.getValueSizeInBits() == 8 && S1Op.getValueSizeInBits() == 8)
13491     return false;
13492 
13493   auto Known0 = DAG.computeKnownBits(S0Op, 0);
13494   bool S0IsUnsigned = Known0.countMinLeadingZeros() > 0;
13495   bool S0IsSigned = Known0.countMinLeadingOnes() > 0;
13496   auto Known1 = DAG.computeKnownBits(S1Op, 0);
13497   bool S1IsUnsigned = Known1.countMinLeadingZeros() > 0;
13498   bool S1IsSigned = Known1.countMinLeadingOnes() > 0;
13499 
13500   assert(!(S0IsUnsigned && S0IsSigned));
13501   assert(!(S1IsUnsigned && S1IsSigned));
13502 
13503   // There are 9 possible permutations of
13504   // {S0IsUnsigned, S0IsSigned, S1IsUnsigned, S1IsSigned}
13505 
13506   // In two permutations, the sign bits are known to be the same for both Ops,
13507   // so simply return Signed / Unsigned corresponding to the MSB
13508 
13509   if ((S0IsUnsigned && S1IsUnsigned) || (S0IsSigned && S1IsSigned))
13510     return S0IsSigned;
13511 
13512   // In another two permutations, the sign bits are known to be opposite. In
13513   // this case return std::nullopt to indicate a bad match.
13514 
13515   if ((S0IsUnsigned && S1IsSigned) || (S0IsSigned && S1IsUnsigned))
13516     return std::nullopt;
13517 
13518   // In the remaining five permutations, we don't know the value of the sign
13519   // bit for at least one Op. Since we have a valid ByteProvider, we know that
13520   // the upper bits must be extension bits. Thus, the only ways for the sign
13521   // bit to be unknown is if it was sign extended from unknown value, or if it
13522   // was any extended. In either case, it is correct to use the signed
13523   // version of the signedness semantics of dot4
13524 
13525   // In two of such permutations, we known the sign bit is set for
13526   // one op, and the other is unknown. It is okay to used signed version of
13527   // dot4.
13528   if ((S0IsSigned && !(S1IsSigned || S1IsUnsigned)) ||
13529       ((S1IsSigned && !(S0IsSigned || S0IsUnsigned))))
13530     return true;
13531 
13532   // In one such permutation, we don't know either of the sign bits. It is okay
13533   // to used the signed version of dot4.
13534   if ((!(S1IsSigned || S1IsUnsigned) && !(S0IsSigned || S0IsUnsigned)))
13535     return true;
13536 
13537   // In two of such permutations, we known the sign bit is unset for
13538   // one op, and the other is unknown. Return std::nullopt to indicate a
13539   // bad match.
13540   if ((S0IsUnsigned && !(S1IsSigned || S1IsUnsigned)) ||
13541       ((S1IsUnsigned && !(S0IsSigned || S0IsUnsigned))))
13542     return std::nullopt;
13543 
13544   llvm_unreachable("Fully covered condition");
13545 }
13546 
13547 SDValue SITargetLowering::performAddCombine(SDNode *N,
13548                                             DAGCombinerInfo &DCI) const {
13549   SelectionDAG &DAG = DCI.DAG;
13550   EVT VT = N->getValueType(0);
13551   SDLoc SL(N);
13552   SDValue LHS = N->getOperand(0);
13553   SDValue RHS = N->getOperand(1);
13554 
13555   if (LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) {
13556     if (Subtarget->hasMad64_32()) {
13557       if (SDValue Folded = tryFoldToMad64_32(N, DCI))
13558         return Folded;
13559     }
13560   }
13561 
13562   if (SDValue V = reassociateScalarOps(N, DAG)) {
13563     return V;
13564   }
13565 
13566   if ((isMul(LHS) || isMul(RHS)) && Subtarget->hasDot7Insts() &&
13567       (Subtarget->hasDot1Insts() || Subtarget->hasDot8Insts())) {
13568     SDValue TempNode(N, 0);
13569     std::optional<bool> IsSigned;
13570     SmallVector<std::pair<SDValue, unsigned>, 4> Src0s;
13571     SmallVector<std::pair<SDValue, unsigned>, 4> Src1s;
13572     SmallVector<SDValue, 4> Src2s;
13573 
13574     // Match the v_dot4 tree, while collecting src nodes.
13575     int ChainLength = 0;
13576     for (int I = 0; I < 4; I++) {
13577       auto MulIdx = isMul(LHS) ? 0 : isMul(RHS) ? 1 : -1;
13578       if (MulIdx == -1)
13579         break;
13580       auto Src0 = handleMulOperand(TempNode->getOperand(MulIdx)->getOperand(0));
13581       if (!Src0)
13582         break;
13583       auto Src1 = handleMulOperand(TempNode->getOperand(MulIdx)->getOperand(1));
13584       if (!Src1)
13585         break;
13586 
13587       auto IterIsSigned = checkDot4MulSignedness(
13588           TempNode->getOperand(MulIdx), *Src0, *Src1,
13589           TempNode->getOperand(MulIdx)->getOperand(0),
13590           TempNode->getOperand(MulIdx)->getOperand(1), DAG);
13591       if (!IterIsSigned)
13592         break;
13593       if (!IsSigned)
13594         IsSigned = *IterIsSigned;
13595       if (*IterIsSigned != *IsSigned)
13596         break;
13597       placeSources(*Src0, *Src1, Src0s, Src1s, I);
13598       auto AddIdx = 1 - MulIdx;
13599       // Allow the special case where add (add (mul24, 0), mul24) became ->
13600       // add (mul24, mul24).
13601       if (I == 2 && isMul(TempNode->getOperand(AddIdx))) {
13602         Src2s.push_back(TempNode->getOperand(AddIdx));
13603         auto Src0 =
13604             handleMulOperand(TempNode->getOperand(AddIdx)->getOperand(0));
13605         if (!Src0)
13606           break;
13607         auto Src1 =
13608             handleMulOperand(TempNode->getOperand(AddIdx)->getOperand(1));
13609         if (!Src1)
13610           break;
13611         auto IterIsSigned = checkDot4MulSignedness(
13612             TempNode->getOperand(AddIdx), *Src0, *Src1,
13613             TempNode->getOperand(AddIdx)->getOperand(0),
13614             TempNode->getOperand(AddIdx)->getOperand(1), DAG);
13615         if (!IterIsSigned)
13616           break;
13617         assert(IsSigned);
13618         if (*IterIsSigned != *IsSigned)
13619           break;
13620         placeSources(*Src0, *Src1, Src0s, Src1s, I + 1);
13621         Src2s.push_back(DAG.getConstant(0, SL, MVT::i32));
13622         ChainLength = I + 2;
13623         break;
13624       }
13625 
13626       TempNode = TempNode->getOperand(AddIdx);
13627       Src2s.push_back(TempNode);
13628       ChainLength = I + 1;
13629       if (TempNode->getNumOperands() < 2)
13630         break;
13631       LHS = TempNode->getOperand(0);
13632       RHS = TempNode->getOperand(1);
13633     }
13634 
13635     if (ChainLength < 2)
13636       return SDValue();
13637 
13638     // Masks were constructed with assumption that we would find a chain of
13639     // length 4. If not, then we need to 0 out the MSB bits (via perm mask of
13640     // 0x0c) so they do not affect dot calculation.
13641     if (ChainLength < 4) {
13642       fixMasks(Src0s, ChainLength);
13643       fixMasks(Src1s, ChainLength);
13644     }
13645 
13646     SDValue Src0, Src1;
13647 
13648     // If we are just using a single source for both, and have permuted the
13649     // bytes consistently, we can just use the sources without permuting
13650     // (commutation).
13651     bool UseOriginalSrc = false;
13652     if (ChainLength == 4 && Src0s.size() == 1 && Src1s.size() == 1 &&
13653         Src0s.begin()->second == Src1s.begin()->second &&
13654         Src0s.begin()->first.getValueSizeInBits() == 32 &&
13655         Src1s.begin()->first.getValueSizeInBits() == 32) {
13656       SmallVector<unsigned, 4> SrcBytes;
13657       auto Src0Mask = Src0s.begin()->second;
13658       SrcBytes.push_back(Src0Mask & 0xFF000000);
13659       bool UniqueEntries = true;
13660       for (auto I = 1; I < 4; I++) {
13661         auto NextByte = Src0Mask & (0xFF << ((3 - I) * 8));
13662 
13663         if (is_contained(SrcBytes, NextByte)) {
13664           UniqueEntries = false;
13665           break;
13666         }
13667         SrcBytes.push_back(NextByte);
13668       }
13669 
13670       if (UniqueEntries) {
13671         UseOriginalSrc = true;
13672         // Must be 32 bits to enter above conditional.
13673         assert(Src0s.begin()->first.getValueSizeInBits() == 32);
13674         assert(Src1s.begin()->first.getValueSizeInBits() == 32);
13675         Src0 = DAG.getBitcast(MVT::getIntegerVT(32), Src0s.begin()->first);
13676         Src1 = DAG.getBitcast(MVT::getIntegerVT(32), Src1s.begin()->first);
13677       }
13678     }
13679 
13680     if (!UseOriginalSrc) {
13681       Src0 = resolveSources(DAG, SL, Src0s, false, true);
13682       Src1 = resolveSources(DAG, SL, Src1s, false, true);
13683     }
13684 
13685     assert(IsSigned);
13686     SDValue Src2 =
13687         DAG.getExtOrTrunc(*IsSigned, Src2s[ChainLength - 1], SL, MVT::i32);
13688 
13689     SDValue IID = DAG.getTargetConstant(*IsSigned ? Intrinsic::amdgcn_sdot4
13690                                                   : Intrinsic::amdgcn_udot4,
13691                                         SL, MVT::i64);
13692 
13693     assert(!VT.isVector());
13694     auto Dot = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SL, MVT::i32, IID, Src0,
13695                            Src1, Src2, DAG.getTargetConstant(0, SL, MVT::i1));
13696 
13697     return DAG.getExtOrTrunc(*IsSigned, Dot, SL, VT);
13698   }
13699 
13700   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
13701     return SDValue();
13702 
13703   // add x, zext (setcc) => uaddo_carry x, 0, setcc
13704   // add x, sext (setcc) => usubo_carry x, 0, setcc
13705   unsigned Opc = LHS.getOpcode();
13706   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
13707       Opc == ISD::ANY_EXTEND || Opc == ISD::UADDO_CARRY)
13708     std::swap(RHS, LHS);
13709 
13710   Opc = RHS.getOpcode();
13711   switch (Opc) {
13712   default: break;
13713   case ISD::ZERO_EXTEND:
13714   case ISD::SIGN_EXTEND:
13715   case ISD::ANY_EXTEND: {
13716     auto Cond = RHS.getOperand(0);
13717     // If this won't be a real VOPC output, we would still need to insert an
13718     // extra instruction anyway.
13719     if (!isBoolSGPR(Cond))
13720       break;
13721     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
13722     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
13723     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::USUBO_CARRY : ISD::UADDO_CARRY;
13724     return DAG.getNode(Opc, SL, VTList, Args);
13725   }
13726   case ISD::UADDO_CARRY: {
13727     // add x, (uaddo_carry y, 0, cc) => uaddo_carry x, y, cc
13728     if (!isNullConstant(RHS.getOperand(1)))
13729       break;
13730     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
13731     return DAG.getNode(ISD::UADDO_CARRY, SDLoc(N), RHS->getVTList(), Args);
13732   }
13733   }
13734   return SDValue();
13735 }
13736 
13737 SDValue SITargetLowering::performSubCombine(SDNode *N,
13738                                             DAGCombinerInfo &DCI) const {
13739   SelectionDAG &DAG = DCI.DAG;
13740   EVT VT = N->getValueType(0);
13741 
13742   if (VT != MVT::i32)
13743     return SDValue();
13744 
13745   SDLoc SL(N);
13746   SDValue LHS = N->getOperand(0);
13747   SDValue RHS = N->getOperand(1);
13748 
13749   // sub x, zext (setcc) => usubo_carry x, 0, setcc
13750   // sub x, sext (setcc) => uaddo_carry x, 0, setcc
13751   unsigned Opc = RHS.getOpcode();
13752   switch (Opc) {
13753   default: break;
13754   case ISD::ZERO_EXTEND:
13755   case ISD::SIGN_EXTEND:
13756   case ISD::ANY_EXTEND: {
13757     auto Cond = RHS.getOperand(0);
13758     // If this won't be a real VOPC output, we would still need to insert an
13759     // extra instruction anyway.
13760     if (!isBoolSGPR(Cond))
13761       break;
13762     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
13763     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
13764     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::UADDO_CARRY : ISD::USUBO_CARRY;
13765     return DAG.getNode(Opc, SL, VTList, Args);
13766   }
13767   }
13768 
13769   if (LHS.getOpcode() == ISD::USUBO_CARRY) {
13770     // sub (usubo_carry x, 0, cc), y => usubo_carry x, y, cc
13771     if (!isNullConstant(LHS.getOperand(1)))
13772       return SDValue();
13773     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
13774     return DAG.getNode(ISD::USUBO_CARRY, SDLoc(N), LHS->getVTList(), Args);
13775   }
13776   return SDValue();
13777 }
13778 
13779 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
13780   DAGCombinerInfo &DCI) const {
13781 
13782   if (N->getValueType(0) != MVT::i32)
13783     return SDValue();
13784 
13785   if (!isNullConstant(N->getOperand(1)))
13786     return SDValue();
13787 
13788   SelectionDAG &DAG = DCI.DAG;
13789   SDValue LHS = N->getOperand(0);
13790 
13791   // uaddo_carry (add x, y), 0, cc => uaddo_carry x, y, cc
13792   // usubo_carry (sub x, y), 0, cc => usubo_carry x, y, cc
13793   unsigned LHSOpc = LHS.getOpcode();
13794   unsigned Opc = N->getOpcode();
13795   if ((LHSOpc == ISD::ADD && Opc == ISD::UADDO_CARRY) ||
13796       (LHSOpc == ISD::SUB && Opc == ISD::USUBO_CARRY)) {
13797     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
13798     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
13799   }
13800   return SDValue();
13801 }
13802 
13803 SDValue SITargetLowering::performFAddCombine(SDNode *N,
13804                                              DAGCombinerInfo &DCI) const {
13805   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
13806     return SDValue();
13807 
13808   SelectionDAG &DAG = DCI.DAG;
13809   EVT VT = N->getValueType(0);
13810 
13811   SDLoc SL(N);
13812   SDValue LHS = N->getOperand(0);
13813   SDValue RHS = N->getOperand(1);
13814 
13815   // These should really be instruction patterns, but writing patterns with
13816   // source modifiers is a pain.
13817 
13818   // fadd (fadd (a, a), b) -> mad 2.0, a, b
13819   if (LHS.getOpcode() == ISD::FADD) {
13820     SDValue A = LHS.getOperand(0);
13821     if (A == LHS.getOperand(1)) {
13822       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
13823       if (FusedOp != 0) {
13824         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
13825         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
13826       }
13827     }
13828   }
13829 
13830   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
13831   if (RHS.getOpcode() == ISD::FADD) {
13832     SDValue A = RHS.getOperand(0);
13833     if (A == RHS.getOperand(1)) {
13834       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
13835       if (FusedOp != 0) {
13836         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
13837         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
13838       }
13839     }
13840   }
13841 
13842   return SDValue();
13843 }
13844 
13845 SDValue SITargetLowering::performFSubCombine(SDNode *N,
13846                                              DAGCombinerInfo &DCI) const {
13847   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
13848     return SDValue();
13849 
13850   SelectionDAG &DAG = DCI.DAG;
13851   SDLoc SL(N);
13852   EVT VT = N->getValueType(0);
13853   assert(!VT.isVector());
13854 
13855   // Try to get the fneg to fold into the source modifier. This undoes generic
13856   // DAG combines and folds them into the mad.
13857   //
13858   // Only do this if we are not trying to support denormals. v_mad_f32 does
13859   // not support denormals ever.
13860   SDValue LHS = N->getOperand(0);
13861   SDValue RHS = N->getOperand(1);
13862   if (LHS.getOpcode() == ISD::FADD) {
13863     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
13864     SDValue A = LHS.getOperand(0);
13865     if (A == LHS.getOperand(1)) {
13866       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
13867       if (FusedOp != 0){
13868         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
13869         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
13870 
13871         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
13872       }
13873     }
13874   }
13875 
13876   if (RHS.getOpcode() == ISD::FADD) {
13877     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
13878 
13879     SDValue A = RHS.getOperand(0);
13880     if (A == RHS.getOperand(1)) {
13881       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
13882       if (FusedOp != 0){
13883         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
13884         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
13885       }
13886     }
13887   }
13888 
13889   return SDValue();
13890 }
13891 
13892 SDValue SITargetLowering::performFDivCombine(SDNode *N,
13893                                              DAGCombinerInfo &DCI) const {
13894   SelectionDAG &DAG = DCI.DAG;
13895   SDLoc SL(N);
13896   EVT VT = N->getValueType(0);
13897   if (VT != MVT::f16 || !Subtarget->has16BitInsts())
13898     return SDValue();
13899 
13900   SDValue LHS = N->getOperand(0);
13901   SDValue RHS = N->getOperand(1);
13902 
13903   SDNodeFlags Flags = N->getFlags();
13904   SDNodeFlags RHSFlags = RHS->getFlags();
13905   if (!Flags.hasAllowContract() || !RHSFlags.hasAllowContract() ||
13906       !RHS->hasOneUse())
13907     return SDValue();
13908 
13909   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
13910     bool IsNegative = false;
13911     if (CLHS->isExactlyValue(1.0) ||
13912         (IsNegative = CLHS->isExactlyValue(-1.0))) {
13913       // fdiv contract 1.0, (sqrt contract x) -> rsq for f16
13914       // fdiv contract -1.0, (sqrt contract x) -> fneg(rsq) for f16
13915       if (RHS.getOpcode() == ISD::FSQRT) {
13916         // TODO: Or in RHS flags, somehow missing from SDNodeFlags
13917         SDValue Rsq =
13918             DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0), Flags);
13919         return IsNegative ? DAG.getNode(ISD::FNEG, SL, VT, Rsq, Flags) : Rsq;
13920       }
13921     }
13922   }
13923 
13924   return SDValue();
13925 }
13926 
13927 SDValue SITargetLowering::performFMACombine(SDNode *N,
13928                                             DAGCombinerInfo &DCI) const {
13929   SelectionDAG &DAG = DCI.DAG;
13930   EVT VT = N->getValueType(0);
13931   SDLoc SL(N);
13932 
13933   if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
13934     return SDValue();
13935 
13936   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
13937   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
13938   SDValue Op1 = N->getOperand(0);
13939   SDValue Op2 = N->getOperand(1);
13940   SDValue FMA = N->getOperand(2);
13941 
13942   if (FMA.getOpcode() != ISD::FMA ||
13943       Op1.getOpcode() != ISD::FP_EXTEND ||
13944       Op2.getOpcode() != ISD::FP_EXTEND)
13945     return SDValue();
13946 
13947   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
13948   // regardless of the denorm mode setting. Therefore,
13949   // unsafe-fp-math/fp-contract is sufficient to allow generating fdot2.
13950   const TargetOptions &Options = DAG.getTarget().Options;
13951   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
13952       (N->getFlags().hasAllowContract() &&
13953        FMA->getFlags().hasAllowContract())) {
13954     Op1 = Op1.getOperand(0);
13955     Op2 = Op2.getOperand(0);
13956     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13957         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13958       return SDValue();
13959 
13960     SDValue Vec1 = Op1.getOperand(0);
13961     SDValue Idx1 = Op1.getOperand(1);
13962     SDValue Vec2 = Op2.getOperand(0);
13963 
13964     SDValue FMAOp1 = FMA.getOperand(0);
13965     SDValue FMAOp2 = FMA.getOperand(1);
13966     SDValue FMAAcc = FMA.getOperand(2);
13967 
13968     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
13969         FMAOp2.getOpcode() != ISD::FP_EXTEND)
13970       return SDValue();
13971 
13972     FMAOp1 = FMAOp1.getOperand(0);
13973     FMAOp2 = FMAOp2.getOperand(0);
13974     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13975         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13976       return SDValue();
13977 
13978     SDValue Vec3 = FMAOp1.getOperand(0);
13979     SDValue Vec4 = FMAOp2.getOperand(0);
13980     SDValue Idx2 = FMAOp1.getOperand(1);
13981 
13982     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
13983         // Idx1 and Idx2 cannot be the same.
13984         Idx1 == Idx2)
13985       return SDValue();
13986 
13987     if (Vec1 == Vec2 || Vec3 == Vec4)
13988       return SDValue();
13989 
13990     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
13991       return SDValue();
13992 
13993     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
13994         (Vec1 == Vec4 && Vec2 == Vec3)) {
13995       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
13996                          DAG.getTargetConstant(0, SL, MVT::i1));
13997     }
13998   }
13999   return SDValue();
14000 }
14001 
14002 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
14003                                               DAGCombinerInfo &DCI) const {
14004   SelectionDAG &DAG = DCI.DAG;
14005   SDLoc SL(N);
14006 
14007   SDValue LHS = N->getOperand(0);
14008   SDValue RHS = N->getOperand(1);
14009   EVT VT = LHS.getValueType();
14010   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
14011 
14012   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
14013   if (!CRHS) {
14014     CRHS = dyn_cast<ConstantSDNode>(LHS);
14015     if (CRHS) {
14016       std::swap(LHS, RHS);
14017       CC = getSetCCSwappedOperands(CC);
14018     }
14019   }
14020 
14021   if (CRHS) {
14022     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
14023         isBoolSGPR(LHS.getOperand(0))) {
14024       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
14025       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
14026       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
14027       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
14028       if ((CRHS->isAllOnes() &&
14029            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
14030           (CRHS->isZero() &&
14031            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
14032         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
14033                            DAG.getConstant(-1, SL, MVT::i1));
14034       if ((CRHS->isAllOnes() &&
14035            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
14036           (CRHS->isZero() &&
14037            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
14038         return LHS.getOperand(0);
14039     }
14040 
14041     const APInt &CRHSVal = CRHS->getAPIntValue();
14042     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
14043         LHS.getOpcode() == ISD::SELECT &&
14044         isa<ConstantSDNode>(LHS.getOperand(1)) &&
14045         isa<ConstantSDNode>(LHS.getOperand(2)) &&
14046         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
14047         isBoolSGPR(LHS.getOperand(0))) {
14048       // Given CT != FT:
14049       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
14050       // setcc (select cc, CT, CF), CF, ne => cc
14051       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
14052       // setcc (select cc, CT, CF), CT, eq => cc
14053       const APInt &CT = LHS.getConstantOperandAPInt(1);
14054       const APInt &CF = LHS.getConstantOperandAPInt(2);
14055 
14056       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
14057           (CT == CRHSVal && CC == ISD::SETNE))
14058         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
14059                            DAG.getConstant(-1, SL, MVT::i1));
14060       if ((CF == CRHSVal && CC == ISD::SETNE) ||
14061           (CT == CRHSVal && CC == ISD::SETEQ))
14062         return LHS.getOperand(0);
14063     }
14064   }
14065 
14066   if (VT != MVT::f32 && VT != MVT::f64 &&
14067       (!Subtarget->has16BitInsts() || VT != MVT::f16))
14068     return SDValue();
14069 
14070   // Match isinf/isfinite pattern
14071   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
14072   // (fcmp one (fabs x), inf) -> (fp_class x,
14073   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
14074   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
14075     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
14076     if (!CRHS)
14077       return SDValue();
14078 
14079     const APFloat &APF = CRHS->getValueAPF();
14080     if (APF.isInfinity() && !APF.isNegative()) {
14081       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
14082                                  SIInstrFlags::N_INFINITY;
14083       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
14084                                     SIInstrFlags::P_ZERO |
14085                                     SIInstrFlags::N_NORMAL |
14086                                     SIInstrFlags::P_NORMAL |
14087                                     SIInstrFlags::N_SUBNORMAL |
14088                                     SIInstrFlags::P_SUBNORMAL;
14089       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
14090       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
14091                          DAG.getConstant(Mask, SL, MVT::i32));
14092     }
14093   }
14094 
14095   return SDValue();
14096 }
14097 
14098 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
14099                                                      DAGCombinerInfo &DCI) const {
14100   SelectionDAG &DAG = DCI.DAG;
14101   SDLoc SL(N);
14102   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
14103 
14104   SDValue Src = N->getOperand(0);
14105   SDValue Shift = N->getOperand(0);
14106 
14107   // TODO: Extend type shouldn't matter (assuming legal types).
14108   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
14109     Shift = Shift.getOperand(0);
14110 
14111   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
14112     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
14113     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
14114     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
14115     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
14116     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
14117     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
14118       SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0),
14119                                  SDLoc(Shift.getOperand(0)), MVT::i32);
14120 
14121       unsigned ShiftOffset = 8 * Offset;
14122       if (Shift.getOpcode() == ISD::SHL)
14123         ShiftOffset -= C->getZExtValue();
14124       else
14125         ShiftOffset += C->getZExtValue();
14126 
14127       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
14128         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
14129                            MVT::f32, Shifted);
14130       }
14131     }
14132   }
14133 
14134   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14135   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
14136   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
14137     // We simplified Src. If this node is not dead, visit it again so it is
14138     // folded properly.
14139     if (N->getOpcode() != ISD::DELETED_NODE)
14140       DCI.AddToWorklist(N);
14141     return SDValue(N, 0);
14142   }
14143 
14144   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
14145   if (SDValue DemandedSrc =
14146           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
14147     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
14148 
14149   return SDValue();
14150 }
14151 
14152 SDValue SITargetLowering::performClampCombine(SDNode *N,
14153                                               DAGCombinerInfo &DCI) const {
14154   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
14155   if (!CSrc)
14156     return SDValue();
14157 
14158   const MachineFunction &MF = DCI.DAG.getMachineFunction();
14159   const APFloat &F = CSrc->getValueAPF();
14160   APFloat Zero = APFloat::getZero(F.getSemantics());
14161   if (F < Zero ||
14162       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
14163     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
14164   }
14165 
14166   APFloat One(F.getSemantics(), "1.0");
14167   if (F > One)
14168     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
14169 
14170   return SDValue(CSrc, 0);
14171 }
14172 
14173 
14174 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
14175                                             DAGCombinerInfo &DCI) const {
14176   if (getTargetMachine().getOptLevel() == CodeGenOptLevel::None)
14177     return SDValue();
14178   switch (N->getOpcode()) {
14179   case ISD::ADD:
14180     return performAddCombine(N, DCI);
14181   case ISD::SUB:
14182     return performSubCombine(N, DCI);
14183   case ISD::UADDO_CARRY:
14184   case ISD::USUBO_CARRY:
14185     return performAddCarrySubCarryCombine(N, DCI);
14186   case ISD::FADD:
14187     return performFAddCombine(N, DCI);
14188   case ISD::FSUB:
14189     return performFSubCombine(N, DCI);
14190   case ISD::FDIV:
14191     return performFDivCombine(N, DCI);
14192   case ISD::SETCC:
14193     return performSetCCCombine(N, DCI);
14194   case ISD::FMAXNUM:
14195   case ISD::FMINNUM:
14196   case ISD::FMAXNUM_IEEE:
14197   case ISD::FMINNUM_IEEE:
14198   case ISD::FMAXIMUM:
14199   case ISD::FMINIMUM:
14200   case ISD::SMAX:
14201   case ISD::SMIN:
14202   case ISD::UMAX:
14203   case ISD::UMIN:
14204   case AMDGPUISD::FMIN_LEGACY:
14205   case AMDGPUISD::FMAX_LEGACY:
14206     return performMinMaxCombine(N, DCI);
14207   case ISD::FMA:
14208     return performFMACombine(N, DCI);
14209   case ISD::AND:
14210     return performAndCombine(N, DCI);
14211   case ISD::OR:
14212     return performOrCombine(N, DCI);
14213   case ISD::FSHR: {
14214     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
14215     if (N->getValueType(0) == MVT::i32 && N->isDivergent() &&
14216         TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
14217       return matchPERM(N, DCI);
14218     }
14219     break;
14220   }
14221   case ISD::XOR:
14222     return performXorCombine(N, DCI);
14223   case ISD::ZERO_EXTEND:
14224     return performZeroExtendCombine(N, DCI);
14225   case ISD::SIGN_EXTEND_INREG:
14226     return performSignExtendInRegCombine(N , DCI);
14227   case AMDGPUISD::FP_CLASS:
14228     return performClassCombine(N, DCI);
14229   case ISD::FCANONICALIZE:
14230     return performFCanonicalizeCombine(N, DCI);
14231   case AMDGPUISD::RCP:
14232     return performRcpCombine(N, DCI);
14233   case ISD::FLDEXP:
14234   case AMDGPUISD::FRACT:
14235   case AMDGPUISD::RSQ:
14236   case AMDGPUISD::RCP_LEGACY:
14237   case AMDGPUISD::RCP_IFLAG:
14238   case AMDGPUISD::RSQ_CLAMP: {
14239     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
14240     SDValue Src = N->getOperand(0);
14241     if (Src.isUndef())
14242       return Src;
14243     break;
14244   }
14245   case ISD::SINT_TO_FP:
14246   case ISD::UINT_TO_FP:
14247     return performUCharToFloatCombine(N, DCI);
14248   case ISD::FCOPYSIGN:
14249     return performFCopySignCombine(N, DCI);
14250   case AMDGPUISD::CVT_F32_UBYTE0:
14251   case AMDGPUISD::CVT_F32_UBYTE1:
14252   case AMDGPUISD::CVT_F32_UBYTE2:
14253   case AMDGPUISD::CVT_F32_UBYTE3:
14254     return performCvtF32UByteNCombine(N, DCI);
14255   case AMDGPUISD::FMED3:
14256     return performFMed3Combine(N, DCI);
14257   case AMDGPUISD::CVT_PKRTZ_F16_F32:
14258     return performCvtPkRTZCombine(N, DCI);
14259   case AMDGPUISD::CLAMP:
14260     return performClampCombine(N, DCI);
14261   case ISD::SCALAR_TO_VECTOR: {
14262     SelectionDAG &DAG = DCI.DAG;
14263     EVT VT = N->getValueType(0);
14264 
14265     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
14266     if (VT == MVT::v2i16 || VT == MVT::v2f16 || VT == MVT::v2f16) {
14267       SDLoc SL(N);
14268       SDValue Src = N->getOperand(0);
14269       EVT EltVT = Src.getValueType();
14270       if (EltVT != MVT::i16)
14271         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
14272 
14273       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
14274       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
14275     }
14276 
14277     break;
14278   }
14279   case ISD::EXTRACT_VECTOR_ELT:
14280     return performExtractVectorEltCombine(N, DCI);
14281   case ISD::INSERT_VECTOR_ELT:
14282     return performInsertVectorEltCombine(N, DCI);
14283   case ISD::FP_ROUND:
14284     return performFPRoundCombine(N, DCI);
14285   case ISD::LOAD: {
14286     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
14287       return Widended;
14288     [[fallthrough]];
14289   }
14290   default: {
14291     if (!DCI.isBeforeLegalize()) {
14292       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
14293         return performMemSDNodeCombine(MemNode, DCI);
14294     }
14295 
14296     break;
14297   }
14298   }
14299 
14300   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
14301 }
14302 
14303 /// Helper function for adjustWritemask
14304 static unsigned SubIdx2Lane(unsigned Idx) {
14305   switch (Idx) {
14306   default: return ~0u;
14307   case AMDGPU::sub0: return 0;
14308   case AMDGPU::sub1: return 1;
14309   case AMDGPU::sub2: return 2;
14310   case AMDGPU::sub3: return 3;
14311   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
14312   }
14313 }
14314 
14315 /// Adjust the writemask of MIMG, VIMAGE or VSAMPLE instructions
14316 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
14317                                           SelectionDAG &DAG) const {
14318   unsigned Opcode = Node->getMachineOpcode();
14319 
14320   // Subtract 1 because the vdata output is not a MachineSDNode operand.
14321   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
14322   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
14323     return Node; // not implemented for D16
14324 
14325   SDNode *Users[5] = { nullptr };
14326   unsigned Lane = 0;
14327   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
14328   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
14329   unsigned NewDmask = 0;
14330   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
14331   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
14332   bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
14333                   (int(LWEIdx) >= 0 && Node->getConstantOperandVal(LWEIdx)))
14334                      ? true
14335                      : false;
14336   unsigned TFCLane = 0;
14337   bool HasChain = Node->getNumValues() > 1;
14338 
14339   if (OldDmask == 0) {
14340     // These are folded out, but on the chance it happens don't assert.
14341     return Node;
14342   }
14343 
14344   unsigned OldBitsSet = llvm::popcount(OldDmask);
14345   // Work out which is the TFE/LWE lane if that is enabled.
14346   if (UsesTFC) {
14347     TFCLane = OldBitsSet;
14348   }
14349 
14350   // Try to figure out the used register components
14351   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
14352        I != E; ++I) {
14353 
14354     // Don't look at users of the chain.
14355     if (I.getUse().getResNo() != 0)
14356       continue;
14357 
14358     // Abort if we can't understand the usage
14359     if (!I->isMachineOpcode() ||
14360         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
14361       return Node;
14362 
14363     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
14364     // Note that subregs are packed, i.e. Lane==0 is the first bit set
14365     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
14366     // set, etc.
14367     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
14368     if (Lane == ~0u)
14369       return Node;
14370 
14371     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
14372     if (UsesTFC && Lane == TFCLane) {
14373       Users[Lane] = *I;
14374     } else {
14375       // Set which texture component corresponds to the lane.
14376       unsigned Comp;
14377       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
14378         Comp = llvm::countr_zero(Dmask);
14379         Dmask &= ~(1 << Comp);
14380       }
14381 
14382       // Abort if we have more than one user per component.
14383       if (Users[Lane])
14384         return Node;
14385 
14386       Users[Lane] = *I;
14387       NewDmask |= 1 << Comp;
14388     }
14389   }
14390 
14391   // Don't allow 0 dmask, as hardware assumes one channel enabled.
14392   bool NoChannels = !NewDmask;
14393   if (NoChannels) {
14394     if (!UsesTFC) {
14395       // No uses of the result and not using TFC. Then do nothing.
14396       return Node;
14397     }
14398     // If the original dmask has one channel - then nothing to do
14399     if (OldBitsSet == 1)
14400       return Node;
14401     // Use an arbitrary dmask - required for the instruction to work
14402     NewDmask = 1;
14403   }
14404   // Abort if there's no change
14405   if (NewDmask == OldDmask)
14406     return Node;
14407 
14408   unsigned BitsSet = llvm::popcount(NewDmask);
14409 
14410   // Check for TFE or LWE - increase the number of channels by one to account
14411   // for the extra return value
14412   // This will need adjustment for D16 if this is also included in
14413   // adjustWriteMask (this function) but at present D16 are excluded.
14414   unsigned NewChannels = BitsSet + UsesTFC;
14415 
14416   int NewOpcode =
14417       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
14418   assert(NewOpcode != -1 &&
14419          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
14420          "failed to find equivalent MIMG op");
14421 
14422   // Adjust the writemask in the node
14423   SmallVector<SDValue, 12> Ops;
14424   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
14425   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
14426   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
14427 
14428   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
14429 
14430   MVT ResultVT = NewChannels == 1 ?
14431     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
14432                            NewChannels == 5 ? 8 : NewChannels);
14433   SDVTList NewVTList = HasChain ?
14434     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
14435 
14436 
14437   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
14438                                               NewVTList, Ops);
14439 
14440   if (HasChain) {
14441     // Update chain.
14442     DAG.setNodeMemRefs(NewNode, Node->memoperands());
14443     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
14444   }
14445 
14446   if (NewChannels == 1) {
14447     assert(Node->hasNUsesOfValue(1, 0));
14448     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
14449                                       SDLoc(Node), Users[Lane]->getValueType(0),
14450                                       SDValue(NewNode, 0));
14451     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
14452     return nullptr;
14453   }
14454 
14455   // Update the users of the node with the new indices
14456   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
14457     SDNode *User = Users[i];
14458     if (!User) {
14459       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
14460       // Users[0] is still nullptr because channel 0 doesn't really have a use.
14461       if (i || !NoChannels)
14462         continue;
14463     } else {
14464       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
14465       SDNode *NewUser = DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
14466       if (NewUser != User) {
14467         DAG.ReplaceAllUsesWith(SDValue(User, 0), SDValue(NewUser, 0));
14468         DAG.RemoveDeadNode(User);
14469       }
14470     }
14471 
14472     switch (Idx) {
14473     default: break;
14474     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
14475     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
14476     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
14477     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
14478     }
14479   }
14480 
14481   DAG.RemoveDeadNode(Node);
14482   return nullptr;
14483 }
14484 
14485 static bool isFrameIndexOp(SDValue Op) {
14486   if (Op.getOpcode() == ISD::AssertZext)
14487     Op = Op.getOperand(0);
14488 
14489   return isa<FrameIndexSDNode>(Op);
14490 }
14491 
14492 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
14493 /// with frame index operands.
14494 /// LLVM assumes that inputs are to these instructions are registers.
14495 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
14496                                                         SelectionDAG &DAG) const {
14497   if (Node->getOpcode() == ISD::CopyToReg) {
14498     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
14499     SDValue SrcVal = Node->getOperand(2);
14500 
14501     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
14502     // to try understanding copies to physical registers.
14503     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
14504       SDLoc SL(Node);
14505       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
14506       SDValue VReg = DAG.getRegister(
14507         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
14508 
14509       SDNode *Glued = Node->getGluedNode();
14510       SDValue ToVReg
14511         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
14512                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
14513       SDValue ToResultReg
14514         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
14515                            VReg, ToVReg.getValue(1));
14516       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
14517       DAG.RemoveDeadNode(Node);
14518       return ToResultReg.getNode();
14519     }
14520   }
14521 
14522   SmallVector<SDValue, 8> Ops;
14523   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
14524     if (!isFrameIndexOp(Node->getOperand(i))) {
14525       Ops.push_back(Node->getOperand(i));
14526       continue;
14527     }
14528 
14529     SDLoc DL(Node);
14530     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
14531                                      Node->getOperand(i).getValueType(),
14532                                      Node->getOperand(i)), 0));
14533   }
14534 
14535   return DAG.UpdateNodeOperands(Node, Ops);
14536 }
14537 
14538 /// Fold the instructions after selecting them.
14539 /// Returns null if users were already updated.
14540 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
14541                                           SelectionDAG &DAG) const {
14542   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
14543   unsigned Opcode = Node->getMachineOpcode();
14544 
14545   if (TII->isImage(Opcode) && !TII->get(Opcode).mayStore() &&
14546       !TII->isGather4(Opcode) &&
14547       AMDGPU::hasNamedOperand(Opcode, AMDGPU::OpName::dmask)) {
14548     return adjustWritemask(Node, DAG);
14549   }
14550 
14551   if (Opcode == AMDGPU::INSERT_SUBREG ||
14552       Opcode == AMDGPU::REG_SEQUENCE) {
14553     legalizeTargetIndependentNode(Node, DAG);
14554     return Node;
14555   }
14556 
14557   switch (Opcode) {
14558   case AMDGPU::V_DIV_SCALE_F32_e64:
14559   case AMDGPU::V_DIV_SCALE_F64_e64: {
14560     // Satisfy the operand register constraint when one of the inputs is
14561     // undefined. Ordinarily each undef value will have its own implicit_def of
14562     // a vreg, so force these to use a single register.
14563     SDValue Src0 = Node->getOperand(1);
14564     SDValue Src1 = Node->getOperand(3);
14565     SDValue Src2 = Node->getOperand(5);
14566 
14567     if ((Src0.isMachineOpcode() &&
14568          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
14569         (Src0 == Src1 || Src0 == Src2))
14570       break;
14571 
14572     MVT VT = Src0.getValueType().getSimpleVT();
14573     const TargetRegisterClass *RC =
14574         getRegClassFor(VT, Src0.getNode()->isDivergent());
14575 
14576     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
14577     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
14578 
14579     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
14580                                       UndefReg, Src0, SDValue());
14581 
14582     // src0 must be the same register as src1 or src2, even if the value is
14583     // undefined, so make sure we don't violate this constraint.
14584     if (Src0.isMachineOpcode() &&
14585         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
14586       if (Src1.isMachineOpcode() &&
14587           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
14588         Src0 = Src1;
14589       else if (Src2.isMachineOpcode() &&
14590                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
14591         Src0 = Src2;
14592       else {
14593         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
14594         Src0 = UndefReg;
14595         Src1 = UndefReg;
14596       }
14597     } else
14598       break;
14599 
14600     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
14601     Ops[1] = Src0;
14602     Ops[3] = Src1;
14603     Ops[5] = Src2;
14604     Ops.push_back(ImpDef.getValue(1));
14605     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
14606   }
14607   default:
14608     break;
14609   }
14610 
14611   return Node;
14612 }
14613 
14614 // Any MIMG instructions that use tfe or lwe require an initialization of the
14615 // result register that will be written in the case of a memory access failure.
14616 // The required code is also added to tie this init code to the result of the
14617 // img instruction.
14618 void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
14619   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
14620   const SIRegisterInfo &TRI = TII->getRegisterInfo();
14621   MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
14622   MachineBasicBlock &MBB = *MI.getParent();
14623 
14624   MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
14625   MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
14626   MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
14627 
14628   if (!TFE && !LWE) // intersect_ray
14629     return;
14630 
14631   unsigned TFEVal = TFE ? TFE->getImm() : 0;
14632   unsigned LWEVal = LWE ? LWE->getImm() : 0;
14633   unsigned D16Val = D16 ? D16->getImm() : 0;
14634 
14635   if (!TFEVal && !LWEVal)
14636     return;
14637 
14638   // At least one of TFE or LWE are non-zero
14639   // We have to insert a suitable initialization of the result value and
14640   // tie this to the dest of the image instruction.
14641 
14642   const DebugLoc &DL = MI.getDebugLoc();
14643 
14644   int DstIdx =
14645       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
14646 
14647   // Calculate which dword we have to initialize to 0.
14648   MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
14649 
14650   // check that dmask operand is found.
14651   assert(MO_Dmask && "Expected dmask operand in instruction");
14652 
14653   unsigned dmask = MO_Dmask->getImm();
14654   // Determine the number of active lanes taking into account the
14655   // Gather4 special case
14656   unsigned ActiveLanes = TII->isGather4(MI) ? 4 : llvm::popcount(dmask);
14657 
14658   bool Packed = !Subtarget->hasUnpackedD16VMem();
14659 
14660   unsigned InitIdx =
14661       D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
14662 
14663   // Abandon attempt if the dst size isn't large enough
14664   // - this is in fact an error but this is picked up elsewhere and
14665   // reported correctly.
14666   uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
14667   if (DstSize < InitIdx)
14668     return;
14669 
14670   // Create a register for the initialization value.
14671   Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
14672   unsigned NewDst = 0; // Final initialized value will be in here
14673 
14674   // If PRTStrictNull feature is enabled (the default) then initialize
14675   // all the result registers to 0, otherwise just the error indication
14676   // register (VGPRn+1)
14677   unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
14678   unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
14679 
14680   BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
14681   for (; SizeLeft; SizeLeft--, CurrIdx++) {
14682     NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
14683     // Initialize dword
14684     Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
14685     BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
14686       .addImm(0);
14687     // Insert into the super-reg
14688     BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
14689       .addReg(PrevDst)
14690       .addReg(SubReg)
14691       .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
14692 
14693     PrevDst = NewDst;
14694   }
14695 
14696   // Add as an implicit operand
14697   MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
14698 
14699   // Tie the just added implicit operand to the dst
14700   MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
14701 }
14702 
14703 /// Assign the register class depending on the number of
14704 /// bits set in the writemask
14705 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
14706                                                      SDNode *Node) const {
14707   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
14708 
14709   MachineFunction *MF = MI.getParent()->getParent();
14710   MachineRegisterInfo &MRI = MF->getRegInfo();
14711   SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
14712 
14713   if (TII->isVOP3(MI.getOpcode())) {
14714     // Make sure constant bus requirements are respected.
14715     TII->legalizeOperandsVOP3(MRI, MI);
14716 
14717     // Prefer VGPRs over AGPRs in mAI instructions where possible.
14718     // This saves a chain-copy of registers and better balance register
14719     // use between vgpr and agpr as agpr tuples tend to be big.
14720     if (!MI.getDesc().operands().empty()) {
14721       unsigned Opc = MI.getOpcode();
14722       bool HasAGPRs = Info->mayNeedAGPRs();
14723       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
14724       int16_t Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2);
14725       for (auto I :
14726            {AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
14727             AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1), Src2Idx}) {
14728         if (I == -1)
14729           break;
14730         if ((I == Src2Idx) && (HasAGPRs))
14731           break;
14732         MachineOperand &Op = MI.getOperand(I);
14733         if (!Op.isReg() || !Op.getReg().isVirtual())
14734           continue;
14735         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
14736         if (!TRI->hasAGPRs(RC))
14737           continue;
14738         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
14739         if (!Src || !Src->isCopy() ||
14740             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
14741           continue;
14742         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
14743         // All uses of agpr64 and agpr32 can also accept vgpr except for
14744         // v_accvgpr_read, but we do not produce agpr reads during selection,
14745         // so no use checks are needed.
14746         MRI.setRegClass(Op.getReg(), NewRC);
14747       }
14748 
14749       if (!HasAGPRs)
14750         return;
14751 
14752       // Resolve the rest of AV operands to AGPRs.
14753       if (auto *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2)) {
14754         if (Src2->isReg() && Src2->getReg().isVirtual()) {
14755           auto *RC = TRI->getRegClassForReg(MRI, Src2->getReg());
14756           if (TRI->isVectorSuperClass(RC)) {
14757             auto *NewRC = TRI->getEquivalentAGPRClass(RC);
14758             MRI.setRegClass(Src2->getReg(), NewRC);
14759             if (Src2->isTied())
14760               MRI.setRegClass(MI.getOperand(0).getReg(), NewRC);
14761           }
14762         }
14763       }
14764     }
14765 
14766     return;
14767   }
14768 
14769   if (TII->isImage(MI)) {
14770     if (!MI.mayStore())
14771       AddIMGInit(MI);
14772     TII->enforceOperandRCAlignment(MI, AMDGPU::OpName::vaddr);
14773   }
14774 }
14775 
14776 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
14777                               uint64_t Val) {
14778   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
14779   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
14780 }
14781 
14782 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
14783                                                 const SDLoc &DL,
14784                                                 SDValue Ptr) const {
14785   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
14786 
14787   // Build the half of the subregister with the constants before building the
14788   // full 128-bit register. If we are building multiple resource descriptors,
14789   // this will allow CSEing of the 2-component register.
14790   const SDValue Ops0[] = {
14791     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
14792     buildSMovImm32(DAG, DL, 0),
14793     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
14794     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
14795     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
14796   };
14797 
14798   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
14799                                                 MVT::v2i32, Ops0), 0);
14800 
14801   // Combine the constants and the pointer.
14802   const SDValue Ops1[] = {
14803     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
14804     Ptr,
14805     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
14806     SubRegHi,
14807     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
14808   };
14809 
14810   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
14811 }
14812 
14813 /// Return a resource descriptor with the 'Add TID' bit enabled
14814 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
14815 ///        of the resource descriptor) to create an offset, which is added to
14816 ///        the resource pointer.
14817 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
14818                                            SDValue Ptr, uint32_t RsrcDword1,
14819                                            uint64_t RsrcDword2And3) const {
14820   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
14821   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
14822   if (RsrcDword1) {
14823     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
14824                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
14825                     0);
14826   }
14827 
14828   SDValue DataLo = buildSMovImm32(DAG, DL,
14829                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
14830   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
14831 
14832   const SDValue Ops[] = {
14833     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
14834     PtrLo,
14835     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
14836     PtrHi,
14837     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
14838     DataLo,
14839     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
14840     DataHi,
14841     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
14842   };
14843 
14844   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
14845 }
14846 
14847 //===----------------------------------------------------------------------===//
14848 //                         SI Inline Assembly Support
14849 //===----------------------------------------------------------------------===//
14850 
14851 std::pair<unsigned, const TargetRegisterClass *>
14852 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
14853                                                StringRef Constraint,
14854                                                MVT VT) const {
14855   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
14856 
14857   const TargetRegisterClass *RC = nullptr;
14858   if (Constraint.size() == 1) {
14859     const unsigned BitWidth = VT.getSizeInBits();
14860     switch (Constraint[0]) {
14861     default:
14862       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
14863     case 's':
14864     case 'r':
14865       switch (BitWidth) {
14866       case 16:
14867         RC = &AMDGPU::SReg_32RegClass;
14868         break;
14869       case 64:
14870         RC = &AMDGPU::SGPR_64RegClass;
14871         break;
14872       default:
14873         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
14874         if (!RC)
14875           return std::pair(0U, nullptr);
14876         break;
14877       }
14878       break;
14879     case 'v':
14880       switch (BitWidth) {
14881       case 16:
14882         RC = &AMDGPU::VGPR_32RegClass;
14883         break;
14884       default:
14885         RC = TRI->getVGPRClassForBitWidth(BitWidth);
14886         if (!RC)
14887           return std::pair(0U, nullptr);
14888         break;
14889       }
14890       break;
14891     case 'a':
14892       if (!Subtarget->hasMAIInsts())
14893         break;
14894       switch (BitWidth) {
14895       case 16:
14896         RC = &AMDGPU::AGPR_32RegClass;
14897         break;
14898       default:
14899         RC = TRI->getAGPRClassForBitWidth(BitWidth);
14900         if (!RC)
14901           return std::pair(0U, nullptr);
14902         break;
14903       }
14904       break;
14905     }
14906     // We actually support i128, i16 and f16 as inline parameters
14907     // even if they are not reported as legal
14908     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
14909                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
14910       return std::pair(0U, RC);
14911   }
14912 
14913   if (Constraint.starts_with("{") && Constraint.ends_with("}")) {
14914     StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
14915     if (RegName.consume_front("v")) {
14916       RC = &AMDGPU::VGPR_32RegClass;
14917     } else if (RegName.consume_front("s")) {
14918       RC = &AMDGPU::SGPR_32RegClass;
14919     } else if (RegName.consume_front("a")) {
14920       RC = &AMDGPU::AGPR_32RegClass;
14921     }
14922 
14923     if (RC) {
14924       uint32_t Idx;
14925       if (RegName.consume_front("[")) {
14926         uint32_t End;
14927         bool Failed = RegName.consumeInteger(10, Idx);
14928         Failed |= !RegName.consume_front(":");
14929         Failed |= RegName.consumeInteger(10, End);
14930         Failed |= !RegName.consume_back("]");
14931         if (!Failed) {
14932           uint32_t Width = (End - Idx + 1) * 32;
14933           MCRegister Reg = RC->getRegister(Idx);
14934           if (SIRegisterInfo::isVGPRClass(RC))
14935             RC = TRI->getVGPRClassForBitWidth(Width);
14936           else if (SIRegisterInfo::isSGPRClass(RC))
14937             RC = TRI->getSGPRClassForBitWidth(Width);
14938           else if (SIRegisterInfo::isAGPRClass(RC))
14939             RC = TRI->getAGPRClassForBitWidth(Width);
14940           if (RC) {
14941             Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC);
14942             return std::pair(Reg, RC);
14943           }
14944         }
14945       } else {
14946         bool Failed = RegName.getAsInteger(10, Idx);
14947         if (!Failed && Idx < RC->getNumRegs())
14948           return std::pair(RC->getRegister(Idx), RC);
14949       }
14950     }
14951   }
14952 
14953   auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
14954   if (Ret.first)
14955     Ret.second = TRI->getPhysRegBaseClass(Ret.first);
14956 
14957   return Ret;
14958 }
14959 
14960 static bool isImmConstraint(StringRef Constraint) {
14961   if (Constraint.size() == 1) {
14962     switch (Constraint[0]) {
14963     default: break;
14964     case 'I':
14965     case 'J':
14966     case 'A':
14967     case 'B':
14968     case 'C':
14969       return true;
14970     }
14971   } else if (Constraint == "DA" ||
14972              Constraint == "DB") {
14973     return true;
14974   }
14975   return false;
14976 }
14977 
14978 SITargetLowering::ConstraintType
14979 SITargetLowering::getConstraintType(StringRef Constraint) const {
14980   if (Constraint.size() == 1) {
14981     switch (Constraint[0]) {
14982     default: break;
14983     case 's':
14984     case 'v':
14985     case 'a':
14986       return C_RegisterClass;
14987     }
14988   }
14989   if (isImmConstraint(Constraint)) {
14990     return C_Other;
14991   }
14992   return TargetLowering::getConstraintType(Constraint);
14993 }
14994 
14995 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
14996   if (!AMDGPU::isInlinableIntLiteral(Val)) {
14997     Val = Val & maskTrailingOnes<uint64_t>(Size);
14998   }
14999   return Val;
15000 }
15001 
15002 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15003                                                     StringRef Constraint,
15004                                                     std::vector<SDValue> &Ops,
15005                                                     SelectionDAG &DAG) const {
15006   if (isImmConstraint(Constraint)) {
15007     uint64_t Val;
15008     if (getAsmOperandConstVal(Op, Val) &&
15009         checkAsmConstraintVal(Op, Constraint, Val)) {
15010       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
15011       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
15012     }
15013   } else {
15014     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15015   }
15016 }
15017 
15018 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
15019   unsigned Size = Op.getScalarValueSizeInBits();
15020   if (Size > 64)
15021     return false;
15022 
15023   if (Size == 16 && !Subtarget->has16BitInsts())
15024     return false;
15025 
15026   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15027     Val = C->getSExtValue();
15028     return true;
15029   }
15030   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
15031     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
15032     return true;
15033   }
15034   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
15035     if (Size != 16 || Op.getNumOperands() != 2)
15036       return false;
15037     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
15038       return false;
15039     if (ConstantSDNode *C = V->getConstantSplatNode()) {
15040       Val = C->getSExtValue();
15041       return true;
15042     }
15043     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
15044       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
15045       return true;
15046     }
15047   }
15048 
15049   return false;
15050 }
15051 
15052 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, StringRef Constraint,
15053                                              uint64_t Val) const {
15054   if (Constraint.size() == 1) {
15055     switch (Constraint[0]) {
15056     case 'I':
15057       return AMDGPU::isInlinableIntLiteral(Val);
15058     case 'J':
15059       return isInt<16>(Val);
15060     case 'A':
15061       return checkAsmConstraintValA(Op, Val);
15062     case 'B':
15063       return isInt<32>(Val);
15064     case 'C':
15065       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
15066              AMDGPU::isInlinableIntLiteral(Val);
15067     default:
15068       break;
15069     }
15070   } else if (Constraint.size() == 2) {
15071     if (Constraint == "DA") {
15072       int64_t HiBits = static_cast<int32_t>(Val >> 32);
15073       int64_t LoBits = static_cast<int32_t>(Val);
15074       return checkAsmConstraintValA(Op, HiBits, 32) &&
15075              checkAsmConstraintValA(Op, LoBits, 32);
15076     }
15077     if (Constraint == "DB") {
15078       return true;
15079     }
15080   }
15081   llvm_unreachable("Invalid asm constraint");
15082 }
15083 
15084 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
15085                                               uint64_t Val,
15086                                               unsigned MaxSize) const {
15087   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
15088   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
15089   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
15090       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
15091       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
15092     return true;
15093   }
15094   return false;
15095 }
15096 
15097 static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
15098   switch (UnalignedClassID) {
15099   case AMDGPU::VReg_64RegClassID:
15100     return AMDGPU::VReg_64_Align2RegClassID;
15101   case AMDGPU::VReg_96RegClassID:
15102     return AMDGPU::VReg_96_Align2RegClassID;
15103   case AMDGPU::VReg_128RegClassID:
15104     return AMDGPU::VReg_128_Align2RegClassID;
15105   case AMDGPU::VReg_160RegClassID:
15106     return AMDGPU::VReg_160_Align2RegClassID;
15107   case AMDGPU::VReg_192RegClassID:
15108     return AMDGPU::VReg_192_Align2RegClassID;
15109   case AMDGPU::VReg_224RegClassID:
15110     return AMDGPU::VReg_224_Align2RegClassID;
15111   case AMDGPU::VReg_256RegClassID:
15112     return AMDGPU::VReg_256_Align2RegClassID;
15113   case AMDGPU::VReg_288RegClassID:
15114     return AMDGPU::VReg_288_Align2RegClassID;
15115   case AMDGPU::VReg_320RegClassID:
15116     return AMDGPU::VReg_320_Align2RegClassID;
15117   case AMDGPU::VReg_352RegClassID:
15118     return AMDGPU::VReg_352_Align2RegClassID;
15119   case AMDGPU::VReg_384RegClassID:
15120     return AMDGPU::VReg_384_Align2RegClassID;
15121   case AMDGPU::VReg_512RegClassID:
15122     return AMDGPU::VReg_512_Align2RegClassID;
15123   case AMDGPU::VReg_1024RegClassID:
15124     return AMDGPU::VReg_1024_Align2RegClassID;
15125   case AMDGPU::AReg_64RegClassID:
15126     return AMDGPU::AReg_64_Align2RegClassID;
15127   case AMDGPU::AReg_96RegClassID:
15128     return AMDGPU::AReg_96_Align2RegClassID;
15129   case AMDGPU::AReg_128RegClassID:
15130     return AMDGPU::AReg_128_Align2RegClassID;
15131   case AMDGPU::AReg_160RegClassID:
15132     return AMDGPU::AReg_160_Align2RegClassID;
15133   case AMDGPU::AReg_192RegClassID:
15134     return AMDGPU::AReg_192_Align2RegClassID;
15135   case AMDGPU::AReg_256RegClassID:
15136     return AMDGPU::AReg_256_Align2RegClassID;
15137   case AMDGPU::AReg_512RegClassID:
15138     return AMDGPU::AReg_512_Align2RegClassID;
15139   case AMDGPU::AReg_1024RegClassID:
15140     return AMDGPU::AReg_1024_Align2RegClassID;
15141   default:
15142     return -1;
15143   }
15144 }
15145 
15146 // Figure out which registers should be reserved for stack access. Only after
15147 // the function is legalized do we know all of the non-spill stack objects or if
15148 // calls are present.
15149 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
15150   MachineRegisterInfo &MRI = MF.getRegInfo();
15151   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
15152   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
15153   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
15154   const SIInstrInfo *TII = ST.getInstrInfo();
15155 
15156   if (Info->isEntryFunction()) {
15157     // Callable functions have fixed registers used for stack access.
15158     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
15159   }
15160 
15161   // TODO: Move this logic to getReservedRegs()
15162   // Reserve the SGPR(s) to save/restore EXEC for WWM spill/copy handling.
15163   unsigned MaxNumSGPRs = ST.getMaxNumSGPRs(MF);
15164   Register SReg = ST.isWave32()
15165                       ? AMDGPU::SGPR_32RegClass.getRegister(MaxNumSGPRs - 1)
15166                       : TRI->getAlignedHighSGPRForRC(MF, /*Align=*/2,
15167                                                      &AMDGPU::SGPR_64RegClass);
15168   Info->setSGPRForEXECCopy(SReg);
15169 
15170   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
15171                              Info->getStackPtrOffsetReg()));
15172   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
15173     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
15174 
15175   // We need to worry about replacing the default register with itself in case
15176   // of MIR testcases missing the MFI.
15177   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
15178     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
15179 
15180   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
15181     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
15182 
15183   Info->limitOccupancy(MF);
15184 
15185   if (ST.isWave32() && !MF.empty()) {
15186     for (auto &MBB : MF) {
15187       for (auto &MI : MBB) {
15188         TII->fixImplicitOperands(MI);
15189       }
15190     }
15191   }
15192 
15193   // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
15194   // classes if required. Ideally the register class constraints would differ
15195   // per-subtarget, but there's no easy way to achieve that right now. This is
15196   // not a problem for VGPRs because the correctly aligned VGPR class is implied
15197   // from using them as the register class for legal types.
15198   if (ST.needsAlignedVGPRs()) {
15199     for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
15200       const Register Reg = Register::index2VirtReg(I);
15201       const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
15202       if (!RC)
15203         continue;
15204       int NewClassID = getAlignedAGPRClassID(RC->getID());
15205       if (NewClassID != -1)
15206         MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
15207     }
15208   }
15209 
15210   TargetLoweringBase::finalizeLowering(MF);
15211 }
15212 
15213 void SITargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
15214                                                      KnownBits &Known,
15215                                                      const APInt &DemandedElts,
15216                                                      const SelectionDAG &DAG,
15217                                                      unsigned Depth) const {
15218   Known.resetAll();
15219   unsigned Opc = Op.getOpcode();
15220   switch (Opc) {
15221   case ISD::INTRINSIC_WO_CHAIN: {
15222     unsigned IID = Op.getConstantOperandVal(0);
15223     switch (IID) {
15224     case Intrinsic::amdgcn_mbcnt_lo:
15225     case Intrinsic::amdgcn_mbcnt_hi: {
15226       const GCNSubtarget &ST =
15227           DAG.getMachineFunction().getSubtarget<GCNSubtarget>();
15228       // These return at most the (wavefront size - 1) + src1
15229       // As long as src1 is an immediate we can calc known bits
15230       KnownBits Src1Known = DAG.computeKnownBits(Op.getOperand(2), Depth + 1);
15231       unsigned Src1ValBits = Src1Known.countMaxActiveBits();
15232       unsigned MaxActiveBits = std::max(Src1ValBits, ST.getWavefrontSizeLog2());
15233       // Cater for potential carry
15234       MaxActiveBits += Src1ValBits ? 1 : 0;
15235       unsigned Size = Op.getValueType().getSizeInBits();
15236       if (MaxActiveBits < Size)
15237         Known.Zero.setHighBits(Size - MaxActiveBits);
15238       return;
15239     }
15240     }
15241     break;
15242   }
15243   }
15244   return AMDGPUTargetLowering::computeKnownBitsForTargetNode(
15245       Op, Known, DemandedElts, DAG, Depth);
15246 }
15247 
15248 void SITargetLowering::computeKnownBitsForFrameIndex(
15249   const int FI, KnownBits &Known, const MachineFunction &MF) const {
15250   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
15251 
15252   // Set the high bits to zero based on the maximum allowed scratch size per
15253   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
15254   // calculation won't overflow, so assume the sign bit is never set.
15255   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
15256 }
15257 
15258 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
15259                                    KnownBits &Known, unsigned Dim) {
15260   unsigned MaxValue =
15261       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
15262   Known.Zero.setHighBits(llvm::countl_zero(MaxValue));
15263 }
15264 
15265 void SITargetLowering::computeKnownBitsForTargetInstr(
15266     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
15267     const MachineRegisterInfo &MRI, unsigned Depth) const {
15268   const MachineInstr *MI = MRI.getVRegDef(R);
15269   switch (MI->getOpcode()) {
15270   case AMDGPU::G_INTRINSIC:
15271   case AMDGPU::G_INTRINSIC_CONVERGENT: {
15272     switch (cast<GIntrinsic>(MI)->getIntrinsicID()) {
15273     case Intrinsic::amdgcn_workitem_id_x:
15274       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
15275       break;
15276     case Intrinsic::amdgcn_workitem_id_y:
15277       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
15278       break;
15279     case Intrinsic::amdgcn_workitem_id_z:
15280       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
15281       break;
15282     case Intrinsic::amdgcn_mbcnt_lo:
15283     case Intrinsic::amdgcn_mbcnt_hi: {
15284       // These return at most the wavefront size - 1.
15285       unsigned Size = MRI.getType(R).getSizeInBits();
15286       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
15287       break;
15288     }
15289     case Intrinsic::amdgcn_groupstaticsize: {
15290       // We can report everything over the maximum size as 0. We can't report
15291       // based on the actual size because we don't know if it's accurate or not
15292       // at any given point.
15293       Known.Zero.setHighBits(
15294           llvm::countl_zero(getSubtarget()->getAddressableLocalMemorySize()));
15295       break;
15296     }
15297     }
15298     break;
15299   }
15300   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
15301     Known.Zero.setHighBits(24);
15302     break;
15303   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
15304     Known.Zero.setHighBits(16);
15305     break;
15306   case AMDGPU::G_AMDGPU_SMED3:
15307   case AMDGPU::G_AMDGPU_UMED3: {
15308     auto [Dst, Src0, Src1, Src2] = MI->getFirst4Regs();
15309 
15310     KnownBits Known2;
15311     KB.computeKnownBitsImpl(Src2, Known2, DemandedElts, Depth + 1);
15312     if (Known2.isUnknown())
15313       break;
15314 
15315     KnownBits Known1;
15316     KB.computeKnownBitsImpl(Src1, Known1, DemandedElts, Depth + 1);
15317     if (Known1.isUnknown())
15318       break;
15319 
15320     KnownBits Known0;
15321     KB.computeKnownBitsImpl(Src0, Known0, DemandedElts, Depth + 1);
15322     if (Known0.isUnknown())
15323       break;
15324 
15325     // TODO: Handle LeadZero/LeadOne from UMIN/UMAX handling.
15326     Known.Zero = Known0.Zero & Known1.Zero & Known2.Zero;
15327     Known.One = Known0.One & Known1.One & Known2.One;
15328     break;
15329   }
15330   }
15331 }
15332 
15333 Align SITargetLowering::computeKnownAlignForTargetInstr(
15334   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
15335   unsigned Depth) const {
15336   const MachineInstr *MI = MRI.getVRegDef(R);
15337   if (auto *GI = dyn_cast<GIntrinsic>(MI)) {
15338     // FIXME: Can this move to generic code? What about the case where the call
15339     // site specifies a lower alignment?
15340     Intrinsic::ID IID = GI->getIntrinsicID();
15341     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
15342     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
15343     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
15344       return *RetAlign;
15345   }
15346   return Align(1);
15347 }
15348 
15349 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
15350   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
15351   const Align CacheLineAlign = Align(64);
15352 
15353   // Pre-GFX10 target did not benefit from loop alignment
15354   if (!ML || DisableLoopAlignment || !getSubtarget()->hasInstPrefetch() ||
15355       getSubtarget()->hasInstFwdPrefetchBug())
15356     return PrefAlign;
15357 
15358   // On GFX10 I$ is 4 x 64 bytes cache lines.
15359   // By default prefetcher keeps one cache line behind and reads two ahead.
15360   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
15361   // behind and one ahead.
15362   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
15363   // If loop fits 64 bytes it always spans no more than two cache lines and
15364   // does not need an alignment.
15365   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
15366   // Else if loop is less or equal 192 bytes we need two lines behind.
15367 
15368   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
15369   const MachineBasicBlock *Header = ML->getHeader();
15370   if (Header->getAlignment() != PrefAlign)
15371     return Header->getAlignment(); // Already processed.
15372 
15373   unsigned LoopSize = 0;
15374   for (const MachineBasicBlock *MBB : ML->blocks()) {
15375     // If inner loop block is aligned assume in average half of the alignment
15376     // size to be added as nops.
15377     if (MBB != Header)
15378       LoopSize += MBB->getAlignment().value() / 2;
15379 
15380     for (const MachineInstr &MI : *MBB) {
15381       LoopSize += TII->getInstSizeInBytes(MI);
15382       if (LoopSize > 192)
15383         return PrefAlign;
15384     }
15385   }
15386 
15387   if (LoopSize <= 64)
15388     return PrefAlign;
15389 
15390   if (LoopSize <= 128)
15391     return CacheLineAlign;
15392 
15393   // If any of parent loops is surrounded by prefetch instructions do not
15394   // insert new for inner loop, which would reset parent's settings.
15395   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
15396     if (MachineBasicBlock *Exit = P->getExitBlock()) {
15397       auto I = Exit->getFirstNonDebugInstr();
15398       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
15399         return CacheLineAlign;
15400     }
15401   }
15402 
15403   MachineBasicBlock *Pre = ML->getLoopPreheader();
15404   MachineBasicBlock *Exit = ML->getExitBlock();
15405 
15406   if (Pre && Exit) {
15407     auto PreTerm = Pre->getFirstTerminator();
15408     if (PreTerm == Pre->begin() ||
15409         std::prev(PreTerm)->getOpcode() != AMDGPU::S_INST_PREFETCH)
15410       BuildMI(*Pre, PreTerm, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH))
15411           .addImm(1); // prefetch 2 lines behind PC
15412 
15413     auto ExitHead = Exit->getFirstNonDebugInstr();
15414     if (ExitHead == Exit->end() ||
15415         ExitHead->getOpcode() != AMDGPU::S_INST_PREFETCH)
15416       BuildMI(*Exit, ExitHead, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH))
15417           .addImm(2); // prefetch 1 line behind PC
15418   }
15419 
15420   return CacheLineAlign;
15421 }
15422 
15423 LLVM_ATTRIBUTE_UNUSED
15424 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
15425   assert(N->getOpcode() == ISD::CopyFromReg);
15426   do {
15427     // Follow the chain until we find an INLINEASM node.
15428     N = N->getOperand(0).getNode();
15429     if (N->getOpcode() == ISD::INLINEASM ||
15430         N->getOpcode() == ISD::INLINEASM_BR)
15431       return true;
15432   } while (N->getOpcode() == ISD::CopyFromReg);
15433   return false;
15434 }
15435 
15436 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode *N,
15437                                                   FunctionLoweringInfo *FLI,
15438                                                   UniformityInfo *UA) const {
15439   switch (N->getOpcode()) {
15440   case ISD::CopyFromReg: {
15441     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
15442     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
15443     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
15444     Register Reg = R->getReg();
15445 
15446     // FIXME: Why does this need to consider isLiveIn?
15447     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
15448       return !TRI->isSGPRReg(MRI, Reg);
15449 
15450     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
15451       return UA->isDivergent(V);
15452 
15453     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
15454     return !TRI->isSGPRReg(MRI, Reg);
15455   }
15456   case ISD::LOAD: {
15457     const LoadSDNode *L = cast<LoadSDNode>(N);
15458     unsigned AS = L->getAddressSpace();
15459     // A flat load may access private memory.
15460     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
15461   }
15462   case ISD::CALLSEQ_END:
15463     return true;
15464   case ISD::INTRINSIC_WO_CHAIN:
15465     return AMDGPU::isIntrinsicSourceOfDivergence(N->getConstantOperandVal(0));
15466   case ISD::INTRINSIC_W_CHAIN:
15467     return AMDGPU::isIntrinsicSourceOfDivergence(N->getConstantOperandVal(1));
15468   case AMDGPUISD::ATOMIC_CMP_SWAP:
15469   case AMDGPUISD::ATOMIC_LOAD_FMIN:
15470   case AMDGPUISD::ATOMIC_LOAD_FMAX:
15471   case AMDGPUISD::BUFFER_ATOMIC_SWAP:
15472   case AMDGPUISD::BUFFER_ATOMIC_ADD:
15473   case AMDGPUISD::BUFFER_ATOMIC_SUB:
15474   case AMDGPUISD::BUFFER_ATOMIC_SMIN:
15475   case AMDGPUISD::BUFFER_ATOMIC_UMIN:
15476   case AMDGPUISD::BUFFER_ATOMIC_SMAX:
15477   case AMDGPUISD::BUFFER_ATOMIC_UMAX:
15478   case AMDGPUISD::BUFFER_ATOMIC_AND:
15479   case AMDGPUISD::BUFFER_ATOMIC_OR:
15480   case AMDGPUISD::BUFFER_ATOMIC_XOR:
15481   case AMDGPUISD::BUFFER_ATOMIC_INC:
15482   case AMDGPUISD::BUFFER_ATOMIC_DEC:
15483   case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
15484   case AMDGPUISD::BUFFER_ATOMIC_CSUB:
15485   case AMDGPUISD::BUFFER_ATOMIC_FADD:
15486   case AMDGPUISD::BUFFER_ATOMIC_FMIN:
15487   case AMDGPUISD::BUFFER_ATOMIC_FMAX:
15488     // Target-specific read-modify-write atomics are sources of divergence.
15489     return true;
15490   default:
15491     if (auto *A = dyn_cast<AtomicSDNode>(N)) {
15492       // Generic read-modify-write atomics are sources of divergence.
15493       return A->readMem() && A->writeMem();
15494     }
15495     return false;
15496   }
15497 }
15498 
15499 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
15500                                                EVT VT) const {
15501   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
15502   case MVT::f32:
15503     return !denormalModeIsFlushAllF32(DAG.getMachineFunction());
15504   case MVT::f64:
15505   case MVT::f16:
15506     return !denormalModeIsFlushAllF64F16(DAG.getMachineFunction());
15507   default:
15508     return false;
15509   }
15510 }
15511 
15512 bool SITargetLowering::denormalsEnabledForType(LLT Ty,
15513                                                MachineFunction &MF) const {
15514   switch (Ty.getScalarSizeInBits()) {
15515   case 32:
15516     return !denormalModeIsFlushAllF32(MF);
15517   case 64:
15518   case 16:
15519     return !denormalModeIsFlushAllF64F16(MF);
15520   default:
15521     return false;
15522   }
15523 }
15524 
15525 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
15526                                                     const SelectionDAG &DAG,
15527                                                     bool SNaN,
15528                                                     unsigned Depth) const {
15529   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
15530     const MachineFunction &MF = DAG.getMachineFunction();
15531     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
15532 
15533     if (Info->getMode().DX10Clamp)
15534       return true; // Clamped to 0.
15535     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
15536   }
15537 
15538   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
15539                                                             SNaN, Depth);
15540 }
15541 
15542 // Global FP atomic instructions have a hardcoded FP mode and do not support
15543 // FP32 denormals, and only support v2f16 denormals.
15544 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
15545   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
15546   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
15547   if (&Flt == &APFloat::IEEEsingle())
15548     return DenormMode == DenormalMode::getPreserveSign();
15549   return DenormMode == DenormalMode::getIEEE();
15550 }
15551 
15552 // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
15553 // floating point atomic instructions. May generate more efficient code,
15554 // but may not respect rounding and denormal modes, and may give incorrect
15555 // results for certain memory destinations.
15556 bool unsafeFPAtomicsDisabled(Function *F) {
15557   return F->getFnAttribute("amdgpu-unsafe-fp-atomics").getValueAsString() !=
15558          "true";
15559 }
15560 
15561 TargetLowering::AtomicExpansionKind
15562 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
15563   unsigned AS = RMW->getPointerAddressSpace();
15564   if (AS == AMDGPUAS::PRIVATE_ADDRESS)
15565     return AtomicExpansionKind::NotAtomic;
15566 
15567   auto SSID = RMW->getSyncScopeID();
15568 
15569   auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) {
15570     OptimizationRemarkEmitter ORE(RMW->getFunction());
15571     LLVMContext &Ctx = RMW->getFunction()->getContext();
15572     SmallVector<StringRef> SSNs;
15573     Ctx.getSyncScopeNames(SSNs);
15574     auto MemScope = SSNs[RMW->getSyncScopeID()].empty()
15575                         ? "system"
15576                         : SSNs[RMW->getSyncScopeID()];
15577     ORE.emit([&]() {
15578       return OptimizationRemark(DEBUG_TYPE, "Passed", RMW)
15579              << "Hardware instruction generated for atomic "
15580              << RMW->getOperationName(RMW->getOperation())
15581              << " operation at memory scope " << MemScope
15582              << " due to an unsafe request.";
15583     });
15584     return Kind;
15585   };
15586 
15587   bool HasSystemScope =
15588       SSID == SyncScope::System ||
15589       SSID == RMW->getContext().getOrInsertSyncScopeID("one-as");
15590 
15591   switch (RMW->getOperation()) {
15592   case AtomicRMWInst::FAdd: {
15593     Type *Ty = RMW->getType();
15594 
15595     if (Ty->isHalfTy())
15596       return AtomicExpansionKind::CmpXChg;
15597 
15598     if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
15599       return AtomicExpansionKind::CmpXChg;
15600 
15601     if (AMDGPU::isFlatGlobalAddrSpace(AS) &&
15602         Subtarget->hasAtomicFaddNoRtnInsts()) {
15603       if (Subtarget->hasGFX940Insts())
15604         return AtomicExpansionKind::None;
15605 
15606       if (unsafeFPAtomicsDisabled(RMW->getFunction()))
15607         return AtomicExpansionKind::CmpXChg;
15608 
15609       // Always expand system scope fp atomics.
15610       if (HasSystemScope)
15611         return AtomicExpansionKind::CmpXChg;
15612 
15613       if (AS == AMDGPUAS::GLOBAL_ADDRESS && Ty->isFloatTy()) {
15614         // global atomic fadd f32 no-rtn: gfx908, gfx90a, gfx940, gfx11+.
15615         if (RMW->use_empty() && Subtarget->hasAtomicFaddNoRtnInsts())
15616           return ReportUnsafeHWInst(AtomicExpansionKind::None);
15617         // global atomic fadd f32 rtn: gfx90a, gfx940, gfx11+.
15618         if (!RMW->use_empty() && Subtarget->hasAtomicFaddRtnInsts())
15619           return ReportUnsafeHWInst(AtomicExpansionKind::None);
15620       }
15621 
15622       // flat atomic fadd f32: gfx940, gfx11+.
15623       if (AS == AMDGPUAS::FLAT_ADDRESS && Ty->isFloatTy() &&
15624           Subtarget->hasFlatAtomicFaddF32Inst())
15625         return ReportUnsafeHWInst(AtomicExpansionKind::None);
15626 
15627       // global and flat atomic fadd f64: gfx90a, gfx940.
15628       if (Ty->isDoubleTy() && Subtarget->hasGFX90AInsts())
15629         return ReportUnsafeHWInst(AtomicExpansionKind::None);
15630 
15631       // If it is in flat address space, and the type is float, we will try to
15632       // expand it, if the target supports global and lds atomic fadd. The
15633       // reason we need that is, in the expansion, we emit the check of address
15634       // space. If it is in global address space, we emit the global atomic
15635       // fadd; if it is in shared address space, we emit the LDS atomic fadd.
15636       if (AS == AMDGPUAS::FLAT_ADDRESS && Ty->isFloatTy() &&
15637           Subtarget->hasLDSFPAtomicAdd()) {
15638         if (RMW->use_empty() && Subtarget->hasAtomicFaddNoRtnInsts())
15639           return AtomicExpansionKind::Expand;
15640         if (!RMW->use_empty() && Subtarget->hasAtomicFaddRtnInsts())
15641           return AtomicExpansionKind::Expand;
15642       }
15643 
15644       return AtomicExpansionKind::CmpXChg;
15645     }
15646 
15647     // DS FP atomics do respect the denormal mode, but the rounding mode is
15648     // fixed to round-to-nearest-even.
15649     // The only exception is DS_ADD_F64 which never flushes regardless of mode.
15650     if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) {
15651       if (!Ty->isDoubleTy())
15652         return AtomicExpansionKind::None;
15653 
15654       if (fpModeMatchesGlobalFPAtomicMode(RMW))
15655         return AtomicExpansionKind::None;
15656 
15657       return RMW->getFunction()
15658                          ->getFnAttribute("amdgpu-unsafe-fp-atomics")
15659                          .getValueAsString() == "true"
15660                  ? ReportUnsafeHWInst(AtomicExpansionKind::None)
15661                  : AtomicExpansionKind::CmpXChg;
15662     }
15663 
15664     return AtomicExpansionKind::CmpXChg;
15665   }
15666   case AtomicRMWInst::FMin:
15667   case AtomicRMWInst::FMax:
15668   case AtomicRMWInst::Min:
15669   case AtomicRMWInst::Max:
15670   case AtomicRMWInst::UMin:
15671   case AtomicRMWInst::UMax: {
15672     if (AMDGPU::isFlatGlobalAddrSpace(AS)) {
15673       if (RMW->getType()->isFloatTy() &&
15674           unsafeFPAtomicsDisabled(RMW->getFunction()))
15675         return AtomicExpansionKind::CmpXChg;
15676 
15677       // Always expand system scope min/max atomics.
15678       if (HasSystemScope)
15679         return AtomicExpansionKind::CmpXChg;
15680     }
15681     break;
15682   }
15683   default:
15684     break;
15685   }
15686 
15687   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
15688 }
15689 
15690 TargetLowering::AtomicExpansionKind
15691 SITargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
15692   return LI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
15693              ? AtomicExpansionKind::NotAtomic
15694              : AtomicExpansionKind::None;
15695 }
15696 
15697 TargetLowering::AtomicExpansionKind
15698 SITargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
15699   return SI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
15700              ? AtomicExpansionKind::NotAtomic
15701              : AtomicExpansionKind::None;
15702 }
15703 
15704 TargetLowering::AtomicExpansionKind
15705 SITargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *CmpX) const {
15706   return CmpX->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
15707              ? AtomicExpansionKind::NotAtomic
15708              : AtomicExpansionKind::None;
15709 }
15710 
15711 const TargetRegisterClass *
15712 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
15713   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
15714   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
15715   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
15716     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
15717                                                : &AMDGPU::SReg_32RegClass;
15718   if (!TRI->isSGPRClass(RC) && !isDivergent)
15719     return TRI->getEquivalentSGPRClass(RC);
15720   else if (TRI->isSGPRClass(RC) && isDivergent)
15721     return TRI->getEquivalentVGPRClass(RC);
15722 
15723   return RC;
15724 }
15725 
15726 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
15727 // uniform values (as produced by the mask results of control flow intrinsics)
15728 // used outside of divergent blocks. The phi users need to also be treated as
15729 // always uniform.
15730 //
15731 // FIXME: DA is no longer in-use. Does this still apply to UniformityAnalysis?
15732 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
15733                       unsigned WaveSize) {
15734   // FIXME: We assume we never cast the mask results of a control flow
15735   // intrinsic.
15736   // Early exit if the type won't be consistent as a compile time hack.
15737   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
15738   if (!IT || IT->getBitWidth() != WaveSize)
15739     return false;
15740 
15741   if (!isa<Instruction>(V))
15742     return false;
15743   if (!Visited.insert(V).second)
15744     return false;
15745   bool Result = false;
15746   for (const auto *U : V->users()) {
15747     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
15748       if (V == U->getOperand(1)) {
15749         switch (Intrinsic->getIntrinsicID()) {
15750         default:
15751           Result = false;
15752           break;
15753         case Intrinsic::amdgcn_if_break:
15754         case Intrinsic::amdgcn_if:
15755         case Intrinsic::amdgcn_else:
15756           Result = true;
15757           break;
15758         }
15759       }
15760       if (V == U->getOperand(0)) {
15761         switch (Intrinsic->getIntrinsicID()) {
15762         default:
15763           Result = false;
15764           break;
15765         case Intrinsic::amdgcn_end_cf:
15766         case Intrinsic::amdgcn_loop:
15767           Result = true;
15768           break;
15769         }
15770       }
15771     } else {
15772       Result = hasCFUser(U, Visited, WaveSize);
15773     }
15774     if (Result)
15775       break;
15776   }
15777   return Result;
15778 }
15779 
15780 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
15781                                                const Value *V) const {
15782   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
15783     if (CI->isInlineAsm()) {
15784       // FIXME: This cannot give a correct answer. This should only trigger in
15785       // the case where inline asm returns mixed SGPR and VGPR results, used
15786       // outside the defining block. We don't have a specific result to
15787       // consider, so this assumes if any value is SGPR, the overall register
15788       // also needs to be SGPR.
15789       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
15790       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
15791           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
15792       for (auto &TC : TargetConstraints) {
15793         if (TC.Type == InlineAsm::isOutput) {
15794           ComputeConstraintToUse(TC, SDValue());
15795           const TargetRegisterClass *RC = getRegForInlineAsmConstraint(
15796               SIRI, TC.ConstraintCode, TC.ConstraintVT).second;
15797           if (RC && SIRI->isSGPRClass(RC))
15798             return true;
15799         }
15800       }
15801     }
15802   }
15803   SmallPtrSet<const Value *, 16> Visited;
15804   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
15805 }
15806 
15807 bool SITargetLowering::hasMemSDNodeUser(SDNode *N) const {
15808   SDNode::use_iterator I = N->use_begin(), E = N->use_end();
15809   for (; I != E; ++I) {
15810     if (MemSDNode *M = dyn_cast<MemSDNode>(*I)) {
15811       if (getBasePtrIndex(M) == I.getOperandNo())
15812         return true;
15813     }
15814   }
15815   return false;
15816 }
15817 
15818 bool SITargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0,
15819                                            SDValue N1) const {
15820   if (!N0.hasOneUse())
15821     return false;
15822   // Take care of the opportunity to keep N0 uniform
15823   if (N0->isDivergent() || !N1->isDivergent())
15824     return true;
15825   // Check if we have a good chance to form the memory access pattern with the
15826   // base and offset
15827   return (DAG.isBaseWithConstantOffset(N0) &&
15828           hasMemSDNodeUser(*N0->use_begin()));
15829 }
15830 
15831 bool SITargetLowering::isReassocProfitable(MachineRegisterInfo &MRI,
15832                                            Register N0, Register N1) const {
15833   return MRI.hasOneNonDBGUse(N0); // FIXME: handle regbanks
15834 }
15835 
15836 MachineMemOperand::Flags
15837 SITargetLowering::getTargetMMOFlags(const Instruction &I) const {
15838   // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load.
15839   if (I.getMetadata("amdgpu.noclobber"))
15840     return MONoClobber;
15841   return MachineMemOperand::MONone;
15842 }
15843 
15844 bool SITargetLowering::checkForPhysRegDependency(
15845     SDNode *Def, SDNode *User, unsigned Op, const TargetRegisterInfo *TRI,
15846     const TargetInstrInfo *TII, unsigned &PhysReg, int &Cost) const {
15847   if (User->getOpcode() != ISD::CopyToReg)
15848     return false;
15849   if (!Def->isMachineOpcode())
15850     return false;
15851   MachineSDNode *MDef = dyn_cast<MachineSDNode>(Def);
15852   if (!MDef)
15853     return false;
15854 
15855   unsigned ResNo = User->getOperand(Op).getResNo();
15856   if (User->getOperand(Op)->getValueType(ResNo) != MVT::i1)
15857     return false;
15858   const MCInstrDesc &II = TII->get(MDef->getMachineOpcode());
15859   if (II.isCompare() && II.hasImplicitDefOfPhysReg(AMDGPU::SCC)) {
15860     PhysReg = AMDGPU::SCC;
15861     const TargetRegisterClass *RC =
15862         TRI->getMinimalPhysRegClass(PhysReg, Def->getSimpleValueType(ResNo));
15863     Cost = RC->getCopyCost();
15864     return true;
15865   }
15866   return false;
15867 }
15868 
15869 void SITargetLowering::emitExpandAtomicRMW(AtomicRMWInst *AI) const {
15870   assert(Subtarget->hasAtomicFaddInsts() &&
15871          "target should have atomic fadd instructions");
15872   assert(AI->getType()->isFloatTy() &&
15873          AI->getPointerAddressSpace() == AMDGPUAS::FLAT_ADDRESS &&
15874          "generic atomicrmw expansion only supports FP32 operand in flat "
15875          "address space");
15876   assert(AI->getOperation() == AtomicRMWInst::FAdd &&
15877          "only fadd is supported for now");
15878 
15879   // Given: atomicrmw fadd ptr %addr, float %val ordering
15880   //
15881   // With this expansion we produce the following code:
15882   //   [...]
15883   //   br label %atomicrmw.check.shared
15884   //
15885   // atomicrmw.check.shared:
15886   //   %is.shared = call i1 @llvm.amdgcn.is.shared(ptr %addr)
15887   //   br i1 %is.shared, label %atomicrmw.shared, label %atomicrmw.check.private
15888   //
15889   // atomicrmw.shared:
15890   //   %cast.shared = addrspacecast ptr %addr to ptr addrspace(3)
15891   //   %loaded.shared = atomicrmw fadd ptr addrspace(3) %cast.shared,
15892   //                                   float %val ordering
15893   //   br label %atomicrmw.phi
15894   //
15895   // atomicrmw.check.private:
15896   //   %is.private = call i1 @llvm.amdgcn.is.private(ptr %int8ptr)
15897   //   br i1 %is.private, label %atomicrmw.private, label %atomicrmw.global
15898   //
15899   // atomicrmw.private:
15900   //   %cast.private = addrspacecast ptr %addr to ptr addrspace(5)
15901   //   %loaded.private = load float, ptr addrspace(5) %cast.private
15902   //   %val.new = fadd float %loaded.private, %val
15903   //   store float %val.new, ptr addrspace(5) %cast.private
15904   //   br label %atomicrmw.phi
15905   //
15906   // atomicrmw.global:
15907   //   %cast.global = addrspacecast ptr %addr to ptr addrspace(1)
15908   //   %loaded.global = atomicrmw fadd ptr addrspace(1) %cast.global,
15909   //                                   float %val ordering
15910   //   br label %atomicrmw.phi
15911   //
15912   // atomicrmw.phi:
15913   //   %loaded.phi = phi float [ %loaded.shared, %atomicrmw.shared ],
15914   //                           [ %loaded.private, %atomicrmw.private ],
15915   //                           [ %loaded.global, %atomicrmw.global ]
15916   //   br label %atomicrmw.end
15917   //
15918   // atomicrmw.end:
15919   //    [...]
15920 
15921   IRBuilder<> Builder(AI);
15922   LLVMContext &Ctx = Builder.getContext();
15923 
15924   BasicBlock *BB = Builder.GetInsertBlock();
15925   Function *F = BB->getParent();
15926   BasicBlock *ExitBB =
15927       BB->splitBasicBlock(Builder.GetInsertPoint(), "atomicrmw.end");
15928   BasicBlock *CheckSharedBB =
15929       BasicBlock::Create(Ctx, "atomicrmw.check.shared", F, ExitBB);
15930   BasicBlock *SharedBB = BasicBlock::Create(Ctx, "atomicrmw.shared", F, ExitBB);
15931   BasicBlock *CheckPrivateBB =
15932       BasicBlock::Create(Ctx, "atomicrmw.check.private", F, ExitBB);
15933   BasicBlock *PrivateBB =
15934       BasicBlock::Create(Ctx, "atomicrmw.private", F, ExitBB);
15935   BasicBlock *GlobalBB = BasicBlock::Create(Ctx, "atomicrmw.global", F, ExitBB);
15936   BasicBlock *PhiBB = BasicBlock::Create(Ctx, "atomicrmw.phi", F, ExitBB);
15937 
15938   Value *Val = AI->getValOperand();
15939   Type *ValTy = Val->getType();
15940   Value *Addr = AI->getPointerOperand();
15941 
15942   auto CreateNewAtomicRMW = [AI](IRBuilder<> &Builder, Value *Addr,
15943                                  Value *Val) -> Value * {
15944     AtomicRMWInst *OldVal =
15945         Builder.CreateAtomicRMW(AI->getOperation(), Addr, Val, AI->getAlign(),
15946                                 AI->getOrdering(), AI->getSyncScopeID());
15947     SmallVector<std::pair<unsigned, MDNode *>> MDs;
15948     AI->getAllMetadata(MDs);
15949     for (auto &P : MDs)
15950       OldVal->setMetadata(P.first, P.second);
15951     return OldVal;
15952   };
15953 
15954   std::prev(BB->end())->eraseFromParent();
15955   Builder.SetInsertPoint(BB);
15956   Builder.CreateBr(CheckSharedBB);
15957 
15958   Builder.SetInsertPoint(CheckSharedBB);
15959   CallInst *IsShared = Builder.CreateIntrinsic(Intrinsic::amdgcn_is_shared, {},
15960                                                {Addr}, nullptr, "is.shared");
15961   Builder.CreateCondBr(IsShared, SharedBB, CheckPrivateBB);
15962 
15963   Builder.SetInsertPoint(SharedBB);
15964   Value *CastToLocal = Builder.CreateAddrSpaceCast(
15965       Addr, PointerType::get(Ctx, AMDGPUAS::LOCAL_ADDRESS));
15966   Value *LoadedShared = CreateNewAtomicRMW(Builder, CastToLocal, Val);
15967   Builder.CreateBr(PhiBB);
15968 
15969   Builder.SetInsertPoint(CheckPrivateBB);
15970   CallInst *IsPrivate = Builder.CreateIntrinsic(
15971       Intrinsic::amdgcn_is_private, {}, {Addr}, nullptr, "is.private");
15972   Builder.CreateCondBr(IsPrivate, PrivateBB, GlobalBB);
15973 
15974   Builder.SetInsertPoint(PrivateBB);
15975   Value *CastToPrivate = Builder.CreateAddrSpaceCast(
15976       Addr, PointerType::get(Ctx, AMDGPUAS::PRIVATE_ADDRESS));
15977   Value *LoadedPrivate =
15978       Builder.CreateLoad(ValTy, CastToPrivate, "loaded.private");
15979   Value *NewVal = Builder.CreateFAdd(LoadedPrivate, Val, "val.new");
15980   Builder.CreateStore(NewVal, CastToPrivate);
15981   Builder.CreateBr(PhiBB);
15982 
15983   Builder.SetInsertPoint(GlobalBB);
15984   Value *CastToGlobal = Builder.CreateAddrSpaceCast(
15985       Addr, PointerType::get(Ctx, AMDGPUAS::GLOBAL_ADDRESS));
15986   Value *LoadedGlobal = CreateNewAtomicRMW(Builder, CastToGlobal, Val);
15987   Builder.CreateBr(PhiBB);
15988 
15989   Builder.SetInsertPoint(PhiBB);
15990   PHINode *Loaded = Builder.CreatePHI(ValTy, 3, "loaded.phi");
15991   Loaded->addIncoming(LoadedShared, SharedBB);
15992   Loaded->addIncoming(LoadedPrivate, PrivateBB);
15993   Loaded->addIncoming(LoadedGlobal, GlobalBB);
15994   Builder.CreateBr(ExitBB);
15995 
15996   AI->replaceAllUsesWith(Loaded);
15997   AI->eraseFromParent();
15998 }
15999 
16000 LoadInst *
16001 SITargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
16002   IRBuilder<> Builder(AI);
16003   auto Order = AI->getOrdering();
16004 
16005   // The optimization removes store aspect of the atomicrmw. Therefore, cache
16006   // must be flushed if the atomic ordering had a release semantics. This is
16007   // not necessary a fence, a release fence just coincides to do that flush.
16008   // Avoid replacing of an atomicrmw with a release semantics.
16009   if (isReleaseOrStronger(Order))
16010     return nullptr;
16011 
16012   LoadInst *LI = Builder.CreateAlignedLoad(
16013       AI->getType(), AI->getPointerOperand(), AI->getAlign());
16014   LI->setAtomic(Order, AI->getSyncScopeID());
16015   LI->copyMetadata(*AI);
16016   LI->takeName(AI);
16017   AI->replaceAllUsesWith(LI);
16018   AI->eraseFromParent();
16019   return LI;
16020 }
16021