xref: /freebsd/contrib/llvm-project/llvm/lib/Target/AMDGPU/SIISelLowering.cpp (revision a4a491e2238b12ccd64d3faf9e6401487f6f1f1b)
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 "SIMachineFunctionInfo.h"
19 #include "SIRegisterInfo.h"
20 #include "llvm/ADT/FloatingPointMode.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
23 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
24 #include "llvm/BinaryFormat/ELF.h"
25 #include "llvm/CodeGen/Analysis.h"
26 #include "llvm/CodeGen/FunctionLoweringInfo.h"
27 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
28 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineLoopInfo.h"
32 #include "llvm/IR/DiagnosticInfo.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/IntrinsicsAMDGPU.h"
35 #include "llvm/IR/IntrinsicsR600.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/KnownBits.h"
38 
39 using namespace llvm;
40 
41 #define DEBUG_TYPE "si-lower"
42 
43 STATISTIC(NumTailCalls, "Number of tail calls");
44 
45 static cl::opt<bool> DisableLoopAlignment(
46   "amdgpu-disable-loop-alignment",
47   cl::desc("Do not align and prefetch loops"),
48   cl::init(false));
49 
50 static cl::opt<bool> UseDivergentRegisterIndexing(
51   "amdgpu-use-divergent-register-indexing",
52   cl::Hidden,
53   cl::desc("Use indirect register addressing for divergent indexes"),
54   cl::init(false));
55 
56 static bool hasFP32Denormals(const MachineFunction &MF) {
57   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
58   return Info->getMode().allFP32Denormals();
59 }
60 
61 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
62   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
63   return Info->getMode().allFP64FP16Denormals();
64 }
65 
66 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
67   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
68   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
69     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
70       return AMDGPU::SGPR0 + Reg;
71     }
72   }
73   llvm_unreachable("Cannot allocate sgpr");
74 }
75 
76 SITargetLowering::SITargetLowering(const TargetMachine &TM,
77                                    const GCNSubtarget &STI)
78     : AMDGPUTargetLowering(TM, STI),
79       Subtarget(&STI) {
80   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
81   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
82 
83   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
84   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
85 
86   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
87 
88   const SIRegisterInfo *TRI = STI.getRegisterInfo();
89   const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class();
90 
91   addRegisterClass(MVT::f64, V64RegClass);
92   addRegisterClass(MVT::v2f32, V64RegClass);
93 
94   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
95   addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96));
96 
97   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
98   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
99 
100   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
101   addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128));
102 
103   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
104   addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160));
105 
106   addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass);
107   addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192));
108 
109   addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass);
110   addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192));
111 
112   addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass);
113   addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224));
114 
115   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
116   addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256));
117 
118   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
119   addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256));
120 
121   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
122   addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512));
123 
124   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
125   addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512));
126 
127   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
128   addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024));
129 
130   if (Subtarget->has16BitInsts()) {
131     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
132     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
133 
134     // Unless there are also VOP3P operations, not operations are really legal.
135     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
136     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
137     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
138     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
139     addRegisterClass(MVT::v8i16, &AMDGPU::SGPR_128RegClass);
140     addRegisterClass(MVT::v8f16, &AMDGPU::SGPR_128RegClass);
141     addRegisterClass(MVT::v16i16, &AMDGPU::SGPR_256RegClass);
142     addRegisterClass(MVT::v16f16, &AMDGPU::SGPR_256RegClass);
143   }
144 
145   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
146   addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024));
147 
148   computeRegisterProperties(Subtarget->getRegisterInfo());
149 
150   // The boolean content concept here is too inflexible. Compares only ever
151   // really produce a 1-bit result. Any copy/extend from these will turn into a
152   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
153   // it's what most targets use.
154   setBooleanContents(ZeroOrOneBooleanContent);
155   setBooleanVectorContents(ZeroOrOneBooleanContent);
156 
157   // We need to custom lower vector stores from local memory
158   setOperationAction(ISD::LOAD,
159                      {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32,
160                       MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v16i32, MVT::i1,
161                       MVT::v32i32},
162                      Custom);
163 
164   setOperationAction(ISD::STORE,
165                      {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32,
166                       MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v16i32, MVT::i1,
167                       MVT::v32i32},
168                      Custom);
169 
170   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
171   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
172   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
173   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
174   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
175   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
176   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
177   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
178   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
179   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
180   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
181   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
182   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
183   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
184   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
185   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
186 
187   setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand);
188   setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand);
189   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
190   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
191   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
192   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
193   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
194 
195   setOperationAction(ISD::GlobalAddress, {MVT::i32, MVT::i64}, Custom);
196 
197   setOperationAction(ISD::SELECT, MVT::i1, Promote);
198   setOperationAction(ISD::SELECT, MVT::i64, Custom);
199   setOperationAction(ISD::SELECT, MVT::f64, Promote);
200   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
201 
202   setOperationAction(ISD::SELECT_CC,
203                      {MVT::f32, MVT::i32, MVT::i64, MVT::f64, MVT::i1}, Expand);
204 
205   setOperationAction(ISD::SETCC, MVT::i1, Promote);
206   setOperationAction(ISD::SETCC, {MVT::v2i1, MVT::v4i1}, Expand);
207   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
208 
209   setOperationAction(ISD::TRUNCATE,
210                      {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32,
211                       MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v16i32},
212                      Expand);
213   setOperationAction(ISD::FP_ROUND,
214                      {MVT::v2f32, MVT::v3f32, MVT::v4f32, MVT::v5f32,
215                       MVT::v6f32, MVT::v7f32, MVT::v8f32, MVT::v16f32},
216                      Expand);
217 
218   setOperationAction(ISD::SIGN_EXTEND_INREG,
219                      {MVT::v2i1, MVT::v4i1, MVT::v2i8, MVT::v4i8, MVT::v2i16,
220                       MVT::v3i16, MVT::v4i16, MVT::Other},
221                      Custom);
222 
223   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
224   setOperationAction(ISD::BR_CC,
225                      {MVT::i1, MVT::i32, MVT::i64, MVT::f32, MVT::f64}, Expand);
226 
227   setOperationAction({ISD::UADDO, ISD::USUBO}, MVT::i32, Legal);
228 
229   setOperationAction({ISD::ADDCARRY, ISD::SUBCARRY}, MVT::i32, Legal);
230 
231   setOperationAction({ISD::SHL_PARTS, ISD::SRA_PARTS, ISD::SRL_PARTS}, MVT::i64,
232                      Expand);
233 
234 #if 0
235   setOperationAction({ISD::ADDCARRY, ISD::SUBCARRY}, MVT::i64, Legal);
236 #endif
237 
238   // We only support LOAD/STORE and vector manipulation ops for vectors
239   // with > 4 elements.
240   for (MVT VT :
241        {MVT::v8i32,  MVT::v8f32,  MVT::v16i32, MVT::v16f32, MVT::v2i64,
242         MVT::v2f64,  MVT::v4i16,  MVT::v4f16,  MVT::v3i64,  MVT::v3f64,
243         MVT::v6i32,  MVT::v6f32,  MVT::v4i64,  MVT::v4f64,  MVT::v8i64,
244         MVT::v8f64,  MVT::v8i16,  MVT::v8f16,  MVT::v16i16, MVT::v16f16,
245         MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32}) {
246     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
247       switch (Op) {
248       case ISD::LOAD:
249       case ISD::STORE:
250       case ISD::BUILD_VECTOR:
251       case ISD::BITCAST:
252       case ISD::EXTRACT_VECTOR_ELT:
253       case ISD::INSERT_VECTOR_ELT:
254       case ISD::EXTRACT_SUBVECTOR:
255       case ISD::SCALAR_TO_VECTOR:
256         break;
257       case ISD::INSERT_SUBVECTOR:
258       case ISD::CONCAT_VECTORS:
259         setOperationAction(Op, VT, Custom);
260         break;
261       default:
262         setOperationAction(Op, VT, Expand);
263         break;
264       }
265     }
266   }
267 
268   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
269 
270   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
271   // is expanded to avoid having two separate loops in case the index is a VGPR.
272 
273   // Most operations are naturally 32-bit vector operations. We only support
274   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
275   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
276     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
277     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
278 
279     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
280     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
281 
282     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
283     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
284 
285     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
286     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
287   }
288 
289   for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) {
290     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
291     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32);
292 
293     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
294     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32);
295 
296     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
297     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32);
298 
299     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
300     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32);
301   }
302 
303   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
304     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
305     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
306 
307     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
308     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
309 
310     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
311     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
312 
313     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
314     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
315   }
316 
317   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
318     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
319     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
320 
321     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
322     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
323 
324     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
325     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
326 
327     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
328     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
329   }
330 
331   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
332     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
333     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
334 
335     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
336     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
337 
338     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
339     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
340 
341     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
342     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
343   }
344 
345   setOperationAction(ISD::VECTOR_SHUFFLE,
346                      {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32},
347                      Expand);
348 
349   setOperationAction(ISD::BUILD_VECTOR, {MVT::v4f16, MVT::v4i16}, Custom);
350 
351   // Avoid stack access for these.
352   // TODO: Generalize to more vector types.
353   setOperationAction({ISD::EXTRACT_VECTOR_ELT, ISD::INSERT_VECTOR_ELT},
354                      {MVT::v2i16, MVT::v2f16, MVT::v2i8, MVT::v4i8, MVT::v8i8,
355                       MVT::v4i16, MVT::v4f16},
356                      Custom);
357 
358   // Deal with vec3 vector operations when widened to vec4.
359   setOperationAction(ISD::INSERT_SUBVECTOR,
360                      {MVT::v3i32, MVT::v3f32, MVT::v4i32, MVT::v4f32}, Custom);
361 
362   // Deal with vec5/6/7 vector operations when widened to vec8.
363   setOperationAction(ISD::INSERT_SUBVECTOR,
364                      {MVT::v5i32, MVT::v5f32, MVT::v6i32, MVT::v6f32,
365                       MVT::v7i32, MVT::v7f32, MVT::v8i32, MVT::v8f32},
366                      Custom);
367 
368   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
369   // and output demarshalling
370   setOperationAction(ISD::ATOMIC_CMP_SWAP, {MVT::i32, MVT::i64}, Custom);
371 
372   // We can't return success/failure, only the old value,
373   // let LLVM add the comparison
374   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, {MVT::i32, MVT::i64},
375                      Expand);
376 
377   if (Subtarget->hasFlatAddressSpace())
378     setOperationAction(ISD::ADDRSPACECAST, {MVT::i32, MVT::i64}, Custom);
379 
380   setOperationAction(ISD::BITREVERSE, {MVT::i32, MVT::i64}, Legal);
381 
382   // FIXME: This should be narrowed to i32, but that only happens if i64 is
383   // illegal.
384   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
385   setOperationAction(ISD::BSWAP, {MVT::i64, MVT::i32}, Legal);
386 
387   // On SI this is s_memtime and s_memrealtime on VI.
388   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
389   setOperationAction({ISD::TRAP, ISD::DEBUGTRAP}, MVT::Other, Custom);
390 
391   if (Subtarget->has16BitInsts()) {
392     setOperationAction({ISD::FPOW, ISD::FPOWI}, MVT::f16, Promote);
393     setOperationAction({ISD::FLOG, ISD::FEXP, ISD::FLOG10}, MVT::f16, Custom);
394   }
395 
396   if (Subtarget->hasMadMacF32Insts())
397     setOperationAction(ISD::FMAD, MVT::f32, Legal);
398 
399   if (!Subtarget->hasBFI())
400     // fcopysign can be done in a single instruction with BFI.
401     setOperationAction(ISD::FCOPYSIGN, {MVT::f32, MVT::f64}, Expand);
402 
403   if (!Subtarget->hasBCNT(32))
404     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
405 
406   if (!Subtarget->hasBCNT(64))
407     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
408 
409   if (Subtarget->hasFFBH())
410     setOperationAction({ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF}, MVT::i32, Custom);
411 
412   if (Subtarget->hasFFBL())
413     setOperationAction({ISD::CTTZ, ISD::CTTZ_ZERO_UNDEF}, MVT::i32, Custom);
414 
415   // We only really have 32-bit BFE instructions (and 16-bit on VI).
416   //
417   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
418   // effort to match them now. We want this to be false for i64 cases when the
419   // extraction isn't restricted to the upper or lower half. Ideally we would
420   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
421   // span the midpoint are probably relatively rare, so don't worry about them
422   // for now.
423   if (Subtarget->hasBFE())
424     setHasExtractBitsInsn(true);
425 
426   // Clamp modifier on add/sub
427   if (Subtarget->hasIntClamp())
428     setOperationAction({ISD::UADDSAT, ISD::USUBSAT}, MVT::i32, Legal);
429 
430   if (Subtarget->hasAddNoCarry())
431     setOperationAction({ISD::SADDSAT, ISD::SSUBSAT}, {MVT::i16, MVT::i32},
432                        Legal);
433 
434   setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, {MVT::f32, MVT::f64},
435                      Custom);
436 
437   // These are really only legal for ieee_mode functions. We should be avoiding
438   // them for functions that don't have ieee_mode enabled, so just say they are
439   // legal.
440   setOperationAction({ISD::FMINNUM_IEEE, ISD::FMAXNUM_IEEE},
441                      {MVT::f32, MVT::f64}, Legal);
442 
443   if (Subtarget->haveRoundOpsF64())
444     setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FRINT}, MVT::f64, Legal);
445   else
446     setOperationAction({ISD::FCEIL, ISD::FTRUNC, ISD::FRINT, ISD::FFLOOR},
447                        MVT::f64, Custom);
448 
449   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
450 
451   setOperationAction({ISD::FSIN, ISD::FCOS, ISD::FDIV}, MVT::f32, Custom);
452   setOperationAction(ISD::FDIV, MVT::f64, Custom);
453 
454   if (Subtarget->has16BitInsts()) {
455     setOperationAction({ISD::Constant, ISD::SMIN, ISD::SMAX, ISD::UMIN,
456                         ISD::UMAX, ISD::UADDSAT, ISD::USUBSAT},
457                        MVT::i16, Legal);
458 
459     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
460 
461     setOperationAction({ISD::ROTR, ISD::ROTL, ISD::SELECT_CC, ISD::BR_CC},
462                        MVT::i16, Expand);
463 
464     setOperationAction({ISD::SIGN_EXTEND, ISD::SDIV, ISD::UDIV, ISD::SREM,
465                         ISD::UREM, ISD::BITREVERSE, ISD::CTTZ,
466                         ISD::CTTZ_ZERO_UNDEF, ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF,
467                         ISD::CTPOP},
468                        MVT::i16, Promote);
469 
470     setOperationAction(ISD::LOAD, MVT::i16, Custom);
471 
472     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
473 
474     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
475     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
476     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
477     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
478 
479     setOperationAction({ISD::FP_TO_SINT, ISD::FP_TO_UINT}, MVT::i16, Custom);
480 
481     // F16 - Constant Actions.
482     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
483 
484     // F16 - Load/Store Actions.
485     setOperationAction(ISD::LOAD, MVT::f16, Promote);
486     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
487     setOperationAction(ISD::STORE, MVT::f16, Promote);
488     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
489 
490     // F16 - VOP1 Actions.
491     setOperationAction(
492         {ISD::FP_ROUND, ISD::FCOS, ISD::FSIN, ISD::FROUND, ISD::FPTRUNC_ROUND},
493         MVT::f16, Custom);
494 
495     setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP}, MVT::i16, Custom);
496 
497     setOperationAction(
498         {ISD::FP_TO_SINT, ISD::FP_TO_UINT, ISD::SINT_TO_FP, ISD::UINT_TO_FP},
499         MVT::f16, Promote);
500 
501     // F16 - VOP2 Actions.
502     setOperationAction({ISD::BR_CC, ISD::SELECT_CC}, MVT::f16, Expand);
503 
504     setOperationAction(ISD::FDIV, MVT::f16, Custom);
505 
506     // F16 - VOP3 Actions.
507     setOperationAction(ISD::FMA, MVT::f16, Legal);
508     if (STI.hasMadF16())
509       setOperationAction(ISD::FMAD, MVT::f16, Legal);
510 
511     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16, MVT::v8i16,
512                    MVT::v8f16, MVT::v16i16, MVT::v16f16}) {
513       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
514         switch (Op) {
515         case ISD::LOAD:
516         case ISD::STORE:
517         case ISD::BUILD_VECTOR:
518         case ISD::BITCAST:
519         case ISD::EXTRACT_VECTOR_ELT:
520         case ISD::INSERT_VECTOR_ELT:
521         case ISD::INSERT_SUBVECTOR:
522         case ISD::EXTRACT_SUBVECTOR:
523         case ISD::SCALAR_TO_VECTOR:
524           break;
525         case ISD::CONCAT_VECTORS:
526           setOperationAction(Op, VT, Custom);
527           break;
528         default:
529           setOperationAction(Op, VT, Expand);
530           break;
531         }
532       }
533     }
534 
535     // v_perm_b32 can handle either of these.
536     setOperationAction(ISD::BSWAP, {MVT::i16, MVT::v2i16}, Legal);
537     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
538 
539     // XXX - Do these do anything? Vector constants turn into build_vector.
540     setOperationAction(ISD::Constant, {MVT::v2i16, MVT::v2f16}, Legal);
541 
542     setOperationAction(ISD::UNDEF, {MVT::v2i16, MVT::v2f16}, Legal);
543 
544     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
545     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
546     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
547     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
548 
549     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
550     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
551     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
552     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
553 
554     setOperationAction(ISD::AND, MVT::v2i16, Promote);
555     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
556     setOperationAction(ISD::OR, MVT::v2i16, Promote);
557     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
558     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
559     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
560 
561     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
562     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
563     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
564     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
565 
566     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
567     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
568     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
569     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
570 
571     setOperationAction(ISD::LOAD, MVT::v8i16, Promote);
572     AddPromotedToType(ISD::LOAD, MVT::v8i16, MVT::v4i32);
573     setOperationAction(ISD::LOAD, MVT::v8f16, Promote);
574     AddPromotedToType(ISD::LOAD, MVT::v8f16, MVT::v4i32);
575 
576     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
577     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
578     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
579     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
580 
581     setOperationAction(ISD::STORE, MVT::v8i16, Promote);
582     AddPromotedToType(ISD::STORE, MVT::v8i16, MVT::v4i32);
583     setOperationAction(ISD::STORE, MVT::v8f16, Promote);
584     AddPromotedToType(ISD::STORE, MVT::v8f16, MVT::v4i32);
585 
586     setOperationAction(ISD::LOAD, MVT::v16i16, Promote);
587     AddPromotedToType(ISD::LOAD, MVT::v16i16, MVT::v8i32);
588     setOperationAction(ISD::LOAD, MVT::v16f16, Promote);
589     AddPromotedToType(ISD::LOAD, MVT::v16f16, MVT::v8i32);
590 
591     setOperationAction(ISD::STORE, MVT::v16i16, Promote);
592     AddPromotedToType(ISD::STORE, MVT::v16i16, MVT::v8i32);
593     setOperationAction(ISD::STORE, MVT::v16f16, Promote);
594     AddPromotedToType(ISD::STORE, MVT::v16f16, MVT::v8i32);
595 
596     setOperationAction({ISD::ANY_EXTEND, ISD::ZERO_EXTEND, ISD::SIGN_EXTEND},
597                        MVT::v2i32, Expand);
598     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
599 
600     setOperationAction({ISD::ANY_EXTEND, ISD::ZERO_EXTEND, ISD::SIGN_EXTEND},
601                        MVT::v4i32, Expand);
602 
603     setOperationAction({ISD::ANY_EXTEND, ISD::ZERO_EXTEND, ISD::SIGN_EXTEND},
604                        MVT::v8i32, Expand);
605 
606     if (!Subtarget->hasVOP3PInsts())
607       setOperationAction(ISD::BUILD_VECTOR, {MVT::v2i16, MVT::v2f16}, Custom);
608 
609     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
610     // This isn't really legal, but this avoids the legalizer unrolling it (and
611     // allows matching fneg (fabs x) patterns)
612     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
613 
614     setOperationAction({ISD::FMAXNUM, ISD::FMINNUM}, MVT::f16, Custom);
615     setOperationAction({ISD::FMAXNUM_IEEE, ISD::FMINNUM_IEEE}, MVT::f16, Legal);
616 
617     setOperationAction({ISD::FMINNUM_IEEE, ISD::FMAXNUM_IEEE},
618                        {MVT::v4f16, MVT::v8f16, MVT::v16f16}, Custom);
619 
620     setOperationAction({ISD::FMINNUM, ISD::FMAXNUM},
621                        {MVT::v4f16, MVT::v8f16, MVT::v16f16}, Expand);
622 
623     for (MVT Vec16 : {MVT::v8i16, MVT::v8f16, MVT::v16i16, MVT::v16f16}) {
624       setOperationAction(
625           {ISD::BUILD_VECTOR, ISD::EXTRACT_VECTOR_ELT, ISD::SCALAR_TO_VECTOR},
626           Vec16, Custom);
627       setOperationAction(ISD::INSERT_VECTOR_ELT, Vec16, Expand);
628     }
629   }
630 
631   if (Subtarget->hasVOP3PInsts()) {
632     setOperationAction({ISD::ADD, ISD::SUB, ISD::MUL, ISD::SHL, ISD::SRL,
633                         ISD::SRA, ISD::SMIN, ISD::UMIN, ISD::SMAX, ISD::UMAX,
634                         ISD::UADDSAT, ISD::USUBSAT, ISD::SADDSAT, ISD::SSUBSAT},
635                        MVT::v2i16, Legal);
636 
637     setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA, ISD::FMINNUM_IEEE,
638                         ISD::FMAXNUM_IEEE, ISD::FCANONICALIZE},
639                        MVT::v2f16, Legal);
640 
641     setOperationAction(ISD::EXTRACT_VECTOR_ELT, {MVT::v2i16, MVT::v2f16},
642                        Custom);
643 
644     setOperationAction(ISD::VECTOR_SHUFFLE,
645                        {MVT::v4f16, MVT::v4i16, MVT::v8f16, MVT::v8i16,
646                         MVT::v16f16, MVT::v16i16},
647                        Custom);
648 
649     for (MVT VT : {MVT::v4i16, MVT::v8i16, MVT::v16i16})
650       // Split vector operations.
651       setOperationAction({ISD::SHL, ISD::SRA, ISD::SRL, ISD::ADD, ISD::SUB,
652                           ISD::MUL, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX,
653                           ISD::UADDSAT, ISD::SADDSAT, ISD::USUBSAT,
654                           ISD::SSUBSAT},
655                          VT, Custom);
656 
657     for (MVT VT : {MVT::v4f16, MVT::v8f16, MVT::v16f16})
658       // Split vector operations.
659       setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA, ISD::FCANONICALIZE},
660                          VT, Custom);
661 
662     setOperationAction({ISD::FMAXNUM, ISD::FMINNUM}, {MVT::v2f16, MVT::v4f16},
663                        Custom);
664 
665     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
666     setOperationAction(ISD::SELECT, {MVT::v4i16, MVT::v4f16}, Custom);
667 
668     if (Subtarget->hasPackedFP32Ops()) {
669       setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA, ISD::FNEG},
670                          MVT::v2f32, Legal);
671       setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA},
672                          {MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32},
673                          Custom);
674     }
675   }
676 
677   setOperationAction({ISD::FNEG, ISD::FABS}, MVT::v4f16, Custom);
678 
679   if (Subtarget->has16BitInsts()) {
680     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
681     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
682     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
683     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
684   } else {
685     // Legalization hack.
686     setOperationAction(ISD::SELECT, {MVT::v2i16, MVT::v2f16}, Custom);
687 
688     setOperationAction({ISD::FNEG, ISD::FABS}, MVT::v2f16, Custom);
689   }
690 
691   setOperationAction(ISD::SELECT,
692                      {MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8,
693                       MVT::v8i16, MVT::v8f16, MVT::v16i16, MVT::v16f16},
694                      Custom);
695 
696   setOperationAction({ISD::SMULO, ISD::UMULO}, MVT::i64, Custom);
697 
698   if (Subtarget->hasMad64_32())
699     setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, MVT::i32, Custom);
700 
701   setOperationAction(ISD::INTRINSIC_WO_CHAIN,
702                      {MVT::Other, MVT::f32, MVT::v4f32, MVT::i16, MVT::f16,
703                       MVT::v2i16, MVT::v2f16},
704                      Custom);
705 
706   setOperationAction(ISD::INTRINSIC_W_CHAIN,
707                      {MVT::v2f16, MVT::v2i16, MVT::v3f16, MVT::v3i16,
708                       MVT::v4f16, MVT::v4i16, MVT::v8f16, MVT::Other, MVT::f16,
709                       MVT::i16, MVT::i8},
710                      Custom);
711 
712   setOperationAction(ISD::INTRINSIC_VOID,
713                      {MVT::Other, MVT::v2i16, MVT::v2f16, MVT::v3i16,
714                       MVT::v3f16, MVT::v4f16, MVT::v4i16, MVT::f16, MVT::i16,
715                       MVT::i8},
716                      Custom);
717 
718   setTargetDAGCombine({ISD::ADD,
719                        ISD::ADDCARRY,
720                        ISD::SUB,
721                        ISD::SUBCARRY,
722                        ISD::FADD,
723                        ISD::FSUB,
724                        ISD::FMINNUM,
725                        ISD::FMAXNUM,
726                        ISD::FMINNUM_IEEE,
727                        ISD::FMAXNUM_IEEE,
728                        ISD::FMA,
729                        ISD::SMIN,
730                        ISD::SMAX,
731                        ISD::UMIN,
732                        ISD::UMAX,
733                        ISD::SETCC,
734                        ISD::AND,
735                        ISD::OR,
736                        ISD::XOR,
737                        ISD::SINT_TO_FP,
738                        ISD::UINT_TO_FP,
739                        ISD::FCANONICALIZE,
740                        ISD::SCALAR_TO_VECTOR,
741                        ISD::ZERO_EXTEND,
742                        ISD::SIGN_EXTEND_INREG,
743                        ISD::EXTRACT_VECTOR_ELT,
744                        ISD::INSERT_VECTOR_ELT});
745 
746   // All memory operations. Some folding on the pointer operand is done to help
747   // matching the constant offsets in the addressing modes.
748   setTargetDAGCombine({ISD::LOAD,
749                        ISD::STORE,
750                        ISD::ATOMIC_LOAD,
751                        ISD::ATOMIC_STORE,
752                        ISD::ATOMIC_CMP_SWAP,
753                        ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
754                        ISD::ATOMIC_SWAP,
755                        ISD::ATOMIC_LOAD_ADD,
756                        ISD::ATOMIC_LOAD_SUB,
757                        ISD::ATOMIC_LOAD_AND,
758                        ISD::ATOMIC_LOAD_OR,
759                        ISD::ATOMIC_LOAD_XOR,
760                        ISD::ATOMIC_LOAD_NAND,
761                        ISD::ATOMIC_LOAD_MIN,
762                        ISD::ATOMIC_LOAD_MAX,
763                        ISD::ATOMIC_LOAD_UMIN,
764                        ISD::ATOMIC_LOAD_UMAX,
765                        ISD::ATOMIC_LOAD_FADD,
766                        ISD::INTRINSIC_VOID,
767                        ISD::INTRINSIC_W_CHAIN});
768 
769   // FIXME: In other contexts we pretend this is a per-function property.
770   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
771 
772   setSchedulingPreference(Sched::RegPressure);
773 }
774 
775 const GCNSubtarget *SITargetLowering::getSubtarget() const {
776   return Subtarget;
777 }
778 
779 //===----------------------------------------------------------------------===//
780 // TargetLowering queries
781 //===----------------------------------------------------------------------===//
782 
783 // v_mad_mix* support a conversion from f16 to f32.
784 //
785 // There is only one special case when denormals are enabled we don't currently,
786 // where this is OK to use.
787 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
788                                        EVT DestVT, EVT SrcVT) const {
789   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
790           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
791     DestVT.getScalarType() == MVT::f32 &&
792     SrcVT.getScalarType() == MVT::f16 &&
793     // TODO: This probably only requires no input flushing?
794     !hasFP32Denormals(DAG.getMachineFunction());
795 }
796 
797 bool SITargetLowering::isFPExtFoldable(const MachineInstr &MI, unsigned Opcode,
798                                        LLT DestTy, LLT SrcTy) const {
799   return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) ||
800           (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) &&
801          DestTy.getScalarSizeInBits() == 32 &&
802          SrcTy.getScalarSizeInBits() == 16 &&
803          // TODO: This probably only requires no input flushing?
804          !hasFP32Denormals(*MI.getMF());
805 }
806 
807 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
808   // SI has some legal vector types, but no legal vector operations. Say no
809   // shuffles are legal in order to prefer scalarizing some vector operations.
810   return false;
811 }
812 
813 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
814                                                     CallingConv::ID CC,
815                                                     EVT VT) const {
816   if (CC == CallingConv::AMDGPU_KERNEL)
817     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
818 
819   if (VT.isVector()) {
820     EVT ScalarVT = VT.getScalarType();
821     unsigned Size = ScalarVT.getSizeInBits();
822     if (Size == 16) {
823       if (Subtarget->has16BitInsts())
824         return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
825       return VT.isInteger() ? MVT::i32 : MVT::f32;
826     }
827 
828     if (Size < 16)
829       return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
830     return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
831   }
832 
833   if (VT.getSizeInBits() > 32)
834     return MVT::i32;
835 
836   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
837 }
838 
839 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
840                                                          CallingConv::ID CC,
841                                                          EVT VT) const {
842   if (CC == CallingConv::AMDGPU_KERNEL)
843     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
844 
845   if (VT.isVector()) {
846     unsigned NumElts = VT.getVectorNumElements();
847     EVT ScalarVT = VT.getScalarType();
848     unsigned Size = ScalarVT.getSizeInBits();
849 
850     // FIXME: Should probably promote 8-bit vectors to i16.
851     if (Size == 16 && Subtarget->has16BitInsts())
852       return (NumElts + 1) / 2;
853 
854     if (Size <= 32)
855       return NumElts;
856 
857     if (Size > 32)
858       return NumElts * ((Size + 31) / 32);
859   } else if (VT.getSizeInBits() > 32)
860     return (VT.getSizeInBits() + 31) / 32;
861 
862   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
863 }
864 
865 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
866   LLVMContext &Context, CallingConv::ID CC,
867   EVT VT, EVT &IntermediateVT,
868   unsigned &NumIntermediates, MVT &RegisterVT) const {
869   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
870     unsigned NumElts = VT.getVectorNumElements();
871     EVT ScalarVT = VT.getScalarType();
872     unsigned Size = ScalarVT.getSizeInBits();
873     // FIXME: We should fix the ABI to be the same on targets without 16-bit
874     // support, but unless we can properly handle 3-vectors, it will be still be
875     // inconsistent.
876     if (Size == 16 && Subtarget->has16BitInsts()) {
877       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
878       IntermediateVT = RegisterVT;
879       NumIntermediates = (NumElts + 1) / 2;
880       return NumIntermediates;
881     }
882 
883     if (Size == 32) {
884       RegisterVT = ScalarVT.getSimpleVT();
885       IntermediateVT = RegisterVT;
886       NumIntermediates = NumElts;
887       return NumIntermediates;
888     }
889 
890     if (Size < 16 && Subtarget->has16BitInsts()) {
891       // FIXME: Should probably form v2i16 pieces
892       RegisterVT = MVT::i16;
893       IntermediateVT = ScalarVT;
894       NumIntermediates = NumElts;
895       return NumIntermediates;
896     }
897 
898 
899     if (Size != 16 && Size <= 32) {
900       RegisterVT = MVT::i32;
901       IntermediateVT = ScalarVT;
902       NumIntermediates = NumElts;
903       return NumIntermediates;
904     }
905 
906     if (Size > 32) {
907       RegisterVT = MVT::i32;
908       IntermediateVT = RegisterVT;
909       NumIntermediates = NumElts * ((Size + 31) / 32);
910       return NumIntermediates;
911     }
912   }
913 
914   return TargetLowering::getVectorTypeBreakdownForCallingConv(
915     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
916 }
917 
918 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
919   assert(DMaskLanes != 0);
920 
921   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
922     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
923     return EVT::getVectorVT(Ty->getContext(),
924                             EVT::getEVT(VT->getElementType()),
925                             NumElts);
926   }
927 
928   return EVT::getEVT(Ty);
929 }
930 
931 // Peek through TFE struct returns to only use the data size.
932 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
933   auto *ST = dyn_cast<StructType>(Ty);
934   if (!ST)
935     return memVTFromImageData(Ty, DMaskLanes);
936 
937   // Some intrinsics return an aggregate type - special case to work out the
938   // correct memVT.
939   //
940   // Only limited forms of aggregate type currently expected.
941   if (ST->getNumContainedTypes() != 2 ||
942       !ST->getContainedType(1)->isIntegerTy(32))
943     return EVT();
944   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
945 }
946 
947 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
948                                           const CallInst &CI,
949                                           MachineFunction &MF,
950                                           unsigned IntrID) const {
951   Info.flags = MachineMemOperand::MONone;
952   if (CI.hasMetadata(LLVMContext::MD_invariant_load))
953     Info.flags |= MachineMemOperand::MOInvariant;
954 
955   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
956           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
957     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
958                                                   (Intrinsic::ID)IntrID);
959     if (Attr.hasFnAttr(Attribute::ReadNone))
960       return false;
961 
962     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
963 
964     const GCNTargetMachine &TM =
965         static_cast<const GCNTargetMachine &>(getTargetMachine());
966 
967     if (RsrcIntr->IsImage) {
968       Info.ptrVal = MFI->getImagePSV(TM);
969       Info.align.reset();
970     } else {
971       Info.ptrVal = MFI->getBufferPSV(TM);
972     }
973 
974     Info.flags |= MachineMemOperand::MODereferenceable;
975     if (Attr.hasFnAttr(Attribute::ReadOnly)) {
976       unsigned DMaskLanes = 4;
977 
978       if (RsrcIntr->IsImage) {
979         const AMDGPU::ImageDimIntrinsicInfo *Intr
980           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
981         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
982           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
983 
984         if (!BaseOpcode->Gather4) {
985           // If this isn't a gather, we may have excess loaded elements in the
986           // IR type. Check the dmask for the real number of elements loaded.
987           unsigned DMask
988             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
989           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
990         }
991 
992         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
993       } else
994         Info.memVT = EVT::getEVT(CI.getType());
995 
996       // FIXME: What does alignment mean for an image?
997       Info.opc = ISD::INTRINSIC_W_CHAIN;
998       Info.flags |= MachineMemOperand::MOLoad;
999     } else if (Attr.hasFnAttr(Attribute::WriteOnly)) {
1000       Info.opc = ISD::INTRINSIC_VOID;
1001 
1002       Type *DataTy = CI.getArgOperand(0)->getType();
1003       if (RsrcIntr->IsImage) {
1004         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1005         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1006         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1007       } else
1008         Info.memVT = EVT::getEVT(DataTy);
1009 
1010       Info.flags |= MachineMemOperand::MOStore;
1011     } else {
1012       // Atomic
1013       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1014                                             ISD::INTRINSIC_W_CHAIN;
1015       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1016       Info.flags |= MachineMemOperand::MOLoad |
1017                     MachineMemOperand::MOStore |
1018                     MachineMemOperand::MODereferenceable;
1019 
1020       // XXX - Should this be volatile without known ordering?
1021       Info.flags |= MachineMemOperand::MOVolatile;
1022 
1023       switch (IntrID) {
1024       default:
1025         break;
1026       case Intrinsic::amdgcn_raw_buffer_load_lds:
1027       case Intrinsic::amdgcn_struct_buffer_load_lds: {
1028         unsigned Width = cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue();
1029         Info.memVT = EVT::getIntegerVT(CI.getContext(), Width * 8);
1030         return true;
1031       }
1032       }
1033     }
1034     return true;
1035   }
1036 
1037   switch (IntrID) {
1038   case Intrinsic::amdgcn_atomic_inc:
1039   case Intrinsic::amdgcn_atomic_dec:
1040   case Intrinsic::amdgcn_ds_ordered_add:
1041   case Intrinsic::amdgcn_ds_ordered_swap:
1042   case Intrinsic::amdgcn_ds_fadd:
1043   case Intrinsic::amdgcn_ds_fmin:
1044   case Intrinsic::amdgcn_ds_fmax: {
1045     Info.opc = ISD::INTRINSIC_W_CHAIN;
1046     Info.memVT = MVT::getVT(CI.getType());
1047     Info.ptrVal = CI.getOperand(0);
1048     Info.align.reset();
1049     Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1050 
1051     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1052     if (!Vol->isZero())
1053       Info.flags |= MachineMemOperand::MOVolatile;
1054 
1055     return true;
1056   }
1057   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1058     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1059 
1060     const GCNTargetMachine &TM =
1061         static_cast<const GCNTargetMachine &>(getTargetMachine());
1062 
1063     Info.opc = ISD::INTRINSIC_W_CHAIN;
1064     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1065     Info.ptrVal = MFI->getBufferPSV(TM);
1066     Info.align.reset();
1067     Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1068 
1069     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1070     if (!Vol || !Vol->isZero())
1071       Info.flags |= MachineMemOperand::MOVolatile;
1072 
1073     return true;
1074   }
1075   case Intrinsic::amdgcn_ds_append:
1076   case Intrinsic::amdgcn_ds_consume: {
1077     Info.opc = ISD::INTRINSIC_W_CHAIN;
1078     Info.memVT = MVT::getVT(CI.getType());
1079     Info.ptrVal = CI.getOperand(0);
1080     Info.align.reset();
1081     Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1082 
1083     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1084     if (!Vol->isZero())
1085       Info.flags |= MachineMemOperand::MOVolatile;
1086 
1087     return true;
1088   }
1089   case Intrinsic::amdgcn_global_atomic_csub: {
1090     Info.opc = ISD::INTRINSIC_W_CHAIN;
1091     Info.memVT = MVT::getVT(CI.getType());
1092     Info.ptrVal = CI.getOperand(0);
1093     Info.align.reset();
1094     Info.flags |= MachineMemOperand::MOLoad |
1095                   MachineMemOperand::MOStore |
1096                   MachineMemOperand::MOVolatile;
1097     return true;
1098   }
1099   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1100     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1101     Info.opc = ISD::INTRINSIC_W_CHAIN;
1102     Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1103 
1104     const GCNTargetMachine &TM =
1105         static_cast<const GCNTargetMachine &>(getTargetMachine());
1106 
1107     Info.ptrVal = MFI->getImagePSV(TM);
1108     Info.align.reset();
1109     Info.flags |= MachineMemOperand::MOLoad |
1110                   MachineMemOperand::MODereferenceable;
1111     return true;
1112   }
1113   case Intrinsic::amdgcn_global_atomic_fadd:
1114   case Intrinsic::amdgcn_global_atomic_fmin:
1115   case Intrinsic::amdgcn_global_atomic_fmax:
1116   case Intrinsic::amdgcn_flat_atomic_fadd:
1117   case Intrinsic::amdgcn_flat_atomic_fmin:
1118   case Intrinsic::amdgcn_flat_atomic_fmax:
1119   case Intrinsic::amdgcn_global_atomic_fadd_v2bf16:
1120   case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16: {
1121     Info.opc = ISD::INTRINSIC_W_CHAIN;
1122     Info.memVT = MVT::getVT(CI.getType());
1123     Info.ptrVal = CI.getOperand(0);
1124     Info.align.reset();
1125     Info.flags |= MachineMemOperand::MOLoad |
1126                   MachineMemOperand::MOStore |
1127                   MachineMemOperand::MODereferenceable |
1128                   MachineMemOperand::MOVolatile;
1129     return true;
1130   }
1131   case Intrinsic::amdgcn_ds_gws_init:
1132   case Intrinsic::amdgcn_ds_gws_barrier:
1133   case Intrinsic::amdgcn_ds_gws_sema_v:
1134   case Intrinsic::amdgcn_ds_gws_sema_br:
1135   case Intrinsic::amdgcn_ds_gws_sema_p:
1136   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1137     Info.opc = ISD::INTRINSIC_VOID;
1138 
1139     const GCNTargetMachine &TM =
1140         static_cast<const GCNTargetMachine &>(getTargetMachine());
1141 
1142     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1143     Info.ptrVal = MFI->getGWSPSV(TM);
1144 
1145     // This is an abstract access, but we need to specify a type and size.
1146     Info.memVT = MVT::i32;
1147     Info.size = 4;
1148     Info.align = Align(4);
1149 
1150     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1151       Info.flags |= MachineMemOperand::MOLoad;
1152     else
1153       Info.flags |= MachineMemOperand::MOStore;
1154     return true;
1155   }
1156   case Intrinsic::amdgcn_global_load_lds: {
1157     Info.opc = ISD::INTRINSIC_VOID;
1158     unsigned Width = cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue();
1159     Info.memVT = EVT::getIntegerVT(CI.getContext(), Width * 8);
1160     Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1161                   MachineMemOperand::MOVolatile;
1162     return true;
1163   }
1164   default:
1165     return false;
1166   }
1167 }
1168 
1169 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1170                                             SmallVectorImpl<Value*> &Ops,
1171                                             Type *&AccessTy) const {
1172   switch (II->getIntrinsicID()) {
1173   case Intrinsic::amdgcn_atomic_inc:
1174   case Intrinsic::amdgcn_atomic_dec:
1175   case Intrinsic::amdgcn_ds_ordered_add:
1176   case Intrinsic::amdgcn_ds_ordered_swap:
1177   case Intrinsic::amdgcn_ds_append:
1178   case Intrinsic::amdgcn_ds_consume:
1179   case Intrinsic::amdgcn_ds_fadd:
1180   case Intrinsic::amdgcn_ds_fmin:
1181   case Intrinsic::amdgcn_ds_fmax:
1182   case Intrinsic::amdgcn_global_atomic_fadd:
1183   case Intrinsic::amdgcn_flat_atomic_fadd:
1184   case Intrinsic::amdgcn_flat_atomic_fmin:
1185   case Intrinsic::amdgcn_flat_atomic_fmax:
1186   case Intrinsic::amdgcn_global_atomic_fadd_v2bf16:
1187   case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16:
1188   case Intrinsic::amdgcn_global_atomic_csub: {
1189     Value *Ptr = II->getArgOperand(0);
1190     AccessTy = II->getType();
1191     Ops.push_back(Ptr);
1192     return true;
1193   }
1194   default:
1195     return false;
1196   }
1197 }
1198 
1199 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1200   if (!Subtarget->hasFlatInstOffsets()) {
1201     // Flat instructions do not have offsets, and only have the register
1202     // address.
1203     return AM.BaseOffs == 0 && AM.Scale == 0;
1204   }
1205 
1206   return AM.Scale == 0 &&
1207          (AM.BaseOffs == 0 ||
1208           Subtarget->getInstrInfo()->isLegalFLATOffset(
1209               AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT));
1210 }
1211 
1212 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1213   if (Subtarget->hasFlatGlobalInsts())
1214     return AM.Scale == 0 &&
1215            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1216                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1217                                     SIInstrFlags::FlatGlobal));
1218 
1219   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1220       // Assume the we will use FLAT for all global memory accesses
1221       // on VI.
1222       // FIXME: This assumption is currently wrong.  On VI we still use
1223       // MUBUF instructions for the r + i addressing mode.  As currently
1224       // implemented, the MUBUF instructions only work on buffer < 4GB.
1225       // It may be possible to support > 4GB buffers with MUBUF instructions,
1226       // by setting the stride value in the resource descriptor which would
1227       // increase the size limit to (stride * 4GB).  However, this is risky,
1228       // because it has never been validated.
1229     return isLegalFlatAddressingMode(AM);
1230   }
1231 
1232   return isLegalMUBUFAddressingMode(AM);
1233 }
1234 
1235 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1236   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1237   // additionally can do r + r + i with addr64. 32-bit has more addressing
1238   // mode options. Depending on the resource constant, it can also do
1239   // (i64 r0) + (i32 r1) * (i14 i).
1240   //
1241   // Private arrays end up using a scratch buffer most of the time, so also
1242   // assume those use MUBUF instructions. Scratch loads / stores are currently
1243   // implemented as mubuf instructions with offen bit set, so slightly
1244   // different than the normal addr64.
1245   if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1246     return false;
1247 
1248   // FIXME: Since we can split immediate into soffset and immediate offset,
1249   // would it make sense to allow any immediate?
1250 
1251   switch (AM.Scale) {
1252   case 0: // r + i or just i, depending on HasBaseReg.
1253     return true;
1254   case 1:
1255     return true; // We have r + r or r + i.
1256   case 2:
1257     if (AM.HasBaseReg) {
1258       // Reject 2 * r + r.
1259       return false;
1260     }
1261 
1262     // Allow 2 * r as r + r
1263     // Or  2 * r + i is allowed as r + r + i.
1264     return true;
1265   default: // Don't allow n * r
1266     return false;
1267   }
1268 }
1269 
1270 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1271                                              const AddrMode &AM, Type *Ty,
1272                                              unsigned AS, Instruction *I) const {
1273   // No global is ever allowed as a base.
1274   if (AM.BaseGV)
1275     return false;
1276 
1277   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1278     return isLegalGlobalAddressingMode(AM);
1279 
1280   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1281       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1282       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1283     // If the offset isn't a multiple of 4, it probably isn't going to be
1284     // correctly aligned.
1285     // FIXME: Can we get the real alignment here?
1286     if (AM.BaseOffs % 4 != 0)
1287       return isLegalMUBUFAddressingMode(AM);
1288 
1289     // There are no SMRD extloads, so if we have to do a small type access we
1290     // will use a MUBUF load.
1291     // FIXME?: We also need to do this if unaligned, but we don't know the
1292     // alignment here.
1293     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1294       return isLegalGlobalAddressingMode(AM);
1295 
1296     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1297       // SMRD instructions have an 8-bit, dword offset on SI.
1298       if (!isUInt<8>(AM.BaseOffs / 4))
1299         return false;
1300     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1301       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1302       // in 8-bits, it can use a smaller encoding.
1303       if (!isUInt<32>(AM.BaseOffs / 4))
1304         return false;
1305     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1306       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1307       if (!isUInt<20>(AM.BaseOffs))
1308         return false;
1309     } else
1310       llvm_unreachable("unhandled generation");
1311 
1312     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1313       return true;
1314 
1315     if (AM.Scale == 1 && AM.HasBaseReg)
1316       return true;
1317 
1318     return false;
1319 
1320   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1321     return isLegalMUBUFAddressingMode(AM);
1322   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1323              AS == AMDGPUAS::REGION_ADDRESS) {
1324     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1325     // field.
1326     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1327     // an 8-bit dword offset but we don't know the alignment here.
1328     if (!isUInt<16>(AM.BaseOffs))
1329       return false;
1330 
1331     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1332       return true;
1333 
1334     if (AM.Scale == 1 && AM.HasBaseReg)
1335       return true;
1336 
1337     return false;
1338   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1339              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1340     // For an unknown address space, this usually means that this is for some
1341     // reason being used for pure arithmetic, and not based on some addressing
1342     // computation. We don't have instructions that compute pointers with any
1343     // addressing modes, so treat them as having no offset like flat
1344     // instructions.
1345     return isLegalFlatAddressingMode(AM);
1346   }
1347 
1348   // Assume a user alias of global for unknown address spaces.
1349   return isLegalGlobalAddressingMode(AM);
1350 }
1351 
1352 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1353                                         const MachineFunction &MF) const {
1354   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1355     return (MemVT.getSizeInBits() <= 4 * 32);
1356   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1357     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1358     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1359   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1360     return (MemVT.getSizeInBits() <= 2 * 32);
1361   }
1362   return true;
1363 }
1364 
1365 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1366     unsigned Size, unsigned AddrSpace, Align Alignment,
1367     MachineMemOperand::Flags Flags, bool *IsFast) const {
1368   if (IsFast)
1369     *IsFast = false;
1370 
1371   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1372       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1373     // Check if alignment requirements for ds_read/write instructions are
1374     // disabled.
1375     if (!Subtarget->hasUnalignedDSAccessEnabled() && Alignment < Align(4))
1376       return false;
1377 
1378     Align RequiredAlignment(PowerOf2Ceil(Size/8)); // Natural alignment.
1379     if (Subtarget->hasLDSMisalignedBug() && Size > 32 &&
1380         Alignment < RequiredAlignment)
1381       return false;
1382 
1383     // Either, the alignment requirements are "enabled", or there is an
1384     // unaligned LDS access related hardware bug though alignment requirements
1385     // are "disabled". In either case, we need to check for proper alignment
1386     // requirements.
1387     //
1388     switch (Size) {
1389     case 64:
1390       // SI has a hardware bug in the LDS / GDS bounds checking: if the base
1391       // address is negative, then the instruction is incorrectly treated as
1392       // out-of-bounds even if base + offsets is in bounds. Split vectorized
1393       // loads here to avoid emitting ds_read2_b32. We may re-combine the
1394       // load later in the SILoadStoreOptimizer.
1395       if (!Subtarget->hasUsableDSOffset() && Alignment < Align(8))
1396         return false;
1397 
1398       // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
1399       // can do a 4 byte aligned, 8 byte access in a single operation using
1400       // ds_read2/write2_b32 with adjacent offsets.
1401       RequiredAlignment = Align(4);
1402 
1403       if (Subtarget->hasUnalignedDSAccessEnabled()) {
1404         // We will either select ds_read_b64/ds_write_b64 or ds_read2_b32/
1405         // ds_write2_b32 depending on the alignment. In either case with either
1406         // alignment there is no faster way of doing this.
1407         if (IsFast)
1408           *IsFast = true;
1409         return true;
1410       }
1411 
1412       break;
1413     case 96:
1414       if (!Subtarget->hasDS96AndDS128())
1415         return false;
1416 
1417       // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
1418       // gfx8 and older.
1419 
1420       if (Subtarget->hasUnalignedDSAccessEnabled()) {
1421         // Naturally aligned access is fastest. However, also report it is Fast
1422         // if memory is aligned less than DWORD. A narrow load or store will be
1423         // be equally slow as a single ds_read_b96/ds_write_b96, but there will
1424         // be more of them, so overall we will pay less penalty issuing a single
1425         // instruction.
1426         if (IsFast)
1427           *IsFast = Alignment >= RequiredAlignment || Alignment < Align(4);
1428         return true;
1429       }
1430 
1431       break;
1432     case 128:
1433       if (!Subtarget->hasDS96AndDS128() || !Subtarget->useDS128())
1434         return false;
1435 
1436       // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
1437       // gfx8 and older, but  we can do a 8 byte aligned, 16 byte access in a
1438       // single operation using ds_read2/write2_b64.
1439       RequiredAlignment = Align(8);
1440 
1441       if (Subtarget->hasUnalignedDSAccessEnabled()) {
1442         // Naturally aligned access is fastest. However, also report it is Fast
1443         // if memory is aligned less than DWORD. A narrow load or store will be
1444         // be equally slow as a single ds_read_b128/ds_write_b128, but there
1445         // will be more of them, so overall we will pay less penalty issuing a
1446         // single instruction.
1447         if (IsFast)
1448           *IsFast = Alignment >= RequiredAlignment || Alignment < Align(4);
1449         return true;
1450       }
1451 
1452       break;
1453     default:
1454       if (Size > 32)
1455         return false;
1456 
1457       break;
1458     }
1459 
1460     if (IsFast)
1461       *IsFast = Alignment >= RequiredAlignment;
1462 
1463     return Alignment >= RequiredAlignment ||
1464            Subtarget->hasUnalignedDSAccessEnabled();
1465   }
1466 
1467   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1468     bool AlignedBy4 = Alignment >= Align(4);
1469     if (IsFast)
1470       *IsFast = AlignedBy4;
1471 
1472     return AlignedBy4 ||
1473            Subtarget->enableFlatScratch() ||
1474            Subtarget->hasUnalignedScratchAccess();
1475   }
1476 
1477   // FIXME: We have to be conservative here and assume that flat operations
1478   // will access scratch.  If we had access to the IR function, then we
1479   // could determine if any private memory was used in the function.
1480   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1481       !Subtarget->hasUnalignedScratchAccess()) {
1482     bool AlignedBy4 = Alignment >= Align(4);
1483     if (IsFast)
1484       *IsFast = AlignedBy4;
1485 
1486     return AlignedBy4;
1487   }
1488 
1489   if (Subtarget->hasUnalignedBufferAccessEnabled()) {
1490     // If we have a uniform constant load, it still requires using a slow
1491     // buffer instruction if unaligned.
1492     if (IsFast) {
1493       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1494       // 2-byte alignment is worse than 1 unless doing a 2-byte access.
1495       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1496                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1497         Alignment >= Align(4) : Alignment != Align(2);
1498     }
1499 
1500     return true;
1501   }
1502 
1503   // Smaller than dword value must be aligned.
1504   if (Size < 32)
1505     return false;
1506 
1507   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1508   // byte-address are ignored, thus forcing Dword alignment.
1509   // This applies to private, global, and constant memory.
1510   if (IsFast)
1511     *IsFast = true;
1512 
1513   return Size >= 32 && Alignment >= Align(4);
1514 }
1515 
1516 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1517     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1518     bool *IsFast) const {
1519   bool Allow = allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1520                                                   Alignment, Flags, IsFast);
1521 
1522   if (Allow && IsFast && Subtarget->hasUnalignedDSAccessEnabled() &&
1523       (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1524        AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1525     // Lie it is fast if +unaligned-access-mode is passed so that DS accesses
1526     // get vectorized. We could use ds_read2_b*/ds_write2_b* instructions on a
1527     // misaligned data which is faster than a pair of ds_read_b*/ds_write_b*
1528     // which would be equally misaligned.
1529     // This is only used by the common passes, selection always calls the
1530     // allowsMisalignedMemoryAccessesImpl version.
1531     *IsFast = true;
1532   }
1533 
1534   return Allow;
1535 }
1536 
1537 EVT SITargetLowering::getOptimalMemOpType(
1538     const MemOp &Op, const AttributeList &FuncAttributes) const {
1539   // FIXME: Should account for address space here.
1540 
1541   // The default fallback uses the private pointer size as a guess for a type to
1542   // use. Make sure we switch these to 64-bit accesses.
1543 
1544   if (Op.size() >= 16 &&
1545       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1546     return MVT::v4i32;
1547 
1548   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1549     return MVT::v2i32;
1550 
1551   // Use the default.
1552   return MVT::Other;
1553 }
1554 
1555 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1556   const MemSDNode *MemNode = cast<MemSDNode>(N);
1557   return MemNode->getMemOperand()->getFlags() & MONoClobber;
1558 }
1559 
1560 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1561   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1562          AS == AMDGPUAS::PRIVATE_ADDRESS;
1563 }
1564 
1565 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1566                                            unsigned DestAS) const {
1567   // Flat -> private/local is a simple truncate.
1568   // Flat -> global is no-op
1569   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1570     return true;
1571 
1572   const GCNTargetMachine &TM =
1573       static_cast<const GCNTargetMachine &>(getTargetMachine());
1574   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1575 }
1576 
1577 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1578   const MemSDNode *MemNode = cast<MemSDNode>(N);
1579 
1580   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1581 }
1582 
1583 TargetLoweringBase::LegalizeTypeAction
1584 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1585   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1586       VT.getScalarType().bitsLE(MVT::i16))
1587     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1588   return TargetLoweringBase::getPreferredVectorAction(VT);
1589 }
1590 
1591 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1592                                                          Type *Ty) const {
1593   // FIXME: Could be smarter if called for vector constants.
1594   return true;
1595 }
1596 
1597 bool SITargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
1598                                                unsigned Index) const {
1599   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
1600     return false;
1601 
1602   // TODO: Add more cases that are cheap.
1603   return Index == 0;
1604 }
1605 
1606 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1607   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1608     switch (Op) {
1609     case ISD::LOAD:
1610     case ISD::STORE:
1611 
1612     // These operations are done with 32-bit instructions anyway.
1613     case ISD::AND:
1614     case ISD::OR:
1615     case ISD::XOR:
1616     case ISD::SELECT:
1617       // TODO: Extensions?
1618       return true;
1619     default:
1620       return false;
1621     }
1622   }
1623 
1624   // SimplifySetCC uses this function to determine whether or not it should
1625   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1626   if (VT == MVT::i1 && Op == ISD::SETCC)
1627     return false;
1628 
1629   return TargetLowering::isTypeDesirableForOp(Op, VT);
1630 }
1631 
1632 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1633                                                    const SDLoc &SL,
1634                                                    SDValue Chain,
1635                                                    uint64_t Offset) const {
1636   const DataLayout &DL = DAG.getDataLayout();
1637   MachineFunction &MF = DAG.getMachineFunction();
1638   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1639 
1640   const ArgDescriptor *InputPtrReg;
1641   const TargetRegisterClass *RC;
1642   LLT ArgTy;
1643   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1644 
1645   std::tie(InputPtrReg, RC, ArgTy) =
1646       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1647 
1648   // We may not have the kernarg segment argument if we have no kernel
1649   // arguments.
1650   if (!InputPtrReg)
1651     return DAG.getConstant(0, SL, PtrVT);
1652 
1653   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1654   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1655     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1656 
1657   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1658 }
1659 
1660 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1661                                             const SDLoc &SL) const {
1662   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1663                                                FIRST_IMPLICIT);
1664   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1665 }
1666 
1667 SDValue SITargetLowering::getLDSKernelId(SelectionDAG &DAG,
1668                                          const SDLoc &SL) const {
1669 
1670   Function &F = DAG.getMachineFunction().getFunction();
1671   Optional<uint32_t> KnownSize =
1672       AMDGPUMachineFunction::getLDSKernelIdMetadata(F);
1673   if (KnownSize.has_value())
1674     return DAG.getConstant(KnownSize.value(), SL, MVT::i32);
1675   return SDValue();
1676 }
1677 
1678 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1679                                          const SDLoc &SL, SDValue Val,
1680                                          bool Signed,
1681                                          const ISD::InputArg *Arg) const {
1682   // First, if it is a widened vector, narrow it.
1683   if (VT.isVector() &&
1684       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1685     EVT NarrowedVT =
1686         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1687                          VT.getVectorNumElements());
1688     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1689                       DAG.getConstant(0, SL, MVT::i32));
1690   }
1691 
1692   // Then convert the vector elements or scalar value.
1693   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1694       VT.bitsLT(MemVT)) {
1695     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1696     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1697   }
1698 
1699   if (MemVT.isFloatingPoint())
1700     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1701   else if (Signed)
1702     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1703   else
1704     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1705 
1706   return Val;
1707 }
1708 
1709 SDValue SITargetLowering::lowerKernargMemParameter(
1710     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1711     uint64_t Offset, Align Alignment, bool Signed,
1712     const ISD::InputArg *Arg) const {
1713   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1714 
1715   // Try to avoid using an extload by loading earlier than the argument address,
1716   // and extracting the relevant bits. The load should hopefully be merged with
1717   // the previous argument.
1718   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1719     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1720     int64_t AlignDownOffset = alignDown(Offset, 4);
1721     int64_t OffsetDiff = Offset - AlignDownOffset;
1722 
1723     EVT IntVT = MemVT.changeTypeToInteger();
1724 
1725     // TODO: If we passed in the base kernel offset we could have a better
1726     // alignment than 4, but we don't really need it.
1727     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1728     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1729                                MachineMemOperand::MODereferenceable |
1730                                    MachineMemOperand::MOInvariant);
1731 
1732     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1733     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1734 
1735     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1736     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1737     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1738 
1739 
1740     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1741   }
1742 
1743   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1744   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1745                              MachineMemOperand::MODereferenceable |
1746                                  MachineMemOperand::MOInvariant);
1747 
1748   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1749   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1750 }
1751 
1752 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1753                                               const SDLoc &SL, SDValue Chain,
1754                                               const ISD::InputArg &Arg) const {
1755   MachineFunction &MF = DAG.getMachineFunction();
1756   MachineFrameInfo &MFI = MF.getFrameInfo();
1757 
1758   if (Arg.Flags.isByVal()) {
1759     unsigned Size = Arg.Flags.getByValSize();
1760     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1761     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1762   }
1763 
1764   unsigned ArgOffset = VA.getLocMemOffset();
1765   unsigned ArgSize = VA.getValVT().getStoreSize();
1766 
1767   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1768 
1769   // Create load nodes to retrieve arguments from the stack.
1770   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1771   SDValue ArgValue;
1772 
1773   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1774   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1775   MVT MemVT = VA.getValVT();
1776 
1777   switch (VA.getLocInfo()) {
1778   default:
1779     break;
1780   case CCValAssign::BCvt:
1781     MemVT = VA.getLocVT();
1782     break;
1783   case CCValAssign::SExt:
1784     ExtType = ISD::SEXTLOAD;
1785     break;
1786   case CCValAssign::ZExt:
1787     ExtType = ISD::ZEXTLOAD;
1788     break;
1789   case CCValAssign::AExt:
1790     ExtType = ISD::EXTLOAD;
1791     break;
1792   }
1793 
1794   ArgValue = DAG.getExtLoad(
1795     ExtType, SL, VA.getLocVT(), Chain, FIN,
1796     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1797     MemVT);
1798   return ArgValue;
1799 }
1800 
1801 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1802   const SIMachineFunctionInfo &MFI,
1803   EVT VT,
1804   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1805   const ArgDescriptor *Reg;
1806   const TargetRegisterClass *RC;
1807   LLT Ty;
1808 
1809   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1810   if (!Reg) {
1811     if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) {
1812       // It's possible for a kernarg intrinsic call to appear in a kernel with
1813       // no allocated segment, in which case we do not add the user sgpr
1814       // argument, so just return null.
1815       return DAG.getConstant(0, SDLoc(), VT);
1816     }
1817 
1818     // It's undefined behavior if a function marked with the amdgpu-no-*
1819     // attributes uses the corresponding intrinsic.
1820     return DAG.getUNDEF(VT);
1821   }
1822 
1823   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1824 }
1825 
1826 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1827                                CallingConv::ID CallConv,
1828                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1829                                FunctionType *FType,
1830                                SIMachineFunctionInfo *Info) {
1831   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1832     const ISD::InputArg *Arg = &Ins[I];
1833 
1834     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1835            "vector type argument should have been split");
1836 
1837     // First check if it's a PS input addr.
1838     if (CallConv == CallingConv::AMDGPU_PS &&
1839         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1840       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1841 
1842       // Inconveniently only the first part of the split is marked as isSplit,
1843       // so skip to the end. We only want to increment PSInputNum once for the
1844       // entire split argument.
1845       if (Arg->Flags.isSplit()) {
1846         while (!Arg->Flags.isSplitEnd()) {
1847           assert((!Arg->VT.isVector() ||
1848                   Arg->VT.getScalarSizeInBits() == 16) &&
1849                  "unexpected vector split in ps argument type");
1850           if (!SkipArg)
1851             Splits.push_back(*Arg);
1852           Arg = &Ins[++I];
1853         }
1854       }
1855 
1856       if (SkipArg) {
1857         // We can safely skip PS inputs.
1858         Skipped.set(Arg->getOrigArgIndex());
1859         ++PSInputNum;
1860         continue;
1861       }
1862 
1863       Info->markPSInputAllocated(PSInputNum);
1864       if (Arg->Used)
1865         Info->markPSInputEnabled(PSInputNum);
1866 
1867       ++PSInputNum;
1868     }
1869 
1870     Splits.push_back(*Arg);
1871   }
1872 }
1873 
1874 // Allocate special inputs passed in VGPRs.
1875 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1876                                                       MachineFunction &MF,
1877                                                       const SIRegisterInfo &TRI,
1878                                                       SIMachineFunctionInfo &Info) const {
1879   const LLT S32 = LLT::scalar(32);
1880   MachineRegisterInfo &MRI = MF.getRegInfo();
1881 
1882   if (Info.hasWorkItemIDX()) {
1883     Register Reg = AMDGPU::VGPR0;
1884     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1885 
1886     CCInfo.AllocateReg(Reg);
1887     unsigned Mask = (Subtarget->hasPackedTID() &&
1888                      Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
1889     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1890   }
1891 
1892   if (Info.hasWorkItemIDY()) {
1893     assert(Info.hasWorkItemIDX());
1894     if (Subtarget->hasPackedTID()) {
1895       Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1896                                                         0x3ff << 10));
1897     } else {
1898       unsigned Reg = AMDGPU::VGPR1;
1899       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1900 
1901       CCInfo.AllocateReg(Reg);
1902       Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1903     }
1904   }
1905 
1906   if (Info.hasWorkItemIDZ()) {
1907     assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
1908     if (Subtarget->hasPackedTID()) {
1909       Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1910                                                         0x3ff << 20));
1911     } else {
1912       unsigned Reg = AMDGPU::VGPR2;
1913       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1914 
1915       CCInfo.AllocateReg(Reg);
1916       Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1917     }
1918   }
1919 }
1920 
1921 // Try to allocate a VGPR at the end of the argument list, or if no argument
1922 // VGPRs are left allocating a stack slot.
1923 // If \p Mask is is given it indicates bitfield position in the register.
1924 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1925 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1926                                          ArgDescriptor Arg = ArgDescriptor()) {
1927   if (Arg.isSet())
1928     return ArgDescriptor::createArg(Arg, Mask);
1929 
1930   ArrayRef<MCPhysReg> ArgVGPRs
1931     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1932   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1933   if (RegIdx == ArgVGPRs.size()) {
1934     // Spill to stack required.
1935     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1936 
1937     return ArgDescriptor::createStack(Offset, Mask);
1938   }
1939 
1940   unsigned Reg = ArgVGPRs[RegIdx];
1941   Reg = CCInfo.AllocateReg(Reg);
1942   assert(Reg != AMDGPU::NoRegister);
1943 
1944   MachineFunction &MF = CCInfo.getMachineFunction();
1945   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1946   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1947   return ArgDescriptor::createRegister(Reg, Mask);
1948 }
1949 
1950 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1951                                              const TargetRegisterClass *RC,
1952                                              unsigned NumArgRegs) {
1953   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1954   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1955   if (RegIdx == ArgSGPRs.size())
1956     report_fatal_error("ran out of SGPRs for arguments");
1957 
1958   unsigned Reg = ArgSGPRs[RegIdx];
1959   Reg = CCInfo.AllocateReg(Reg);
1960   assert(Reg != AMDGPU::NoRegister);
1961 
1962   MachineFunction &MF = CCInfo.getMachineFunction();
1963   MF.addLiveIn(Reg, RC);
1964   return ArgDescriptor::createRegister(Reg);
1965 }
1966 
1967 // If this has a fixed position, we still should allocate the register in the
1968 // CCInfo state. Technically we could get away with this for values passed
1969 // outside of the normal argument range.
1970 static void allocateFixedSGPRInputImpl(CCState &CCInfo,
1971                                        const TargetRegisterClass *RC,
1972                                        MCRegister Reg) {
1973   Reg = CCInfo.AllocateReg(Reg);
1974   assert(Reg != AMDGPU::NoRegister);
1975   MachineFunction &MF = CCInfo.getMachineFunction();
1976   MF.addLiveIn(Reg, RC);
1977 }
1978 
1979 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
1980   if (Arg) {
1981     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
1982                                Arg.getRegister());
1983   } else
1984     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1985 }
1986 
1987 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
1988   if (Arg) {
1989     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
1990                                Arg.getRegister());
1991   } else
1992     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1993 }
1994 
1995 /// Allocate implicit function VGPR arguments at the end of allocated user
1996 /// arguments.
1997 void SITargetLowering::allocateSpecialInputVGPRs(
1998   CCState &CCInfo, MachineFunction &MF,
1999   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2000   const unsigned Mask = 0x3ff;
2001   ArgDescriptor Arg;
2002 
2003   if (Info.hasWorkItemIDX()) {
2004     Arg = allocateVGPR32Input(CCInfo, Mask);
2005     Info.setWorkItemIDX(Arg);
2006   }
2007 
2008   if (Info.hasWorkItemIDY()) {
2009     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
2010     Info.setWorkItemIDY(Arg);
2011   }
2012 
2013   if (Info.hasWorkItemIDZ())
2014     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
2015 }
2016 
2017 /// Allocate implicit function VGPR arguments in fixed registers.
2018 void SITargetLowering::allocateSpecialInputVGPRsFixed(
2019   CCState &CCInfo, MachineFunction &MF,
2020   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2021   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
2022   if (!Reg)
2023     report_fatal_error("failed to allocated VGPR for implicit arguments");
2024 
2025   const unsigned Mask = 0x3ff;
2026   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2027   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
2028   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
2029 }
2030 
2031 void SITargetLowering::allocateSpecialInputSGPRs(
2032   CCState &CCInfo,
2033   MachineFunction &MF,
2034   const SIRegisterInfo &TRI,
2035   SIMachineFunctionInfo &Info) const {
2036   auto &ArgInfo = Info.getArgInfo();
2037 
2038   // TODO: Unify handling with private memory pointers.
2039   if (Info.hasDispatchPtr())
2040     allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
2041 
2042   if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5)
2043     allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
2044 
2045   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
2046   // constant offset from the kernarg segment.
2047   if (Info.hasImplicitArgPtr())
2048     allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
2049 
2050   if (Info.hasDispatchID())
2051     allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2052 
2053   // flat_scratch_init is not applicable for non-kernel functions.
2054 
2055   if (Info.hasWorkGroupIDX())
2056     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2057 
2058   if (Info.hasWorkGroupIDY())
2059     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2060 
2061   if (Info.hasWorkGroupIDZ())
2062     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2063 
2064   if (Info.hasLDSKernelId())
2065     allocateSGPR32Input(CCInfo, ArgInfo.LDSKernelId);
2066 }
2067 
2068 // Allocate special inputs passed in user SGPRs.
2069 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2070                                             MachineFunction &MF,
2071                                             const SIRegisterInfo &TRI,
2072                                             SIMachineFunctionInfo &Info) const {
2073   if (Info.hasImplicitBufferPtr()) {
2074     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2075     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2076     CCInfo.AllocateReg(ImplicitBufferPtrReg);
2077   }
2078 
2079   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2080   if (Info.hasPrivateSegmentBuffer()) {
2081     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2082     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2083     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2084   }
2085 
2086   if (Info.hasDispatchPtr()) {
2087     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2088     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2089     CCInfo.AllocateReg(DispatchPtrReg);
2090   }
2091 
2092   if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) {
2093     Register QueuePtrReg = Info.addQueuePtr(TRI);
2094     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2095     CCInfo.AllocateReg(QueuePtrReg);
2096   }
2097 
2098   if (Info.hasKernargSegmentPtr()) {
2099     MachineRegisterInfo &MRI = MF.getRegInfo();
2100     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2101     CCInfo.AllocateReg(InputPtrReg);
2102 
2103     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2104     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2105   }
2106 
2107   if (Info.hasDispatchID()) {
2108     Register DispatchIDReg = Info.addDispatchID(TRI);
2109     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2110     CCInfo.AllocateReg(DispatchIDReg);
2111   }
2112 
2113   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2114     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2115     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2116     CCInfo.AllocateReg(FlatScratchInitReg);
2117   }
2118 
2119   if (Info.hasLDSKernelId()) {
2120     Register Reg = Info.addLDSKernelId();
2121     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2122     CCInfo.AllocateReg(Reg);
2123   }
2124 
2125   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2126   // these from the dispatch pointer.
2127 }
2128 
2129 // Allocate special input registers that are initialized per-wave.
2130 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2131                                            MachineFunction &MF,
2132                                            SIMachineFunctionInfo &Info,
2133                                            CallingConv::ID CallConv,
2134                                            bool IsShader) const {
2135   if (Subtarget->hasUserSGPRInit16Bug() && !IsShader) {
2136     // Note: user SGPRs are handled by the front-end for graphics shaders
2137     // Pad up the used user SGPRs with dead inputs.
2138     unsigned CurrentUserSGPRs = Info.getNumUserSGPRs();
2139 
2140     // Note we do not count the PrivateSegmentWaveByteOffset. We do not want to
2141     // rely on it to reach 16 since if we end up having no stack usage, it will
2142     // not really be added.
2143     unsigned NumRequiredSystemSGPRs = Info.hasWorkGroupIDX() +
2144                                       Info.hasWorkGroupIDY() +
2145                                       Info.hasWorkGroupIDZ() +
2146                                       Info.hasWorkGroupInfo();
2147     for (unsigned i = NumRequiredSystemSGPRs + CurrentUserSGPRs; i < 16; ++i) {
2148       Register Reg = Info.addReservedUserSGPR();
2149       MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2150       CCInfo.AllocateReg(Reg);
2151     }
2152   }
2153 
2154   if (Info.hasWorkGroupIDX()) {
2155     Register Reg = Info.addWorkGroupIDX();
2156     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2157     CCInfo.AllocateReg(Reg);
2158   }
2159 
2160   if (Info.hasWorkGroupIDY()) {
2161     Register Reg = Info.addWorkGroupIDY();
2162     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2163     CCInfo.AllocateReg(Reg);
2164   }
2165 
2166   if (Info.hasWorkGroupIDZ()) {
2167     Register Reg = Info.addWorkGroupIDZ();
2168     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2169     CCInfo.AllocateReg(Reg);
2170   }
2171 
2172   if (Info.hasWorkGroupInfo()) {
2173     Register Reg = Info.addWorkGroupInfo();
2174     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2175     CCInfo.AllocateReg(Reg);
2176   }
2177 
2178   if (Info.hasPrivateSegmentWaveByteOffset()) {
2179     // Scratch wave offset passed in system SGPR.
2180     unsigned PrivateSegmentWaveByteOffsetReg;
2181 
2182     if (IsShader) {
2183       PrivateSegmentWaveByteOffsetReg =
2184         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2185 
2186       // This is true if the scratch wave byte offset doesn't have a fixed
2187       // location.
2188       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2189         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2190         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2191       }
2192     } else
2193       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2194 
2195     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2196     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2197   }
2198 
2199   assert(!Subtarget->hasUserSGPRInit16Bug() || IsShader ||
2200          Info.getNumPreloadedSGPRs() >= 16);
2201 }
2202 
2203 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2204                                      MachineFunction &MF,
2205                                      const SIRegisterInfo &TRI,
2206                                      SIMachineFunctionInfo &Info) {
2207   // Now that we've figured out where the scratch register inputs are, see if
2208   // should reserve the arguments and use them directly.
2209   MachineFrameInfo &MFI = MF.getFrameInfo();
2210   bool HasStackObjects = MFI.hasStackObjects();
2211   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2212 
2213   // Record that we know we have non-spill stack objects so we don't need to
2214   // check all stack objects later.
2215   if (HasStackObjects)
2216     Info.setHasNonSpillStackObjects(true);
2217 
2218   // Everything live out of a block is spilled with fast regalloc, so it's
2219   // almost certain that spilling will be required.
2220   if (TM.getOptLevel() == CodeGenOpt::None)
2221     HasStackObjects = true;
2222 
2223   // For now assume stack access is needed in any callee functions, so we need
2224   // the scratch registers to pass in.
2225   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2226 
2227   if (!ST.enableFlatScratch()) {
2228     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2229       // If we have stack objects, we unquestionably need the private buffer
2230       // resource. For the Code Object V2 ABI, this will be the first 4 user
2231       // SGPR inputs. We can reserve those and use them directly.
2232 
2233       Register PrivateSegmentBufferReg =
2234           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2235       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2236     } else {
2237       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2238       // We tentatively reserve the last registers (skipping the last registers
2239       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2240       // we'll replace these with the ones immediately after those which were
2241       // really allocated. In the prologue copies will be inserted from the
2242       // argument to these reserved registers.
2243 
2244       // Without HSA, relocations are used for the scratch pointer and the
2245       // buffer resource setup is always inserted in the prologue. Scratch wave
2246       // offset is still in an input SGPR.
2247       Info.setScratchRSrcReg(ReservedBufferReg);
2248     }
2249   }
2250 
2251   MachineRegisterInfo &MRI = MF.getRegInfo();
2252 
2253   // For entry functions we have to set up the stack pointer if we use it,
2254   // whereas non-entry functions get this "for free". This means there is no
2255   // intrinsic advantage to using S32 over S34 in cases where we do not have
2256   // calls but do need a frame pointer (i.e. if we are requested to have one
2257   // because frame pointer elimination is disabled). To keep things simple we
2258   // only ever use S32 as the call ABI stack pointer, and so using it does not
2259   // imply we need a separate frame pointer.
2260   //
2261   // Try to use s32 as the SP, but move it if it would interfere with input
2262   // arguments. This won't work with calls though.
2263   //
2264   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2265   // registers.
2266   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2267     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2268   } else {
2269     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2270 
2271     if (MFI.hasCalls())
2272       report_fatal_error("call in graphics shader with too many input SGPRs");
2273 
2274     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2275       if (!MRI.isLiveIn(Reg)) {
2276         Info.setStackPtrOffsetReg(Reg);
2277         break;
2278       }
2279     }
2280 
2281     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2282       report_fatal_error("failed to find register for SP");
2283   }
2284 
2285   // hasFP should be accurate for entry functions even before the frame is
2286   // finalized, because it does not rely on the known stack size, only
2287   // properties like whether variable sized objects are present.
2288   if (ST.getFrameLowering()->hasFP(MF)) {
2289     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2290   }
2291 }
2292 
2293 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2294   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2295   return !Info->isEntryFunction();
2296 }
2297 
2298 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2299 
2300 }
2301 
2302 void SITargetLowering::insertCopiesSplitCSR(
2303   MachineBasicBlock *Entry,
2304   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2305   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2306 
2307   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2308   if (!IStart)
2309     return;
2310 
2311   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2312   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2313   MachineBasicBlock::iterator MBBI = Entry->begin();
2314   for (const MCPhysReg *I = IStart; *I; ++I) {
2315     const TargetRegisterClass *RC = nullptr;
2316     if (AMDGPU::SReg_64RegClass.contains(*I))
2317       RC = &AMDGPU::SGPR_64RegClass;
2318     else if (AMDGPU::SReg_32RegClass.contains(*I))
2319       RC = &AMDGPU::SGPR_32RegClass;
2320     else
2321       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2322 
2323     Register NewVR = MRI->createVirtualRegister(RC);
2324     // Create copy from CSR to a virtual register.
2325     Entry->addLiveIn(*I);
2326     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2327       .addReg(*I);
2328 
2329     // Insert the copy-back instructions right before the terminator.
2330     for (auto *Exit : Exits)
2331       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2332               TII->get(TargetOpcode::COPY), *I)
2333         .addReg(NewVR);
2334   }
2335 }
2336 
2337 SDValue SITargetLowering::LowerFormalArguments(
2338     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2339     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2340     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2341   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2342 
2343   MachineFunction &MF = DAG.getMachineFunction();
2344   const Function &Fn = MF.getFunction();
2345   FunctionType *FType = MF.getFunction().getFunctionType();
2346   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2347 
2348   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2349     DiagnosticInfoUnsupported NoGraphicsHSA(
2350         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2351     DAG.getContext()->diagnose(NoGraphicsHSA);
2352     return DAG.getEntryNode();
2353   }
2354 
2355   Info->allocateModuleLDSGlobal(Fn);
2356 
2357   SmallVector<ISD::InputArg, 16> Splits;
2358   SmallVector<CCValAssign, 16> ArgLocs;
2359   BitVector Skipped(Ins.size());
2360   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2361                  *DAG.getContext());
2362 
2363   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2364   bool IsKernel = AMDGPU::isKernel(CallConv);
2365   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2366 
2367   if (IsGraphics) {
2368     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2369            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2370            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2371            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2372            !Info->hasLDSKernelId() && !Info->hasWorkItemIDX() &&
2373            !Info->hasWorkItemIDY() && !Info->hasWorkItemIDZ());
2374   }
2375 
2376   if (CallConv == CallingConv::AMDGPU_PS) {
2377     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2378 
2379     // At least one interpolation mode must be enabled or else the GPU will
2380     // hang.
2381     //
2382     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2383     // set PSInputAddr, the user wants to enable some bits after the compilation
2384     // based on run-time states. Since we can't know what the final PSInputEna
2385     // will look like, so we shouldn't do anything here and the user should take
2386     // responsibility for the correct programming.
2387     //
2388     // Otherwise, the following restrictions apply:
2389     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2390     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2391     //   enabled too.
2392     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2393         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2394       CCInfo.AllocateReg(AMDGPU::VGPR0);
2395       CCInfo.AllocateReg(AMDGPU::VGPR1);
2396       Info->markPSInputAllocated(0);
2397       Info->markPSInputEnabled(0);
2398     }
2399     if (Subtarget->isAmdPalOS()) {
2400       // For isAmdPalOS, the user does not enable some bits after compilation
2401       // based on run-time states; the register values being generated here are
2402       // the final ones set in hardware. Therefore we need to apply the
2403       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2404       // a bit is set in PSInputAddr but not PSInputEnable is where the
2405       // frontend set up an input arg for a particular interpolation mode, but
2406       // nothing uses that input arg. Really we should have an earlier pass
2407       // that removes such an arg.)
2408       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2409       if ((PsInputBits & 0x7F) == 0 ||
2410           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2411         Info->markPSInputEnabled(
2412             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2413     }
2414   } else if (IsKernel) {
2415     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2416   } else {
2417     Splits.append(Ins.begin(), Ins.end());
2418   }
2419 
2420   if (IsEntryFunc) {
2421     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2422     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2423   } else if (!IsGraphics) {
2424     // For the fixed ABI, pass workitem IDs in the last argument register.
2425     allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2426   }
2427 
2428   if (IsKernel) {
2429     analyzeFormalArgumentsCompute(CCInfo, Ins);
2430   } else {
2431     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2432     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2433   }
2434 
2435   SmallVector<SDValue, 16> Chains;
2436 
2437   // FIXME: This is the minimum kernel argument alignment. We should improve
2438   // this to the maximum alignment of the arguments.
2439   //
2440   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2441   // kern arg offset.
2442   const Align KernelArgBaseAlign = Align(16);
2443 
2444   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2445     const ISD::InputArg &Arg = Ins[i];
2446     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2447       InVals.push_back(DAG.getUNDEF(Arg.VT));
2448       continue;
2449     }
2450 
2451     CCValAssign &VA = ArgLocs[ArgIdx++];
2452     MVT VT = VA.getLocVT();
2453 
2454     if (IsEntryFunc && VA.isMemLoc()) {
2455       VT = Ins[i].VT;
2456       EVT MemVT = VA.getLocVT();
2457 
2458       const uint64_t Offset = VA.getLocMemOffset();
2459       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2460 
2461       if (Arg.Flags.isByRef()) {
2462         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2463 
2464         const GCNTargetMachine &TM =
2465             static_cast<const GCNTargetMachine &>(getTargetMachine());
2466         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2467                                     Arg.Flags.getPointerAddrSpace())) {
2468           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2469                                      Arg.Flags.getPointerAddrSpace());
2470         }
2471 
2472         InVals.push_back(Ptr);
2473         continue;
2474       }
2475 
2476       SDValue Arg = lowerKernargMemParameter(
2477         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2478       Chains.push_back(Arg.getValue(1));
2479 
2480       auto *ParamTy =
2481         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2482       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2483           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2484                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2485         // On SI local pointers are just offsets into LDS, so they are always
2486         // less than 16-bits.  On CI and newer they could potentially be
2487         // real pointers, so we can't guarantee their size.
2488         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2489                           DAG.getValueType(MVT::i16));
2490       }
2491 
2492       InVals.push_back(Arg);
2493       continue;
2494     } else if (!IsEntryFunc && VA.isMemLoc()) {
2495       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2496       InVals.push_back(Val);
2497       if (!Arg.Flags.isByVal())
2498         Chains.push_back(Val.getValue(1));
2499       continue;
2500     }
2501 
2502     assert(VA.isRegLoc() && "Parameter must be in a register!");
2503 
2504     Register Reg = VA.getLocReg();
2505     const TargetRegisterClass *RC = nullptr;
2506     if (AMDGPU::VGPR_32RegClass.contains(Reg))
2507       RC = &AMDGPU::VGPR_32RegClass;
2508     else if (AMDGPU::SGPR_32RegClass.contains(Reg))
2509       RC = &AMDGPU::SGPR_32RegClass;
2510     else
2511       llvm_unreachable("Unexpected register class in LowerFormalArguments!");
2512     EVT ValVT = VA.getValVT();
2513 
2514     Reg = MF.addLiveIn(Reg, RC);
2515     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2516 
2517     if (Arg.Flags.isSRet()) {
2518       // The return object should be reasonably addressable.
2519 
2520       // FIXME: This helps when the return is a real sret. If it is a
2521       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2522       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2523       unsigned NumBits
2524         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2525       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2526         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2527     }
2528 
2529     // If this is an 8 or 16-bit value, it is really passed promoted
2530     // to 32 bits. Insert an assert[sz]ext to capture this, then
2531     // truncate to the right size.
2532     switch (VA.getLocInfo()) {
2533     case CCValAssign::Full:
2534       break;
2535     case CCValAssign::BCvt:
2536       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2537       break;
2538     case CCValAssign::SExt:
2539       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2540                         DAG.getValueType(ValVT));
2541       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2542       break;
2543     case CCValAssign::ZExt:
2544       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2545                         DAG.getValueType(ValVT));
2546       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2547       break;
2548     case CCValAssign::AExt:
2549       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2550       break;
2551     default:
2552       llvm_unreachable("Unknown loc info!");
2553     }
2554 
2555     InVals.push_back(Val);
2556   }
2557 
2558   // Start adding system SGPRs.
2559   if (IsEntryFunc) {
2560     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2561   } else {
2562     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2563     if (!IsGraphics)
2564       allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2565   }
2566 
2567   auto &ArgUsageInfo =
2568     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2569   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2570 
2571   unsigned StackArgSize = CCInfo.getNextStackOffset();
2572   Info->setBytesInStackArgArea(StackArgSize);
2573 
2574   return Chains.empty() ? Chain :
2575     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2576 }
2577 
2578 // TODO: If return values can't fit in registers, we should return as many as
2579 // possible in registers before passing on stack.
2580 bool SITargetLowering::CanLowerReturn(
2581   CallingConv::ID CallConv,
2582   MachineFunction &MF, bool IsVarArg,
2583   const SmallVectorImpl<ISD::OutputArg> &Outs,
2584   LLVMContext &Context) const {
2585   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2586   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2587   // for shaders. Vector types should be explicitly handled by CC.
2588   if (AMDGPU::isEntryFunctionCC(CallConv))
2589     return true;
2590 
2591   SmallVector<CCValAssign, 16> RVLocs;
2592   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2593   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2594 }
2595 
2596 SDValue
2597 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2598                               bool isVarArg,
2599                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2600                               const SmallVectorImpl<SDValue> &OutVals,
2601                               const SDLoc &DL, SelectionDAG &DAG) const {
2602   MachineFunction &MF = DAG.getMachineFunction();
2603   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2604 
2605   if (AMDGPU::isKernel(CallConv)) {
2606     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2607                                              OutVals, DL, DAG);
2608   }
2609 
2610   bool IsShader = AMDGPU::isShader(CallConv);
2611 
2612   Info->setIfReturnsVoid(Outs.empty());
2613   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2614 
2615   // CCValAssign - represent the assignment of the return value to a location.
2616   SmallVector<CCValAssign, 48> RVLocs;
2617   SmallVector<ISD::OutputArg, 48> Splits;
2618 
2619   // CCState - Info about the registers and stack slots.
2620   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2621                  *DAG.getContext());
2622 
2623   // Analyze outgoing return values.
2624   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2625 
2626   SDValue Flag;
2627   SmallVector<SDValue, 48> RetOps;
2628   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2629 
2630   // Copy the result values into the output registers.
2631   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2632        ++I, ++RealRVLocIdx) {
2633     CCValAssign &VA = RVLocs[I];
2634     assert(VA.isRegLoc() && "Can only return in registers!");
2635     // TODO: Partially return in registers if return values don't fit.
2636     SDValue Arg = OutVals[RealRVLocIdx];
2637 
2638     // Copied from other backends.
2639     switch (VA.getLocInfo()) {
2640     case CCValAssign::Full:
2641       break;
2642     case CCValAssign::BCvt:
2643       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2644       break;
2645     case CCValAssign::SExt:
2646       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2647       break;
2648     case CCValAssign::ZExt:
2649       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2650       break;
2651     case CCValAssign::AExt:
2652       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2653       break;
2654     default:
2655       llvm_unreachable("Unknown loc info!");
2656     }
2657 
2658     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2659     Flag = Chain.getValue(1);
2660     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2661   }
2662 
2663   // FIXME: Does sret work properly?
2664   if (!Info->isEntryFunction()) {
2665     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2666     const MCPhysReg *I =
2667       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2668     if (I) {
2669       for (; *I; ++I) {
2670         if (AMDGPU::SReg_64RegClass.contains(*I))
2671           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2672         else if (AMDGPU::SReg_32RegClass.contains(*I))
2673           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2674         else
2675           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2676       }
2677     }
2678   }
2679 
2680   // Update chain and glue.
2681   RetOps[0] = Chain;
2682   if (Flag.getNode())
2683     RetOps.push_back(Flag);
2684 
2685   unsigned Opc = AMDGPUISD::ENDPGM;
2686   if (!IsWaveEnd)
2687     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2688   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2689 }
2690 
2691 SDValue SITargetLowering::LowerCallResult(
2692     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2693     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2694     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2695     SDValue ThisVal) const {
2696   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2697 
2698   // Assign locations to each value returned by this call.
2699   SmallVector<CCValAssign, 16> RVLocs;
2700   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2701                  *DAG.getContext());
2702   CCInfo.AnalyzeCallResult(Ins, RetCC);
2703 
2704   // Copy all of the result registers out of their specified physreg.
2705   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2706     CCValAssign VA = RVLocs[i];
2707     SDValue Val;
2708 
2709     if (VA.isRegLoc()) {
2710       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2711       Chain = Val.getValue(1);
2712       InFlag = Val.getValue(2);
2713     } else if (VA.isMemLoc()) {
2714       report_fatal_error("TODO: return values in memory");
2715     } else
2716       llvm_unreachable("unknown argument location type");
2717 
2718     switch (VA.getLocInfo()) {
2719     case CCValAssign::Full:
2720       break;
2721     case CCValAssign::BCvt:
2722       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2723       break;
2724     case CCValAssign::ZExt:
2725       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2726                         DAG.getValueType(VA.getValVT()));
2727       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2728       break;
2729     case CCValAssign::SExt:
2730       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2731                         DAG.getValueType(VA.getValVT()));
2732       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2733       break;
2734     case CCValAssign::AExt:
2735       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2736       break;
2737     default:
2738       llvm_unreachable("Unknown loc info!");
2739     }
2740 
2741     InVals.push_back(Val);
2742   }
2743 
2744   return Chain;
2745 }
2746 
2747 // Add code to pass special inputs required depending on used features separate
2748 // from the explicit user arguments present in the IR.
2749 void SITargetLowering::passSpecialInputs(
2750     CallLoweringInfo &CLI,
2751     CCState &CCInfo,
2752     const SIMachineFunctionInfo &Info,
2753     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2754     SmallVectorImpl<SDValue> &MemOpChains,
2755     SDValue Chain) const {
2756   // If we don't have a call site, this was a call inserted by
2757   // legalization. These can never use special inputs.
2758   if (!CLI.CB)
2759     return;
2760 
2761   SelectionDAG &DAG = CLI.DAG;
2762   const SDLoc &DL = CLI.DL;
2763   const Function &F = DAG.getMachineFunction().getFunction();
2764 
2765   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2766   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2767 
2768   const AMDGPUFunctionArgInfo *CalleeArgInfo
2769     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2770   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2771     auto &ArgUsageInfo =
2772       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2773     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2774   }
2775 
2776   // TODO: Unify with private memory register handling. This is complicated by
2777   // the fact that at least in kernels, the input argument is not necessarily
2778   // in the same location as the input.
2779   static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
2780                              StringLiteral> ImplicitAttrs[] = {
2781     {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"},
2782     {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" },
2783     {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"},
2784     {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"},
2785     {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"},
2786     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"},
2787     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"},
2788     {AMDGPUFunctionArgInfo::LDS_KERNEL_ID,"amdgpu-no-lds-kernel-id"},
2789   };
2790 
2791   for (auto Attr : ImplicitAttrs) {
2792     const ArgDescriptor *OutgoingArg;
2793     const TargetRegisterClass *ArgRC;
2794     LLT ArgTy;
2795 
2796     AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first;
2797 
2798     // If the callee does not use the attribute value, skip copying the value.
2799     if (CLI.CB->hasFnAttr(Attr.second))
2800       continue;
2801 
2802     std::tie(OutgoingArg, ArgRC, ArgTy) =
2803         CalleeArgInfo->getPreloadedValue(InputID);
2804     if (!OutgoingArg)
2805       continue;
2806 
2807     const ArgDescriptor *IncomingArg;
2808     const TargetRegisterClass *IncomingArgRC;
2809     LLT Ty;
2810     std::tie(IncomingArg, IncomingArgRC, Ty) =
2811         CallerArgInfo.getPreloadedValue(InputID);
2812     assert(IncomingArgRC == ArgRC);
2813 
2814     // All special arguments are ints for now.
2815     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2816     SDValue InputReg;
2817 
2818     if (IncomingArg) {
2819       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2820     } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
2821       // The implicit arg ptr is special because it doesn't have a corresponding
2822       // input for kernels, and is computed from the kernarg segment pointer.
2823       InputReg = getImplicitArgPtr(DAG, DL);
2824     } else if (InputID == AMDGPUFunctionArgInfo::LDS_KERNEL_ID) {
2825       Optional<uint32_t> Id = AMDGPUMachineFunction::getLDSKernelIdMetadata(F);
2826       if (Id.has_value()) {
2827         InputReg = DAG.getConstant(Id.value(), DL, ArgVT);
2828       } else {
2829         InputReg = DAG.getUNDEF(ArgVT);
2830       }
2831     } else {
2832       // We may have proven the input wasn't needed, although the ABI is
2833       // requiring it. We just need to allocate the register appropriately.
2834       InputReg = DAG.getUNDEF(ArgVT);
2835     }
2836 
2837     if (OutgoingArg->isRegister()) {
2838       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2839       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2840         report_fatal_error("failed to allocate implicit input argument");
2841     } else {
2842       unsigned SpecialArgOffset =
2843           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2844       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2845                                               SpecialArgOffset);
2846       MemOpChains.push_back(ArgStore);
2847     }
2848   }
2849 
2850   // Pack workitem IDs into a single register or pass it as is if already
2851   // packed.
2852   const ArgDescriptor *OutgoingArg;
2853   const TargetRegisterClass *ArgRC;
2854   LLT Ty;
2855 
2856   std::tie(OutgoingArg, ArgRC, Ty) =
2857       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2858   if (!OutgoingArg)
2859     std::tie(OutgoingArg, ArgRC, Ty) =
2860         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2861   if (!OutgoingArg)
2862     std::tie(OutgoingArg, ArgRC, Ty) =
2863         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2864   if (!OutgoingArg)
2865     return;
2866 
2867   const ArgDescriptor *IncomingArgX = std::get<0>(
2868       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2869   const ArgDescriptor *IncomingArgY = std::get<0>(
2870       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2871   const ArgDescriptor *IncomingArgZ = std::get<0>(
2872       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2873 
2874   SDValue InputReg;
2875   SDLoc SL;
2876 
2877   const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
2878   const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
2879   const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
2880 
2881   // If incoming ids are not packed we need to pack them.
2882   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
2883       NeedWorkItemIDX) {
2884     if (Subtarget->getMaxWorkitemID(F, 0) != 0) {
2885       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2886     } else {
2887       InputReg = DAG.getConstant(0, DL, MVT::i32);
2888     }
2889   }
2890 
2891   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
2892       NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) {
2893     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2894     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2895                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2896     InputReg = InputReg.getNode() ?
2897                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2898   }
2899 
2900   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
2901       NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) {
2902     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2903     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2904                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2905     InputReg = InputReg.getNode() ?
2906                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2907   }
2908 
2909   if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
2910     if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) {
2911       // We're in a situation where the outgoing function requires the workitem
2912       // ID, but the calling function does not have it (e.g a graphics function
2913       // calling a C calling convention function). This is illegal, but we need
2914       // to produce something.
2915       InputReg = DAG.getUNDEF(MVT::i32);
2916     } else {
2917       // Workitem ids are already packed, any of present incoming arguments
2918       // will carry all required fields.
2919       ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2920         IncomingArgX ? *IncomingArgX :
2921         IncomingArgY ? *IncomingArgY :
2922         *IncomingArgZ, ~0u);
2923       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2924     }
2925   }
2926 
2927   if (OutgoingArg->isRegister()) {
2928     if (InputReg)
2929       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2930 
2931     CCInfo.AllocateReg(OutgoingArg->getRegister());
2932   } else {
2933     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2934     if (InputReg) {
2935       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2936                                               SpecialArgOffset);
2937       MemOpChains.push_back(ArgStore);
2938     }
2939   }
2940 }
2941 
2942 static bool canGuaranteeTCO(CallingConv::ID CC) {
2943   return CC == CallingConv::Fast;
2944 }
2945 
2946 /// Return true if we might ever do TCO for calls with this calling convention.
2947 static bool mayTailCallThisCC(CallingConv::ID CC) {
2948   switch (CC) {
2949   case CallingConv::C:
2950   case CallingConv::AMDGPU_Gfx:
2951     return true;
2952   default:
2953     return canGuaranteeTCO(CC);
2954   }
2955 }
2956 
2957 bool SITargetLowering::isEligibleForTailCallOptimization(
2958     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2959     const SmallVectorImpl<ISD::OutputArg> &Outs,
2960     const SmallVectorImpl<SDValue> &OutVals,
2961     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2962   if (!mayTailCallThisCC(CalleeCC))
2963     return false;
2964 
2965   // For a divergent call target, we need to do a waterfall loop over the
2966   // possible callees which precludes us from using a simple jump.
2967   if (Callee->isDivergent())
2968     return false;
2969 
2970   MachineFunction &MF = DAG.getMachineFunction();
2971   const Function &CallerF = MF.getFunction();
2972   CallingConv::ID CallerCC = CallerF.getCallingConv();
2973   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2974   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2975 
2976   // Kernels aren't callable, and don't have a live in return address so it
2977   // doesn't make sense to do a tail call with entry functions.
2978   if (!CallerPreserved)
2979     return false;
2980 
2981   bool CCMatch = CallerCC == CalleeCC;
2982 
2983   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2984     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2985       return true;
2986     return false;
2987   }
2988 
2989   // TODO: Can we handle var args?
2990   if (IsVarArg)
2991     return false;
2992 
2993   for (const Argument &Arg : CallerF.args()) {
2994     if (Arg.hasByValAttr())
2995       return false;
2996   }
2997 
2998   LLVMContext &Ctx = *DAG.getContext();
2999 
3000   // Check that the call results are passed in the same way.
3001   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
3002                                   CCAssignFnForCall(CalleeCC, IsVarArg),
3003                                   CCAssignFnForCall(CallerCC, IsVarArg)))
3004     return false;
3005 
3006   // The callee has to preserve all registers the caller needs to preserve.
3007   if (!CCMatch) {
3008     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3009     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3010       return false;
3011   }
3012 
3013   // Nothing more to check if the callee is taking no arguments.
3014   if (Outs.empty())
3015     return true;
3016 
3017   SmallVector<CCValAssign, 16> ArgLocs;
3018   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
3019 
3020   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
3021 
3022   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
3023   // If the stack arguments for this call do not fit into our own save area then
3024   // the call cannot be made tail.
3025   // TODO: Is this really necessary?
3026   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3027     return false;
3028 
3029   const MachineRegisterInfo &MRI = MF.getRegInfo();
3030   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
3031 }
3032 
3033 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3034   if (!CI->isTailCall())
3035     return false;
3036 
3037   const Function *ParentFn = CI->getParent()->getParent();
3038   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
3039     return false;
3040   return true;
3041 }
3042 
3043 // The wave scratch offset register is used as the global base pointer.
3044 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
3045                                     SmallVectorImpl<SDValue> &InVals) const {
3046   SelectionDAG &DAG = CLI.DAG;
3047   const SDLoc &DL = CLI.DL;
3048   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3049   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3050   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3051   SDValue Chain = CLI.Chain;
3052   SDValue Callee = CLI.Callee;
3053   bool &IsTailCall = CLI.IsTailCall;
3054   CallingConv::ID CallConv = CLI.CallConv;
3055   bool IsVarArg = CLI.IsVarArg;
3056   bool IsSibCall = false;
3057   bool IsThisReturn = false;
3058   MachineFunction &MF = DAG.getMachineFunction();
3059 
3060   if (Callee.isUndef() || isNullConstant(Callee)) {
3061     if (!CLI.IsTailCall) {
3062       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
3063         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
3064     }
3065 
3066     return Chain;
3067   }
3068 
3069   if (IsVarArg) {
3070     return lowerUnhandledCall(CLI, InVals,
3071                               "unsupported call to variadic function ");
3072   }
3073 
3074   if (!CLI.CB)
3075     report_fatal_error("unsupported libcall legalization");
3076 
3077   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
3078     return lowerUnhandledCall(CLI, InVals,
3079                               "unsupported required tail call to function ");
3080   }
3081 
3082   if (AMDGPU::isShader(CallConv)) {
3083     // Note the issue is with the CC of the called function, not of the call
3084     // itself.
3085     return lowerUnhandledCall(CLI, InVals,
3086                               "unsupported call to a shader function ");
3087   }
3088 
3089   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
3090       CallConv != CallingConv::AMDGPU_Gfx) {
3091     // Only allow calls with specific calling conventions.
3092     return lowerUnhandledCall(CLI, InVals,
3093                               "unsupported calling convention for call from "
3094                               "graphics shader of function ");
3095   }
3096 
3097   if (IsTailCall) {
3098     IsTailCall = isEligibleForTailCallOptimization(
3099       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3100     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
3101       report_fatal_error("failed to perform tail call elimination on a call "
3102                          "site marked musttail");
3103     }
3104 
3105     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3106 
3107     // A sibling call is one where we're under the usual C ABI and not planning
3108     // to change that but can still do a tail call:
3109     if (!TailCallOpt && IsTailCall)
3110       IsSibCall = true;
3111 
3112     if (IsTailCall)
3113       ++NumTailCalls;
3114   }
3115 
3116   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3117   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3118   SmallVector<SDValue, 8> MemOpChains;
3119 
3120   // Analyze operands of the call, assigning locations to each operand.
3121   SmallVector<CCValAssign, 16> ArgLocs;
3122   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3123   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3124 
3125   if (CallConv != CallingConv::AMDGPU_Gfx) {
3126     // With a fixed ABI, allocate fixed registers before user arguments.
3127     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3128   }
3129 
3130   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3131 
3132   // Get a count of how many bytes are to be pushed on the stack.
3133   unsigned NumBytes = CCInfo.getNextStackOffset();
3134 
3135   if (IsSibCall) {
3136     // Since we're not changing the ABI to make this a tail call, the memory
3137     // operands are already available in the caller's incoming argument space.
3138     NumBytes = 0;
3139   }
3140 
3141   // FPDiff is the byte offset of the call's argument area from the callee's.
3142   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3143   // by this amount for a tail call. In a sibling call it must be 0 because the
3144   // caller will deallocate the entire stack and the callee still expects its
3145   // arguments to begin at SP+0. Completely unused for non-tail calls.
3146   int32_t FPDiff = 0;
3147   MachineFrameInfo &MFI = MF.getFrameInfo();
3148 
3149   // Adjust the stack pointer for the new arguments...
3150   // These operations are automatically eliminated by the prolog/epilog pass
3151   if (!IsSibCall) {
3152     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3153 
3154     if (!Subtarget->enableFlatScratch()) {
3155       SmallVector<SDValue, 4> CopyFromChains;
3156 
3157       // In the HSA case, this should be an identity copy.
3158       SDValue ScratchRSrcReg
3159         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3160       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3161       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3162       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3163     }
3164   }
3165 
3166   MVT PtrVT = MVT::i32;
3167 
3168   // Walk the register/memloc assignments, inserting copies/loads.
3169   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3170     CCValAssign &VA = ArgLocs[i];
3171     SDValue Arg = OutVals[i];
3172 
3173     // Promote the value if needed.
3174     switch (VA.getLocInfo()) {
3175     case CCValAssign::Full:
3176       break;
3177     case CCValAssign::BCvt:
3178       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3179       break;
3180     case CCValAssign::ZExt:
3181       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3182       break;
3183     case CCValAssign::SExt:
3184       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3185       break;
3186     case CCValAssign::AExt:
3187       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3188       break;
3189     case CCValAssign::FPExt:
3190       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3191       break;
3192     default:
3193       llvm_unreachable("Unknown loc info!");
3194     }
3195 
3196     if (VA.isRegLoc()) {
3197       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3198     } else {
3199       assert(VA.isMemLoc());
3200 
3201       SDValue DstAddr;
3202       MachinePointerInfo DstInfo;
3203 
3204       unsigned LocMemOffset = VA.getLocMemOffset();
3205       int32_t Offset = LocMemOffset;
3206 
3207       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3208       MaybeAlign Alignment;
3209 
3210       if (IsTailCall) {
3211         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3212         unsigned OpSize = Flags.isByVal() ?
3213           Flags.getByValSize() : VA.getValVT().getStoreSize();
3214 
3215         // FIXME: We can have better than the minimum byval required alignment.
3216         Alignment =
3217             Flags.isByVal()
3218                 ? Flags.getNonZeroByValAlign()
3219                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3220 
3221         Offset = Offset + FPDiff;
3222         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3223 
3224         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3225         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3226 
3227         // Make sure any stack arguments overlapping with where we're storing
3228         // are loaded before this eventual operation. Otherwise they'll be
3229         // clobbered.
3230 
3231         // FIXME: Why is this really necessary? This seems to just result in a
3232         // lot of code to copy the stack and write them back to the same
3233         // locations, which are supposed to be immutable?
3234         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3235       } else {
3236         // Stores to the argument stack area are relative to the stack pointer.
3237         SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3238                                         MVT::i32);
3239         DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3240         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3241         Alignment =
3242             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3243       }
3244 
3245       if (Outs[i].Flags.isByVal()) {
3246         SDValue SizeNode =
3247             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3248         SDValue Cpy =
3249             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3250                           Outs[i].Flags.getNonZeroByValAlign(),
3251                           /*isVol = */ false, /*AlwaysInline = */ true,
3252                           /*isTailCall = */ false, DstInfo,
3253                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3254 
3255         MemOpChains.push_back(Cpy);
3256       } else {
3257         SDValue Store =
3258             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3259         MemOpChains.push_back(Store);
3260       }
3261     }
3262   }
3263 
3264   if (!MemOpChains.empty())
3265     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3266 
3267   // Build a sequence of copy-to-reg nodes chained together with token chain
3268   // and flag operands which copy the outgoing args into the appropriate regs.
3269   SDValue InFlag;
3270   for (auto &RegToPass : RegsToPass) {
3271     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3272                              RegToPass.second, InFlag);
3273     InFlag = Chain.getValue(1);
3274   }
3275 
3276 
3277   // We don't usually want to end the call-sequence here because we would tidy
3278   // the frame up *after* the call, however in the ABI-changing tail-call case
3279   // we've carefully laid out the parameters so that when sp is reset they'll be
3280   // in the correct location.
3281   if (IsTailCall && !IsSibCall) {
3282     Chain = DAG.getCALLSEQ_END(Chain,
3283                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3284                                DAG.getTargetConstant(0, DL, MVT::i32),
3285                                InFlag, DL);
3286     InFlag = Chain.getValue(1);
3287   }
3288 
3289   std::vector<SDValue> Ops;
3290   Ops.push_back(Chain);
3291   Ops.push_back(Callee);
3292   // Add a redundant copy of the callee global which will not be legalized, as
3293   // we need direct access to the callee later.
3294   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3295     const GlobalValue *GV = GSD->getGlobal();
3296     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3297   } else {
3298     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3299   }
3300 
3301   if (IsTailCall) {
3302     // Each tail call may have to adjust the stack by a different amount, so
3303     // this information must travel along with the operation for eventual
3304     // consumption by emitEpilogue.
3305     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3306   }
3307 
3308   // Add argument registers to the end of the list so that they are known live
3309   // into the call.
3310   for (auto &RegToPass : RegsToPass) {
3311     Ops.push_back(DAG.getRegister(RegToPass.first,
3312                                   RegToPass.second.getValueType()));
3313   }
3314 
3315   // Add a register mask operand representing the call-preserved registers.
3316 
3317   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3318   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3319   assert(Mask && "Missing call preserved mask for calling convention");
3320   Ops.push_back(DAG.getRegisterMask(Mask));
3321 
3322   if (InFlag.getNode())
3323     Ops.push_back(InFlag);
3324 
3325   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3326 
3327   // If we're doing a tall call, use a TC_RETURN here rather than an
3328   // actual call instruction.
3329   if (IsTailCall) {
3330     MFI.setHasTailCall();
3331     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3332   }
3333 
3334   // Returns a chain and a flag for retval copy to use.
3335   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3336   Chain = Call.getValue(0);
3337   InFlag = Call.getValue(1);
3338 
3339   uint64_t CalleePopBytes = NumBytes;
3340   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3341                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3342                              InFlag, DL);
3343   if (!Ins.empty())
3344     InFlag = Chain.getValue(1);
3345 
3346   // Handle result values, copying them out of physregs into vregs that we
3347   // return.
3348   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3349                          InVals, IsThisReturn,
3350                          IsThisReturn ? OutVals[0] : SDValue());
3351 }
3352 
3353 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3354 // except for applying the wave size scale to the increment amount.
3355 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3356     SDValue Op, SelectionDAG &DAG) const {
3357   const MachineFunction &MF = DAG.getMachineFunction();
3358   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3359 
3360   SDLoc dl(Op);
3361   EVT VT = Op.getValueType();
3362   SDValue Tmp1 = Op;
3363   SDValue Tmp2 = Op.getValue(1);
3364   SDValue Tmp3 = Op.getOperand(2);
3365   SDValue Chain = Tmp1.getOperand(0);
3366 
3367   Register SPReg = Info->getStackPtrOffsetReg();
3368 
3369   // Chain the dynamic stack allocation so that it doesn't modify the stack
3370   // pointer when other instructions are using the stack.
3371   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3372 
3373   SDValue Size  = Tmp2.getOperand(1);
3374   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3375   Chain = SP.getValue(1);
3376   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3377   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3378   const TargetFrameLowering *TFL = ST.getFrameLowering();
3379   unsigned Opc =
3380     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3381     ISD::ADD : ISD::SUB;
3382 
3383   SDValue ScaledSize = DAG.getNode(
3384       ISD::SHL, dl, VT, Size,
3385       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3386 
3387   Align StackAlign = TFL->getStackAlign();
3388   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3389   if (Alignment && *Alignment > StackAlign) {
3390     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3391                        DAG.getConstant(-(uint64_t)Alignment->value()
3392                                            << ST.getWavefrontSizeLog2(),
3393                                        dl, VT));
3394   }
3395 
3396   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3397   Tmp2 = DAG.getCALLSEQ_END(
3398       Chain, DAG.getIntPtrConstant(0, dl, true),
3399       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3400 
3401   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3402 }
3403 
3404 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3405                                                   SelectionDAG &DAG) const {
3406   // We only handle constant sizes here to allow non-entry block, static sized
3407   // allocas. A truly dynamic value is more difficult to support because we
3408   // don't know if the size value is uniform or not. If the size isn't uniform,
3409   // we would need to do a wave reduction to get the maximum size to know how
3410   // much to increment the uniform stack pointer.
3411   SDValue Size = Op.getOperand(1);
3412   if (isa<ConstantSDNode>(Size))
3413       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3414 
3415   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3416 }
3417 
3418 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3419                                              const MachineFunction &MF) const {
3420   Register Reg = StringSwitch<Register>(RegName)
3421     .Case("m0", AMDGPU::M0)
3422     .Case("exec", AMDGPU::EXEC)
3423     .Case("exec_lo", AMDGPU::EXEC_LO)
3424     .Case("exec_hi", AMDGPU::EXEC_HI)
3425     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3426     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3427     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3428     .Default(Register());
3429 
3430   if (Reg == AMDGPU::NoRegister) {
3431     report_fatal_error(Twine("invalid register name \""
3432                              + StringRef(RegName)  + "\"."));
3433 
3434   }
3435 
3436   if (!Subtarget->hasFlatScrRegister() &&
3437        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3438     report_fatal_error(Twine("invalid register \""
3439                              + StringRef(RegName)  + "\" for subtarget."));
3440   }
3441 
3442   switch (Reg) {
3443   case AMDGPU::M0:
3444   case AMDGPU::EXEC_LO:
3445   case AMDGPU::EXEC_HI:
3446   case AMDGPU::FLAT_SCR_LO:
3447   case AMDGPU::FLAT_SCR_HI:
3448     if (VT.getSizeInBits() == 32)
3449       return Reg;
3450     break;
3451   case AMDGPU::EXEC:
3452   case AMDGPU::FLAT_SCR:
3453     if (VT.getSizeInBits() == 64)
3454       return Reg;
3455     break;
3456   default:
3457     llvm_unreachable("missing register type checking");
3458   }
3459 
3460   report_fatal_error(Twine("invalid type for register \""
3461                            + StringRef(RegName) + "\"."));
3462 }
3463 
3464 // If kill is not the last instruction, split the block so kill is always a
3465 // proper terminator.
3466 MachineBasicBlock *
3467 SITargetLowering::splitKillBlock(MachineInstr &MI,
3468                                  MachineBasicBlock *BB) const {
3469   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3470   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3471   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3472   return SplitBB;
3473 }
3474 
3475 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3476 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3477 // be the first instruction in the remainder block.
3478 //
3479 /// \returns { LoopBody, Remainder }
3480 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3481 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3482   MachineFunction *MF = MBB.getParent();
3483   MachineBasicBlock::iterator I(&MI);
3484 
3485   // To insert the loop we need to split the block. Move everything after this
3486   // point to a new block, and insert a new empty block between the two.
3487   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3488   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3489   MachineFunction::iterator MBBI(MBB);
3490   ++MBBI;
3491 
3492   MF->insert(MBBI, LoopBB);
3493   MF->insert(MBBI, RemainderBB);
3494 
3495   LoopBB->addSuccessor(LoopBB);
3496   LoopBB->addSuccessor(RemainderBB);
3497 
3498   // Move the rest of the block into a new block.
3499   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3500 
3501   if (InstInLoop) {
3502     auto Next = std::next(I);
3503 
3504     // Move instruction to loop body.
3505     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3506 
3507     // Move the rest of the block.
3508     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3509   } else {
3510     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3511   }
3512 
3513   MBB.addSuccessor(LoopBB);
3514 
3515   return std::make_pair(LoopBB, RemainderBB);
3516 }
3517 
3518 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3519 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3520   MachineBasicBlock *MBB = MI.getParent();
3521   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3522   auto I = MI.getIterator();
3523   auto E = std::next(I);
3524 
3525   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3526     .addImm(0);
3527 
3528   MIBundleBuilder Bundler(*MBB, I, E);
3529   finalizeBundle(*MBB, Bundler.begin());
3530 }
3531 
3532 MachineBasicBlock *
3533 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3534                                          MachineBasicBlock *BB) const {
3535   const DebugLoc &DL = MI.getDebugLoc();
3536 
3537   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3538 
3539   MachineBasicBlock *LoopBB;
3540   MachineBasicBlock *RemainderBB;
3541   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3542 
3543   // Apparently kill flags are only valid if the def is in the same block?
3544   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3545     Src->setIsKill(false);
3546 
3547   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3548 
3549   MachineBasicBlock::iterator I = LoopBB->end();
3550 
3551   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3552     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3553 
3554   // Clear TRAP_STS.MEM_VIOL
3555   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3556     .addImm(0)
3557     .addImm(EncodedReg);
3558 
3559   bundleInstWithWaitcnt(MI);
3560 
3561   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3562 
3563   // Load and check TRAP_STS.MEM_VIOL
3564   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3565     .addImm(EncodedReg);
3566 
3567   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3568   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3569     .addReg(Reg, RegState::Kill)
3570     .addImm(0);
3571   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3572     .addMBB(LoopBB);
3573 
3574   return RemainderBB;
3575 }
3576 
3577 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3578 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3579 // will only do one iteration. In the worst case, this will loop 64 times.
3580 //
3581 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3582 static MachineBasicBlock::iterator
3583 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3584                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3585                        const DebugLoc &DL, const MachineOperand &Idx,
3586                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3587                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3588                        Register &SGPRIdxReg) {
3589 
3590   MachineFunction *MF = OrigBB.getParent();
3591   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3592   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3593   MachineBasicBlock::iterator I = LoopBB.begin();
3594 
3595   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3596   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3597   Register NewExec = MRI.createVirtualRegister(BoolRC);
3598   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3599   Register CondReg = MRI.createVirtualRegister(BoolRC);
3600 
3601   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3602     .addReg(InitReg)
3603     .addMBB(&OrigBB)
3604     .addReg(ResultReg)
3605     .addMBB(&LoopBB);
3606 
3607   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3608     .addReg(InitSaveExecReg)
3609     .addMBB(&OrigBB)
3610     .addReg(NewExec)
3611     .addMBB(&LoopBB);
3612 
3613   // Read the next variant <- also loop target.
3614   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3615       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3616 
3617   // Compare the just read M0 value to all possible Idx values.
3618   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3619       .addReg(CurrentIdxReg)
3620       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3621 
3622   // Update EXEC, save the original EXEC value to VCC.
3623   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3624                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3625           NewExec)
3626     .addReg(CondReg, RegState::Kill);
3627 
3628   MRI.setSimpleHint(NewExec, CondReg);
3629 
3630   if (UseGPRIdxMode) {
3631     if (Offset == 0) {
3632       SGPRIdxReg = CurrentIdxReg;
3633     } else {
3634       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3635       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3636           .addReg(CurrentIdxReg, RegState::Kill)
3637           .addImm(Offset);
3638     }
3639   } else {
3640     // Move index from VCC into M0
3641     if (Offset == 0) {
3642       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3643         .addReg(CurrentIdxReg, RegState::Kill);
3644     } else {
3645       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3646         .addReg(CurrentIdxReg, RegState::Kill)
3647         .addImm(Offset);
3648     }
3649   }
3650 
3651   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3652   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3653   MachineInstr *InsertPt =
3654     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3655                                                   : AMDGPU::S_XOR_B64_term), Exec)
3656       .addReg(Exec)
3657       .addReg(NewExec);
3658 
3659   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3660   // s_cbranch_scc0?
3661 
3662   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3663   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3664     .addMBB(&LoopBB);
3665 
3666   return InsertPt->getIterator();
3667 }
3668 
3669 // This has slightly sub-optimal regalloc when the source vector is killed by
3670 // the read. The register allocator does not understand that the kill is
3671 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3672 // subregister from it, using 1 more VGPR than necessary. This was saved when
3673 // this was expanded after register allocation.
3674 static MachineBasicBlock::iterator
3675 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3676                unsigned InitResultReg, unsigned PhiReg, int Offset,
3677                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3678   MachineFunction *MF = MBB.getParent();
3679   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3680   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3681   MachineRegisterInfo &MRI = MF->getRegInfo();
3682   const DebugLoc &DL = MI.getDebugLoc();
3683   MachineBasicBlock::iterator I(&MI);
3684 
3685   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3686   Register DstReg = MI.getOperand(0).getReg();
3687   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3688   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3689   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3690   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3691 
3692   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3693 
3694   // Save the EXEC mask
3695   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3696     .addReg(Exec);
3697 
3698   MachineBasicBlock *LoopBB;
3699   MachineBasicBlock *RemainderBB;
3700   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3701 
3702   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3703 
3704   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3705                                       InitResultReg, DstReg, PhiReg, TmpExec,
3706                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3707 
3708   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3709   MachineFunction::iterator MBBI(LoopBB);
3710   ++MBBI;
3711   MF->insert(MBBI, LandingPad);
3712   LoopBB->removeSuccessor(RemainderBB);
3713   LandingPad->addSuccessor(RemainderBB);
3714   LoopBB->addSuccessor(LandingPad);
3715   MachineBasicBlock::iterator First = LandingPad->begin();
3716   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3717     .addReg(SaveExec);
3718 
3719   return InsPt;
3720 }
3721 
3722 // Returns subreg index, offset
3723 static std::pair<unsigned, int>
3724 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3725                             const TargetRegisterClass *SuperRC,
3726                             unsigned VecReg,
3727                             int Offset) {
3728   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3729 
3730   // Skip out of bounds offsets, or else we would end up using an undefined
3731   // register.
3732   if (Offset >= NumElts || Offset < 0)
3733     return std::make_pair(AMDGPU::sub0, Offset);
3734 
3735   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3736 }
3737 
3738 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3739                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3740                                  int Offset) {
3741   MachineBasicBlock *MBB = MI.getParent();
3742   const DebugLoc &DL = MI.getDebugLoc();
3743   MachineBasicBlock::iterator I(&MI);
3744 
3745   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3746 
3747   assert(Idx->getReg() != AMDGPU::NoRegister);
3748 
3749   if (Offset == 0) {
3750     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3751   } else {
3752     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3753         .add(*Idx)
3754         .addImm(Offset);
3755   }
3756 }
3757 
3758 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3759                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3760                                    int Offset) {
3761   MachineBasicBlock *MBB = MI.getParent();
3762   const DebugLoc &DL = MI.getDebugLoc();
3763   MachineBasicBlock::iterator I(&MI);
3764 
3765   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3766 
3767   if (Offset == 0)
3768     return Idx->getReg();
3769 
3770   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3771   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3772       .add(*Idx)
3773       .addImm(Offset);
3774   return Tmp;
3775 }
3776 
3777 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3778                                           MachineBasicBlock &MBB,
3779                                           const GCNSubtarget &ST) {
3780   const SIInstrInfo *TII = ST.getInstrInfo();
3781   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3782   MachineFunction *MF = MBB.getParent();
3783   MachineRegisterInfo &MRI = MF->getRegInfo();
3784 
3785   Register Dst = MI.getOperand(0).getReg();
3786   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3787   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3788   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3789 
3790   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3791   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3792 
3793   unsigned SubReg;
3794   std::tie(SubReg, Offset)
3795     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3796 
3797   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3798 
3799   // Check for a SGPR index.
3800   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3801     MachineBasicBlock::iterator I(&MI);
3802     const DebugLoc &DL = MI.getDebugLoc();
3803 
3804     if (UseGPRIdxMode) {
3805       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3806       // to avoid interfering with other uses, so probably requires a new
3807       // optimization pass.
3808       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3809 
3810       const MCInstrDesc &GPRIDXDesc =
3811           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3812       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3813           .addReg(SrcReg)
3814           .addReg(Idx)
3815           .addImm(SubReg);
3816     } else {
3817       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3818 
3819       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3820         .addReg(SrcReg, 0, SubReg)
3821         .addReg(SrcReg, RegState::Implicit);
3822     }
3823 
3824     MI.eraseFromParent();
3825 
3826     return &MBB;
3827   }
3828 
3829   // Control flow needs to be inserted if indexing with a VGPR.
3830   const DebugLoc &DL = MI.getDebugLoc();
3831   MachineBasicBlock::iterator I(&MI);
3832 
3833   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3834   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3835 
3836   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3837 
3838   Register SGPRIdxReg;
3839   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3840                               UseGPRIdxMode, SGPRIdxReg);
3841 
3842   MachineBasicBlock *LoopBB = InsPt->getParent();
3843 
3844   if (UseGPRIdxMode) {
3845     const MCInstrDesc &GPRIDXDesc =
3846         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3847 
3848     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3849         .addReg(SrcReg)
3850         .addReg(SGPRIdxReg)
3851         .addImm(SubReg);
3852   } else {
3853     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3854       .addReg(SrcReg, 0, SubReg)
3855       .addReg(SrcReg, RegState::Implicit);
3856   }
3857 
3858   MI.eraseFromParent();
3859 
3860   return LoopBB;
3861 }
3862 
3863 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3864                                           MachineBasicBlock &MBB,
3865                                           const GCNSubtarget &ST) {
3866   const SIInstrInfo *TII = ST.getInstrInfo();
3867   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3868   MachineFunction *MF = MBB.getParent();
3869   MachineRegisterInfo &MRI = MF->getRegInfo();
3870 
3871   Register Dst = MI.getOperand(0).getReg();
3872   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3873   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3874   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3875   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3876   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3877   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3878 
3879   // This can be an immediate, but will be folded later.
3880   assert(Val->getReg());
3881 
3882   unsigned SubReg;
3883   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3884                                                          SrcVec->getReg(),
3885                                                          Offset);
3886   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3887 
3888   if (Idx->getReg() == AMDGPU::NoRegister) {
3889     MachineBasicBlock::iterator I(&MI);
3890     const DebugLoc &DL = MI.getDebugLoc();
3891 
3892     assert(Offset == 0);
3893 
3894     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3895         .add(*SrcVec)
3896         .add(*Val)
3897         .addImm(SubReg);
3898 
3899     MI.eraseFromParent();
3900     return &MBB;
3901   }
3902 
3903   // Check for a SGPR index.
3904   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3905     MachineBasicBlock::iterator I(&MI);
3906     const DebugLoc &DL = MI.getDebugLoc();
3907 
3908     if (UseGPRIdxMode) {
3909       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3910 
3911       const MCInstrDesc &GPRIDXDesc =
3912           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3913       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3914           .addReg(SrcVec->getReg())
3915           .add(*Val)
3916           .addReg(Idx)
3917           .addImm(SubReg);
3918     } else {
3919       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3920 
3921       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3922           TRI.getRegSizeInBits(*VecRC), 32, false);
3923       BuildMI(MBB, I, DL, MovRelDesc, Dst)
3924           .addReg(SrcVec->getReg())
3925           .add(*Val)
3926           .addImm(SubReg);
3927     }
3928     MI.eraseFromParent();
3929     return &MBB;
3930   }
3931 
3932   // Control flow needs to be inserted if indexing with a VGPR.
3933   if (Val->isReg())
3934     MRI.clearKillFlags(Val->getReg());
3935 
3936   const DebugLoc &DL = MI.getDebugLoc();
3937 
3938   Register PhiReg = MRI.createVirtualRegister(VecRC);
3939 
3940   Register SGPRIdxReg;
3941   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
3942                               UseGPRIdxMode, SGPRIdxReg);
3943   MachineBasicBlock *LoopBB = InsPt->getParent();
3944 
3945   if (UseGPRIdxMode) {
3946     const MCInstrDesc &GPRIDXDesc =
3947         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3948 
3949     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3950         .addReg(PhiReg)
3951         .add(*Val)
3952         .addReg(SGPRIdxReg)
3953         .addImm(AMDGPU::sub0);
3954   } else {
3955     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3956         TRI.getRegSizeInBits(*VecRC), 32, false);
3957     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3958         .addReg(PhiReg)
3959         .add(*Val)
3960         .addImm(AMDGPU::sub0);
3961   }
3962 
3963   MI.eraseFromParent();
3964   return LoopBB;
3965 }
3966 
3967 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3968   MachineInstr &MI, MachineBasicBlock *BB) const {
3969 
3970   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3971   MachineFunction *MF = BB->getParent();
3972   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3973 
3974   switch (MI.getOpcode()) {
3975   case AMDGPU::S_UADDO_PSEUDO:
3976   case AMDGPU::S_USUBO_PSEUDO: {
3977     const DebugLoc &DL = MI.getDebugLoc();
3978     MachineOperand &Dest0 = MI.getOperand(0);
3979     MachineOperand &Dest1 = MI.getOperand(1);
3980     MachineOperand &Src0 = MI.getOperand(2);
3981     MachineOperand &Src1 = MI.getOperand(3);
3982 
3983     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3984                        ? AMDGPU::S_ADD_I32
3985                        : AMDGPU::S_SUB_I32;
3986     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3987 
3988     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3989         .addImm(1)
3990         .addImm(0);
3991 
3992     MI.eraseFromParent();
3993     return BB;
3994   }
3995   case AMDGPU::S_ADD_U64_PSEUDO:
3996   case AMDGPU::S_SUB_U64_PSEUDO: {
3997     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3998     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3999     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4000     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
4001     const DebugLoc &DL = MI.getDebugLoc();
4002 
4003     MachineOperand &Dest = MI.getOperand(0);
4004     MachineOperand &Src0 = MI.getOperand(1);
4005     MachineOperand &Src1 = MI.getOperand(2);
4006 
4007     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4008     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4009 
4010     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
4011         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4012     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
4013         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4014 
4015     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
4016         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4017     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
4018         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4019 
4020     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
4021 
4022     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
4023     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
4024     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
4025     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
4026     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4027         .addReg(DestSub0)
4028         .addImm(AMDGPU::sub0)
4029         .addReg(DestSub1)
4030         .addImm(AMDGPU::sub1);
4031     MI.eraseFromParent();
4032     return BB;
4033   }
4034   case AMDGPU::V_ADD_U64_PSEUDO:
4035   case AMDGPU::V_SUB_U64_PSEUDO: {
4036     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4037     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4038     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4039     const DebugLoc &DL = MI.getDebugLoc();
4040 
4041     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
4042 
4043     MachineOperand &Dest = MI.getOperand(0);
4044     MachineOperand &Src0 = MI.getOperand(1);
4045     MachineOperand &Src1 = MI.getOperand(2);
4046 
4047     if (IsAdd && ST.hasLshlAddB64()) {
4048       auto Add = BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_LSHL_ADD_U64_e64),
4049                          Dest.getReg())
4050                      .add(Src0)
4051                      .addImm(0)
4052                      .add(Src1);
4053       TII->legalizeOperands(*Add);
4054       MI.eraseFromParent();
4055       return BB;
4056     }
4057 
4058     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4059 
4060     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4061     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4062 
4063     Register CarryReg = MRI.createVirtualRegister(CarryRC);
4064     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
4065 
4066     const TargetRegisterClass *Src0RC = Src0.isReg()
4067                                             ? MRI.getRegClass(Src0.getReg())
4068                                             : &AMDGPU::VReg_64RegClass;
4069     const TargetRegisterClass *Src1RC = Src1.isReg()
4070                                             ? MRI.getRegClass(Src1.getReg())
4071                                             : &AMDGPU::VReg_64RegClass;
4072 
4073     const TargetRegisterClass *Src0SubRC =
4074         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
4075     const TargetRegisterClass *Src1SubRC =
4076         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
4077 
4078     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
4079         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
4080     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
4081         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
4082 
4083     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
4084         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
4085     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
4086         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
4087 
4088     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
4089     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
4090                                .addReg(CarryReg, RegState::Define)
4091                                .add(SrcReg0Sub0)
4092                                .add(SrcReg1Sub0)
4093                                .addImm(0); // clamp bit
4094 
4095     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
4096     MachineInstr *HiHalf =
4097         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4098             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4099             .add(SrcReg0Sub1)
4100             .add(SrcReg1Sub1)
4101             .addReg(CarryReg, RegState::Kill)
4102             .addImm(0); // clamp bit
4103 
4104     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4105         .addReg(DestSub0)
4106         .addImm(AMDGPU::sub0)
4107         .addReg(DestSub1)
4108         .addImm(AMDGPU::sub1);
4109     TII->legalizeOperands(*LoHalf);
4110     TII->legalizeOperands(*HiHalf);
4111     MI.eraseFromParent();
4112     return BB;
4113   }
4114   case AMDGPU::S_ADD_CO_PSEUDO:
4115   case AMDGPU::S_SUB_CO_PSEUDO: {
4116     // This pseudo has a chance to be selected
4117     // only from uniform add/subcarry node. All the VGPR operands
4118     // therefore assumed to be splat vectors.
4119     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4120     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4121     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4122     MachineBasicBlock::iterator MII = MI;
4123     const DebugLoc &DL = MI.getDebugLoc();
4124     MachineOperand &Dest = MI.getOperand(0);
4125     MachineOperand &CarryDest = MI.getOperand(1);
4126     MachineOperand &Src0 = MI.getOperand(2);
4127     MachineOperand &Src1 = MI.getOperand(3);
4128     MachineOperand &Src2 = MI.getOperand(4);
4129     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4130                        ? AMDGPU::S_ADDC_U32
4131                        : AMDGPU::S_SUBB_U32;
4132     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4133       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4134       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4135           .addReg(Src0.getReg());
4136       Src0.setReg(RegOp0);
4137     }
4138     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4139       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4140       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4141           .addReg(Src1.getReg());
4142       Src1.setReg(RegOp1);
4143     }
4144     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4145     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4146       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4147           .addReg(Src2.getReg());
4148       Src2.setReg(RegOp2);
4149     }
4150 
4151     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4152     unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC);
4153     assert(WaveSize == 64 || WaveSize == 32);
4154 
4155     if (WaveSize == 64) {
4156       if (ST.hasScalarCompareEq64()) {
4157         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4158             .addReg(Src2.getReg())
4159             .addImm(0);
4160       } else {
4161         const TargetRegisterClass *SubRC =
4162             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4163         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4164             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4165         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4166             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4167         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4168 
4169         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4170             .add(Src2Sub0)
4171             .add(Src2Sub1);
4172 
4173         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4174             .addReg(Src2_32, RegState::Kill)
4175             .addImm(0);
4176       }
4177     } else {
4178       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4179           .addReg(Src2.getReg())
4180           .addImm(0);
4181     }
4182 
4183     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4184 
4185     unsigned SelOpc =
4186         (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
4187 
4188     BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg())
4189         .addImm(-1)
4190         .addImm(0);
4191 
4192     MI.eraseFromParent();
4193     return BB;
4194   }
4195   case AMDGPU::SI_INIT_M0: {
4196     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4197             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4198         .add(MI.getOperand(0));
4199     MI.eraseFromParent();
4200     return BB;
4201   }
4202   case AMDGPU::GET_GROUPSTATICSIZE: {
4203     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4204            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4205     DebugLoc DL = MI.getDebugLoc();
4206     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4207         .add(MI.getOperand(0))
4208         .addImm(MFI->getLDSSize());
4209     MI.eraseFromParent();
4210     return BB;
4211   }
4212   case AMDGPU::SI_INDIRECT_SRC_V1:
4213   case AMDGPU::SI_INDIRECT_SRC_V2:
4214   case AMDGPU::SI_INDIRECT_SRC_V4:
4215   case AMDGPU::SI_INDIRECT_SRC_V8:
4216   case AMDGPU::SI_INDIRECT_SRC_V16:
4217   case AMDGPU::SI_INDIRECT_SRC_V32:
4218     return emitIndirectSrc(MI, *BB, *getSubtarget());
4219   case AMDGPU::SI_INDIRECT_DST_V1:
4220   case AMDGPU::SI_INDIRECT_DST_V2:
4221   case AMDGPU::SI_INDIRECT_DST_V4:
4222   case AMDGPU::SI_INDIRECT_DST_V8:
4223   case AMDGPU::SI_INDIRECT_DST_V16:
4224   case AMDGPU::SI_INDIRECT_DST_V32:
4225     return emitIndirectDst(MI, *BB, *getSubtarget());
4226   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4227   case AMDGPU::SI_KILL_I1_PSEUDO:
4228     return splitKillBlock(MI, BB);
4229   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4230     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4231     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4232     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4233 
4234     Register Dst = MI.getOperand(0).getReg();
4235     Register Src0 = MI.getOperand(1).getReg();
4236     Register Src1 = MI.getOperand(2).getReg();
4237     const DebugLoc &DL = MI.getDebugLoc();
4238     Register SrcCond = MI.getOperand(3).getReg();
4239 
4240     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4241     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4242     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4243     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4244 
4245     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4246       .addReg(SrcCond);
4247     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4248       .addImm(0)
4249       .addReg(Src0, 0, AMDGPU::sub0)
4250       .addImm(0)
4251       .addReg(Src1, 0, AMDGPU::sub0)
4252       .addReg(SrcCondCopy);
4253     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4254       .addImm(0)
4255       .addReg(Src0, 0, AMDGPU::sub1)
4256       .addImm(0)
4257       .addReg(Src1, 0, AMDGPU::sub1)
4258       .addReg(SrcCondCopy);
4259 
4260     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4261       .addReg(DstLo)
4262       .addImm(AMDGPU::sub0)
4263       .addReg(DstHi)
4264       .addImm(AMDGPU::sub1);
4265     MI.eraseFromParent();
4266     return BB;
4267   }
4268   case AMDGPU::SI_BR_UNDEF: {
4269     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4270     const DebugLoc &DL = MI.getDebugLoc();
4271     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4272                            .add(MI.getOperand(0));
4273     Br->getOperand(1).setIsUndef(true); // read undef SCC
4274     MI.eraseFromParent();
4275     return BB;
4276   }
4277   case AMDGPU::ADJCALLSTACKUP:
4278   case AMDGPU::ADJCALLSTACKDOWN: {
4279     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4280     MachineInstrBuilder MIB(*MF, &MI);
4281     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4282        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4283     return BB;
4284   }
4285   case AMDGPU::SI_CALL_ISEL: {
4286     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4287     const DebugLoc &DL = MI.getDebugLoc();
4288 
4289     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4290 
4291     MachineInstrBuilder MIB;
4292     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4293 
4294     for (const MachineOperand &MO : MI.operands())
4295       MIB.add(MO);
4296 
4297     MIB.cloneMemRefs(MI);
4298     MI.eraseFromParent();
4299     return BB;
4300   }
4301   case AMDGPU::V_ADD_CO_U32_e32:
4302   case AMDGPU::V_SUB_CO_U32_e32:
4303   case AMDGPU::V_SUBREV_CO_U32_e32: {
4304     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4305     const DebugLoc &DL = MI.getDebugLoc();
4306     unsigned Opc = MI.getOpcode();
4307 
4308     bool NeedClampOperand = false;
4309     if (TII->pseudoToMCOpcode(Opc) == -1) {
4310       Opc = AMDGPU::getVOPe64(Opc);
4311       NeedClampOperand = true;
4312     }
4313 
4314     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4315     if (TII->isVOP3(*I)) {
4316       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4317       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4318       I.addReg(TRI->getVCC(), RegState::Define);
4319     }
4320     I.add(MI.getOperand(1))
4321      .add(MI.getOperand(2));
4322     if (NeedClampOperand)
4323       I.addImm(0); // clamp bit for e64 encoding
4324 
4325     TII->legalizeOperands(*I);
4326 
4327     MI.eraseFromParent();
4328     return BB;
4329   }
4330   case AMDGPU::V_ADDC_U32_e32:
4331   case AMDGPU::V_SUBB_U32_e32:
4332   case AMDGPU::V_SUBBREV_U32_e32:
4333     // These instructions have an implicit use of vcc which counts towards the
4334     // constant bus limit.
4335     TII->legalizeOperands(MI);
4336     return BB;
4337   case AMDGPU::DS_GWS_INIT:
4338   case AMDGPU::DS_GWS_SEMA_BR:
4339   case AMDGPU::DS_GWS_BARRIER:
4340     TII->enforceOperandRCAlignment(MI, AMDGPU::OpName::data0);
4341     LLVM_FALLTHROUGH;
4342   case AMDGPU::DS_GWS_SEMA_V:
4343   case AMDGPU::DS_GWS_SEMA_P:
4344   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4345     // A s_waitcnt 0 is required to be the instruction immediately following.
4346     if (getSubtarget()->hasGWSAutoReplay()) {
4347       bundleInstWithWaitcnt(MI);
4348       return BB;
4349     }
4350 
4351     return emitGWSMemViolTestLoop(MI, BB);
4352   case AMDGPU::S_SETREG_B32: {
4353     // Try to optimize cases that only set the denormal mode or rounding mode.
4354     //
4355     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4356     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4357     // instead.
4358     //
4359     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4360     // allow you to have a no side effect instruction in the output of a
4361     // sideeffecting pattern.
4362     unsigned ID, Offset, Width;
4363     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4364     if (ID != AMDGPU::Hwreg::ID_MODE)
4365       return BB;
4366 
4367     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4368     const unsigned SetMask = WidthMask << Offset;
4369 
4370     if (getSubtarget()->hasDenormModeInst()) {
4371       unsigned SetDenormOp = 0;
4372       unsigned SetRoundOp = 0;
4373 
4374       // The dedicated instructions can only set the whole denorm or round mode
4375       // at once, not a subset of bits in either.
4376       if (SetMask ==
4377           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4378         // If this fully sets both the round and denorm mode, emit the two
4379         // dedicated instructions for these.
4380         SetRoundOp = AMDGPU::S_ROUND_MODE;
4381         SetDenormOp = AMDGPU::S_DENORM_MODE;
4382       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4383         SetRoundOp = AMDGPU::S_ROUND_MODE;
4384       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4385         SetDenormOp = AMDGPU::S_DENORM_MODE;
4386       }
4387 
4388       if (SetRoundOp || SetDenormOp) {
4389         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4390         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4391         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4392           unsigned ImmVal = Def->getOperand(1).getImm();
4393           if (SetRoundOp) {
4394             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4395                 .addImm(ImmVal & 0xf);
4396 
4397             // If we also have the denorm mode, get just the denorm mode bits.
4398             ImmVal >>= 4;
4399           }
4400 
4401           if (SetDenormOp) {
4402             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4403                 .addImm(ImmVal & 0xf);
4404           }
4405 
4406           MI.eraseFromParent();
4407           return BB;
4408         }
4409       }
4410     }
4411 
4412     // If only FP bits are touched, used the no side effects pseudo.
4413     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4414                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4415       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4416 
4417     return BB;
4418   }
4419   default:
4420     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4421   }
4422 }
4423 
4424 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4425   return isTypeLegal(VT.getScalarType());
4426 }
4427 
4428 bool SITargetLowering::hasAtomicFaddRtnForTy(SDValue &Op) const {
4429   switch (Op.getValue(0).getSimpleValueType().SimpleTy) {
4430   case MVT::f32:
4431     return Subtarget->hasAtomicFaddRtnInsts();
4432   case MVT::v2f16:
4433   case MVT::f64:
4434     return Subtarget->hasGFX90AInsts();
4435   default:
4436     return false;
4437   }
4438 }
4439 
4440 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4441   // This currently forces unfolding various combinations of fsub into fma with
4442   // free fneg'd operands. As long as we have fast FMA (controlled by
4443   // isFMAFasterThanFMulAndFAdd), we should perform these.
4444 
4445   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4446   // most of these combines appear to be cycle neutral but save on instruction
4447   // count / code size.
4448   return true;
4449 }
4450 
4451 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; }
4452 
4453 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4454                                          EVT VT) const {
4455   if (!VT.isVector()) {
4456     return MVT::i1;
4457   }
4458   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4459 }
4460 
4461 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4462   // TODO: Should i16 be used always if legal? For now it would force VALU
4463   // shifts.
4464   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4465 }
4466 
4467 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4468   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4469              ? Ty.changeElementSize(16)
4470              : Ty.changeElementSize(32);
4471 }
4472 
4473 // Answering this is somewhat tricky and depends on the specific device which
4474 // have different rates for fma or all f64 operations.
4475 //
4476 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4477 // regardless of which device (although the number of cycles differs between
4478 // devices), so it is always profitable for f64.
4479 //
4480 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4481 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4482 // which we can always do even without fused FP ops since it returns the same
4483 // result as the separate operations and since it is always full
4484 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4485 // however does not support denormals, so we do report fma as faster if we have
4486 // a fast fma device and require denormals.
4487 //
4488 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4489                                                   EVT VT) const {
4490   VT = VT.getScalarType();
4491 
4492   switch (VT.getSimpleVT().SimpleTy) {
4493   case MVT::f32: {
4494     // If mad is not available this depends only on if f32 fma is full rate.
4495     if (!Subtarget->hasMadMacF32Insts())
4496       return Subtarget->hasFastFMAF32();
4497 
4498     // Otherwise f32 mad is always full rate and returns the same result as
4499     // the separate operations so should be preferred over fma.
4500     // However does not support denormals.
4501     if (hasFP32Denormals(MF))
4502       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4503 
4504     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4505     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4506   }
4507   case MVT::f64:
4508     return true;
4509   case MVT::f16:
4510     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4511   default:
4512     break;
4513   }
4514 
4515   return false;
4516 }
4517 
4518 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4519                                                   LLT Ty) const {
4520   switch (Ty.getScalarSizeInBits()) {
4521   case 16:
4522     return isFMAFasterThanFMulAndFAdd(MF, MVT::f16);
4523   case 32:
4524     return isFMAFasterThanFMulAndFAdd(MF, MVT::f32);
4525   case 64:
4526     return isFMAFasterThanFMulAndFAdd(MF, MVT::f64);
4527   default:
4528     break;
4529   }
4530 
4531   return false;
4532 }
4533 
4534 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const {
4535   if (!Ty.isScalar())
4536     return false;
4537 
4538   if (Ty.getScalarSizeInBits() == 16)
4539     return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF());
4540   if (Ty.getScalarSizeInBits() == 32)
4541     return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF());
4542 
4543   return false;
4544 }
4545 
4546 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4547                                    const SDNode *N) const {
4548   // TODO: Check future ftz flag
4549   // v_mad_f32/v_mac_f32 do not support denormals.
4550   EVT VT = N->getValueType(0);
4551   if (VT == MVT::f32)
4552     return Subtarget->hasMadMacF32Insts() &&
4553            !hasFP32Denormals(DAG.getMachineFunction());
4554   if (VT == MVT::f16) {
4555     return Subtarget->hasMadF16() &&
4556            !hasFP64FP16Denormals(DAG.getMachineFunction());
4557   }
4558 
4559   return false;
4560 }
4561 
4562 //===----------------------------------------------------------------------===//
4563 // Custom DAG Lowering Operations
4564 //===----------------------------------------------------------------------===//
4565 
4566 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4567 // wider vector type is legal.
4568 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4569                                              SelectionDAG &DAG) const {
4570   unsigned Opc = Op.getOpcode();
4571   EVT VT = Op.getValueType();
4572   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4573 
4574   SDValue Lo, Hi;
4575   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4576 
4577   SDLoc SL(Op);
4578   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4579                              Op->getFlags());
4580   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4581                              Op->getFlags());
4582 
4583   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4584 }
4585 
4586 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4587 // wider vector type is legal.
4588 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4589                                               SelectionDAG &DAG) const {
4590   unsigned Opc = Op.getOpcode();
4591   EVT VT = Op.getValueType();
4592   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4593          VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i16 ||
4594          VT == MVT::v16f16 || VT == MVT::v8f32 || VT == MVT::v16f32 ||
4595          VT == MVT::v32f32);
4596 
4597   SDValue Lo0, Hi0;
4598   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4599   SDValue Lo1, Hi1;
4600   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4601 
4602   SDLoc SL(Op);
4603 
4604   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4605                              Op->getFlags());
4606   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4607                              Op->getFlags());
4608 
4609   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4610 }
4611 
4612 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4613                                               SelectionDAG &DAG) const {
4614   unsigned Opc = Op.getOpcode();
4615   EVT VT = Op.getValueType();
4616   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 ||
4617          VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v16i16 ||
4618          VT == MVT::v16f16 || VT == MVT::v8f32 || VT == MVT::v16f32 ||
4619          VT == MVT::v32f32);
4620 
4621   SDValue Lo0, Hi0;
4622   SDValue Op0 = Op.getOperand(0);
4623   std::tie(Lo0, Hi0) = Op0.getValueType().isVector()
4624                          ? DAG.SplitVectorOperand(Op.getNode(), 0)
4625                          : std::make_pair(Op0, Op0);
4626   SDValue Lo1, Hi1;
4627   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4628   SDValue Lo2, Hi2;
4629   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4630 
4631   SDLoc SL(Op);
4632   auto ResVT = DAG.GetSplitDestVTs(VT);
4633 
4634   SDValue OpLo = DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2,
4635                              Op->getFlags());
4636   SDValue OpHi = DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2,
4637                              Op->getFlags());
4638 
4639   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4640 }
4641 
4642 
4643 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4644   switch (Op.getOpcode()) {
4645   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4646   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4647   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4648   case ISD::LOAD: {
4649     SDValue Result = LowerLOAD(Op, DAG);
4650     assert((!Result.getNode() ||
4651             Result.getNode()->getNumValues() == 2) &&
4652            "Load should return a value and a chain");
4653     return Result;
4654   }
4655 
4656   case ISD::FSIN:
4657   case ISD::FCOS:
4658     return LowerTrig(Op, DAG);
4659   case ISD::SELECT: return LowerSELECT(Op, DAG);
4660   case ISD::FDIV: return LowerFDIV(Op, DAG);
4661   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4662   case ISD::STORE: return LowerSTORE(Op, DAG);
4663   case ISD::GlobalAddress: {
4664     MachineFunction &MF = DAG.getMachineFunction();
4665     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4666     return LowerGlobalAddress(MFI, Op, DAG);
4667   }
4668   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4669   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4670   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4671   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4672   case ISD::INSERT_SUBVECTOR:
4673     return lowerINSERT_SUBVECTOR(Op, DAG);
4674   case ISD::INSERT_VECTOR_ELT:
4675     return lowerINSERT_VECTOR_ELT(Op, DAG);
4676   case ISD::EXTRACT_VECTOR_ELT:
4677     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4678   case ISD::VECTOR_SHUFFLE:
4679     return lowerVECTOR_SHUFFLE(Op, DAG);
4680   case ISD::SCALAR_TO_VECTOR:
4681     return lowerSCALAR_TO_VECTOR(Op, DAG);
4682   case ISD::BUILD_VECTOR:
4683     return lowerBUILD_VECTOR(Op, DAG);
4684   case ISD::FP_ROUND:
4685     return lowerFP_ROUND(Op, DAG);
4686   case ISD::FPTRUNC_ROUND: {
4687     unsigned Opc;
4688     SDLoc DL(Op);
4689 
4690     if (Op.getOperand(0)->getValueType(0) != MVT::f32)
4691       return SDValue();
4692 
4693     // Get the rounding mode from the last operand
4694     int RoundMode = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4695     if (RoundMode == (int)RoundingMode::TowardPositive)
4696       Opc = AMDGPUISD::FPTRUNC_ROUND_UPWARD;
4697     else if (RoundMode == (int)RoundingMode::TowardNegative)
4698       Opc = AMDGPUISD::FPTRUNC_ROUND_DOWNWARD;
4699     else
4700       return SDValue();
4701 
4702     return DAG.getNode(Opc, DL, Op.getNode()->getVTList(), Op->getOperand(0));
4703   }
4704   case ISD::TRAP:
4705     return lowerTRAP(Op, DAG);
4706   case ISD::DEBUGTRAP:
4707     return lowerDEBUGTRAP(Op, DAG);
4708   case ISD::FABS:
4709   case ISD::FNEG:
4710   case ISD::FCANONICALIZE:
4711   case ISD::BSWAP:
4712     return splitUnaryVectorOp(Op, DAG);
4713   case ISD::FMINNUM:
4714   case ISD::FMAXNUM:
4715     return lowerFMINNUM_FMAXNUM(Op, DAG);
4716   case ISD::FMA:
4717     return splitTernaryVectorOp(Op, DAG);
4718   case ISD::FP_TO_SINT:
4719   case ISD::FP_TO_UINT:
4720     return LowerFP_TO_INT(Op, DAG);
4721   case ISD::SHL:
4722   case ISD::SRA:
4723   case ISD::SRL:
4724   case ISD::ADD:
4725   case ISD::SUB:
4726   case ISD::MUL:
4727   case ISD::SMIN:
4728   case ISD::SMAX:
4729   case ISD::UMIN:
4730   case ISD::UMAX:
4731   case ISD::FADD:
4732   case ISD::FMUL:
4733   case ISD::FMINNUM_IEEE:
4734   case ISD::FMAXNUM_IEEE:
4735   case ISD::UADDSAT:
4736   case ISD::USUBSAT:
4737   case ISD::SADDSAT:
4738   case ISD::SSUBSAT:
4739     return splitBinaryVectorOp(Op, DAG);
4740   case ISD::SMULO:
4741   case ISD::UMULO:
4742     return lowerXMULO(Op, DAG);
4743   case ISD::SMUL_LOHI:
4744   case ISD::UMUL_LOHI:
4745     return lowerXMUL_LOHI(Op, DAG);
4746   case ISD::DYNAMIC_STACKALLOC:
4747     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4748   }
4749   return SDValue();
4750 }
4751 
4752 // Used for D16: Casts the result of an instruction into the right vector,
4753 // packs values if loads return unpacked values.
4754 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4755                                        const SDLoc &DL,
4756                                        SelectionDAG &DAG, bool Unpacked) {
4757   if (!LoadVT.isVector())
4758     return Result;
4759 
4760   // Cast back to the original packed type or to a larger type that is a
4761   // multiple of 32 bit for D16. Widening the return type is a required for
4762   // legalization.
4763   EVT FittingLoadVT = LoadVT;
4764   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4765     FittingLoadVT =
4766         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4767                          LoadVT.getVectorNumElements() + 1);
4768   }
4769 
4770   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4771     // Truncate to v2i16/v4i16.
4772     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4773 
4774     // Workaround legalizer not scalarizing truncate after vector op
4775     // legalization but not creating intermediate vector trunc.
4776     SmallVector<SDValue, 4> Elts;
4777     DAG.ExtractVectorElements(Result, Elts);
4778     for (SDValue &Elt : Elts)
4779       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4780 
4781     // Pad illegal v1i16/v3fi6 to v4i16
4782     if ((LoadVT.getVectorNumElements() % 2) == 1)
4783       Elts.push_back(DAG.getUNDEF(MVT::i16));
4784 
4785     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4786 
4787     // Bitcast to original type (v2f16/v4f16).
4788     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4789   }
4790 
4791   // Cast back to the original packed type.
4792   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4793 }
4794 
4795 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4796                                               MemSDNode *M,
4797                                               SelectionDAG &DAG,
4798                                               ArrayRef<SDValue> Ops,
4799                                               bool IsIntrinsic) const {
4800   SDLoc DL(M);
4801 
4802   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4803   EVT LoadVT = M->getValueType(0);
4804 
4805   EVT EquivLoadVT = LoadVT;
4806   if (LoadVT.isVector()) {
4807     if (Unpacked) {
4808       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4809                                      LoadVT.getVectorNumElements());
4810     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4811       // Widen v3f16 to legal type
4812       EquivLoadVT =
4813           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4814                            LoadVT.getVectorNumElements() + 1);
4815     }
4816   }
4817 
4818   // Change from v4f16/v2f16 to EquivLoadVT.
4819   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4820 
4821   SDValue Load
4822     = DAG.getMemIntrinsicNode(
4823       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4824       VTList, Ops, M->getMemoryVT(),
4825       M->getMemOperand());
4826 
4827   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4828 
4829   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4830 }
4831 
4832 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4833                                              SelectionDAG &DAG,
4834                                              ArrayRef<SDValue> Ops) const {
4835   SDLoc DL(M);
4836   EVT LoadVT = M->getValueType(0);
4837   EVT EltType = LoadVT.getScalarType();
4838   EVT IntVT = LoadVT.changeTypeToInteger();
4839 
4840   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4841 
4842   unsigned Opc =
4843       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4844 
4845   if (IsD16) {
4846     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4847   }
4848 
4849   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4850   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4851     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4852 
4853   if (isTypeLegal(LoadVT)) {
4854     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4855                                M->getMemOperand(), DAG);
4856   }
4857 
4858   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4859   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4860   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4861                                         M->getMemOperand(), DAG);
4862   return DAG.getMergeValues(
4863       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4864       DL);
4865 }
4866 
4867 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4868                                   SDNode *N, SelectionDAG &DAG) {
4869   EVT VT = N->getValueType(0);
4870   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4871   unsigned CondCode = CD->getZExtValue();
4872   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4873     return DAG.getUNDEF(VT);
4874 
4875   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4876 
4877   SDValue LHS = N->getOperand(1);
4878   SDValue RHS = N->getOperand(2);
4879 
4880   SDLoc DL(N);
4881 
4882   EVT CmpVT = LHS.getValueType();
4883   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4884     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4885       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4886     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4887     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4888   }
4889 
4890   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4891 
4892   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4893   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4894 
4895   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4896                               DAG.getCondCode(CCOpcode));
4897   if (VT.bitsEq(CCVT))
4898     return SetCC;
4899   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4900 }
4901 
4902 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4903                                   SDNode *N, SelectionDAG &DAG) {
4904   EVT VT = N->getValueType(0);
4905   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4906 
4907   unsigned CondCode = CD->getZExtValue();
4908   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4909     return DAG.getUNDEF(VT);
4910 
4911   SDValue Src0 = N->getOperand(1);
4912   SDValue Src1 = N->getOperand(2);
4913   EVT CmpVT = Src0.getValueType();
4914   SDLoc SL(N);
4915 
4916   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4917     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4918     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4919   }
4920 
4921   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4922   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4923   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4924   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4925   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4926                               Src1, DAG.getCondCode(CCOpcode));
4927   if (VT.bitsEq(CCVT))
4928     return SetCC;
4929   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4930 }
4931 
4932 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4933                                     SelectionDAG &DAG) {
4934   EVT VT = N->getValueType(0);
4935   SDValue Src = N->getOperand(1);
4936   SDLoc SL(N);
4937 
4938   if (Src.getOpcode() == ISD::SETCC) {
4939     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4940     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4941                        Src.getOperand(1), Src.getOperand(2));
4942   }
4943   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4944     // (ballot 0) -> 0
4945     if (Arg->isZero())
4946       return DAG.getConstant(0, SL, VT);
4947 
4948     // (ballot 1) -> EXEC/EXEC_LO
4949     if (Arg->isOne()) {
4950       Register Exec;
4951       if (VT.getScalarSizeInBits() == 32)
4952         Exec = AMDGPU::EXEC_LO;
4953       else if (VT.getScalarSizeInBits() == 64)
4954         Exec = AMDGPU::EXEC;
4955       else
4956         return SDValue();
4957 
4958       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4959     }
4960   }
4961 
4962   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4963   // ISD::SETNE)
4964   return DAG.getNode(
4965       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4966       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4967 }
4968 
4969 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4970                                           SmallVectorImpl<SDValue> &Results,
4971                                           SelectionDAG &DAG) const {
4972   switch (N->getOpcode()) {
4973   case ISD::INSERT_VECTOR_ELT: {
4974     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4975       Results.push_back(Res);
4976     return;
4977   }
4978   case ISD::EXTRACT_VECTOR_ELT: {
4979     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4980       Results.push_back(Res);
4981     return;
4982   }
4983   case ISD::INTRINSIC_WO_CHAIN: {
4984     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4985     switch (IID) {
4986     case Intrinsic::amdgcn_cvt_pkrtz: {
4987       SDValue Src0 = N->getOperand(1);
4988       SDValue Src1 = N->getOperand(2);
4989       SDLoc SL(N);
4990       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4991                                 Src0, Src1);
4992       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4993       return;
4994     }
4995     case Intrinsic::amdgcn_cvt_pknorm_i16:
4996     case Intrinsic::amdgcn_cvt_pknorm_u16:
4997     case Intrinsic::amdgcn_cvt_pk_i16:
4998     case Intrinsic::amdgcn_cvt_pk_u16: {
4999       SDValue Src0 = N->getOperand(1);
5000       SDValue Src1 = N->getOperand(2);
5001       SDLoc SL(N);
5002       unsigned Opcode;
5003 
5004       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
5005         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
5006       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
5007         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
5008       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
5009         Opcode = AMDGPUISD::CVT_PK_I16_I32;
5010       else
5011         Opcode = AMDGPUISD::CVT_PK_U16_U32;
5012 
5013       EVT VT = N->getValueType(0);
5014       if (isTypeLegal(VT))
5015         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
5016       else {
5017         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
5018         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
5019       }
5020       return;
5021     }
5022     }
5023     break;
5024   }
5025   case ISD::INTRINSIC_W_CHAIN: {
5026     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
5027       if (Res.getOpcode() == ISD::MERGE_VALUES) {
5028         // FIXME: Hacky
5029         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
5030           Results.push_back(Res.getOperand(I));
5031         }
5032       } else {
5033         Results.push_back(Res);
5034         Results.push_back(Res.getValue(1));
5035       }
5036       return;
5037     }
5038 
5039     break;
5040   }
5041   case ISD::SELECT: {
5042     SDLoc SL(N);
5043     EVT VT = N->getValueType(0);
5044     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
5045     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
5046     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
5047 
5048     EVT SelectVT = NewVT;
5049     if (NewVT.bitsLT(MVT::i32)) {
5050       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
5051       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
5052       SelectVT = MVT::i32;
5053     }
5054 
5055     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
5056                                     N->getOperand(0), LHS, RHS);
5057 
5058     if (NewVT != SelectVT)
5059       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
5060     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
5061     return;
5062   }
5063   case ISD::FNEG: {
5064     if (N->getValueType(0) != MVT::v2f16)
5065       break;
5066 
5067     SDLoc SL(N);
5068     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5069 
5070     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
5071                              BC,
5072                              DAG.getConstant(0x80008000, SL, MVT::i32));
5073     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5074     return;
5075   }
5076   case ISD::FABS: {
5077     if (N->getValueType(0) != MVT::v2f16)
5078       break;
5079 
5080     SDLoc SL(N);
5081     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5082 
5083     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
5084                              BC,
5085                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
5086     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5087     return;
5088   }
5089   default:
5090     break;
5091   }
5092 }
5093 
5094 /// Helper function for LowerBRCOND
5095 static SDNode *findUser(SDValue Value, unsigned Opcode) {
5096 
5097   SDNode *Parent = Value.getNode();
5098   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
5099        I != E; ++I) {
5100 
5101     if (I.getUse().get() != Value)
5102       continue;
5103 
5104     if (I->getOpcode() == Opcode)
5105       return *I;
5106   }
5107   return nullptr;
5108 }
5109 
5110 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
5111   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
5112     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
5113     case Intrinsic::amdgcn_if:
5114       return AMDGPUISD::IF;
5115     case Intrinsic::amdgcn_else:
5116       return AMDGPUISD::ELSE;
5117     case Intrinsic::amdgcn_loop:
5118       return AMDGPUISD::LOOP;
5119     case Intrinsic::amdgcn_end_cf:
5120       llvm_unreachable("should not occur");
5121     default:
5122       return 0;
5123     }
5124   }
5125 
5126   // break, if_break, else_break are all only used as inputs to loop, not
5127   // directly as branch conditions.
5128   return 0;
5129 }
5130 
5131 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
5132   const Triple &TT = getTargetMachine().getTargetTriple();
5133   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5134           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5135          AMDGPU::shouldEmitConstantsToTextSection(TT);
5136 }
5137 
5138 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
5139   // FIXME: Either avoid relying on address space here or change the default
5140   // address space for functions to avoid the explicit check.
5141   return (GV->getValueType()->isFunctionTy() ||
5142           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
5143          !shouldEmitFixup(GV) &&
5144          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
5145 }
5146 
5147 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
5148   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
5149 }
5150 
5151 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
5152   if (!GV->hasExternalLinkage())
5153     return true;
5154 
5155   const auto OS = getTargetMachine().getTargetTriple().getOS();
5156   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
5157 }
5158 
5159 /// This transforms the control flow intrinsics to get the branch destination as
5160 /// last parameter, also switches branch target with BR if the need arise
5161 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
5162                                       SelectionDAG &DAG) const {
5163   SDLoc DL(BRCOND);
5164 
5165   SDNode *Intr = BRCOND.getOperand(1).getNode();
5166   SDValue Target = BRCOND.getOperand(2);
5167   SDNode *BR = nullptr;
5168   SDNode *SetCC = nullptr;
5169 
5170   if (Intr->getOpcode() == ISD::SETCC) {
5171     // As long as we negate the condition everything is fine
5172     SetCC = Intr;
5173     Intr = SetCC->getOperand(0).getNode();
5174 
5175   } else {
5176     // Get the target from BR if we don't negate the condition
5177     BR = findUser(BRCOND, ISD::BR);
5178     assert(BR && "brcond missing unconditional branch user");
5179     Target = BR->getOperand(1);
5180   }
5181 
5182   unsigned CFNode = isCFIntrinsic(Intr);
5183   if (CFNode == 0) {
5184     // This is a uniform branch so we don't need to legalize.
5185     return BRCOND;
5186   }
5187 
5188   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5189                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5190 
5191   assert(!SetCC ||
5192         (SetCC->getConstantOperandVal(1) == 1 &&
5193          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5194                                                              ISD::SETNE));
5195 
5196   // operands of the new intrinsic call
5197   SmallVector<SDValue, 4> Ops;
5198   if (HaveChain)
5199     Ops.push_back(BRCOND.getOperand(0));
5200 
5201   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5202   Ops.push_back(Target);
5203 
5204   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5205 
5206   // build the new intrinsic call
5207   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5208 
5209   if (!HaveChain) {
5210     SDValue Ops[] =  {
5211       SDValue(Result, 0),
5212       BRCOND.getOperand(0)
5213     };
5214 
5215     Result = DAG.getMergeValues(Ops, DL).getNode();
5216   }
5217 
5218   if (BR) {
5219     // Give the branch instruction our target
5220     SDValue Ops[] = {
5221       BR->getOperand(0),
5222       BRCOND.getOperand(2)
5223     };
5224     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5225     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5226   }
5227 
5228   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5229 
5230   // Copy the intrinsic results to registers
5231   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5232     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5233     if (!CopyToReg)
5234       continue;
5235 
5236     Chain = DAG.getCopyToReg(
5237       Chain, DL,
5238       CopyToReg->getOperand(1),
5239       SDValue(Result, i - 1),
5240       SDValue());
5241 
5242     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5243   }
5244 
5245   // Remove the old intrinsic from the chain
5246   DAG.ReplaceAllUsesOfValueWith(
5247     SDValue(Intr, Intr->getNumValues() - 1),
5248     Intr->getOperand(0));
5249 
5250   return Chain;
5251 }
5252 
5253 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5254                                           SelectionDAG &DAG) const {
5255   MVT VT = Op.getSimpleValueType();
5256   SDLoc DL(Op);
5257   // Checking the depth
5258   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5259     return DAG.getConstant(0, DL, VT);
5260 
5261   MachineFunction &MF = DAG.getMachineFunction();
5262   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5263   // Check for kernel and shader functions
5264   if (Info->isEntryFunction())
5265     return DAG.getConstant(0, DL, VT);
5266 
5267   MachineFrameInfo &MFI = MF.getFrameInfo();
5268   // There is a call to @llvm.returnaddress in this function
5269   MFI.setReturnAddressIsTaken(true);
5270 
5271   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5272   // Get the return address reg and mark it as an implicit live-in
5273   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5274 
5275   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5276 }
5277 
5278 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5279                                             SDValue Op,
5280                                             const SDLoc &DL,
5281                                             EVT VT) const {
5282   return Op.getValueType().bitsLE(VT) ?
5283       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5284     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5285                 DAG.getTargetConstant(0, DL, MVT::i32));
5286 }
5287 
5288 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5289   assert(Op.getValueType() == MVT::f16 &&
5290          "Do not know how to custom lower FP_ROUND for non-f16 type");
5291 
5292   SDValue Src = Op.getOperand(0);
5293   EVT SrcVT = Src.getValueType();
5294   if (SrcVT != MVT::f64)
5295     return Op;
5296 
5297   SDLoc DL(Op);
5298 
5299   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5300   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5301   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5302 }
5303 
5304 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5305                                                SelectionDAG &DAG) const {
5306   EVT VT = Op.getValueType();
5307   const MachineFunction &MF = DAG.getMachineFunction();
5308   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5309   bool IsIEEEMode = Info->getMode().IEEE;
5310 
5311   // FIXME: Assert during selection that this is only selected for
5312   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5313   // mode functions, but this happens to be OK since it's only done in cases
5314   // where there is known no sNaN.
5315   if (IsIEEEMode)
5316     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5317 
5318   if (VT == MVT::v4f16 || VT == MVT::v8f16 || VT == MVT::v16f16)
5319     return splitBinaryVectorOp(Op, DAG);
5320   return Op;
5321 }
5322 
5323 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5324   EVT VT = Op.getValueType();
5325   SDLoc SL(Op);
5326   SDValue LHS = Op.getOperand(0);
5327   SDValue RHS = Op.getOperand(1);
5328   bool isSigned = Op.getOpcode() == ISD::SMULO;
5329 
5330   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5331     const APInt &C = RHSC->getAPIntValue();
5332     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5333     if (C.isPowerOf2()) {
5334       // smulo(x, signed_min) is same as umulo(x, signed_min).
5335       bool UseArithShift = isSigned && !C.isMinSignedValue();
5336       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5337       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5338       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5339           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5340                       SL, VT, Result, ShiftAmt),
5341           LHS, ISD::SETNE);
5342       return DAG.getMergeValues({ Result, Overflow }, SL);
5343     }
5344   }
5345 
5346   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5347   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5348                             SL, VT, LHS, RHS);
5349 
5350   SDValue Sign = isSigned
5351     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5352                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5353     : DAG.getConstant(0, SL, VT);
5354   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5355 
5356   return DAG.getMergeValues({ Result, Overflow }, SL);
5357 }
5358 
5359 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const {
5360   if (Op->isDivergent()) {
5361     // Select to V_MAD_[IU]64_[IU]32.
5362     return Op;
5363   }
5364   if (Subtarget->hasSMulHi()) {
5365     // Expand to S_MUL_I32 + S_MUL_HI_[IU]32.
5366     return SDValue();
5367   }
5368   // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to
5369   // calculate the high part, so we might as well do the whole thing with
5370   // V_MAD_[IU]64_[IU]32.
5371   return Op;
5372 }
5373 
5374 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5375   if (!Subtarget->isTrapHandlerEnabled() ||
5376       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5377     return lowerTrapEndpgm(Op, DAG);
5378 
5379   if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) {
5380     switch (*HsaAbiVer) {
5381     case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
5382     case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
5383       return lowerTrapHsaQueuePtr(Op, DAG);
5384     case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
5385     case ELF::ELFABIVERSION_AMDGPU_HSA_V5:
5386       return Subtarget->supportsGetDoorbellID() ?
5387           lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG);
5388     }
5389   }
5390 
5391   llvm_unreachable("Unknown trap handler");
5392 }
5393 
5394 SDValue SITargetLowering::lowerTrapEndpgm(
5395     SDValue Op, SelectionDAG &DAG) const {
5396   SDLoc SL(Op);
5397   SDValue Chain = Op.getOperand(0);
5398   return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5399 }
5400 
5401 SDValue SITargetLowering::loadImplicitKernelArgument(SelectionDAG &DAG, MVT VT,
5402     const SDLoc &DL, Align Alignment, ImplicitParameter Param) const {
5403   MachineFunction &MF = DAG.getMachineFunction();
5404   uint64_t Offset = getImplicitParameterOffset(MF, Param);
5405   SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), Offset);
5406   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5407   return DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, PtrInfo, Alignment,
5408                      MachineMemOperand::MODereferenceable |
5409                          MachineMemOperand::MOInvariant);
5410 }
5411 
5412 SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5413     SDValue Op, SelectionDAG &DAG) const {
5414   SDLoc SL(Op);
5415   SDValue Chain = Op.getOperand(0);
5416 
5417   SDValue QueuePtr;
5418   // For code object version 5, QueuePtr is passed through implicit kernarg.
5419   if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) {
5420     QueuePtr =
5421         loadImplicitKernelArgument(DAG, MVT::i64, SL, Align(8), QUEUE_PTR);
5422   } else {
5423     MachineFunction &MF = DAG.getMachineFunction();
5424     SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5425     Register UserSGPR = Info->getQueuePtrUserSGPR();
5426 
5427     if (UserSGPR == AMDGPU::NoRegister) {
5428       // We probably are in a function incorrectly marked with
5429       // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the
5430       // trap, so just use a null pointer.
5431       QueuePtr = DAG.getConstant(0, SL, MVT::i64);
5432     } else {
5433       QueuePtr = CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, UserSGPR,
5434                                       MVT::i64);
5435     }
5436   }
5437 
5438   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5439   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5440                                    QueuePtr, SDValue());
5441 
5442   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5443   SDValue Ops[] = {
5444     ToReg,
5445     DAG.getTargetConstant(TrapID, SL, MVT::i16),
5446     SGPR01,
5447     ToReg.getValue(1)
5448   };
5449   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5450 }
5451 
5452 SDValue SITargetLowering::lowerTrapHsa(
5453     SDValue Op, SelectionDAG &DAG) const {
5454   SDLoc SL(Op);
5455   SDValue Chain = Op.getOperand(0);
5456 
5457   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5458   SDValue Ops[] = {
5459     Chain,
5460     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5461   };
5462   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5463 }
5464 
5465 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5466   SDLoc SL(Op);
5467   SDValue Chain = Op.getOperand(0);
5468   MachineFunction &MF = DAG.getMachineFunction();
5469 
5470   if (!Subtarget->isTrapHandlerEnabled() ||
5471       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5472     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5473                                      "debugtrap handler not supported",
5474                                      Op.getDebugLoc(),
5475                                      DS_Warning);
5476     LLVMContext &Ctx = MF.getFunction().getContext();
5477     Ctx.diagnose(NoTrap);
5478     return Chain;
5479   }
5480 
5481   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5482   SDValue Ops[] = {
5483     Chain,
5484     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5485   };
5486   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5487 }
5488 
5489 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5490                                              SelectionDAG &DAG) const {
5491   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5492   if (Subtarget->hasApertureRegs()) {
5493     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5494         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5495         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5496     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5497         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5498         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5499     unsigned Encoding =
5500         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5501         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5502         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5503 
5504     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5505     SDValue ApertureReg = SDValue(
5506         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5507     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5508     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5509   }
5510 
5511   // For code object version 5, private_base and shared_base are passed through
5512   // implicit kernargs.
5513   if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) {
5514     ImplicitParameter Param =
5515         (AS == AMDGPUAS::LOCAL_ADDRESS) ? SHARED_BASE : PRIVATE_BASE;
5516     return loadImplicitKernelArgument(DAG, MVT::i32, DL, Align(4), Param);
5517   }
5518 
5519   MachineFunction &MF = DAG.getMachineFunction();
5520   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5521   Register UserSGPR = Info->getQueuePtrUserSGPR();
5522   if (UserSGPR == AMDGPU::NoRegister) {
5523     // We probably are in a function incorrectly marked with
5524     // amdgpu-no-queue-ptr. This is undefined.
5525     return DAG.getUNDEF(MVT::i32);
5526   }
5527 
5528   SDValue QueuePtr = CreateLiveInRegister(
5529     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5530 
5531   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5532   // private_segment_aperture_base_hi.
5533   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5534 
5535   SDValue Ptr =
5536       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5537 
5538   // TODO: Use custom target PseudoSourceValue.
5539   // TODO: We should use the value from the IR intrinsic call, but it might not
5540   // be available and how do we get it?
5541   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5542   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5543                      commonAlignment(Align(64), StructOffset),
5544                      MachineMemOperand::MODereferenceable |
5545                          MachineMemOperand::MOInvariant);
5546 }
5547 
5548 /// Return true if the value is a known valid address, such that a null check is
5549 /// not necessary.
5550 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG,
5551                            const AMDGPUTargetMachine &TM, unsigned AddrSpace) {
5552   if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) ||
5553       isa<BasicBlockSDNode>(Val))
5554     return true;
5555 
5556   if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val))
5557     return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace);
5558 
5559   // TODO: Search through arithmetic, handle arguments and loads
5560   // marked nonnull.
5561   return false;
5562 }
5563 
5564 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5565                                              SelectionDAG &DAG) const {
5566   SDLoc SL(Op);
5567   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5568 
5569   SDValue Src = ASC->getOperand(0);
5570   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5571   unsigned SrcAS = ASC->getSrcAddressSpace();
5572 
5573   const AMDGPUTargetMachine &TM =
5574     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5575 
5576   // flat -> local/private
5577   if (SrcAS == AMDGPUAS::FLAT_ADDRESS) {
5578     unsigned DestAS = ASC->getDestAddressSpace();
5579 
5580     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5581         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5582       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5583 
5584       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5585         return Ptr;
5586 
5587       unsigned NullVal = TM.getNullPointerValue(DestAS);
5588       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5589       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5590 
5591       return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr,
5592                          SegmentNullPtr);
5593     }
5594   }
5595 
5596   // local/private -> flat
5597   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5598     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5599         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5600 
5601       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5602       SDValue CvtPtr =
5603           DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5604       CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr);
5605 
5606       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5607         return CvtPtr;
5608 
5609       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5610       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5611 
5612       SDValue NonNull
5613         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5614 
5615       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr,
5616                          FlatNullPtr);
5617     }
5618   }
5619 
5620   if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5621       Op.getValueType() == MVT::i64) {
5622     const SIMachineFunctionInfo *Info =
5623         DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>();
5624     SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32);
5625     SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi);
5626     return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
5627   }
5628 
5629   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5630       Src.getValueType() == MVT::i64)
5631     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5632 
5633   // global <-> flat are no-ops and never emitted.
5634 
5635   const MachineFunction &MF = DAG.getMachineFunction();
5636   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5637     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5638   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5639 
5640   return DAG.getUNDEF(ASC->getValueType(0));
5641 }
5642 
5643 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5644 // the small vector and inserting them into the big vector. That is better than
5645 // the default expansion of doing it via a stack slot. Even though the use of
5646 // the stack slot would be optimized away afterwards, the stack slot itself
5647 // remains.
5648 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5649                                                 SelectionDAG &DAG) const {
5650   SDValue Vec = Op.getOperand(0);
5651   SDValue Ins = Op.getOperand(1);
5652   SDValue Idx = Op.getOperand(2);
5653   EVT VecVT = Vec.getValueType();
5654   EVT InsVT = Ins.getValueType();
5655   EVT EltVT = VecVT.getVectorElementType();
5656   unsigned InsNumElts = InsVT.getVectorNumElements();
5657   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5658   SDLoc SL(Op);
5659 
5660   for (unsigned I = 0; I != InsNumElts; ++I) {
5661     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5662                               DAG.getConstant(I, SL, MVT::i32));
5663     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5664                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5665   }
5666   return Vec;
5667 }
5668 
5669 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5670                                                  SelectionDAG &DAG) const {
5671   SDValue Vec = Op.getOperand(0);
5672   SDValue InsVal = Op.getOperand(1);
5673   SDValue Idx = Op.getOperand(2);
5674   EVT VecVT = Vec.getValueType();
5675   EVT EltVT = VecVT.getVectorElementType();
5676   unsigned VecSize = VecVT.getSizeInBits();
5677   unsigned EltSize = EltVT.getSizeInBits();
5678   SDLoc SL(Op);
5679 
5680   // Specially handle the case of v4i16 with static indexing.
5681   unsigned NumElts = VecVT.getVectorNumElements();
5682   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5683   if (NumElts == 4 && EltSize == 16 && KIdx) {
5684     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5685 
5686     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5687                                  DAG.getConstant(0, SL, MVT::i32));
5688     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5689                                  DAG.getConstant(1, SL, MVT::i32));
5690 
5691     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5692     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5693 
5694     unsigned Idx = KIdx->getZExtValue();
5695     bool InsertLo = Idx < 2;
5696     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5697       InsertLo ? LoVec : HiVec,
5698       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5699       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5700 
5701     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5702 
5703     SDValue Concat = InsertLo ?
5704       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5705       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5706 
5707     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5708   }
5709 
5710   // Static indexing does not lower to stack access, and hence there is no need
5711   // for special custom lowering to avoid stack access.
5712   if (isa<ConstantSDNode>(Idx))
5713     return SDValue();
5714 
5715   // Avoid stack access for dynamic indexing by custom lowering to
5716   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5717 
5718   assert(VecSize <= 64 && "Expected target vector size to be <= 64 bits");
5719 
5720   MVT IntVT = MVT::getIntegerVT(VecSize);
5721 
5722   // Convert vector index to bit-index and get the required bit mask.
5723   assert(isPowerOf2_32(EltSize));
5724   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5725   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5726   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5727                             DAG.getConstant(0xffff, SL, IntVT),
5728                             ScaledIdx);
5729 
5730   // 1. Create a congruent vector with the target value in each element.
5731   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5732                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5733 
5734   // 2. Mask off all other indicies except the required index within (1).
5735   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5736 
5737   // 3. Mask off the required index within the target vector.
5738   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5739   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5740                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5741 
5742   // 4. Get (2) and (3) ORed into the target vector.
5743   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5744 
5745   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5746 }
5747 
5748 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5749                                                   SelectionDAG &DAG) const {
5750   SDLoc SL(Op);
5751 
5752   EVT ResultVT = Op.getValueType();
5753   SDValue Vec = Op.getOperand(0);
5754   SDValue Idx = Op.getOperand(1);
5755   EVT VecVT = Vec.getValueType();
5756   unsigned VecSize = VecVT.getSizeInBits();
5757   EVT EltVT = VecVT.getVectorElementType();
5758 
5759   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5760 
5761   // Make sure we do any optimizations that will make it easier to fold
5762   // source modifiers before obscuring it with bit operations.
5763 
5764   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5765   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5766     return Combined;
5767 
5768   if (VecSize == 128 || VecSize == 256) {
5769     SDValue Lo, Hi;
5770     EVT LoVT, HiVT;
5771     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5772 
5773     if (VecSize == 128) {
5774       SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec);
5775       Lo = DAG.getBitcast(LoVT,
5776                           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, V2,
5777                                       DAG.getConstant(0, SL, MVT::i32)));
5778       Hi = DAG.getBitcast(HiVT,
5779                           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, V2,
5780                                       DAG.getConstant(1, SL, MVT::i32)));
5781     } else {
5782       assert(VecSize == 256);
5783 
5784       SDValue V2 = DAG.getBitcast(MVT::v4i64, Vec);
5785       SDValue Parts[4];
5786       for (unsigned P = 0; P < 4; ++P) {
5787         Parts[P] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64, V2,
5788                                DAG.getConstant(P, SL, MVT::i32));
5789       }
5790 
5791       Lo = DAG.getBitcast(LoVT, DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i64,
5792                                             Parts[0], Parts[1]));
5793       Hi = DAG.getBitcast(HiVT, DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i64,
5794                                             Parts[2], Parts[3]));
5795     }
5796 
5797     EVT IdxVT = Idx.getValueType();
5798     unsigned NElem = VecVT.getVectorNumElements();
5799     assert(isPowerOf2_32(NElem));
5800     SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT);
5801     SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask);
5802     SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT);
5803     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx);
5804   }
5805 
5806   assert(VecSize <= 64);
5807 
5808   MVT IntVT = MVT::getIntegerVT(VecSize);
5809 
5810   // If Vec is just a SCALAR_TO_VECTOR, then use the scalar integer directly.
5811   SDValue VecBC = peekThroughBitcasts(Vec);
5812   if (VecBC.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5813     SDValue Src = VecBC.getOperand(0);
5814     Src = DAG.getBitcast(Src.getValueType().changeTypeToInteger(), Src);
5815     Vec = DAG.getAnyExtOrTrunc(Src, SL, IntVT);
5816   }
5817 
5818   unsigned EltSize = EltVT.getSizeInBits();
5819   assert(isPowerOf2_32(EltSize));
5820 
5821   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5822 
5823   // Convert vector index to bit-index (* EltSize)
5824   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5825 
5826   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5827   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5828 
5829   if (ResultVT == MVT::f16) {
5830     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5831     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5832   }
5833 
5834   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5835 }
5836 
5837 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5838   assert(Elt % 2 == 0);
5839   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5840 }
5841 
5842 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5843                                               SelectionDAG &DAG) const {
5844   SDLoc SL(Op);
5845   EVT ResultVT = Op.getValueType();
5846   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5847 
5848   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5849   EVT EltVT = PackVT.getVectorElementType();
5850   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5851 
5852   // vector_shuffle <0,1,6,7> lhs, rhs
5853   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5854   //
5855   // vector_shuffle <6,7,2,3> lhs, rhs
5856   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5857   //
5858   // vector_shuffle <6,7,0,1> lhs, rhs
5859   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5860 
5861   // Avoid scalarizing when both halves are reading from consecutive elements.
5862   SmallVector<SDValue, 4> Pieces;
5863   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5864     if (elementPairIsContiguous(SVN->getMask(), I)) {
5865       const int Idx = SVN->getMaskElt(I);
5866       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5867       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5868       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5869                                     PackVT, SVN->getOperand(VecIdx),
5870                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5871       Pieces.push_back(SubVec);
5872     } else {
5873       const int Idx0 = SVN->getMaskElt(I);
5874       const int Idx1 = SVN->getMaskElt(I + 1);
5875       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5876       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5877       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5878       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5879 
5880       SDValue Vec0 = SVN->getOperand(VecIdx0);
5881       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5882                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5883 
5884       SDValue Vec1 = SVN->getOperand(VecIdx1);
5885       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5886                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5887       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5888     }
5889   }
5890 
5891   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5892 }
5893 
5894 SDValue SITargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
5895                                                 SelectionDAG &DAG) const {
5896   SDValue SVal = Op.getOperand(0);
5897   EVT ResultVT = Op.getValueType();
5898   EVT SValVT = SVal.getValueType();
5899   SDValue UndefVal = DAG.getUNDEF(SValVT);
5900   SDLoc SL(Op);
5901 
5902   SmallVector<SDValue, 8> VElts;
5903   VElts.push_back(SVal);
5904   for (int I = 1, E = ResultVT.getVectorNumElements(); I < E; ++I)
5905     VElts.push_back(UndefVal);
5906 
5907   return DAG.getBuildVector(ResultVT, SL, VElts);
5908 }
5909 
5910 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5911                                             SelectionDAG &DAG) const {
5912   SDLoc SL(Op);
5913   EVT VT = Op.getValueType();
5914 
5915   if (VT == MVT::v4i16 || VT == MVT::v4f16 ||
5916       VT == MVT::v8i16 || VT == MVT::v8f16) {
5917     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(),
5918                                   VT.getVectorNumElements() / 2);
5919     MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits());
5920 
5921     // Turn into pair of packed build_vectors.
5922     // TODO: Special case for constants that can be materialized with s_mov_b64.
5923     SmallVector<SDValue, 4> LoOps, HiOps;
5924     for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) {
5925       LoOps.push_back(Op.getOperand(I));
5926       HiOps.push_back(Op.getOperand(I + E));
5927     }
5928     SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps);
5929     SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps);
5930 
5931     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo);
5932     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi);
5933 
5934     SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL,
5935                                        { CastLo, CastHi });
5936     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5937   }
5938 
5939   if (VT == MVT::v16i16 || VT == MVT::v16f16) {
5940     EVT QuarterVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(),
5941                                      VT.getVectorNumElements() / 4);
5942     MVT QuarterIntVT = MVT::getIntegerVT(QuarterVT.getSizeInBits());
5943 
5944     SmallVector<SDValue, 4> Parts[4];
5945     for (unsigned I = 0, E = VT.getVectorNumElements() / 4; I != E; ++I) {
5946       for (unsigned P = 0; P < 4; ++P)
5947         Parts[P].push_back(Op.getOperand(I + P * E));
5948     }
5949     SDValue Casts[4];
5950     for (unsigned P = 0; P < 4; ++P) {
5951       SDValue Vec = DAG.getBuildVector(QuarterVT, SL, Parts[P]);
5952       Casts[P] = DAG.getNode(ISD::BITCAST, SL, QuarterIntVT, Vec);
5953     }
5954 
5955     SDValue Blend =
5956         DAG.getBuildVector(MVT::getVectorVT(QuarterIntVT, 4), SL, Casts);
5957     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5958   }
5959 
5960   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5961   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5962 
5963   SDValue Lo = Op.getOperand(0);
5964   SDValue Hi = Op.getOperand(1);
5965 
5966   // Avoid adding defined bits with the zero_extend.
5967   if (Hi.isUndef()) {
5968     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5969     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5970     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5971   }
5972 
5973   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5974   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5975 
5976   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5977                               DAG.getConstant(16, SL, MVT::i32));
5978   if (Lo.isUndef())
5979     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5980 
5981   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5982   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5983 
5984   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5985   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5986 }
5987 
5988 bool
5989 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5990   // We can fold offsets for anything that doesn't require a GOT relocation.
5991   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5992           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5993           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5994          !shouldEmitGOTReloc(GA->getGlobal());
5995 }
5996 
5997 static SDValue
5998 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5999                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
6000                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
6001   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
6002   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
6003   // lowered to the following code sequence:
6004   //
6005   // For constant address space:
6006   //   s_getpc_b64 s[0:1]
6007   //   s_add_u32 s0, s0, $symbol
6008   //   s_addc_u32 s1, s1, 0
6009   //
6010   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
6011   //   a fixup or relocation is emitted to replace $symbol with a literal
6012   //   constant, which is a pc-relative offset from the encoding of the $symbol
6013   //   operand to the global variable.
6014   //
6015   // For global address space:
6016   //   s_getpc_b64 s[0:1]
6017   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
6018   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
6019   //
6020   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
6021   //   fixups or relocations are emitted to replace $symbol@*@lo and
6022   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
6023   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
6024   //   operand to the global variable.
6025   //
6026   // What we want here is an offset from the value returned by s_getpc
6027   // (which is the address of the s_add_u32 instruction) to the global
6028   // variable, but since the encoding of $symbol starts 4 bytes after the start
6029   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
6030   // small. This requires us to add 4 to the global variable offset in order to
6031   // compute the correct address. Similarly for the s_addc_u32 instruction, the
6032   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
6033   // instruction.
6034   SDValue PtrLo =
6035       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
6036   SDValue PtrHi;
6037   if (GAFlags == SIInstrInfo::MO_NONE) {
6038     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
6039   } else {
6040     PtrHi =
6041         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
6042   }
6043   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
6044 }
6045 
6046 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
6047                                              SDValue Op,
6048                                              SelectionDAG &DAG) const {
6049   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
6050   SDLoc DL(GSD);
6051   EVT PtrVT = Op.getValueType();
6052 
6053   const GlobalValue *GV = GSD->getGlobal();
6054   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
6055        shouldUseLDSConstAddress(GV)) ||
6056       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
6057       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
6058     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
6059         GV->hasExternalLinkage()) {
6060       Type *Ty = GV->getValueType();
6061       // HIP uses an unsized array `extern __shared__ T s[]` or similar
6062       // zero-sized type in other languages to declare the dynamic shared
6063       // memory which size is not known at the compile time. They will be
6064       // allocated by the runtime and placed directly after the static
6065       // allocated ones. They all share the same offset.
6066       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
6067         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
6068         // Adjust alignment for that dynamic shared memory array.
6069         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
6070         return SDValue(
6071             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
6072       }
6073     }
6074     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
6075   }
6076 
6077   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
6078     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
6079                                             SIInstrInfo::MO_ABS32_LO);
6080     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
6081   }
6082 
6083   if (shouldEmitFixup(GV))
6084     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
6085   else if (shouldEmitPCReloc(GV))
6086     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
6087                                    SIInstrInfo::MO_REL32);
6088 
6089   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
6090                                             SIInstrInfo::MO_GOTPCREL32);
6091 
6092   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
6093   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
6094   const DataLayout &DataLayout = DAG.getDataLayout();
6095   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
6096   MachinePointerInfo PtrInfo
6097     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
6098 
6099   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
6100                      MachineMemOperand::MODereferenceable |
6101                          MachineMemOperand::MOInvariant);
6102 }
6103 
6104 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
6105                                    const SDLoc &DL, SDValue V) const {
6106   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
6107   // the destination register.
6108   //
6109   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
6110   // so we will end up with redundant moves to m0.
6111   //
6112   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
6113 
6114   // A Null SDValue creates a glue result.
6115   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
6116                                   V, Chain);
6117   return SDValue(M0, 0);
6118 }
6119 
6120 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
6121                                                  SDValue Op,
6122                                                  MVT VT,
6123                                                  unsigned Offset) const {
6124   SDLoc SL(Op);
6125   SDValue Param = lowerKernargMemParameter(
6126       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
6127   // The local size values will have the hi 16-bits as zero.
6128   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
6129                      DAG.getValueType(VT));
6130 }
6131 
6132 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6133                                         EVT VT) {
6134   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6135                                       "non-hsa intrinsic with hsa target",
6136                                       DL.getDebugLoc());
6137   DAG.getContext()->diagnose(BadIntrin);
6138   return DAG.getUNDEF(VT);
6139 }
6140 
6141 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6142                                          EVT VT) {
6143   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6144                                       "intrinsic not supported on subtarget",
6145                                       DL.getDebugLoc());
6146   DAG.getContext()->diagnose(BadIntrin);
6147   return DAG.getUNDEF(VT);
6148 }
6149 
6150 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
6151                                     ArrayRef<SDValue> Elts) {
6152   assert(!Elts.empty());
6153   MVT Type;
6154   unsigned NumElts = Elts.size();
6155 
6156   if (NumElts <= 8) {
6157     Type = MVT::getVectorVT(MVT::f32, NumElts);
6158   } else {
6159     assert(Elts.size() <= 16);
6160     Type = MVT::v16f32;
6161     NumElts = 16;
6162   }
6163 
6164   SmallVector<SDValue, 16> VecElts(NumElts);
6165   for (unsigned i = 0; i < Elts.size(); ++i) {
6166     SDValue Elt = Elts[i];
6167     if (Elt.getValueType() != MVT::f32)
6168       Elt = DAG.getBitcast(MVT::f32, Elt);
6169     VecElts[i] = Elt;
6170   }
6171   for (unsigned i = Elts.size(); i < NumElts; ++i)
6172     VecElts[i] = DAG.getUNDEF(MVT::f32);
6173 
6174   if (NumElts == 1)
6175     return VecElts[0];
6176   return DAG.getBuildVector(Type, DL, VecElts);
6177 }
6178 
6179 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
6180                               SDValue Src, int ExtraElts) {
6181   EVT SrcVT = Src.getValueType();
6182 
6183   SmallVector<SDValue, 8> Elts;
6184 
6185   if (SrcVT.isVector())
6186     DAG.ExtractVectorElements(Src, Elts);
6187   else
6188     Elts.push_back(Src);
6189 
6190   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
6191   while (ExtraElts--)
6192     Elts.push_back(Undef);
6193 
6194   return DAG.getBuildVector(CastVT, DL, Elts);
6195 }
6196 
6197 // Re-construct the required return value for a image load intrinsic.
6198 // This is more complicated due to the optional use TexFailCtrl which means the required
6199 // return type is an aggregate
6200 static SDValue constructRetValue(SelectionDAG &DAG,
6201                                  MachineSDNode *Result,
6202                                  ArrayRef<EVT> ResultTypes,
6203                                  bool IsTexFail, bool Unpacked, bool IsD16,
6204                                  int DMaskPop, int NumVDataDwords,
6205                                  const SDLoc &DL) {
6206   // Determine the required return type. This is the same regardless of IsTexFail flag
6207   EVT ReqRetVT = ResultTypes[0];
6208   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
6209   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6210     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
6211 
6212   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6213     DMaskPop : (DMaskPop + 1) / 2;
6214 
6215   MVT DataDwordVT = NumDataDwords == 1 ?
6216     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
6217 
6218   MVT MaskPopVT = MaskPopDwords == 1 ?
6219     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
6220 
6221   SDValue Data(Result, 0);
6222   SDValue TexFail;
6223 
6224   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
6225     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
6226     if (MaskPopVT.isVector()) {
6227       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
6228                          SDValue(Result, 0), ZeroIdx);
6229     } else {
6230       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
6231                          SDValue(Result, 0), ZeroIdx);
6232     }
6233   }
6234 
6235   if (DataDwordVT.isVector())
6236     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
6237                           NumDataDwords - MaskPopDwords);
6238 
6239   if (IsD16)
6240     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
6241 
6242   EVT LegalReqRetVT = ReqRetVT;
6243   if (!ReqRetVT.isVector()) {
6244     if (!Data.getValueType().isInteger())
6245       Data = DAG.getNode(ISD::BITCAST, DL,
6246                          Data.getValueType().changeTypeToInteger(), Data);
6247     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
6248   } else {
6249     // We need to widen the return vector to a legal type
6250     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
6251         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
6252       LegalReqRetVT =
6253           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
6254                            ReqRetVT.getVectorNumElements() + 1);
6255     }
6256   }
6257   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
6258 
6259   if (IsTexFail) {
6260     TexFail =
6261         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
6262                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
6263 
6264     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
6265   }
6266 
6267   if (Result->getNumValues() == 1)
6268     return Data;
6269 
6270   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
6271 }
6272 
6273 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
6274                          SDValue *LWE, bool &IsTexFail) {
6275   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
6276 
6277   uint64_t Value = TexFailCtrlConst->getZExtValue();
6278   if (Value) {
6279     IsTexFail = true;
6280   }
6281 
6282   SDLoc DL(TexFailCtrlConst);
6283   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
6284   Value &= ~(uint64_t)0x1;
6285   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
6286   Value &= ~(uint64_t)0x2;
6287 
6288   return Value == 0;
6289 }
6290 
6291 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
6292                                       MVT PackVectorVT,
6293                                       SmallVectorImpl<SDValue> &PackedAddrs,
6294                                       unsigned DimIdx, unsigned EndIdx,
6295                                       unsigned NumGradients) {
6296   SDLoc DL(Op);
6297   for (unsigned I = DimIdx; I < EndIdx; I++) {
6298     SDValue Addr = Op.getOperand(I);
6299 
6300     // Gradients are packed with undef for each coordinate.
6301     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
6302     // 1D: undef,dx/dh; undef,dx/dv
6303     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
6304     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
6305     if (((I + 1) >= EndIdx) ||
6306         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
6307                                          I == DimIdx + NumGradients - 1))) {
6308       if (Addr.getValueType() != MVT::i16)
6309         Addr = DAG.getBitcast(MVT::i16, Addr);
6310       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
6311     } else {
6312       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
6313       I++;
6314     }
6315     Addr = DAG.getBitcast(MVT::f32, Addr);
6316     PackedAddrs.push_back(Addr);
6317   }
6318 }
6319 
6320 SDValue SITargetLowering::lowerImage(SDValue Op,
6321                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
6322                                      SelectionDAG &DAG, bool WithChain) const {
6323   SDLoc DL(Op);
6324   MachineFunction &MF = DAG.getMachineFunction();
6325   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
6326   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
6327       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
6328   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
6329   unsigned IntrOpcode = Intr->BaseOpcode;
6330   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6331   bool IsGFX11Plus = AMDGPU::isGFX11Plus(*Subtarget);
6332 
6333   SmallVector<EVT, 3> ResultTypes(Op->values());
6334   SmallVector<EVT, 3> OrigResultTypes(Op->values());
6335   bool IsD16 = false;
6336   bool IsG16 = false;
6337   bool IsA16 = false;
6338   SDValue VData;
6339   int NumVDataDwords;
6340   bool AdjustRetType = false;
6341 
6342   // Offset of intrinsic arguments
6343   const unsigned ArgOffset = WithChain ? 2 : 1;
6344 
6345   unsigned DMask;
6346   unsigned DMaskLanes = 0;
6347 
6348   if (BaseOpcode->Atomic) {
6349     VData = Op.getOperand(2);
6350 
6351     bool Is64Bit = VData.getValueType() == MVT::i64;
6352     if (BaseOpcode->AtomicX2) {
6353       SDValue VData2 = Op.getOperand(3);
6354       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6355                                  {VData, VData2});
6356       if (Is64Bit)
6357         VData = DAG.getBitcast(MVT::v4i32, VData);
6358 
6359       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6360       DMask = Is64Bit ? 0xf : 0x3;
6361       NumVDataDwords = Is64Bit ? 4 : 2;
6362     } else {
6363       DMask = Is64Bit ? 0x3 : 0x1;
6364       NumVDataDwords = Is64Bit ? 2 : 1;
6365     }
6366   } else {
6367     auto *DMaskConst =
6368         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6369     DMask = DMaskConst->getZExtValue();
6370     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6371 
6372     if (BaseOpcode->Store) {
6373       VData = Op.getOperand(2);
6374 
6375       MVT StoreVT = VData.getSimpleValueType();
6376       if (StoreVT.getScalarType() == MVT::f16) {
6377         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6378           return Op; // D16 is unsupported for this instruction
6379 
6380         IsD16 = true;
6381         VData = handleD16VData(VData, DAG, true);
6382       }
6383 
6384       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6385     } else {
6386       // Work out the num dwords based on the dmask popcount and underlying type
6387       // and whether packing is supported.
6388       MVT LoadVT = ResultTypes[0].getSimpleVT();
6389       if (LoadVT.getScalarType() == MVT::f16) {
6390         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6391           return Op; // D16 is unsupported for this instruction
6392 
6393         IsD16 = true;
6394       }
6395 
6396       // Confirm that the return type is large enough for the dmask specified
6397       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6398           (!LoadVT.isVector() && DMaskLanes > 1))
6399           return Op;
6400 
6401       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6402       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6403       // instructions.
6404       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6405           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6406         NumVDataDwords = (DMaskLanes + 1) / 2;
6407       else
6408         NumVDataDwords = DMaskLanes;
6409 
6410       AdjustRetType = true;
6411     }
6412   }
6413 
6414   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6415   SmallVector<SDValue, 4> VAddrs;
6416 
6417   // Check for 16 bit addresses or derivatives and pack if true.
6418   MVT VAddrVT =
6419       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6420   MVT VAddrScalarVT = VAddrVT.getScalarType();
6421   MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6422   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6423 
6424   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6425   VAddrScalarVT = VAddrVT.getScalarType();
6426   MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6427   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6428 
6429   // Push back extra arguments.
6430   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) {
6431     if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) {
6432       assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument");
6433       // Special handling of bias when A16 is on. Bias is of type half but
6434       // occupies full 32-bit.
6435       SDValue Bias = DAG.getBuildVector(
6436           MVT::v2f16, DL,
6437           {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)});
6438       VAddrs.push_back(Bias);
6439     } else {
6440       assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) &&
6441              "Bias needs to be converted to 16 bit in A16 mode");
6442       VAddrs.push_back(Op.getOperand(ArgOffset + I));
6443     }
6444   }
6445 
6446   if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
6447     // 16 bit gradients are supported, but are tied to the A16 control
6448     // so both gradients and addresses must be 16 bit
6449     LLVM_DEBUG(
6450         dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6451                   "require 16 bit args for both gradients and addresses");
6452     return Op;
6453   }
6454 
6455   if (IsA16) {
6456     if (!ST->hasA16()) {
6457       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6458                            "support 16 bit addresses\n");
6459       return Op;
6460     }
6461   }
6462 
6463   // We've dealt with incorrect input so we know that if IsA16, IsG16
6464   // are set then we have to compress/pack operands (either address,
6465   // gradient or both)
6466   // In the case where a16 and gradients are tied (no G16 support) then we
6467   // have already verified that both IsA16 and IsG16 are true
6468   if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
6469     // Activate g16
6470     const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6471         AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6472     IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6473   }
6474 
6475   // Add gradients (packed or unpacked)
6476   if (IsG16) {
6477     // Pack the gradients
6478     // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6479     packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
6480                               ArgOffset + Intr->GradientStart,
6481                               ArgOffset + Intr->CoordStart, Intr->NumGradients);
6482   } else {
6483     for (unsigned I = ArgOffset + Intr->GradientStart;
6484          I < ArgOffset + Intr->CoordStart; I++)
6485       VAddrs.push_back(Op.getOperand(I));
6486   }
6487 
6488   // Add addresses (packed or unpacked)
6489   if (IsA16) {
6490     packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
6491                               ArgOffset + Intr->CoordStart, VAddrEnd,
6492                               0 /* No gradients */);
6493   } else {
6494     // Add uncompressed address
6495     for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6496       VAddrs.push_back(Op.getOperand(I));
6497   }
6498 
6499   // If the register allocator cannot place the address registers contiguously
6500   // without introducing moves, then using the non-sequential address encoding
6501   // is always preferable, since it saves VALU instructions and is usually a
6502   // wash in terms of code size or even better.
6503   //
6504   // However, we currently have no way of hinting to the register allocator that
6505   // MIMG addresses should be placed contiguously when it is possible to do so,
6506   // so force non-NSA for the common 2-address case as a heuristic.
6507   //
6508   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6509   // allocation when possible.
6510   //
6511   // TODO: we can actually allow partial NSA where the final register is a
6512   // contiguous set of the remaining addresses.
6513   // This could help where there are more addresses than supported.
6514   bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) &&
6515                 VAddrs.size() >= 3 &&
6516                 VAddrs.size() <= (unsigned)ST->getNSAMaxSize();
6517   SDValue VAddr;
6518   if (!UseNSA)
6519     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6520 
6521   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6522   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6523   SDValue Unorm;
6524   if (!BaseOpcode->Sampler) {
6525     Unorm = True;
6526   } else {
6527     auto UnormConst =
6528         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6529 
6530     Unorm = UnormConst->getZExtValue() ? True : False;
6531   }
6532 
6533   SDValue TFE;
6534   SDValue LWE;
6535   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6536   bool IsTexFail = false;
6537   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6538     return Op;
6539 
6540   if (IsTexFail) {
6541     if (!DMaskLanes) {
6542       // Expecting to get an error flag since TFC is on - and dmask is 0
6543       // Force dmask to be at least 1 otherwise the instruction will fail
6544       DMask = 0x1;
6545       DMaskLanes = 1;
6546       NumVDataDwords = 1;
6547     }
6548     NumVDataDwords += 1;
6549     AdjustRetType = true;
6550   }
6551 
6552   // Has something earlier tagged that the return type needs adjusting
6553   // This happens if the instruction is a load or has set TexFailCtrl flags
6554   if (AdjustRetType) {
6555     // NumVDataDwords reflects the true number of dwords required in the return type
6556     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6557       // This is a no-op load. This can be eliminated
6558       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6559       if (isa<MemSDNode>(Op))
6560         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6561       return Undef;
6562     }
6563 
6564     EVT NewVT = NumVDataDwords > 1 ?
6565                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6566                 : MVT::i32;
6567 
6568     ResultTypes[0] = NewVT;
6569     if (ResultTypes.size() == 3) {
6570       // Original result was aggregate type used for TexFailCtrl results
6571       // The actual instruction returns as a vector type which has now been
6572       // created. Remove the aggregate result.
6573       ResultTypes.erase(&ResultTypes[1]);
6574     }
6575   }
6576 
6577   unsigned CPol = cast<ConstantSDNode>(
6578       Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6579   if (BaseOpcode->Atomic)
6580     CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6581   if (CPol & ~AMDGPU::CPol::ALL)
6582     return Op;
6583 
6584   SmallVector<SDValue, 26> Ops;
6585   if (BaseOpcode->Store || BaseOpcode->Atomic)
6586     Ops.push_back(VData); // vdata
6587   if (UseNSA)
6588     append_range(Ops, VAddrs);
6589   else
6590     Ops.push_back(VAddr);
6591   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6592   if (BaseOpcode->Sampler)
6593     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6594   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6595   if (IsGFX10Plus)
6596     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6597   Ops.push_back(Unorm);
6598   Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6599   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6600                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6601   if (IsGFX10Plus)
6602     Ops.push_back(IsA16 ? True : False);
6603   if (!Subtarget->hasGFX90AInsts()) {
6604     Ops.push_back(TFE); //tfe
6605   } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6606     report_fatal_error("TFE is not supported on this GPU");
6607   }
6608   Ops.push_back(LWE); // lwe
6609   if (!IsGFX10Plus)
6610     Ops.push_back(DimInfo->DA ? True : False);
6611   if (BaseOpcode->HasD16)
6612     Ops.push_back(IsD16 ? True : False);
6613   if (isa<MemSDNode>(Op))
6614     Ops.push_back(Op.getOperand(0)); // chain
6615 
6616   int NumVAddrDwords =
6617       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6618   int Opcode = -1;
6619 
6620   if (IsGFX11Plus) {
6621     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6622                                    UseNSA ? AMDGPU::MIMGEncGfx11NSA
6623                                           : AMDGPU::MIMGEncGfx11Default,
6624                                    NumVDataDwords, NumVAddrDwords);
6625   } else if (IsGFX10Plus) {
6626     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6627                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6628                                           : AMDGPU::MIMGEncGfx10Default,
6629                                    NumVDataDwords, NumVAddrDwords);
6630   } else {
6631     if (Subtarget->hasGFX90AInsts()) {
6632       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6633                                      NumVDataDwords, NumVAddrDwords);
6634       if (Opcode == -1)
6635         report_fatal_error(
6636             "requested image instruction is not supported on this GPU");
6637     }
6638     if (Opcode == -1 &&
6639         Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6640       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6641                                      NumVDataDwords, NumVAddrDwords);
6642     if (Opcode == -1)
6643       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6644                                      NumVDataDwords, NumVAddrDwords);
6645   }
6646   assert(Opcode != -1);
6647 
6648   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6649   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6650     MachineMemOperand *MemRef = MemOp->getMemOperand();
6651     DAG.setNodeMemRefs(NewNode, {MemRef});
6652   }
6653 
6654   if (BaseOpcode->AtomicX2) {
6655     SmallVector<SDValue, 1> Elt;
6656     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6657     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6658   }
6659   if (BaseOpcode->Store)
6660     return SDValue(NewNode, 0);
6661   return constructRetValue(DAG, NewNode,
6662                            OrigResultTypes, IsTexFail,
6663                            Subtarget->hasUnpackedD16VMem(), IsD16,
6664                            DMaskLanes, NumVDataDwords, DL);
6665 }
6666 
6667 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6668                                        SDValue Offset, SDValue CachePolicy,
6669                                        SelectionDAG &DAG) const {
6670   MachineFunction &MF = DAG.getMachineFunction();
6671 
6672   const DataLayout &DataLayout = DAG.getDataLayout();
6673   Align Alignment =
6674       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6675 
6676   MachineMemOperand *MMO = MF.getMachineMemOperand(
6677       MachinePointerInfo(),
6678       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6679           MachineMemOperand::MOInvariant,
6680       VT.getStoreSize(), Alignment);
6681 
6682   if (!Offset->isDivergent()) {
6683     SDValue Ops[] = {
6684         Rsrc,
6685         Offset, // Offset
6686         CachePolicy
6687     };
6688 
6689     // Widen vec3 load to vec4.
6690     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6691       EVT WidenedVT =
6692           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6693       auto WidenedOp = DAG.getMemIntrinsicNode(
6694           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6695           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6696       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6697                                    DAG.getVectorIdxConstant(0, DL));
6698       return Subvector;
6699     }
6700 
6701     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6702                                    DAG.getVTList(VT), Ops, VT, MMO);
6703   }
6704 
6705   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6706   // assume that the buffer is unswizzled.
6707   SmallVector<SDValue, 4> Loads;
6708   unsigned NumLoads = 1;
6709   MVT LoadVT = VT.getSimpleVT();
6710   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6711   assert((LoadVT.getScalarType() == MVT::i32 ||
6712           LoadVT.getScalarType() == MVT::f32));
6713 
6714   if (NumElts == 8 || NumElts == 16) {
6715     NumLoads = NumElts / 4;
6716     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6717   }
6718 
6719   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6720   SDValue Ops[] = {
6721       DAG.getEntryNode(),                               // Chain
6722       Rsrc,                                             // rsrc
6723       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6724       {},                                               // voffset
6725       {},                                               // soffset
6726       {},                                               // offset
6727       CachePolicy,                                      // cachepolicy
6728       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6729   };
6730 
6731   // Use the alignment to ensure that the required offsets will fit into the
6732   // immediate offsets.
6733   setBufferOffsets(Offset, DAG, &Ops[3],
6734                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6735 
6736   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6737   for (unsigned i = 0; i < NumLoads; ++i) {
6738     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6739     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6740                                         LoadVT, MMO, DAG));
6741   }
6742 
6743   if (NumElts == 8 || NumElts == 16)
6744     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6745 
6746   return Loads[0];
6747 }
6748 
6749 SDValue SITargetLowering::lowerWorkitemID(SelectionDAG &DAG, SDValue Op,
6750                                           unsigned Dim,
6751                                           const ArgDescriptor &Arg) const {
6752   SDLoc SL(Op);
6753   MachineFunction &MF = DAG.getMachineFunction();
6754   unsigned MaxID = Subtarget->getMaxWorkitemID(MF.getFunction(), Dim);
6755   if (MaxID == 0)
6756     return DAG.getConstant(0, SL, MVT::i32);
6757 
6758   SDValue Val = loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6759                                SDLoc(DAG.getEntryNode()), Arg);
6760 
6761   // Don't bother inserting AssertZext for packed IDs since we're emitting the
6762   // masking operations anyway.
6763   //
6764   // TODO: We could assert the top bit is 0 for the source copy.
6765   if (Arg.isMasked())
6766     return Val;
6767 
6768   // Preserve the known bits after expansion to a copy.
6769   EVT SmallVT =
6770       EVT::getIntegerVT(*DAG.getContext(), 32 - countLeadingZeros(MaxID));
6771   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Val,
6772                      DAG.getValueType(SmallVT));
6773 }
6774 
6775 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6776                                                   SelectionDAG &DAG) const {
6777   MachineFunction &MF = DAG.getMachineFunction();
6778   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6779 
6780   EVT VT = Op.getValueType();
6781   SDLoc DL(Op);
6782   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6783 
6784   // TODO: Should this propagate fast-math-flags?
6785 
6786   switch (IntrinsicID) {
6787   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6788     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6789       return emitNonHSAIntrinsicError(DAG, DL, VT);
6790     return getPreloadedValue(DAG, *MFI, VT,
6791                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6792   }
6793   case Intrinsic::amdgcn_dispatch_ptr:
6794   case Intrinsic::amdgcn_queue_ptr: {
6795     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6796       DiagnosticInfoUnsupported BadIntrin(
6797           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6798           DL.getDebugLoc());
6799       DAG.getContext()->diagnose(BadIntrin);
6800       return DAG.getUNDEF(VT);
6801     }
6802 
6803     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6804       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6805     return getPreloadedValue(DAG, *MFI, VT, RegID);
6806   }
6807   case Intrinsic::amdgcn_implicitarg_ptr: {
6808     if (MFI->isEntryFunction())
6809       return getImplicitArgPtr(DAG, DL);
6810     return getPreloadedValue(DAG, *MFI, VT,
6811                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6812   }
6813   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6814     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6815       // This only makes sense to call in a kernel, so just lower to null.
6816       return DAG.getConstant(0, DL, VT);
6817     }
6818 
6819     return getPreloadedValue(DAG, *MFI, VT,
6820                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6821   }
6822   case Intrinsic::amdgcn_dispatch_id: {
6823     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6824   }
6825   case Intrinsic::amdgcn_rcp:
6826     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6827   case Intrinsic::amdgcn_rsq:
6828     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6829   case Intrinsic::amdgcn_rsq_legacy:
6830     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6831       return emitRemovedIntrinsicError(DAG, DL, VT);
6832     return SDValue();
6833   case Intrinsic::amdgcn_rcp_legacy:
6834     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6835       return emitRemovedIntrinsicError(DAG, DL, VT);
6836     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6837   case Intrinsic::amdgcn_rsq_clamp: {
6838     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6839       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6840 
6841     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6842     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6843     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6844 
6845     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6846     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6847                               DAG.getConstantFP(Max, DL, VT));
6848     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6849                        DAG.getConstantFP(Min, DL, VT));
6850   }
6851   case Intrinsic::r600_read_ngroups_x:
6852     if (Subtarget->isAmdHsaOS())
6853       return emitNonHSAIntrinsicError(DAG, DL, VT);
6854 
6855     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6856                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6857                                     false);
6858   case Intrinsic::r600_read_ngroups_y:
6859     if (Subtarget->isAmdHsaOS())
6860       return emitNonHSAIntrinsicError(DAG, DL, VT);
6861 
6862     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6863                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6864                                     false);
6865   case Intrinsic::r600_read_ngroups_z:
6866     if (Subtarget->isAmdHsaOS())
6867       return emitNonHSAIntrinsicError(DAG, DL, VT);
6868 
6869     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6870                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6871                                     false);
6872   case Intrinsic::r600_read_global_size_x:
6873     if (Subtarget->isAmdHsaOS())
6874       return emitNonHSAIntrinsicError(DAG, DL, VT);
6875 
6876     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6877                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6878                                     Align(4), false);
6879   case Intrinsic::r600_read_global_size_y:
6880     if (Subtarget->isAmdHsaOS())
6881       return emitNonHSAIntrinsicError(DAG, DL, VT);
6882 
6883     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6884                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6885                                     Align(4), false);
6886   case Intrinsic::r600_read_global_size_z:
6887     if (Subtarget->isAmdHsaOS())
6888       return emitNonHSAIntrinsicError(DAG, DL, VT);
6889 
6890     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6891                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6892                                     Align(4), false);
6893   case Intrinsic::r600_read_local_size_x:
6894     if (Subtarget->isAmdHsaOS())
6895       return emitNonHSAIntrinsicError(DAG, DL, VT);
6896 
6897     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6898                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6899   case Intrinsic::r600_read_local_size_y:
6900     if (Subtarget->isAmdHsaOS())
6901       return emitNonHSAIntrinsicError(DAG, DL, VT);
6902 
6903     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6904                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6905   case Intrinsic::r600_read_local_size_z:
6906     if (Subtarget->isAmdHsaOS())
6907       return emitNonHSAIntrinsicError(DAG, DL, VT);
6908 
6909     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6910                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6911   case Intrinsic::amdgcn_workgroup_id_x:
6912     return getPreloadedValue(DAG, *MFI, VT,
6913                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6914   case Intrinsic::amdgcn_workgroup_id_y:
6915     return getPreloadedValue(DAG, *MFI, VT,
6916                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6917   case Intrinsic::amdgcn_workgroup_id_z:
6918     return getPreloadedValue(DAG, *MFI, VT,
6919                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6920   case Intrinsic::amdgcn_lds_kernel_id: {
6921     if (MFI->isEntryFunction())
6922       return getLDSKernelId(DAG, DL);
6923     return getPreloadedValue(DAG, *MFI, VT,
6924                              AMDGPUFunctionArgInfo::LDS_KERNEL_ID);
6925   }
6926   case Intrinsic::amdgcn_workitem_id_x:
6927     return lowerWorkitemID(DAG, Op, 0, MFI->getArgInfo().WorkItemIDX);
6928   case Intrinsic::amdgcn_workitem_id_y:
6929     return lowerWorkitemID(DAG, Op, 1, MFI->getArgInfo().WorkItemIDY);
6930   case Intrinsic::amdgcn_workitem_id_z:
6931     return lowerWorkitemID(DAG, Op, 2, MFI->getArgInfo().WorkItemIDZ);
6932   case Intrinsic::amdgcn_wavefrontsize:
6933     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6934                            SDLoc(Op), MVT::i32);
6935   case Intrinsic::amdgcn_s_buffer_load: {
6936     unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6937     if (CPol & ~AMDGPU::CPol::ALL)
6938       return Op;
6939     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6940                         DAG);
6941   }
6942   case Intrinsic::amdgcn_fdiv_fast:
6943     return lowerFDIV_FAST(Op, DAG);
6944   case Intrinsic::amdgcn_sin:
6945     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6946 
6947   case Intrinsic::amdgcn_cos:
6948     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6949 
6950   case Intrinsic::amdgcn_mul_u24:
6951     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6952   case Intrinsic::amdgcn_mul_i24:
6953     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6954 
6955   case Intrinsic::amdgcn_log_clamp: {
6956     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6957       return SDValue();
6958 
6959     return emitRemovedIntrinsicError(DAG, DL, VT);
6960   }
6961   case Intrinsic::amdgcn_ldexp:
6962     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6963                        Op.getOperand(1), Op.getOperand(2));
6964 
6965   case Intrinsic::amdgcn_fract:
6966     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6967 
6968   case Intrinsic::amdgcn_class:
6969     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6970                        Op.getOperand(1), Op.getOperand(2));
6971   case Intrinsic::amdgcn_div_fmas:
6972     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6973                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6974                        Op.getOperand(4));
6975 
6976   case Intrinsic::amdgcn_div_fixup:
6977     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6978                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6979 
6980   case Intrinsic::amdgcn_div_scale: {
6981     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6982 
6983     // Translate to the operands expected by the machine instruction. The
6984     // first parameter must be the same as the first instruction.
6985     SDValue Numerator = Op.getOperand(1);
6986     SDValue Denominator = Op.getOperand(2);
6987 
6988     // Note this order is opposite of the machine instruction's operations,
6989     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6990     // intrinsic has the numerator as the first operand to match a normal
6991     // division operation.
6992 
6993     SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator;
6994 
6995     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6996                        Denominator, Numerator);
6997   }
6998   case Intrinsic::amdgcn_icmp: {
6999     // There is a Pat that handles this variant, so return it as-is.
7000     if (Op.getOperand(1).getValueType() == MVT::i1 &&
7001         Op.getConstantOperandVal(2) == 0 &&
7002         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
7003       return Op;
7004     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
7005   }
7006   case Intrinsic::amdgcn_fcmp: {
7007     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
7008   }
7009   case Intrinsic::amdgcn_ballot:
7010     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
7011   case Intrinsic::amdgcn_fmed3:
7012     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
7013                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
7014   case Intrinsic::amdgcn_fdot2:
7015     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
7016                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
7017                        Op.getOperand(4));
7018   case Intrinsic::amdgcn_fmul_legacy:
7019     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
7020                        Op.getOperand(1), Op.getOperand(2));
7021   case Intrinsic::amdgcn_sffbh:
7022     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
7023   case Intrinsic::amdgcn_sbfe:
7024     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
7025                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
7026   case Intrinsic::amdgcn_ubfe:
7027     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
7028                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
7029   case Intrinsic::amdgcn_cvt_pkrtz:
7030   case Intrinsic::amdgcn_cvt_pknorm_i16:
7031   case Intrinsic::amdgcn_cvt_pknorm_u16:
7032   case Intrinsic::amdgcn_cvt_pk_i16:
7033   case Intrinsic::amdgcn_cvt_pk_u16: {
7034     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
7035     EVT VT = Op.getValueType();
7036     unsigned Opcode;
7037 
7038     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
7039       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
7040     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
7041       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
7042     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
7043       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
7044     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
7045       Opcode = AMDGPUISD::CVT_PK_I16_I32;
7046     else
7047       Opcode = AMDGPUISD::CVT_PK_U16_U32;
7048 
7049     if (isTypeLegal(VT))
7050       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
7051 
7052     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
7053                                Op.getOperand(1), Op.getOperand(2));
7054     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
7055   }
7056   case Intrinsic::amdgcn_fmad_ftz:
7057     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
7058                        Op.getOperand(2), Op.getOperand(3));
7059 
7060   case Intrinsic::amdgcn_if_break:
7061     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
7062                                       Op->getOperand(1), Op->getOperand(2)), 0);
7063 
7064   case Intrinsic::amdgcn_groupstaticsize: {
7065     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
7066     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
7067       return Op;
7068 
7069     const Module *M = MF.getFunction().getParent();
7070     const GlobalValue *GV =
7071         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
7072     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
7073                                             SIInstrInfo::MO_ABS32_LO);
7074     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
7075   }
7076   case Intrinsic::amdgcn_is_shared:
7077   case Intrinsic::amdgcn_is_private: {
7078     SDLoc SL(Op);
7079     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
7080       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
7081     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
7082     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
7083                                  Op.getOperand(1));
7084 
7085     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
7086                                 DAG.getConstant(1, SL, MVT::i32));
7087     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
7088   }
7089   case Intrinsic::amdgcn_perm:
7090     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
7091                        Op.getOperand(2), Op.getOperand(3));
7092   case Intrinsic::amdgcn_reloc_constant: {
7093     Module *M = const_cast<Module *>(MF.getFunction().getParent());
7094     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
7095     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
7096     auto RelocSymbol = cast<GlobalVariable>(
7097         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
7098     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
7099                                             SIInstrInfo::MO_ABS32_LO);
7100     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
7101   }
7102   default:
7103     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7104             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7105       return lowerImage(Op, ImageDimIntr, DAG, false);
7106 
7107     return Op;
7108   }
7109 }
7110 
7111 /// Update \p MMO based on the offset inputs to an intrinsic.
7112 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset,
7113                             SDValue SOffset, SDValue Offset,
7114                             SDValue VIndex = SDValue()) {
7115   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
7116       !isa<ConstantSDNode>(Offset)) {
7117     // The combined offset is not known to be constant, so we cannot represent
7118     // it in the MMO. Give up.
7119     MMO->setValue((Value *)nullptr);
7120     return;
7121   }
7122 
7123   if (VIndex && (!isa<ConstantSDNode>(VIndex) ||
7124                  !cast<ConstantSDNode>(VIndex)->isZero())) {
7125     // The strided index component of the address is not known to be zero, so we
7126     // cannot represent it in the MMO. Give up.
7127     MMO->setValue((Value *)nullptr);
7128     return;
7129   }
7130 
7131   MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() +
7132                  cast<ConstantSDNode>(SOffset)->getSExtValue() +
7133                  cast<ConstantSDNode>(Offset)->getSExtValue());
7134 }
7135 
7136 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
7137                                                      SelectionDAG &DAG,
7138                                                      unsigned NewOpcode) const {
7139   SDLoc DL(Op);
7140 
7141   SDValue VData = Op.getOperand(2);
7142   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7143   SDValue Ops[] = {
7144     Op.getOperand(0), // Chain
7145     VData,            // vdata
7146     Op.getOperand(3), // rsrc
7147     DAG.getConstant(0, DL, MVT::i32), // vindex
7148     Offsets.first,    // voffset
7149     Op.getOperand(5), // soffset
7150     Offsets.second,   // offset
7151     Op.getOperand(6), // cachepolicy
7152     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7153   };
7154 
7155   auto *M = cast<MemSDNode>(Op);
7156   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
7157 
7158   EVT MemVT = VData.getValueType();
7159   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7160                                  M->getMemOperand());
7161 }
7162 
7163 // Return a value to use for the idxen operand by examining the vindex operand.
7164 static unsigned getIdxEn(SDValue VIndex) {
7165   if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex))
7166     // No need to set idxen if vindex is known to be zero.
7167     return VIndexC->getZExtValue() != 0;
7168   return 1;
7169 }
7170 
7171 SDValue
7172 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
7173                                                 unsigned NewOpcode) const {
7174   SDLoc DL(Op);
7175 
7176   SDValue VData = Op.getOperand(2);
7177   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7178   SDValue Ops[] = {
7179     Op.getOperand(0), // Chain
7180     VData,            // vdata
7181     Op.getOperand(3), // rsrc
7182     Op.getOperand(4), // vindex
7183     Offsets.first,    // voffset
7184     Op.getOperand(6), // soffset
7185     Offsets.second,   // offset
7186     Op.getOperand(7), // cachepolicy
7187     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7188   };
7189 
7190   auto *M = cast<MemSDNode>(Op);
7191   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7192 
7193   EVT MemVT = VData.getValueType();
7194   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7195                                  M->getMemOperand());
7196 }
7197 
7198 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
7199                                                  SelectionDAG &DAG) const {
7200   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7201   SDLoc DL(Op);
7202 
7203   switch (IntrID) {
7204   case Intrinsic::amdgcn_ds_ordered_add:
7205   case Intrinsic::amdgcn_ds_ordered_swap: {
7206     MemSDNode *M = cast<MemSDNode>(Op);
7207     SDValue Chain = M->getOperand(0);
7208     SDValue M0 = M->getOperand(2);
7209     SDValue Value = M->getOperand(3);
7210     unsigned IndexOperand = M->getConstantOperandVal(7);
7211     unsigned WaveRelease = M->getConstantOperandVal(8);
7212     unsigned WaveDone = M->getConstantOperandVal(9);
7213 
7214     unsigned OrderedCountIndex = IndexOperand & 0x3f;
7215     IndexOperand &= ~0x3f;
7216     unsigned CountDw = 0;
7217 
7218     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
7219       CountDw = (IndexOperand >> 24) & 0xf;
7220       IndexOperand &= ~(0xf << 24);
7221 
7222       if (CountDw < 1 || CountDw > 4) {
7223         report_fatal_error(
7224             "ds_ordered_count: dword count must be between 1 and 4");
7225       }
7226     }
7227 
7228     if (IndexOperand)
7229       report_fatal_error("ds_ordered_count: bad index operand");
7230 
7231     if (WaveDone && !WaveRelease)
7232       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
7233 
7234     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
7235     unsigned ShaderType =
7236         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
7237     unsigned Offset0 = OrderedCountIndex << 2;
7238     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (Instruction << 4);
7239 
7240     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
7241       Offset1 |= (CountDw - 1) << 6;
7242 
7243     if (Subtarget->getGeneration() < AMDGPUSubtarget::GFX11)
7244       Offset1 |= ShaderType << 2;
7245 
7246     unsigned Offset = Offset0 | (Offset1 << 8);
7247 
7248     SDValue Ops[] = {
7249       Chain,
7250       Value,
7251       DAG.getTargetConstant(Offset, DL, MVT::i16),
7252       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
7253     };
7254     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
7255                                    M->getVTList(), Ops, M->getMemoryVT(),
7256                                    M->getMemOperand());
7257   }
7258   case Intrinsic::amdgcn_ds_fadd: {
7259     MemSDNode *M = cast<MemSDNode>(Op);
7260     unsigned Opc;
7261     switch (IntrID) {
7262     case Intrinsic::amdgcn_ds_fadd:
7263       Opc = ISD::ATOMIC_LOAD_FADD;
7264       break;
7265     }
7266 
7267     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
7268                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
7269                          M->getMemOperand());
7270   }
7271   case Intrinsic::amdgcn_atomic_inc:
7272   case Intrinsic::amdgcn_atomic_dec:
7273   case Intrinsic::amdgcn_ds_fmin:
7274   case Intrinsic::amdgcn_ds_fmax: {
7275     MemSDNode *M = cast<MemSDNode>(Op);
7276     unsigned Opc;
7277     switch (IntrID) {
7278     case Intrinsic::amdgcn_atomic_inc:
7279       Opc = AMDGPUISD::ATOMIC_INC;
7280       break;
7281     case Intrinsic::amdgcn_atomic_dec:
7282       Opc = AMDGPUISD::ATOMIC_DEC;
7283       break;
7284     case Intrinsic::amdgcn_ds_fmin:
7285       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
7286       break;
7287     case Intrinsic::amdgcn_ds_fmax:
7288       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
7289       break;
7290     default:
7291       llvm_unreachable("Unknown intrinsic!");
7292     }
7293     SDValue Ops[] = {
7294       M->getOperand(0), // Chain
7295       M->getOperand(2), // Ptr
7296       M->getOperand(3)  // Value
7297     };
7298 
7299     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
7300                                    M->getMemoryVT(), M->getMemOperand());
7301   }
7302   case Intrinsic::amdgcn_buffer_load:
7303   case Intrinsic::amdgcn_buffer_load_format: {
7304     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
7305     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7306     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7307     SDValue Ops[] = {
7308       Op.getOperand(0), // Chain
7309       Op.getOperand(2), // rsrc
7310       Op.getOperand(3), // vindex
7311       SDValue(),        // voffset -- will be set by setBufferOffsets
7312       SDValue(),        // soffset -- will be set by setBufferOffsets
7313       SDValue(),        // offset -- will be set by setBufferOffsets
7314       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7315       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7316     };
7317     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
7318 
7319     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
7320         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
7321 
7322     EVT VT = Op.getValueType();
7323     EVT IntVT = VT.changeTypeToInteger();
7324     auto *M = cast<MemSDNode>(Op);
7325     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7326     EVT LoadVT = Op.getValueType();
7327 
7328     if (LoadVT.getScalarType() == MVT::f16)
7329       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
7330                                  M, DAG, Ops);
7331 
7332     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
7333     if (LoadVT.getScalarType() == MVT::i8 ||
7334         LoadVT.getScalarType() == MVT::i16)
7335       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
7336 
7337     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
7338                                M->getMemOperand(), DAG);
7339   }
7340   case Intrinsic::amdgcn_raw_buffer_load:
7341   case Intrinsic::amdgcn_raw_buffer_load_format: {
7342     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
7343 
7344     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7345     SDValue Ops[] = {
7346       Op.getOperand(0), // Chain
7347       Op.getOperand(2), // rsrc
7348       DAG.getConstant(0, DL, MVT::i32), // vindex
7349       Offsets.first,    // voffset
7350       Op.getOperand(4), // soffset
7351       Offsets.second,   // offset
7352       Op.getOperand(5), // cachepolicy, swizzled buffer
7353       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7354     };
7355 
7356     auto *M = cast<MemSDNode>(Op);
7357     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]);
7358     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
7359   }
7360   case Intrinsic::amdgcn_struct_buffer_load:
7361   case Intrinsic::amdgcn_struct_buffer_load_format: {
7362     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
7363 
7364     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7365     SDValue Ops[] = {
7366       Op.getOperand(0), // Chain
7367       Op.getOperand(2), // rsrc
7368       Op.getOperand(3), // vindex
7369       Offsets.first,    // voffset
7370       Op.getOperand(5), // soffset
7371       Offsets.second,   // offset
7372       Op.getOperand(6), // cachepolicy, swizzled buffer
7373       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7374     };
7375 
7376     auto *M = cast<MemSDNode>(Op);
7377     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7378     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7379   }
7380   case Intrinsic::amdgcn_tbuffer_load: {
7381     MemSDNode *M = cast<MemSDNode>(Op);
7382     EVT LoadVT = Op.getValueType();
7383 
7384     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7385     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7386     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7387     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7388     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7389     SDValue Ops[] = {
7390       Op.getOperand(0),  // Chain
7391       Op.getOperand(2),  // rsrc
7392       Op.getOperand(3),  // vindex
7393       Op.getOperand(4),  // voffset
7394       Op.getOperand(5),  // soffset
7395       Op.getOperand(6),  // offset
7396       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7397       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7398       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7399     };
7400 
7401     if (LoadVT.getScalarType() == MVT::f16)
7402       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7403                                  M, DAG, Ops);
7404     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7405                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7406                                DAG);
7407   }
7408   case Intrinsic::amdgcn_raw_tbuffer_load: {
7409     MemSDNode *M = cast<MemSDNode>(Op);
7410     EVT LoadVT = Op.getValueType();
7411     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7412 
7413     SDValue Ops[] = {
7414       Op.getOperand(0),  // Chain
7415       Op.getOperand(2),  // rsrc
7416       DAG.getConstant(0, DL, MVT::i32), // vindex
7417       Offsets.first,     // voffset
7418       Op.getOperand(4),  // soffset
7419       Offsets.second,    // offset
7420       Op.getOperand(5),  // format
7421       Op.getOperand(6),  // cachepolicy, swizzled buffer
7422       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7423     };
7424 
7425     if (LoadVT.getScalarType() == MVT::f16)
7426       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7427                                  M, DAG, Ops);
7428     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7429                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7430                                DAG);
7431   }
7432   case Intrinsic::amdgcn_struct_tbuffer_load: {
7433     MemSDNode *M = cast<MemSDNode>(Op);
7434     EVT LoadVT = Op.getValueType();
7435     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7436 
7437     SDValue Ops[] = {
7438       Op.getOperand(0),  // Chain
7439       Op.getOperand(2),  // rsrc
7440       Op.getOperand(3),  // vindex
7441       Offsets.first,     // voffset
7442       Op.getOperand(5),  // soffset
7443       Offsets.second,    // offset
7444       Op.getOperand(6),  // format
7445       Op.getOperand(7),  // cachepolicy, swizzled buffer
7446       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7447     };
7448 
7449     if (LoadVT.getScalarType() == MVT::f16)
7450       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7451                                  M, DAG, Ops);
7452     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7453                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7454                                DAG);
7455   }
7456   case Intrinsic::amdgcn_buffer_atomic_swap:
7457   case Intrinsic::amdgcn_buffer_atomic_add:
7458   case Intrinsic::amdgcn_buffer_atomic_sub:
7459   case Intrinsic::amdgcn_buffer_atomic_csub:
7460   case Intrinsic::amdgcn_buffer_atomic_smin:
7461   case Intrinsic::amdgcn_buffer_atomic_umin:
7462   case Intrinsic::amdgcn_buffer_atomic_smax:
7463   case Intrinsic::amdgcn_buffer_atomic_umax:
7464   case Intrinsic::amdgcn_buffer_atomic_and:
7465   case Intrinsic::amdgcn_buffer_atomic_or:
7466   case Intrinsic::amdgcn_buffer_atomic_xor:
7467   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7468     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7469     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7470     SDValue Ops[] = {
7471       Op.getOperand(0), // Chain
7472       Op.getOperand(2), // vdata
7473       Op.getOperand(3), // rsrc
7474       Op.getOperand(4), // vindex
7475       SDValue(),        // voffset -- will be set by setBufferOffsets
7476       SDValue(),        // soffset -- will be set by setBufferOffsets
7477       SDValue(),        // offset -- will be set by setBufferOffsets
7478       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7479       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7480     };
7481     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7482 
7483     EVT VT = Op.getValueType();
7484 
7485     auto *M = cast<MemSDNode>(Op);
7486     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7487     unsigned Opcode = 0;
7488 
7489     switch (IntrID) {
7490     case Intrinsic::amdgcn_buffer_atomic_swap:
7491       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7492       break;
7493     case Intrinsic::amdgcn_buffer_atomic_add:
7494       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7495       break;
7496     case Intrinsic::amdgcn_buffer_atomic_sub:
7497       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7498       break;
7499     case Intrinsic::amdgcn_buffer_atomic_csub:
7500       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7501       break;
7502     case Intrinsic::amdgcn_buffer_atomic_smin:
7503       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7504       break;
7505     case Intrinsic::amdgcn_buffer_atomic_umin:
7506       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7507       break;
7508     case Intrinsic::amdgcn_buffer_atomic_smax:
7509       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7510       break;
7511     case Intrinsic::amdgcn_buffer_atomic_umax:
7512       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7513       break;
7514     case Intrinsic::amdgcn_buffer_atomic_and:
7515       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7516       break;
7517     case Intrinsic::amdgcn_buffer_atomic_or:
7518       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7519       break;
7520     case Intrinsic::amdgcn_buffer_atomic_xor:
7521       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7522       break;
7523     case Intrinsic::amdgcn_buffer_atomic_fadd:
7524       if (!Op.getValue(0).use_empty() && !hasAtomicFaddRtnForTy(Op)) {
7525         DiagnosticInfoUnsupported
7526           NoFpRet(DAG.getMachineFunction().getFunction(),
7527                   "return versions of fp atomics not supported",
7528                   DL.getDebugLoc(), DS_Error);
7529         DAG.getContext()->diagnose(NoFpRet);
7530         return SDValue();
7531       }
7532       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7533       break;
7534     default:
7535       llvm_unreachable("unhandled atomic opcode");
7536     }
7537 
7538     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7539                                    M->getMemOperand());
7540   }
7541   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7542     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7543   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7544     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7545   case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7546     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7547   case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7548     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7549   case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7550     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7551   case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7552     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7553   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7554     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7555   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7556     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7557   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7558     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7559   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7560     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7561   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7562     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7563   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7564     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7565   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7566     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7567   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7568     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7569   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7570     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7571   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7572     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7573   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7574     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7575   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7576     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7577   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7578     return lowerStructBufferAtomicIntrin(Op, DAG,
7579                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7580   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7581     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7582   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7583     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7584   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7585     return lowerStructBufferAtomicIntrin(Op, DAG,
7586                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7587   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7588     return lowerStructBufferAtomicIntrin(Op, DAG,
7589                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7590   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7591     return lowerStructBufferAtomicIntrin(Op, DAG,
7592                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7593   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7594     return lowerStructBufferAtomicIntrin(Op, DAG,
7595                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7596   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7597     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7598   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7599     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7600   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7601     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7602   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7603     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7604   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7605     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7606 
7607   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7608     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7609     unsigned IdxEn = getIdxEn(Op.getOperand(5));
7610     SDValue Ops[] = {
7611       Op.getOperand(0), // Chain
7612       Op.getOperand(2), // src
7613       Op.getOperand(3), // cmp
7614       Op.getOperand(4), // rsrc
7615       Op.getOperand(5), // vindex
7616       SDValue(),        // voffset -- will be set by setBufferOffsets
7617       SDValue(),        // soffset -- will be set by setBufferOffsets
7618       SDValue(),        // offset -- will be set by setBufferOffsets
7619       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7620       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7621     };
7622     setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7623 
7624     EVT VT = Op.getValueType();
7625     auto *M = cast<MemSDNode>(Op);
7626     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7627 
7628     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7629                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7630   }
7631   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7632     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7633     SDValue Ops[] = {
7634       Op.getOperand(0), // Chain
7635       Op.getOperand(2), // src
7636       Op.getOperand(3), // cmp
7637       Op.getOperand(4), // rsrc
7638       DAG.getConstant(0, DL, MVT::i32), // vindex
7639       Offsets.first,    // voffset
7640       Op.getOperand(6), // soffset
7641       Offsets.second,   // offset
7642       Op.getOperand(7), // cachepolicy
7643       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7644     };
7645     EVT VT = Op.getValueType();
7646     auto *M = cast<MemSDNode>(Op);
7647     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]);
7648 
7649     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7650                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7651   }
7652   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7653     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7654     SDValue Ops[] = {
7655       Op.getOperand(0), // Chain
7656       Op.getOperand(2), // src
7657       Op.getOperand(3), // cmp
7658       Op.getOperand(4), // rsrc
7659       Op.getOperand(5), // vindex
7660       Offsets.first,    // voffset
7661       Op.getOperand(7), // soffset
7662       Offsets.second,   // offset
7663       Op.getOperand(8), // cachepolicy
7664       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7665     };
7666     EVT VT = Op.getValueType();
7667     auto *M = cast<MemSDNode>(Op);
7668     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7669 
7670     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7671                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7672   }
7673   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7674     MemSDNode *M = cast<MemSDNode>(Op);
7675     SDValue NodePtr = M->getOperand(2);
7676     SDValue RayExtent = M->getOperand(3);
7677     SDValue RayOrigin = M->getOperand(4);
7678     SDValue RayDir = M->getOperand(5);
7679     SDValue RayInvDir = M->getOperand(6);
7680     SDValue TDescr = M->getOperand(7);
7681 
7682     assert(NodePtr.getValueType() == MVT::i32 ||
7683            NodePtr.getValueType() == MVT::i64);
7684     assert(RayDir.getValueType() == MVT::v3f16 ||
7685            RayDir.getValueType() == MVT::v3f32);
7686 
7687     if (!Subtarget->hasGFX10_AEncoding()) {
7688       emitRemovedIntrinsicError(DAG, DL, Op.getValueType());
7689       return SDValue();
7690     }
7691 
7692     const bool IsGFX11Plus = AMDGPU::isGFX11Plus(*Subtarget);
7693     const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7694     const bool Is64 = NodePtr.getValueType() == MVT::i64;
7695     const unsigned NumVDataDwords = 4;
7696     const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
7697     const unsigned NumVAddrs = IsGFX11Plus ? (IsA16 ? 4 : 5) : NumVAddrDwords;
7698     const bool UseNSA =
7699         Subtarget->hasNSAEncoding() && NumVAddrs <= Subtarget->getNSAMaxSize();
7700     const unsigned BaseOpcodes[2][2] = {
7701         {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
7702         {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
7703          AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
7704     int Opcode;
7705     if (UseNSA) {
7706       Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7707                                      IsGFX11Plus ? AMDGPU::MIMGEncGfx11NSA
7708                                                  : AMDGPU::MIMGEncGfx10NSA,
7709                                      NumVDataDwords, NumVAddrDwords);
7710     } else {
7711       Opcode =
7712           AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7713                                 IsGFX11Plus ? AMDGPU::MIMGEncGfx11Default
7714                                             : AMDGPU::MIMGEncGfx10Default,
7715                                 NumVDataDwords, PowerOf2Ceil(NumVAddrDwords));
7716     }
7717     assert(Opcode != -1);
7718 
7719     SmallVector<SDValue, 16> Ops;
7720 
7721     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7722       SmallVector<SDValue, 3> Lanes;
7723       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7724       if (Lanes[0].getValueSizeInBits() == 32) {
7725         for (unsigned I = 0; I < 3; ++I)
7726           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7727       } else {
7728         if (IsAligned) {
7729           Ops.push_back(
7730             DAG.getBitcast(MVT::i32,
7731                            DAG.getBuildVector(MVT::v2f16, DL,
7732                                               { Lanes[0], Lanes[1] })));
7733           Ops.push_back(Lanes[2]);
7734         } else {
7735           SDValue Elt0 = Ops.pop_back_val();
7736           Ops.push_back(
7737             DAG.getBitcast(MVT::i32,
7738                            DAG.getBuildVector(MVT::v2f16, DL,
7739                                               { Elt0, Lanes[0] })));
7740           Ops.push_back(
7741             DAG.getBitcast(MVT::i32,
7742                            DAG.getBuildVector(MVT::v2f16, DL,
7743                                               { Lanes[1], Lanes[2] })));
7744         }
7745       }
7746     };
7747 
7748     if (UseNSA && IsGFX11Plus) {
7749       Ops.push_back(NodePtr);
7750       Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7751       Ops.push_back(RayOrigin);
7752       if (IsA16) {
7753         SmallVector<SDValue, 3> DirLanes, InvDirLanes, MergedLanes;
7754         DAG.ExtractVectorElements(RayDir, DirLanes, 0, 3);
7755         DAG.ExtractVectorElements(RayInvDir, InvDirLanes, 0, 3);
7756         for (unsigned I = 0; I < 3; ++I) {
7757           MergedLanes.push_back(DAG.getBitcast(
7758               MVT::i32, DAG.getBuildVector(MVT::v2f16, DL,
7759                                            {DirLanes[I], InvDirLanes[I]})));
7760         }
7761         Ops.push_back(DAG.getBuildVector(MVT::v3i32, DL, MergedLanes));
7762       } else {
7763         Ops.push_back(RayDir);
7764         Ops.push_back(RayInvDir);
7765       }
7766     } else {
7767       if (Is64)
7768         DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0,
7769                                   2);
7770       else
7771         Ops.push_back(NodePtr);
7772 
7773       Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7774       packLanes(RayOrigin, true);
7775       packLanes(RayDir, true);
7776       packLanes(RayInvDir, false);
7777     }
7778 
7779     if (!UseNSA) {
7780       // Build a single vector containing all the operands so far prepared.
7781       if (NumVAddrDwords > 8) {
7782         SDValue Undef = DAG.getUNDEF(MVT::i32);
7783         Ops.append(16 - Ops.size(), Undef);
7784       }
7785       assert(Ops.size() == 8 || Ops.size() == 16);
7786       SDValue MergedOps = DAG.getBuildVector(
7787           Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops);
7788       Ops.clear();
7789       Ops.push_back(MergedOps);
7790     }
7791 
7792     Ops.push_back(TDescr);
7793     if (IsA16)
7794       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7795     Ops.push_back(M->getChain());
7796 
7797     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7798     MachineMemOperand *MemRef = M->getMemOperand();
7799     DAG.setNodeMemRefs(NewNode, {MemRef});
7800     return SDValue(NewNode, 0);
7801   }
7802   case Intrinsic::amdgcn_global_atomic_fadd:
7803     if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7804       DiagnosticInfoUnsupported
7805         NoFpRet(DAG.getMachineFunction().getFunction(),
7806                 "return versions of fp atomics not supported",
7807                 DL.getDebugLoc(), DS_Error);
7808       DAG.getContext()->diagnose(NoFpRet);
7809       return SDValue();
7810     }
7811     LLVM_FALLTHROUGH;
7812   case Intrinsic::amdgcn_global_atomic_fmin:
7813   case Intrinsic::amdgcn_global_atomic_fmax:
7814   case Intrinsic::amdgcn_flat_atomic_fadd:
7815   case Intrinsic::amdgcn_flat_atomic_fmin:
7816   case Intrinsic::amdgcn_flat_atomic_fmax: {
7817     MemSDNode *M = cast<MemSDNode>(Op);
7818     SDValue Ops[] = {
7819       M->getOperand(0), // Chain
7820       M->getOperand(2), // Ptr
7821       M->getOperand(3)  // Value
7822     };
7823     unsigned Opcode = 0;
7824     switch (IntrID) {
7825     case Intrinsic::amdgcn_global_atomic_fadd:
7826     case Intrinsic::amdgcn_flat_atomic_fadd: {
7827       EVT VT = Op.getOperand(3).getValueType();
7828       return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7829                            DAG.getVTList(VT, MVT::Other), Ops,
7830                            M->getMemOperand());
7831     }
7832     case Intrinsic::amdgcn_global_atomic_fmin:
7833     case Intrinsic::amdgcn_flat_atomic_fmin: {
7834       Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7835       break;
7836     }
7837     case Intrinsic::amdgcn_global_atomic_fmax:
7838     case Intrinsic::amdgcn_flat_atomic_fmax: {
7839       Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7840       break;
7841     }
7842     default:
7843       llvm_unreachable("unhandled atomic opcode");
7844     }
7845     return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7846                                    M->getVTList(), Ops, M->getMemoryVT(),
7847                                    M->getMemOperand());
7848   }
7849   default:
7850 
7851     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7852             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7853       return lowerImage(Op, ImageDimIntr, DAG, true);
7854 
7855     return SDValue();
7856   }
7857 }
7858 
7859 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7860 // dwordx4 if on SI.
7861 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7862                                               SDVTList VTList,
7863                                               ArrayRef<SDValue> Ops, EVT MemVT,
7864                                               MachineMemOperand *MMO,
7865                                               SelectionDAG &DAG) const {
7866   EVT VT = VTList.VTs[0];
7867   EVT WidenedVT = VT;
7868   EVT WidenedMemVT = MemVT;
7869   if (!Subtarget->hasDwordx3LoadStores() &&
7870       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7871     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7872                                  WidenedVT.getVectorElementType(), 4);
7873     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7874                                     WidenedMemVT.getVectorElementType(), 4);
7875     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7876   }
7877 
7878   assert(VTList.NumVTs == 2);
7879   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7880 
7881   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7882                                        WidenedMemVT, MMO);
7883   if (WidenedVT != VT) {
7884     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7885                                DAG.getVectorIdxConstant(0, DL));
7886     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7887   }
7888   return NewOp;
7889 }
7890 
7891 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7892                                          bool ImageStore) const {
7893   EVT StoreVT = VData.getValueType();
7894 
7895   // No change for f16 and legal vector D16 types.
7896   if (!StoreVT.isVector())
7897     return VData;
7898 
7899   SDLoc DL(VData);
7900   unsigned NumElements = StoreVT.getVectorNumElements();
7901 
7902   if (Subtarget->hasUnpackedD16VMem()) {
7903     // We need to unpack the packed data to store.
7904     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7905     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7906 
7907     EVT EquivStoreVT =
7908         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7909     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7910     return DAG.UnrollVectorOp(ZExt.getNode());
7911   }
7912 
7913   // The sq block of gfx8.1 does not estimate register use correctly for d16
7914   // image store instructions. The data operand is computed as if it were not a
7915   // d16 image instruction.
7916   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7917     // Bitcast to i16
7918     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7919     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7920 
7921     // Decompose into scalars
7922     SmallVector<SDValue, 4> Elts;
7923     DAG.ExtractVectorElements(IntVData, Elts);
7924 
7925     // Group pairs of i16 into v2i16 and bitcast to i32
7926     SmallVector<SDValue, 4> PackedElts;
7927     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7928       SDValue Pair =
7929           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7930       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7931       PackedElts.push_back(IntPair);
7932     }
7933     if ((NumElements % 2) == 1) {
7934       // Handle v3i16
7935       unsigned I = Elts.size() / 2;
7936       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7937                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7938       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7939       PackedElts.push_back(IntPair);
7940     }
7941 
7942     // Pad using UNDEF
7943     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7944 
7945     // Build final vector
7946     EVT VecVT =
7947         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7948     return DAG.getBuildVector(VecVT, DL, PackedElts);
7949   }
7950 
7951   if (NumElements == 3) {
7952     EVT IntStoreVT =
7953         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7954     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7955 
7956     EVT WidenedStoreVT = EVT::getVectorVT(
7957         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7958     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7959                                          WidenedStoreVT.getStoreSizeInBits());
7960     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7961     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7962   }
7963 
7964   assert(isTypeLegal(StoreVT));
7965   return VData;
7966 }
7967 
7968 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7969                                               SelectionDAG &DAG) const {
7970   SDLoc DL(Op);
7971   SDValue Chain = Op.getOperand(0);
7972   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7973   MachineFunction &MF = DAG.getMachineFunction();
7974 
7975   switch (IntrinsicID) {
7976   case Intrinsic::amdgcn_exp_compr: {
7977     if (!Subtarget->hasCompressedExport()) {
7978       DiagnosticInfoUnsupported BadIntrin(
7979           DAG.getMachineFunction().getFunction(),
7980           "intrinsic not supported on subtarget", DL.getDebugLoc());
7981       DAG.getContext()->diagnose(BadIntrin);
7982     }
7983     SDValue Src0 = Op.getOperand(4);
7984     SDValue Src1 = Op.getOperand(5);
7985     // Hack around illegal type on SI by directly selecting it.
7986     if (isTypeLegal(Src0.getValueType()))
7987       return SDValue();
7988 
7989     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7990     SDValue Undef = DAG.getUNDEF(MVT::f32);
7991     const SDValue Ops[] = {
7992       Op.getOperand(2), // tgt
7993       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7994       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7995       Undef, // src2
7996       Undef, // src3
7997       Op.getOperand(7), // vm
7998       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7999       Op.getOperand(3), // en
8000       Op.getOperand(0) // Chain
8001     };
8002 
8003     unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
8004     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
8005   }
8006   case Intrinsic::amdgcn_s_barrier: {
8007     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
8008       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
8009       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
8010       if (WGSize <= ST.getWavefrontSize())
8011         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
8012                                           Op.getOperand(0)), 0);
8013     }
8014     return SDValue();
8015   };
8016   case Intrinsic::amdgcn_tbuffer_store: {
8017     SDValue VData = Op.getOperand(2);
8018     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8019     if (IsD16)
8020       VData = handleD16VData(VData, DAG);
8021     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
8022     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
8023     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
8024     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
8025     unsigned IdxEn = getIdxEn(Op.getOperand(4));
8026     SDValue Ops[] = {
8027       Chain,
8028       VData,             // vdata
8029       Op.getOperand(3),  // rsrc
8030       Op.getOperand(4),  // vindex
8031       Op.getOperand(5),  // voffset
8032       Op.getOperand(6),  // soffset
8033       Op.getOperand(7),  // offset
8034       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
8035       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
8036       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
8037     };
8038     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
8039                            AMDGPUISD::TBUFFER_STORE_FORMAT;
8040     MemSDNode *M = cast<MemSDNode>(Op);
8041     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8042                                    M->getMemoryVT(), M->getMemOperand());
8043   }
8044 
8045   case Intrinsic::amdgcn_struct_tbuffer_store: {
8046     SDValue VData = Op.getOperand(2);
8047     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8048     if (IsD16)
8049       VData = handleD16VData(VData, DAG);
8050     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
8051     SDValue Ops[] = {
8052       Chain,
8053       VData,             // vdata
8054       Op.getOperand(3),  // rsrc
8055       Op.getOperand(4),  // vindex
8056       Offsets.first,     // voffset
8057       Op.getOperand(6),  // soffset
8058       Offsets.second,    // offset
8059       Op.getOperand(7),  // format
8060       Op.getOperand(8),  // cachepolicy, swizzled buffer
8061       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8062     };
8063     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
8064                            AMDGPUISD::TBUFFER_STORE_FORMAT;
8065     MemSDNode *M = cast<MemSDNode>(Op);
8066     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8067                                    M->getMemoryVT(), M->getMemOperand());
8068   }
8069 
8070   case Intrinsic::amdgcn_raw_tbuffer_store: {
8071     SDValue VData = Op.getOperand(2);
8072     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8073     if (IsD16)
8074       VData = handleD16VData(VData, DAG);
8075     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
8076     SDValue Ops[] = {
8077       Chain,
8078       VData,             // vdata
8079       Op.getOperand(3),  // rsrc
8080       DAG.getConstant(0, DL, MVT::i32), // vindex
8081       Offsets.first,     // voffset
8082       Op.getOperand(5),  // soffset
8083       Offsets.second,    // offset
8084       Op.getOperand(6),  // format
8085       Op.getOperand(7),  // cachepolicy, swizzled buffer
8086       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8087     };
8088     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
8089                            AMDGPUISD::TBUFFER_STORE_FORMAT;
8090     MemSDNode *M = cast<MemSDNode>(Op);
8091     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8092                                    M->getMemoryVT(), M->getMemOperand());
8093   }
8094 
8095   case Intrinsic::amdgcn_buffer_store:
8096   case Intrinsic::amdgcn_buffer_store_format: {
8097     SDValue VData = Op.getOperand(2);
8098     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8099     if (IsD16)
8100       VData = handleD16VData(VData, DAG);
8101     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
8102     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
8103     unsigned IdxEn = getIdxEn(Op.getOperand(4));
8104     SDValue Ops[] = {
8105       Chain,
8106       VData,
8107       Op.getOperand(3), // rsrc
8108       Op.getOperand(4), // vindex
8109       SDValue(), // voffset -- will be set by setBufferOffsets
8110       SDValue(), // soffset -- will be set by setBufferOffsets
8111       SDValue(), // offset -- will be set by setBufferOffsets
8112       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
8113       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
8114     };
8115     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
8116 
8117     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
8118                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8119     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8120     MemSDNode *M = cast<MemSDNode>(Op);
8121     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8122 
8123     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8124     EVT VDataType = VData.getValueType().getScalarType();
8125     if (VDataType == MVT::i8 || VDataType == MVT::i16)
8126       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8127 
8128     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8129                                    M->getMemoryVT(), M->getMemOperand());
8130   }
8131 
8132   case Intrinsic::amdgcn_raw_buffer_store:
8133   case Intrinsic::amdgcn_raw_buffer_store_format: {
8134     const bool IsFormat =
8135         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
8136 
8137     SDValue VData = Op.getOperand(2);
8138     EVT VDataVT = VData.getValueType();
8139     EVT EltType = VDataVT.getScalarType();
8140     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8141     if (IsD16) {
8142       VData = handleD16VData(VData, DAG);
8143       VDataVT = VData.getValueType();
8144     }
8145 
8146     if (!isTypeLegal(VDataVT)) {
8147       VData =
8148           DAG.getNode(ISD::BITCAST, DL,
8149                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8150     }
8151 
8152     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
8153     SDValue Ops[] = {
8154       Chain,
8155       VData,
8156       Op.getOperand(3), // rsrc
8157       DAG.getConstant(0, DL, MVT::i32), // vindex
8158       Offsets.first,    // voffset
8159       Op.getOperand(5), // soffset
8160       Offsets.second,   // offset
8161       Op.getOperand(6), // cachepolicy, swizzled buffer
8162       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8163     };
8164     unsigned Opc =
8165         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
8166     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8167     MemSDNode *M = cast<MemSDNode>(Op);
8168     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
8169 
8170     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8171     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8172       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
8173 
8174     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8175                                    M->getMemoryVT(), M->getMemOperand());
8176   }
8177 
8178   case Intrinsic::amdgcn_struct_buffer_store:
8179   case Intrinsic::amdgcn_struct_buffer_store_format: {
8180     const bool IsFormat =
8181         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
8182 
8183     SDValue VData = Op.getOperand(2);
8184     EVT VDataVT = VData.getValueType();
8185     EVT EltType = VDataVT.getScalarType();
8186     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8187 
8188     if (IsD16) {
8189       VData = handleD16VData(VData, DAG);
8190       VDataVT = VData.getValueType();
8191     }
8192 
8193     if (!isTypeLegal(VDataVT)) {
8194       VData =
8195           DAG.getNode(ISD::BITCAST, DL,
8196                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8197     }
8198 
8199     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
8200     SDValue Ops[] = {
8201       Chain,
8202       VData,
8203       Op.getOperand(3), // rsrc
8204       Op.getOperand(4), // vindex
8205       Offsets.first,    // voffset
8206       Op.getOperand(6), // soffset
8207       Offsets.second,   // offset
8208       Op.getOperand(7), // cachepolicy, swizzled buffer
8209       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8210     };
8211     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
8212                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8213     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8214     MemSDNode *M = cast<MemSDNode>(Op);
8215     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8216 
8217     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8218     EVT VDataType = VData.getValueType().getScalarType();
8219     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8220       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8221 
8222     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8223                                    M->getMemoryVT(), M->getMemOperand());
8224   }
8225   case Intrinsic::amdgcn_raw_buffer_load_lds:
8226   case Intrinsic::amdgcn_struct_buffer_load_lds: {
8227     unsigned Opc;
8228     bool HasVIndex = IntrinsicID == Intrinsic::amdgcn_struct_buffer_load_lds;
8229     unsigned OpOffset = HasVIndex ? 1 : 0;
8230     SDValue VOffset = Op.getOperand(5 + OpOffset);
8231     auto CVOffset = dyn_cast<ConstantSDNode>(VOffset);
8232     bool HasVOffset = !CVOffset || !CVOffset->isZero();
8233     unsigned Size = Op->getConstantOperandVal(4);
8234 
8235     switch (Size) {
8236     default:
8237       return SDValue();
8238     case 1:
8239       Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_BOTHEN
8240                                    : AMDGPU::BUFFER_LOAD_UBYTE_LDS_IDXEN
8241                       : HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFEN
8242                                    : AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFSET;
8243       break;
8244     case 2:
8245       Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_BOTHEN
8246                                    : AMDGPU::BUFFER_LOAD_USHORT_LDS_IDXEN
8247                       : HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFEN
8248                                    : AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFSET;
8249       break;
8250     case 4:
8251       Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_BOTHEN
8252                                    : AMDGPU::BUFFER_LOAD_DWORD_LDS_IDXEN
8253                       : HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFEN
8254                                    : AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFSET;
8255       break;
8256     }
8257 
8258     SDValue M0Val = copyToM0(DAG, Chain, DL, Op.getOperand(3));
8259 
8260     SmallVector<SDValue, 8> Ops;
8261 
8262     if (HasVIndex && HasVOffset)
8263       Ops.push_back(DAG.getBuildVector(MVT::v2i32, DL,
8264                                        { Op.getOperand(5), // VIndex
8265                                          VOffset }));
8266     else if (HasVIndex)
8267       Ops.push_back(Op.getOperand(5));
8268     else if (HasVOffset)
8269       Ops.push_back(VOffset);
8270 
8271     Ops.push_back(Op.getOperand(2));           // rsrc
8272     Ops.push_back(Op.getOperand(6 + OpOffset)); // soffset
8273     Ops.push_back(Op.getOperand(7 + OpOffset)); // imm offset
8274     unsigned Aux = Op.getConstantOperandVal(8 + OpOffset);
8275     Ops.push_back(
8276       DAG.getTargetConstant(Aux & AMDGPU::CPol::ALL, DL, MVT::i8)); // cpol
8277     Ops.push_back(
8278       DAG.getTargetConstant((Aux >> 3) & 1, DL, MVT::i8));          // swz
8279     Ops.push_back(M0Val.getValue(0)); // Chain
8280     Ops.push_back(M0Val.getValue(1)); // Glue
8281 
8282     auto *M = cast<MemSDNode>(Op);
8283     MachineMemOperand *LoadMMO = M->getMemOperand();
8284     MachinePointerInfo LoadPtrI = LoadMMO->getPointerInfo();
8285     LoadPtrI.Offset = Op->getConstantOperandVal(7 + OpOffset);
8286     MachinePointerInfo StorePtrI = LoadPtrI;
8287     StorePtrI.V = nullptr;
8288     StorePtrI.AddrSpace = AMDGPUAS::LOCAL_ADDRESS;
8289 
8290     auto F = LoadMMO->getFlags() &
8291              ~(MachineMemOperand::MOStore | MachineMemOperand::MOLoad);
8292     LoadMMO = MF.getMachineMemOperand(LoadPtrI, F | MachineMemOperand::MOLoad,
8293                                       Size, LoadMMO->getBaseAlign());
8294 
8295     MachineMemOperand *StoreMMO =
8296         MF.getMachineMemOperand(StorePtrI, F | MachineMemOperand::MOStore,
8297                                 sizeof(int32_t), LoadMMO->getBaseAlign());
8298 
8299     auto Load = DAG.getMachineNode(Opc, DL, M->getVTList(), Ops);
8300     DAG.setNodeMemRefs(Load, {LoadMMO, StoreMMO});
8301 
8302     return SDValue(Load, 0);
8303   }
8304   case Intrinsic::amdgcn_global_load_lds: {
8305     unsigned Opc;
8306     unsigned Size = Op->getConstantOperandVal(4);
8307     switch (Size) {
8308     default:
8309       return SDValue();
8310     case 1:
8311       Opc = AMDGPU::GLOBAL_LOAD_LDS_UBYTE;
8312       break;
8313     case 2:
8314       Opc = AMDGPU::GLOBAL_LOAD_LDS_USHORT;
8315       break;
8316     case 4:
8317       Opc = AMDGPU::GLOBAL_LOAD_LDS_DWORD;
8318       break;
8319     }
8320 
8321     auto *M = cast<MemSDNode>(Op);
8322     SDValue M0Val = copyToM0(DAG, Chain, DL, Op.getOperand(3));
8323 
8324     SmallVector<SDValue, 6> Ops;
8325 
8326     SDValue Addr = Op.getOperand(2); // Global ptr
8327     SDValue VOffset;
8328     // Try to split SAddr and VOffset. Global and LDS pointers share the same
8329     // immediate offset, so we cannot use a regular SelectGlobalSAddr().
8330     if (Addr->isDivergent() && Addr.getOpcode() == ISD::ADD) {
8331       SDValue LHS = Addr.getOperand(0);
8332       SDValue RHS = Addr.getOperand(1);
8333 
8334       if (LHS->isDivergent())
8335         std::swap(LHS, RHS);
8336 
8337       if (!LHS->isDivergent() && RHS.getOpcode() == ISD::ZERO_EXTEND &&
8338           RHS.getOperand(0).getValueType() == MVT::i32) {
8339         // add (i64 sgpr), (zero_extend (i32 vgpr))
8340         Addr = LHS;
8341         VOffset = RHS.getOperand(0);
8342       }
8343     }
8344 
8345     Ops.push_back(Addr);
8346     if (!Addr->isDivergent()) {
8347       Opc = AMDGPU::getGlobalSaddrOp(Opc);
8348       if (!VOffset)
8349         VOffset = SDValue(
8350             DAG.getMachineNode(AMDGPU::V_MOV_B32_e32, DL, MVT::i32,
8351                                DAG.getTargetConstant(0, DL, MVT::i32)), 0);
8352       Ops.push_back(VOffset);
8353     }
8354 
8355     Ops.push_back(Op.getOperand(5));  // Offset
8356     Ops.push_back(Op.getOperand(6));  // CPol
8357     Ops.push_back(M0Val.getValue(0)); // Chain
8358     Ops.push_back(M0Val.getValue(1)); // Glue
8359 
8360     MachineMemOperand *LoadMMO = M->getMemOperand();
8361     MachinePointerInfo LoadPtrI = LoadMMO->getPointerInfo();
8362     LoadPtrI.Offset = Op->getConstantOperandVal(5);
8363     MachinePointerInfo StorePtrI = LoadPtrI;
8364     LoadPtrI.AddrSpace = AMDGPUAS::GLOBAL_ADDRESS;
8365     StorePtrI.AddrSpace = AMDGPUAS::LOCAL_ADDRESS;
8366     auto F = LoadMMO->getFlags() &
8367              ~(MachineMemOperand::MOStore | MachineMemOperand::MOLoad);
8368     LoadMMO = MF.getMachineMemOperand(LoadPtrI, F | MachineMemOperand::MOLoad,
8369                                       Size, LoadMMO->getBaseAlign());
8370     MachineMemOperand *StoreMMO =
8371         MF.getMachineMemOperand(StorePtrI, F | MachineMemOperand::MOStore,
8372                                 sizeof(int32_t), Align(4));
8373 
8374     auto Load = DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops);
8375     DAG.setNodeMemRefs(Load, {LoadMMO, StoreMMO});
8376 
8377     return SDValue(Load, 0);
8378   }
8379   case Intrinsic::amdgcn_end_cf:
8380     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
8381                                       Op->getOperand(2), Chain), 0);
8382 
8383   default: {
8384     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
8385             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
8386       return lowerImage(Op, ImageDimIntr, DAG, true);
8387 
8388     return Op;
8389   }
8390   }
8391 }
8392 
8393 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
8394 // offset (the offset that is included in bounds checking and swizzling, to be
8395 // split between the instruction's voffset and immoffset fields) and soffset
8396 // (the offset that is excluded from bounds checking and swizzling, to go in
8397 // the instruction's soffset field).  This function takes the first kind of
8398 // offset and figures out how to split it between voffset and immoffset.
8399 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
8400     SDValue Offset, SelectionDAG &DAG) const {
8401   SDLoc DL(Offset);
8402   const unsigned MaxImm = 4095;
8403   SDValue N0 = Offset;
8404   ConstantSDNode *C1 = nullptr;
8405 
8406   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
8407     N0 = SDValue();
8408   else if (DAG.isBaseWithConstantOffset(N0)) {
8409     C1 = cast<ConstantSDNode>(N0.getOperand(1));
8410     N0 = N0.getOperand(0);
8411   }
8412 
8413   if (C1) {
8414     unsigned ImmOffset = C1->getZExtValue();
8415     // If the immediate value is too big for the immoffset field, put the value
8416     // and -4096 into the immoffset field so that the value that is copied/added
8417     // for the voffset field is a multiple of 4096, and it stands more chance
8418     // of being CSEd with the copy/add for another similar load/store.
8419     // However, do not do that rounding down to a multiple of 4096 if that is a
8420     // negative number, as it appears to be illegal to have a negative offset
8421     // in the vgpr, even if adding the immediate offset makes it positive.
8422     unsigned Overflow = ImmOffset & ~MaxImm;
8423     ImmOffset -= Overflow;
8424     if ((int32_t)Overflow < 0) {
8425       Overflow += ImmOffset;
8426       ImmOffset = 0;
8427     }
8428     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
8429     if (Overflow) {
8430       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
8431       if (!N0)
8432         N0 = OverflowVal;
8433       else {
8434         SDValue Ops[] = { N0, OverflowVal };
8435         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
8436       }
8437     }
8438   }
8439   if (!N0)
8440     N0 = DAG.getConstant(0, DL, MVT::i32);
8441   if (!C1)
8442     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
8443   return {N0, SDValue(C1, 0)};
8444 }
8445 
8446 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
8447 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
8448 // pointed to by Offsets.
8449 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
8450                                         SelectionDAG &DAG, SDValue *Offsets,
8451                                         Align Alignment) const {
8452   SDLoc DL(CombinedOffset);
8453   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
8454     uint32_t Imm = C->getZExtValue();
8455     uint32_t SOffset, ImmOffset;
8456     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
8457                                  Alignment)) {
8458       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
8459       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8460       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8461       return;
8462     }
8463   }
8464   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
8465     SDValue N0 = CombinedOffset.getOperand(0);
8466     SDValue N1 = CombinedOffset.getOperand(1);
8467     uint32_t SOffset, ImmOffset;
8468     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
8469     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
8470                                                 Subtarget, Alignment)) {
8471       Offsets[0] = N0;
8472       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8473       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8474       return;
8475     }
8476   }
8477   Offsets[0] = CombinedOffset;
8478   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
8479   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
8480 }
8481 
8482 // Handle 8 bit and 16 bit buffer loads
8483 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
8484                                                      EVT LoadVT, SDLoc DL,
8485                                                      ArrayRef<SDValue> Ops,
8486                                                      MemSDNode *M) const {
8487   EVT IntVT = LoadVT.changeTypeToInteger();
8488   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
8489          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
8490 
8491   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
8492   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
8493                                                Ops, IntVT,
8494                                                M->getMemOperand());
8495   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
8496   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
8497 
8498   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
8499 }
8500 
8501 // Handle 8 bit and 16 bit buffer stores
8502 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
8503                                                       EVT VDataType, SDLoc DL,
8504                                                       SDValue Ops[],
8505                                                       MemSDNode *M) const {
8506   if (VDataType == MVT::f16)
8507     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
8508 
8509   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
8510   Ops[1] = BufferStoreExt;
8511   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
8512                                  AMDGPUISD::BUFFER_STORE_SHORT;
8513   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
8514   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
8515                                      M->getMemOperand());
8516 }
8517 
8518 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
8519                                  ISD::LoadExtType ExtType, SDValue Op,
8520                                  const SDLoc &SL, EVT VT) {
8521   if (VT.bitsLT(Op.getValueType()))
8522     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
8523 
8524   switch (ExtType) {
8525   case ISD::SEXTLOAD:
8526     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
8527   case ISD::ZEXTLOAD:
8528     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
8529   case ISD::EXTLOAD:
8530     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
8531   case ISD::NON_EXTLOAD:
8532     return Op;
8533   }
8534 
8535   llvm_unreachable("invalid ext type");
8536 }
8537 
8538 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
8539   SelectionDAG &DAG = DCI.DAG;
8540   if (Ld->getAlign() < Align(4) || Ld->isDivergent())
8541     return SDValue();
8542 
8543   // FIXME: Constant loads should all be marked invariant.
8544   unsigned AS = Ld->getAddressSpace();
8545   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
8546       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
8547       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
8548     return SDValue();
8549 
8550   // Don't do this early, since it may interfere with adjacent load merging for
8551   // illegal types. We can avoid losing alignment information for exotic types
8552   // pre-legalize.
8553   EVT MemVT = Ld->getMemoryVT();
8554   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
8555       MemVT.getSizeInBits() >= 32)
8556     return SDValue();
8557 
8558   SDLoc SL(Ld);
8559 
8560   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
8561          "unexpected vector extload");
8562 
8563   // TODO: Drop only high part of range.
8564   SDValue Ptr = Ld->getBasePtr();
8565   SDValue NewLoad = DAG.getLoad(
8566       ISD::UNINDEXED, ISD::NON_EXTLOAD, MVT::i32, SL, Ld->getChain(), Ptr,
8567       Ld->getOffset(), Ld->getPointerInfo(), MVT::i32, Ld->getAlign(),
8568       Ld->getMemOperand()->getFlags(), Ld->getAAInfo(),
8569       nullptr); // Drop ranges
8570 
8571   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
8572   if (MemVT.isFloatingPoint()) {
8573     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
8574            "unexpected fp extload");
8575     TruncVT = MemVT.changeTypeToInteger();
8576   }
8577 
8578   SDValue Cvt = NewLoad;
8579   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
8580     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
8581                       DAG.getValueType(TruncVT));
8582   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
8583              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
8584     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
8585   } else {
8586     assert(Ld->getExtensionType() == ISD::EXTLOAD);
8587   }
8588 
8589   EVT VT = Ld->getValueType(0);
8590   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8591 
8592   DCI.AddToWorklist(Cvt.getNode());
8593 
8594   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
8595   // the appropriate extension from the 32-bit load.
8596   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
8597   DCI.AddToWorklist(Cvt.getNode());
8598 
8599   // Handle conversion back to floating point if necessary.
8600   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8601 
8602   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8603 }
8604 
8605 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8606   SDLoc DL(Op);
8607   LoadSDNode *Load = cast<LoadSDNode>(Op);
8608   ISD::LoadExtType ExtType = Load->getExtensionType();
8609   EVT MemVT = Load->getMemoryVT();
8610 
8611   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8612     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8613       return SDValue();
8614 
8615     // FIXME: Copied from PPC
8616     // First, load into 32 bits, then truncate to 1 bit.
8617 
8618     SDValue Chain = Load->getChain();
8619     SDValue BasePtr = Load->getBasePtr();
8620     MachineMemOperand *MMO = Load->getMemOperand();
8621 
8622     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8623 
8624     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8625                                    BasePtr, RealMemVT, MMO);
8626 
8627     if (!MemVT.isVector()) {
8628       SDValue Ops[] = {
8629         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8630         NewLD.getValue(1)
8631       };
8632 
8633       return DAG.getMergeValues(Ops, DL);
8634     }
8635 
8636     SmallVector<SDValue, 3> Elts;
8637     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8638       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8639                                 DAG.getConstant(I, DL, MVT::i32));
8640 
8641       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8642     }
8643 
8644     SDValue Ops[] = {
8645       DAG.getBuildVector(MemVT, DL, Elts),
8646       NewLD.getValue(1)
8647     };
8648 
8649     return DAG.getMergeValues(Ops, DL);
8650   }
8651 
8652   if (!MemVT.isVector())
8653     return SDValue();
8654 
8655   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8656          "Custom lowering for non-i32 vectors hasn't been implemented.");
8657 
8658   Align Alignment = Load->getAlign();
8659   unsigned AS = Load->getAddressSpace();
8660   if (Subtarget->hasLDSMisalignedBug() && AS == AMDGPUAS::FLAT_ADDRESS &&
8661       Alignment.value() < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8662     return SplitVectorLoad(Op, DAG);
8663   }
8664 
8665   MachineFunction &MF = DAG.getMachineFunction();
8666   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8667   // If there is a possibility that flat instruction access scratch memory
8668   // then we need to use the same legalization rules we use for private.
8669   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8670       !Subtarget->hasMultiDwordFlatScratchAddressing())
8671     AS = MFI->hasFlatScratchInit() ?
8672          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8673 
8674   unsigned NumElements = MemVT.getVectorNumElements();
8675 
8676   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8677       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8678     if (!Op->isDivergent() && Alignment >= Align(4) && NumElements < 32) {
8679       if (MemVT.isPow2VectorType())
8680         return SDValue();
8681       return WidenOrSplitVectorLoad(Op, DAG);
8682     }
8683     // Non-uniform loads will be selected to MUBUF instructions, so they
8684     // have the same legalization requirements as global and private
8685     // loads.
8686     //
8687   }
8688 
8689   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8690       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8691       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8692     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8693         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8694         Alignment >= Align(4) && NumElements < 32) {
8695       if (MemVT.isPow2VectorType())
8696         return SDValue();
8697       return WidenOrSplitVectorLoad(Op, DAG);
8698     }
8699     // Non-uniform loads will be selected to MUBUF instructions, so they
8700     // have the same legalization requirements as global and private
8701     // loads.
8702     //
8703   }
8704   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8705       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8706       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8707       AS == AMDGPUAS::FLAT_ADDRESS) {
8708     if (NumElements > 4)
8709       return SplitVectorLoad(Op, DAG);
8710     // v3 loads not supported on SI.
8711     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8712       return WidenOrSplitVectorLoad(Op, DAG);
8713 
8714     // v3 and v4 loads are supported for private and global memory.
8715     return SDValue();
8716   }
8717   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8718     // Depending on the setting of the private_element_size field in the
8719     // resource descriptor, we can only make private accesses up to a certain
8720     // size.
8721     switch (Subtarget->getMaxPrivateElementSize()) {
8722     case 4: {
8723       SDValue Ops[2];
8724       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8725       return DAG.getMergeValues(Ops, DL);
8726     }
8727     case 8:
8728       if (NumElements > 2)
8729         return SplitVectorLoad(Op, DAG);
8730       return SDValue();
8731     case 16:
8732       // Same as global/flat
8733       if (NumElements > 4)
8734         return SplitVectorLoad(Op, DAG);
8735       // v3 loads not supported on SI.
8736       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8737         return WidenOrSplitVectorLoad(Op, DAG);
8738 
8739       return SDValue();
8740     default:
8741       llvm_unreachable("unsupported private_element_size");
8742     }
8743   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8744     bool Fast = false;
8745     auto Flags = Load->getMemOperand()->getFlags();
8746     if (allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8747                                            Load->getAlign(), Flags, &Fast) &&
8748         Fast)
8749       return SDValue();
8750 
8751     if (MemVT.isVector())
8752       return SplitVectorLoad(Op, DAG);
8753   }
8754 
8755   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8756                                       MemVT, *Load->getMemOperand())) {
8757     SDValue Ops[2];
8758     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8759     return DAG.getMergeValues(Ops, DL);
8760   }
8761 
8762   return SDValue();
8763 }
8764 
8765 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8766   EVT VT = Op.getValueType();
8767   if (VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
8768     return splitTernaryVectorOp(Op, DAG);
8769 
8770   assert(VT.getSizeInBits() == 64);
8771 
8772   SDLoc DL(Op);
8773   SDValue Cond = Op.getOperand(0);
8774 
8775   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8776   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8777 
8778   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8779   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8780 
8781   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8782   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8783 
8784   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8785 
8786   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8787   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8788 
8789   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8790 
8791   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8792   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8793 }
8794 
8795 // Catch division cases where we can use shortcuts with rcp and rsq
8796 // instructions.
8797 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8798                                               SelectionDAG &DAG) const {
8799   SDLoc SL(Op);
8800   SDValue LHS = Op.getOperand(0);
8801   SDValue RHS = Op.getOperand(1);
8802   EVT VT = Op.getValueType();
8803   const SDNodeFlags Flags = Op->getFlags();
8804 
8805   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8806 
8807   // Without !fpmath accuracy information, we can't do more because we don't
8808   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8809   if (!AllowInaccurateRcp)
8810     return SDValue();
8811 
8812   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8813     if (CLHS->isExactlyValue(1.0)) {
8814       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8815       // the CI documentation has a worst case error of 1 ulp.
8816       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8817       // use it as long as we aren't trying to use denormals.
8818       //
8819       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8820 
8821       // 1.0 / sqrt(x) -> rsq(x)
8822 
8823       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8824       // error seems really high at 2^29 ULP.
8825       if (RHS.getOpcode() == ISD::FSQRT)
8826         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8827 
8828       // 1.0 / x -> rcp(x)
8829       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8830     }
8831 
8832     // Same as for 1.0, but expand the sign out of the constant.
8833     if (CLHS->isExactlyValue(-1.0)) {
8834       // -1.0 / x -> rcp (fneg x)
8835       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8836       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8837     }
8838   }
8839 
8840   // Turn into multiply by the reciprocal.
8841   // x / y -> x * (1.0 / y)
8842   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8843   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8844 }
8845 
8846 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8847                                                 SelectionDAG &DAG) const {
8848   SDLoc SL(Op);
8849   SDValue X = Op.getOperand(0);
8850   SDValue Y = Op.getOperand(1);
8851   EVT VT = Op.getValueType();
8852   const SDNodeFlags Flags = Op->getFlags();
8853 
8854   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8855                             DAG.getTarget().Options.UnsafeFPMath;
8856   if (!AllowInaccurateDiv)
8857     return SDValue();
8858 
8859   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8860   SDValue One = DAG.getConstantFP(1.0, SL, VT);
8861 
8862   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8863   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8864 
8865   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8866   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8867   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8868   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8869   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8870   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8871 }
8872 
8873 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8874                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8875                           SDNodeFlags Flags) {
8876   if (GlueChain->getNumValues() <= 1) {
8877     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8878   }
8879 
8880   assert(GlueChain->getNumValues() == 3);
8881 
8882   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8883   switch (Opcode) {
8884   default: llvm_unreachable("no chain equivalent for opcode");
8885   case ISD::FMUL:
8886     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8887     break;
8888   }
8889 
8890   return DAG.getNode(Opcode, SL, VTList,
8891                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8892                      Flags);
8893 }
8894 
8895 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8896                            EVT VT, SDValue A, SDValue B, SDValue C,
8897                            SDValue GlueChain, SDNodeFlags Flags) {
8898   if (GlueChain->getNumValues() <= 1) {
8899     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8900   }
8901 
8902   assert(GlueChain->getNumValues() == 3);
8903 
8904   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8905   switch (Opcode) {
8906   default: llvm_unreachable("no chain equivalent for opcode");
8907   case ISD::FMA:
8908     Opcode = AMDGPUISD::FMA_W_CHAIN;
8909     break;
8910   }
8911 
8912   return DAG.getNode(Opcode, SL, VTList,
8913                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8914                      Flags);
8915 }
8916 
8917 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8918   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8919     return FastLowered;
8920 
8921   SDLoc SL(Op);
8922   SDValue Src0 = Op.getOperand(0);
8923   SDValue Src1 = Op.getOperand(1);
8924 
8925   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8926   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8927 
8928   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8929   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8930 
8931   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8932   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8933 
8934   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8935 }
8936 
8937 // Faster 2.5 ULP division that does not support denormals.
8938 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8939   SDLoc SL(Op);
8940   SDValue LHS = Op.getOperand(1);
8941   SDValue RHS = Op.getOperand(2);
8942 
8943   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8944 
8945   const APFloat K0Val(BitsToFloat(0x6f800000));
8946   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8947 
8948   const APFloat K1Val(BitsToFloat(0x2f800000));
8949   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8950 
8951   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8952 
8953   EVT SetCCVT =
8954     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8955 
8956   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8957 
8958   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8959 
8960   // TODO: Should this propagate fast-math-flags?
8961   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8962 
8963   // rcp does not support denormals.
8964   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8965 
8966   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8967 
8968   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8969 }
8970 
8971 // Returns immediate value for setting the F32 denorm mode when using the
8972 // S_DENORM_MODE instruction.
8973 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8974                                     const SDLoc &SL, const GCNSubtarget *ST) {
8975   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8976   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8977                                 ? FP_DENORM_FLUSH_NONE
8978                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8979 
8980   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8981   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8982 }
8983 
8984 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8985   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8986     return FastLowered;
8987 
8988   // The selection matcher assumes anything with a chain selecting to a
8989   // mayRaiseFPException machine instruction. Since we're introducing a chain
8990   // here, we need to explicitly report nofpexcept for the regular fdiv
8991   // lowering.
8992   SDNodeFlags Flags = Op->getFlags();
8993   Flags.setNoFPExcept(true);
8994 
8995   SDLoc SL(Op);
8996   SDValue LHS = Op.getOperand(0);
8997   SDValue RHS = Op.getOperand(1);
8998 
8999   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
9000 
9001   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
9002 
9003   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
9004                                           {RHS, RHS, LHS}, Flags);
9005   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
9006                                         {LHS, RHS, LHS}, Flags);
9007 
9008   // Denominator is scaled to not be denormal, so using rcp is ok.
9009   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
9010                                   DenominatorScaled, Flags);
9011   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
9012                                      DenominatorScaled, Flags);
9013 
9014   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
9015                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
9016                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
9017   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
9018 
9019   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
9020 
9021   if (!HasFP32Denormals) {
9022     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
9023     // lowering. The chain dependence is insufficient, and we need glue. We do
9024     // not need the glue variants in a strictfp function.
9025 
9026     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
9027 
9028     SDNode *EnableDenorm;
9029     if (Subtarget->hasDenormModeInst()) {
9030       const SDValue EnableDenormValue =
9031           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
9032 
9033       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
9034                                  DAG.getEntryNode(), EnableDenormValue).getNode();
9035     } else {
9036       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
9037                                                         SL, MVT::i32);
9038       EnableDenorm =
9039           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
9040                              {EnableDenormValue, BitField, DAG.getEntryNode()});
9041     }
9042 
9043     SDValue Ops[3] = {
9044       NegDivScale0,
9045       SDValue(EnableDenorm, 0),
9046       SDValue(EnableDenorm, 1)
9047     };
9048 
9049     NegDivScale0 = DAG.getMergeValues(Ops, SL);
9050   }
9051 
9052   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
9053                              ApproxRcp, One, NegDivScale0, Flags);
9054 
9055   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
9056                              ApproxRcp, Fma0, Flags);
9057 
9058   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
9059                            Fma1, Fma1, Flags);
9060 
9061   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
9062                              NumeratorScaled, Mul, Flags);
9063 
9064   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
9065                              Fma2, Fma1, Mul, Fma2, Flags);
9066 
9067   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
9068                              NumeratorScaled, Fma3, Flags);
9069 
9070   if (!HasFP32Denormals) {
9071     SDNode *DisableDenorm;
9072     if (Subtarget->hasDenormModeInst()) {
9073       const SDValue DisableDenormValue =
9074           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
9075 
9076       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
9077                                   Fma4.getValue(1), DisableDenormValue,
9078                                   Fma4.getValue(2)).getNode();
9079     } else {
9080       const SDValue DisableDenormValue =
9081           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
9082 
9083       DisableDenorm = DAG.getMachineNode(
9084           AMDGPU::S_SETREG_B32, SL, MVT::Other,
9085           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
9086     }
9087 
9088     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
9089                                       SDValue(DisableDenorm, 0), DAG.getRoot());
9090     DAG.setRoot(OutputChain);
9091   }
9092 
9093   SDValue Scale = NumeratorScaled.getValue(1);
9094   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
9095                              {Fma4, Fma1, Fma3, Scale}, Flags);
9096 
9097   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
9098 }
9099 
9100 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
9101   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
9102     return FastLowered;
9103 
9104   SDLoc SL(Op);
9105   SDValue X = Op.getOperand(0);
9106   SDValue Y = Op.getOperand(1);
9107 
9108   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
9109 
9110   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
9111 
9112   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
9113 
9114   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
9115 
9116   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
9117 
9118   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
9119 
9120   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
9121 
9122   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
9123 
9124   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
9125 
9126   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
9127   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
9128 
9129   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
9130                              NegDivScale0, Mul, DivScale1);
9131 
9132   SDValue Scale;
9133 
9134   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
9135     // Workaround a hardware bug on SI where the condition output from div_scale
9136     // is not usable.
9137 
9138     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
9139 
9140     // Figure out if the scale to use for div_fmas.
9141     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
9142     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
9143     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
9144     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
9145 
9146     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
9147     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
9148 
9149     SDValue Scale0Hi
9150       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
9151     SDValue Scale1Hi
9152       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
9153 
9154     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
9155     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
9156     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
9157   } else {
9158     Scale = DivScale1.getValue(1);
9159   }
9160 
9161   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
9162                              Fma4, Fma3, Mul, Scale);
9163 
9164   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
9165 }
9166 
9167 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
9168   EVT VT = Op.getValueType();
9169 
9170   if (VT == MVT::f32)
9171     return LowerFDIV32(Op, DAG);
9172 
9173   if (VT == MVT::f64)
9174     return LowerFDIV64(Op, DAG);
9175 
9176   if (VT == MVT::f16)
9177     return LowerFDIV16(Op, DAG);
9178 
9179   llvm_unreachable("Unexpected type for fdiv");
9180 }
9181 
9182 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
9183   SDLoc DL(Op);
9184   StoreSDNode *Store = cast<StoreSDNode>(Op);
9185   EVT VT = Store->getMemoryVT();
9186 
9187   if (VT == MVT::i1) {
9188     return DAG.getTruncStore(Store->getChain(), DL,
9189        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
9190        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
9191   }
9192 
9193   assert(VT.isVector() &&
9194          Store->getValue().getValueType().getScalarType() == MVT::i32);
9195 
9196   unsigned AS = Store->getAddressSpace();
9197   if (Subtarget->hasLDSMisalignedBug() &&
9198       AS == AMDGPUAS::FLAT_ADDRESS &&
9199       Store->getAlign().value() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
9200     return SplitVectorStore(Op, DAG);
9201   }
9202 
9203   MachineFunction &MF = DAG.getMachineFunction();
9204   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
9205   // If there is a possibility that flat instruction access scratch memory
9206   // then we need to use the same legalization rules we use for private.
9207   if (AS == AMDGPUAS::FLAT_ADDRESS &&
9208       !Subtarget->hasMultiDwordFlatScratchAddressing())
9209     AS = MFI->hasFlatScratchInit() ?
9210          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
9211 
9212   unsigned NumElements = VT.getVectorNumElements();
9213   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
9214       AS == AMDGPUAS::FLAT_ADDRESS) {
9215     if (NumElements > 4)
9216       return SplitVectorStore(Op, DAG);
9217     // v3 stores not supported on SI.
9218     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
9219       return SplitVectorStore(Op, DAG);
9220 
9221     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
9222                                         VT, *Store->getMemOperand()))
9223       return expandUnalignedStore(Store, DAG);
9224 
9225     return SDValue();
9226   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
9227     switch (Subtarget->getMaxPrivateElementSize()) {
9228     case 4:
9229       return scalarizeVectorStore(Store, DAG);
9230     case 8:
9231       if (NumElements > 2)
9232         return SplitVectorStore(Op, DAG);
9233       return SDValue();
9234     case 16:
9235       if (NumElements > 4 ||
9236           (NumElements == 3 && !Subtarget->enableFlatScratch()))
9237         return SplitVectorStore(Op, DAG);
9238       return SDValue();
9239     default:
9240       llvm_unreachable("unsupported private_element_size");
9241     }
9242   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
9243     bool Fast = false;
9244     auto Flags = Store->getMemOperand()->getFlags();
9245     if (allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
9246                                            Store->getAlign(), Flags, &Fast) &&
9247         Fast)
9248       return SDValue();
9249 
9250     if (VT.isVector())
9251       return SplitVectorStore(Op, DAG);
9252 
9253     return expandUnalignedStore(Store, DAG);
9254   }
9255 
9256   // Probably an invalid store. If so we'll end up emitting a selection error.
9257   return SDValue();
9258 }
9259 
9260 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
9261   SDLoc DL(Op);
9262   EVT VT = Op.getValueType();
9263   SDValue Arg = Op.getOperand(0);
9264   SDValue TrigVal;
9265 
9266   // Propagate fast-math flags so that the multiply we introduce can be folded
9267   // if Arg is already the result of a multiply by constant.
9268   auto Flags = Op->getFlags();
9269 
9270   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
9271 
9272   if (Subtarget->hasTrigReducedRange()) {
9273     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9274     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
9275   } else {
9276     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9277   }
9278 
9279   switch (Op.getOpcode()) {
9280   case ISD::FCOS:
9281     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
9282   case ISD::FSIN:
9283     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
9284   default:
9285     llvm_unreachable("Wrong trig opcode");
9286   }
9287 }
9288 
9289 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9290   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
9291   assert(AtomicNode->isCompareAndSwap());
9292   unsigned AS = AtomicNode->getAddressSpace();
9293 
9294   // No custom lowering required for local address space
9295   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
9296     return Op;
9297 
9298   // Non-local address space requires custom lowering for atomic compare
9299   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
9300   SDLoc DL(Op);
9301   SDValue ChainIn = Op.getOperand(0);
9302   SDValue Addr = Op.getOperand(1);
9303   SDValue Old = Op.getOperand(2);
9304   SDValue New = Op.getOperand(3);
9305   EVT VT = Op.getValueType();
9306   MVT SimpleVT = VT.getSimpleVT();
9307   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
9308 
9309   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
9310   SDValue Ops[] = { ChainIn, Addr, NewOld };
9311 
9312   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
9313                                  Ops, VT, AtomicNode->getMemOperand());
9314 }
9315 
9316 //===----------------------------------------------------------------------===//
9317 // Custom DAG optimizations
9318 //===----------------------------------------------------------------------===//
9319 
9320 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
9321                                                      DAGCombinerInfo &DCI) const {
9322   EVT VT = N->getValueType(0);
9323   EVT ScalarVT = VT.getScalarType();
9324   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
9325     return SDValue();
9326 
9327   SelectionDAG &DAG = DCI.DAG;
9328   SDLoc DL(N);
9329 
9330   SDValue Src = N->getOperand(0);
9331   EVT SrcVT = Src.getValueType();
9332 
9333   // TODO: We could try to match extracting the higher bytes, which would be
9334   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
9335   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
9336   // about in practice.
9337   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
9338     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
9339       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
9340       DCI.AddToWorklist(Cvt.getNode());
9341 
9342       // For the f16 case, fold to a cast to f32 and then cast back to f16.
9343       if (ScalarVT != MVT::f32) {
9344         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
9345                           DAG.getTargetConstant(0, DL, MVT::i32));
9346       }
9347       return Cvt;
9348     }
9349   }
9350 
9351   return SDValue();
9352 }
9353 
9354 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
9355 
9356 // This is a variant of
9357 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
9358 //
9359 // The normal DAG combiner will do this, but only if the add has one use since
9360 // that would increase the number of instructions.
9361 //
9362 // This prevents us from seeing a constant offset that can be folded into a
9363 // memory instruction's addressing mode. If we know the resulting add offset of
9364 // a pointer can be folded into an addressing offset, we can replace the pointer
9365 // operand with the add of new constant offset. This eliminates one of the uses,
9366 // and may allow the remaining use to also be simplified.
9367 //
9368 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
9369                                                unsigned AddrSpace,
9370                                                EVT MemVT,
9371                                                DAGCombinerInfo &DCI) const {
9372   SDValue N0 = N->getOperand(0);
9373   SDValue N1 = N->getOperand(1);
9374 
9375   // We only do this to handle cases where it's profitable when there are
9376   // multiple uses of the add, so defer to the standard combine.
9377   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
9378       N0->hasOneUse())
9379     return SDValue();
9380 
9381   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
9382   if (!CN1)
9383     return SDValue();
9384 
9385   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9386   if (!CAdd)
9387     return SDValue();
9388 
9389   // If the resulting offset is too large, we can't fold it into the addressing
9390   // mode offset.
9391   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
9392   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
9393 
9394   AddrMode AM;
9395   AM.HasBaseReg = true;
9396   AM.BaseOffs = Offset.getSExtValue();
9397   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
9398     return SDValue();
9399 
9400   SelectionDAG &DAG = DCI.DAG;
9401   SDLoc SL(N);
9402   EVT VT = N->getValueType(0);
9403 
9404   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
9405   SDValue COffset = DAG.getConstant(Offset, SL, VT);
9406 
9407   SDNodeFlags Flags;
9408   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
9409                           (N0.getOpcode() == ISD::OR ||
9410                            N0->getFlags().hasNoUnsignedWrap()));
9411 
9412   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
9413 }
9414 
9415 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
9416 /// by the chain and intrinsic ID. Theoretically we would also need to check the
9417 /// specific intrinsic, but they all place the pointer operand first.
9418 static unsigned getBasePtrIndex(const MemSDNode *N) {
9419   switch (N->getOpcode()) {
9420   case ISD::STORE:
9421   case ISD::INTRINSIC_W_CHAIN:
9422   case ISD::INTRINSIC_VOID:
9423     return 2;
9424   default:
9425     return 1;
9426   }
9427 }
9428 
9429 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
9430                                                   DAGCombinerInfo &DCI) const {
9431   SelectionDAG &DAG = DCI.DAG;
9432   SDLoc SL(N);
9433 
9434   unsigned PtrIdx = getBasePtrIndex(N);
9435   SDValue Ptr = N->getOperand(PtrIdx);
9436 
9437   // TODO: We could also do this for multiplies.
9438   if (Ptr.getOpcode() == ISD::SHL) {
9439     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
9440                                           N->getMemoryVT(), DCI);
9441     if (NewPtr) {
9442       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
9443 
9444       NewOps[PtrIdx] = NewPtr;
9445       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
9446     }
9447   }
9448 
9449   return SDValue();
9450 }
9451 
9452 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
9453   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
9454          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
9455          (Opc == ISD::XOR && Val == 0);
9456 }
9457 
9458 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
9459 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
9460 // integer combine opportunities since most 64-bit operations are decomposed
9461 // this way.  TODO: We won't want this for SALU especially if it is an inline
9462 // immediate.
9463 SDValue SITargetLowering::splitBinaryBitConstantOp(
9464   DAGCombinerInfo &DCI,
9465   const SDLoc &SL,
9466   unsigned Opc, SDValue LHS,
9467   const ConstantSDNode *CRHS) const {
9468   uint64_t Val = CRHS->getZExtValue();
9469   uint32_t ValLo = Lo_32(Val);
9470   uint32_t ValHi = Hi_32(Val);
9471   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9472 
9473     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
9474          bitOpWithConstantIsReducible(Opc, ValHi)) ||
9475         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
9476     // If we need to materialize a 64-bit immediate, it will be split up later
9477     // anyway. Avoid creating the harder to understand 64-bit immediate
9478     // materialization.
9479     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
9480   }
9481 
9482   return SDValue();
9483 }
9484 
9485 // Returns true if argument is a boolean value which is not serialized into
9486 // memory or argument and does not require v_cndmask_b32 to be deserialized.
9487 static bool isBoolSGPR(SDValue V) {
9488   if (V.getValueType() != MVT::i1)
9489     return false;
9490   switch (V.getOpcode()) {
9491   default:
9492     break;
9493   case ISD::SETCC:
9494   case AMDGPUISD::FP_CLASS:
9495     return true;
9496   case ISD::AND:
9497   case ISD::OR:
9498   case ISD::XOR:
9499     return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
9500   }
9501   return false;
9502 }
9503 
9504 // If a constant has all zeroes or all ones within each byte return it.
9505 // Otherwise return 0.
9506 static uint32_t getConstantPermuteMask(uint32_t C) {
9507   // 0xff for any zero byte in the mask
9508   uint32_t ZeroByteMask = 0;
9509   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
9510   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
9511   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
9512   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
9513   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
9514   if ((NonZeroByteMask & C) != NonZeroByteMask)
9515     return 0; // Partial bytes selected.
9516   return C;
9517 }
9518 
9519 // Check if a node selects whole bytes from its operand 0 starting at a byte
9520 // boundary while masking the rest. Returns select mask as in the v_perm_b32
9521 // or -1 if not succeeded.
9522 // Note byte select encoding:
9523 // value 0-3 selects corresponding source byte;
9524 // value 0xc selects zero;
9525 // value 0xff selects 0xff.
9526 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
9527   assert(V.getValueSizeInBits() == 32);
9528 
9529   if (V.getNumOperands() != 2)
9530     return ~0;
9531 
9532   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
9533   if (!N1)
9534     return ~0;
9535 
9536   uint32_t C = N1->getZExtValue();
9537 
9538   switch (V.getOpcode()) {
9539   default:
9540     break;
9541   case ISD::AND:
9542     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9543       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
9544     }
9545     break;
9546 
9547   case ISD::OR:
9548     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9549       return (0x03020100 & ~ConstMask) | ConstMask;
9550     }
9551     break;
9552 
9553   case ISD::SHL:
9554     if (C % 8)
9555       return ~0;
9556 
9557     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
9558 
9559   case ISD::SRL:
9560     if (C % 8)
9561       return ~0;
9562 
9563     return uint32_t(0x0c0c0c0c03020100ull >> C);
9564   }
9565 
9566   return ~0;
9567 }
9568 
9569 SDValue SITargetLowering::performAndCombine(SDNode *N,
9570                                             DAGCombinerInfo &DCI) const {
9571   if (DCI.isBeforeLegalize())
9572     return SDValue();
9573 
9574   SelectionDAG &DAG = DCI.DAG;
9575   EVT VT = N->getValueType(0);
9576   SDValue LHS = N->getOperand(0);
9577   SDValue RHS = N->getOperand(1);
9578 
9579 
9580   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9581   if (VT == MVT::i64 && CRHS) {
9582     if (SDValue Split
9583         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9584       return Split;
9585   }
9586 
9587   if (CRHS && VT == MVT::i32) {
9588     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9589     // nb = number of trailing zeroes in mask
9590     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9591     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9592     uint64_t Mask = CRHS->getZExtValue();
9593     unsigned Bits = countPopulation(Mask);
9594     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9595         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9596       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9597         unsigned Shift = CShift->getZExtValue();
9598         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9599         unsigned Offset = NB + Shift;
9600         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9601           SDLoc SL(N);
9602           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9603                                     LHS->getOperand(0),
9604                                     DAG.getConstant(Offset, SL, MVT::i32),
9605                                     DAG.getConstant(Bits, SL, MVT::i32));
9606           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9607           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9608                                     DAG.getValueType(NarrowVT));
9609           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9610                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9611           return Shl;
9612         }
9613       }
9614     }
9615 
9616     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9617     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9618         isa<ConstantSDNode>(LHS.getOperand(2))) {
9619       uint32_t Sel = getConstantPermuteMask(Mask);
9620       if (!Sel)
9621         return SDValue();
9622 
9623       // Select 0xc for all zero bytes
9624       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9625       SDLoc DL(N);
9626       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9627                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9628     }
9629   }
9630 
9631   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9632   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9633   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9634     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9635     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9636 
9637     SDValue X = LHS.getOperand(0);
9638     SDValue Y = RHS.getOperand(0);
9639     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9640       return SDValue();
9641 
9642     if (LCC == ISD::SETO) {
9643       if (X != LHS.getOperand(1))
9644         return SDValue();
9645 
9646       if (RCC == ISD::SETUNE) {
9647         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9648         if (!C1 || !C1->isInfinity() || C1->isNegative())
9649           return SDValue();
9650 
9651         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9652                               SIInstrFlags::N_SUBNORMAL |
9653                               SIInstrFlags::N_ZERO |
9654                               SIInstrFlags::P_ZERO |
9655                               SIInstrFlags::P_SUBNORMAL |
9656                               SIInstrFlags::P_NORMAL;
9657 
9658         static_assert(((~(SIInstrFlags::S_NAN |
9659                           SIInstrFlags::Q_NAN |
9660                           SIInstrFlags::N_INFINITY |
9661                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9662                       "mask not equal");
9663 
9664         SDLoc DL(N);
9665         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9666                            X, DAG.getConstant(Mask, DL, MVT::i32));
9667       }
9668     }
9669   }
9670 
9671   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9672     std::swap(LHS, RHS);
9673 
9674   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9675       RHS.hasOneUse()) {
9676     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9677     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9678     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9679     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9680     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9681         (RHS.getOperand(0) == LHS.getOperand(0) &&
9682          LHS.getOperand(0) == LHS.getOperand(1))) {
9683       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9684       unsigned NewMask = LCC == ISD::SETO ?
9685         Mask->getZExtValue() & ~OrdMask :
9686         Mask->getZExtValue() & OrdMask;
9687 
9688       SDLoc DL(N);
9689       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9690                          DAG.getConstant(NewMask, DL, MVT::i32));
9691     }
9692   }
9693 
9694   if (VT == MVT::i32 &&
9695       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9696     // and x, (sext cc from i1) => select cc, x, 0
9697     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9698       std::swap(LHS, RHS);
9699     if (isBoolSGPR(RHS.getOperand(0)))
9700       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9701                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9702   }
9703 
9704   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9705   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9706   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9707       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9708     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9709     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9710     if (LHSMask != ~0u && RHSMask != ~0u) {
9711       // Canonicalize the expression in an attempt to have fewer unique masks
9712       // and therefore fewer registers used to hold the masks.
9713       if (LHSMask > RHSMask) {
9714         std::swap(LHSMask, RHSMask);
9715         std::swap(LHS, RHS);
9716       }
9717 
9718       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9719       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9720       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9721       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9722 
9723       // Check of we need to combine values from two sources within a byte.
9724       if (!(LHSUsedLanes & RHSUsedLanes) &&
9725           // If we select high and lower word keep it for SDWA.
9726           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9727           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9728         // Each byte in each mask is either selector mask 0-3, or has higher
9729         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9730         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9731         // mask which is not 0xff wins. By anding both masks we have a correct
9732         // result except that 0x0c shall be corrected to give 0x0c only.
9733         uint32_t Mask = LHSMask & RHSMask;
9734         for (unsigned I = 0; I < 32; I += 8) {
9735           uint32_t ByteSel = 0xff << I;
9736           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9737             Mask &= (0x0c << I) & 0xffffffff;
9738         }
9739 
9740         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9741         // or 0x0c.
9742         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9743         SDLoc DL(N);
9744 
9745         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9746                            LHS.getOperand(0), RHS.getOperand(0),
9747                            DAG.getConstant(Sel, DL, MVT::i32));
9748       }
9749     }
9750   }
9751 
9752   return SDValue();
9753 }
9754 
9755 SDValue SITargetLowering::performOrCombine(SDNode *N,
9756                                            DAGCombinerInfo &DCI) const {
9757   SelectionDAG &DAG = DCI.DAG;
9758   SDValue LHS = N->getOperand(0);
9759   SDValue RHS = N->getOperand(1);
9760 
9761   EVT VT = N->getValueType(0);
9762   if (VT == MVT::i1) {
9763     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9764     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9765         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9766       SDValue Src = LHS.getOperand(0);
9767       if (Src != RHS.getOperand(0))
9768         return SDValue();
9769 
9770       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9771       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9772       if (!CLHS || !CRHS)
9773         return SDValue();
9774 
9775       // Only 10 bits are used.
9776       static const uint32_t MaxMask = 0x3ff;
9777 
9778       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9779       SDLoc DL(N);
9780       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9781                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9782     }
9783 
9784     return SDValue();
9785   }
9786 
9787   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9788   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9789       LHS.getOpcode() == AMDGPUISD::PERM &&
9790       isa<ConstantSDNode>(LHS.getOperand(2))) {
9791     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9792     if (!Sel)
9793       return SDValue();
9794 
9795     Sel |= LHS.getConstantOperandVal(2);
9796     SDLoc DL(N);
9797     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9798                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9799   }
9800 
9801   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9802   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9803   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9804       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9805     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9806     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9807     if (LHSMask != ~0u && RHSMask != ~0u) {
9808       // Canonicalize the expression in an attempt to have fewer unique masks
9809       // and therefore fewer registers used to hold the masks.
9810       if (LHSMask > RHSMask) {
9811         std::swap(LHSMask, RHSMask);
9812         std::swap(LHS, RHS);
9813       }
9814 
9815       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9816       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9817       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9818       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9819 
9820       // Check of we need to combine values from two sources within a byte.
9821       if (!(LHSUsedLanes & RHSUsedLanes) &&
9822           // If we select high and lower word keep it for SDWA.
9823           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9824           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9825         // Kill zero bytes selected by other mask. Zero value is 0xc.
9826         LHSMask &= ~RHSUsedLanes;
9827         RHSMask &= ~LHSUsedLanes;
9828         // Add 4 to each active LHS lane
9829         LHSMask |= LHSUsedLanes & 0x04040404;
9830         // Combine masks
9831         uint32_t Sel = LHSMask | RHSMask;
9832         SDLoc DL(N);
9833 
9834         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9835                            LHS.getOperand(0), RHS.getOperand(0),
9836                            DAG.getConstant(Sel, DL, MVT::i32));
9837       }
9838     }
9839   }
9840 
9841   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9842     return SDValue();
9843 
9844   // TODO: This could be a generic combine with a predicate for extracting the
9845   // high half of an integer being free.
9846 
9847   // (or i64:x, (zero_extend i32:y)) ->
9848   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9849   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9850       RHS.getOpcode() != ISD::ZERO_EXTEND)
9851     std::swap(LHS, RHS);
9852 
9853   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9854     SDValue ExtSrc = RHS.getOperand(0);
9855     EVT SrcVT = ExtSrc.getValueType();
9856     if (SrcVT == MVT::i32) {
9857       SDLoc SL(N);
9858       SDValue LowLHS, HiBits;
9859       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9860       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9861 
9862       DCI.AddToWorklist(LowOr.getNode());
9863       DCI.AddToWorklist(HiBits.getNode());
9864 
9865       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9866                                 LowOr, HiBits);
9867       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9868     }
9869   }
9870 
9871   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9872   if (CRHS) {
9873     if (SDValue Split
9874           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR,
9875                                      N->getOperand(0), CRHS))
9876       return Split;
9877   }
9878 
9879   return SDValue();
9880 }
9881 
9882 SDValue SITargetLowering::performXorCombine(SDNode *N,
9883                                             DAGCombinerInfo &DCI) const {
9884   if (SDValue RV = reassociateScalarOps(N, DCI.DAG))
9885     return RV;
9886 
9887   EVT VT = N->getValueType(0);
9888   if (VT != MVT::i64)
9889     return SDValue();
9890 
9891   SDValue LHS = N->getOperand(0);
9892   SDValue RHS = N->getOperand(1);
9893 
9894   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9895   if (CRHS) {
9896     if (SDValue Split
9897           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9898       return Split;
9899   }
9900 
9901   return SDValue();
9902 }
9903 
9904 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9905                                                    DAGCombinerInfo &DCI) const {
9906   if (!Subtarget->has16BitInsts() ||
9907       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9908     return SDValue();
9909 
9910   EVT VT = N->getValueType(0);
9911   if (VT != MVT::i32)
9912     return SDValue();
9913 
9914   SDValue Src = N->getOperand(0);
9915   if (Src.getValueType() != MVT::i16)
9916     return SDValue();
9917 
9918   return SDValue();
9919 }
9920 
9921 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9922                                                         DAGCombinerInfo &DCI)
9923                                                         const {
9924   SDValue Src = N->getOperand(0);
9925   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9926 
9927   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9928       VTSign->getVT() == MVT::i8) ||
9929       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9930       VTSign->getVT() == MVT::i16)) &&
9931       Src.hasOneUse()) {
9932     auto *M = cast<MemSDNode>(Src);
9933     SDValue Ops[] = {
9934       Src.getOperand(0), // Chain
9935       Src.getOperand(1), // rsrc
9936       Src.getOperand(2), // vindex
9937       Src.getOperand(3), // voffset
9938       Src.getOperand(4), // soffset
9939       Src.getOperand(5), // offset
9940       Src.getOperand(6),
9941       Src.getOperand(7)
9942     };
9943     // replace with BUFFER_LOAD_BYTE/SHORT
9944     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9945                                          Src.getOperand(0).getValueType());
9946     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9947                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9948     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9949                                                           ResList,
9950                                                           Ops, M->getMemoryVT(),
9951                                                           M->getMemOperand());
9952     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9953                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9954   }
9955   return SDValue();
9956 }
9957 
9958 SDValue SITargetLowering::performClassCombine(SDNode *N,
9959                                               DAGCombinerInfo &DCI) const {
9960   SelectionDAG &DAG = DCI.DAG;
9961   SDValue Mask = N->getOperand(1);
9962 
9963   // fp_class x, 0 -> false
9964   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9965     if (CMask->isZero())
9966       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9967   }
9968 
9969   if (N->getOperand(0).isUndef())
9970     return DAG.getUNDEF(MVT::i1);
9971 
9972   return SDValue();
9973 }
9974 
9975 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9976                                             DAGCombinerInfo &DCI) const {
9977   EVT VT = N->getValueType(0);
9978   SDValue N0 = N->getOperand(0);
9979 
9980   if (N0.isUndef())
9981     return N0;
9982 
9983   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9984                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9985     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9986                            N->getFlags());
9987   }
9988 
9989   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9990     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9991                            N0.getOperand(0), N->getFlags());
9992   }
9993 
9994   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9995 }
9996 
9997 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9998                                        unsigned MaxDepth) const {
9999   unsigned Opcode = Op.getOpcode();
10000   if (Opcode == ISD::FCANONICALIZE)
10001     return true;
10002 
10003   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
10004     auto F = CFP->getValueAPF();
10005     if (F.isNaN() && F.isSignaling())
10006       return false;
10007     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
10008   }
10009 
10010   // If source is a result of another standard FP operation it is already in
10011   // canonical form.
10012   if (MaxDepth == 0)
10013     return false;
10014 
10015   switch (Opcode) {
10016   // These will flush denorms if required.
10017   case ISD::FADD:
10018   case ISD::FSUB:
10019   case ISD::FMUL:
10020   case ISD::FCEIL:
10021   case ISD::FFLOOR:
10022   case ISD::FMA:
10023   case ISD::FMAD:
10024   case ISD::FSQRT:
10025   case ISD::FDIV:
10026   case ISD::FREM:
10027   case ISD::FP_ROUND:
10028   case ISD::FP_EXTEND:
10029   case AMDGPUISD::FMUL_LEGACY:
10030   case AMDGPUISD::FMAD_FTZ:
10031   case AMDGPUISD::RCP:
10032   case AMDGPUISD::RSQ:
10033   case AMDGPUISD::RSQ_CLAMP:
10034   case AMDGPUISD::RCP_LEGACY:
10035   case AMDGPUISD::RCP_IFLAG:
10036   case AMDGPUISD::DIV_SCALE:
10037   case AMDGPUISD::DIV_FMAS:
10038   case AMDGPUISD::DIV_FIXUP:
10039   case AMDGPUISD::FRACT:
10040   case AMDGPUISD::LDEXP:
10041   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10042   case AMDGPUISD::CVT_F32_UBYTE0:
10043   case AMDGPUISD::CVT_F32_UBYTE1:
10044   case AMDGPUISD::CVT_F32_UBYTE2:
10045   case AMDGPUISD::CVT_F32_UBYTE3:
10046     return true;
10047 
10048   // It can/will be lowered or combined as a bit operation.
10049   // Need to check their input recursively to handle.
10050   case ISD::FNEG:
10051   case ISD::FABS:
10052   case ISD::FCOPYSIGN:
10053     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
10054 
10055   case ISD::FSIN:
10056   case ISD::FCOS:
10057   case ISD::FSINCOS:
10058     return Op.getValueType().getScalarType() != MVT::f16;
10059 
10060   case ISD::FMINNUM:
10061   case ISD::FMAXNUM:
10062   case ISD::FMINNUM_IEEE:
10063   case ISD::FMAXNUM_IEEE:
10064   case AMDGPUISD::CLAMP:
10065   case AMDGPUISD::FMED3:
10066   case AMDGPUISD::FMAX3:
10067   case AMDGPUISD::FMIN3: {
10068     // FIXME: Shouldn't treat the generic operations different based these.
10069     // However, we aren't really required to flush the result from
10070     // minnum/maxnum..
10071 
10072     // snans will be quieted, so we only need to worry about denormals.
10073     if (Subtarget->supportsMinMaxDenormModes() ||
10074         denormalsEnabledForType(DAG, Op.getValueType()))
10075       return true;
10076 
10077     // Flushing may be required.
10078     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
10079     // targets need to check their input recursively.
10080 
10081     // FIXME: Does this apply with clamp? It's implemented with max.
10082     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
10083       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
10084         return false;
10085     }
10086 
10087     return true;
10088   }
10089   case ISD::SELECT: {
10090     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
10091            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
10092   }
10093   case ISD::BUILD_VECTOR: {
10094     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
10095       SDValue SrcOp = Op.getOperand(i);
10096       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
10097         return false;
10098     }
10099 
10100     return true;
10101   }
10102   case ISD::EXTRACT_VECTOR_ELT:
10103   case ISD::EXTRACT_SUBVECTOR: {
10104     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
10105   }
10106   case ISD::INSERT_VECTOR_ELT: {
10107     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
10108            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
10109   }
10110   case ISD::UNDEF:
10111     // Could be anything.
10112     return false;
10113 
10114   case ISD::BITCAST:
10115     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
10116   case ISD::TRUNCATE: {
10117     // Hack round the mess we make when legalizing extract_vector_elt
10118     if (Op.getValueType() == MVT::i16) {
10119       SDValue TruncSrc = Op.getOperand(0);
10120       if (TruncSrc.getValueType() == MVT::i32 &&
10121           TruncSrc.getOpcode() == ISD::BITCAST &&
10122           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
10123         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
10124       }
10125     }
10126     return false;
10127   }
10128   case ISD::INTRINSIC_WO_CHAIN: {
10129     unsigned IntrinsicID
10130       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10131     // TODO: Handle more intrinsics
10132     switch (IntrinsicID) {
10133     case Intrinsic::amdgcn_cvt_pkrtz:
10134     case Intrinsic::amdgcn_cubeid:
10135     case Intrinsic::amdgcn_frexp_mant:
10136     case Intrinsic::amdgcn_fdot2:
10137     case Intrinsic::amdgcn_rcp:
10138     case Intrinsic::amdgcn_rsq:
10139     case Intrinsic::amdgcn_rsq_clamp:
10140     case Intrinsic::amdgcn_rcp_legacy:
10141     case Intrinsic::amdgcn_rsq_legacy:
10142     case Intrinsic::amdgcn_trig_preop:
10143       return true;
10144     default:
10145       break;
10146     }
10147 
10148     LLVM_FALLTHROUGH;
10149   }
10150   default:
10151     return denormalsEnabledForType(DAG, Op.getValueType()) &&
10152            DAG.isKnownNeverSNaN(Op);
10153   }
10154 
10155   llvm_unreachable("invalid operation");
10156 }
10157 
10158 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
10159                                        unsigned MaxDepth) const {
10160   MachineRegisterInfo &MRI = MF.getRegInfo();
10161   MachineInstr *MI = MRI.getVRegDef(Reg);
10162   unsigned Opcode = MI->getOpcode();
10163 
10164   if (Opcode == AMDGPU::G_FCANONICALIZE)
10165     return true;
10166 
10167   Optional<FPValueAndVReg> FCR;
10168   // Constant splat (can be padded with undef) or scalar constant.
10169   if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) {
10170     if (FCR->Value.isSignaling())
10171       return false;
10172     return !FCR->Value.isDenormal() ||
10173            denormalsEnabledForType(MRI.getType(FCR->VReg), MF);
10174   }
10175 
10176   if (MaxDepth == 0)
10177     return false;
10178 
10179   switch (Opcode) {
10180   case AMDGPU::G_FMINNUM_IEEE:
10181   case AMDGPU::G_FMAXNUM_IEEE: {
10182     if (Subtarget->supportsMinMaxDenormModes() ||
10183         denormalsEnabledForType(MRI.getType(Reg), MF))
10184       return true;
10185     for (const MachineOperand &MO : llvm::drop_begin(MI->operands()))
10186       if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1))
10187         return false;
10188     return true;
10189   }
10190   default:
10191     return denormalsEnabledForType(MRI.getType(Reg), MF) &&
10192            isKnownNeverSNaN(Reg, MRI);
10193   }
10194 
10195   llvm_unreachable("invalid operation");
10196 }
10197 
10198 // Constant fold canonicalize.
10199 SDValue SITargetLowering::getCanonicalConstantFP(
10200   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
10201   // Flush denormals to 0 if not enabled.
10202   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
10203     return DAG.getConstantFP(0.0, SL, VT);
10204 
10205   if (C.isNaN()) {
10206     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
10207     if (C.isSignaling()) {
10208       // Quiet a signaling NaN.
10209       // FIXME: Is this supposed to preserve payload bits?
10210       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
10211     }
10212 
10213     // Make sure it is the canonical NaN bitpattern.
10214     //
10215     // TODO: Can we use -1 as the canonical NaN value since it's an inline
10216     // immediate?
10217     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
10218       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
10219   }
10220 
10221   // Already canonical.
10222   return DAG.getConstantFP(C, SL, VT);
10223 }
10224 
10225 static bool vectorEltWillFoldAway(SDValue Op) {
10226   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
10227 }
10228 
10229 SDValue SITargetLowering::performFCanonicalizeCombine(
10230   SDNode *N,
10231   DAGCombinerInfo &DCI) const {
10232   SelectionDAG &DAG = DCI.DAG;
10233   SDValue N0 = N->getOperand(0);
10234   EVT VT = N->getValueType(0);
10235 
10236   // fcanonicalize undef -> qnan
10237   if (N0.isUndef()) {
10238     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
10239     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
10240   }
10241 
10242   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
10243     EVT VT = N->getValueType(0);
10244     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
10245   }
10246 
10247   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
10248   //                                                   (fcanonicalize k)
10249   //
10250   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
10251 
10252   // TODO: This could be better with wider vectors that will be split to v2f16,
10253   // and to consider uses since there aren't that many packed operations.
10254   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
10255       isTypeLegal(MVT::v2f16)) {
10256     SDLoc SL(N);
10257     SDValue NewElts[2];
10258     SDValue Lo = N0.getOperand(0);
10259     SDValue Hi = N0.getOperand(1);
10260     EVT EltVT = Lo.getValueType();
10261 
10262     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
10263       for (unsigned I = 0; I != 2; ++I) {
10264         SDValue Op = N0.getOperand(I);
10265         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
10266           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
10267                                               CFP->getValueAPF());
10268         } else if (Op.isUndef()) {
10269           // Handled below based on what the other operand is.
10270           NewElts[I] = Op;
10271         } else {
10272           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
10273         }
10274       }
10275 
10276       // If one half is undef, and one is constant, prefer a splat vector rather
10277       // than the normal qNaN. If it's a register, prefer 0.0 since that's
10278       // cheaper to use and may be free with a packed operation.
10279       if (NewElts[0].isUndef()) {
10280         if (isa<ConstantFPSDNode>(NewElts[1]))
10281           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
10282             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
10283       }
10284 
10285       if (NewElts[1].isUndef()) {
10286         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
10287           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
10288       }
10289 
10290       return DAG.getBuildVector(VT, SL, NewElts);
10291     }
10292   }
10293 
10294   unsigned SrcOpc = N0.getOpcode();
10295 
10296   // If it's free to do so, push canonicalizes further up the source, which may
10297   // find a canonical source.
10298   //
10299   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
10300   // sNaNs.
10301   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
10302     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10303     if (CRHS && N0.hasOneUse()) {
10304       SDLoc SL(N);
10305       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
10306                                    N0.getOperand(0));
10307       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
10308       DCI.AddToWorklist(Canon0.getNode());
10309 
10310       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
10311     }
10312   }
10313 
10314   return isCanonicalized(DAG, N0) ? N0 : SDValue();
10315 }
10316 
10317 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
10318   switch (Opc) {
10319   case ISD::FMAXNUM:
10320   case ISD::FMAXNUM_IEEE:
10321     return AMDGPUISD::FMAX3;
10322   case ISD::SMAX:
10323     return AMDGPUISD::SMAX3;
10324   case ISD::UMAX:
10325     return AMDGPUISD::UMAX3;
10326   case ISD::FMINNUM:
10327   case ISD::FMINNUM_IEEE:
10328     return AMDGPUISD::FMIN3;
10329   case ISD::SMIN:
10330     return AMDGPUISD::SMIN3;
10331   case ISD::UMIN:
10332     return AMDGPUISD::UMIN3;
10333   default:
10334     llvm_unreachable("Not a min/max opcode");
10335   }
10336 }
10337 
10338 SDValue SITargetLowering::performIntMed3ImmCombine(
10339   SelectionDAG &DAG, const SDLoc &SL,
10340   SDValue Op0, SDValue Op1, bool Signed) const {
10341   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
10342   if (!K1)
10343     return SDValue();
10344 
10345   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
10346   if (!K0)
10347     return SDValue();
10348 
10349   if (Signed) {
10350     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
10351       return SDValue();
10352   } else {
10353     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
10354       return SDValue();
10355   }
10356 
10357   EVT VT = K0->getValueType(0);
10358   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
10359   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
10360     return DAG.getNode(Med3Opc, SL, VT,
10361                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
10362   }
10363 
10364   // If there isn't a 16-bit med3 operation, convert to 32-bit.
10365   if (VT == MVT::i16) {
10366     MVT NVT = MVT::i32;
10367     unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
10368 
10369     SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
10370     SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
10371     SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
10372 
10373     SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
10374     return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
10375   }
10376 
10377   return SDValue();
10378 }
10379 
10380 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
10381   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
10382     return C;
10383 
10384   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
10385     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
10386       return C;
10387   }
10388 
10389   return nullptr;
10390 }
10391 
10392 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
10393                                                   const SDLoc &SL,
10394                                                   SDValue Op0,
10395                                                   SDValue Op1) const {
10396   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
10397   if (!K1)
10398     return SDValue();
10399 
10400   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
10401   if (!K0)
10402     return SDValue();
10403 
10404   // Ordered >= (although NaN inputs should have folded away by now).
10405   if (K0->getValueAPF() > K1->getValueAPF())
10406     return SDValue();
10407 
10408   const MachineFunction &MF = DAG.getMachineFunction();
10409   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10410 
10411   // TODO: Check IEEE bit enabled?
10412   EVT VT = Op0.getValueType();
10413   if (Info->getMode().DX10Clamp) {
10414     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
10415     // hardware fmed3 behavior converting to a min.
10416     // FIXME: Should this be allowing -0.0?
10417     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
10418       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
10419   }
10420 
10421   // med3 for f16 is only available on gfx9+, and not available for v2f16.
10422   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
10423     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
10424     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
10425     // then give the other result, which is different from med3 with a NaN
10426     // input.
10427     SDValue Var = Op0.getOperand(0);
10428     if (!DAG.isKnownNeverSNaN(Var))
10429       return SDValue();
10430 
10431     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10432 
10433     if ((!K0->hasOneUse() ||
10434          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
10435         (!K1->hasOneUse() ||
10436          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
10437       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
10438                          Var, SDValue(K0, 0), SDValue(K1, 0));
10439     }
10440   }
10441 
10442   return SDValue();
10443 }
10444 
10445 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
10446                                                DAGCombinerInfo &DCI) const {
10447   SelectionDAG &DAG = DCI.DAG;
10448 
10449   EVT VT = N->getValueType(0);
10450   unsigned Opc = N->getOpcode();
10451   SDValue Op0 = N->getOperand(0);
10452   SDValue Op1 = N->getOperand(1);
10453 
10454   // Only do this if the inner op has one use since this will just increases
10455   // register pressure for no benefit.
10456 
10457   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
10458       !VT.isVector() &&
10459       (VT == MVT::i32 || VT == MVT::f32 ||
10460        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
10461     // max(max(a, b), c) -> max3(a, b, c)
10462     // min(min(a, b), c) -> min3(a, b, c)
10463     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
10464       SDLoc DL(N);
10465       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10466                          DL,
10467                          N->getValueType(0),
10468                          Op0.getOperand(0),
10469                          Op0.getOperand(1),
10470                          Op1);
10471     }
10472 
10473     // Try commuted.
10474     // max(a, max(b, c)) -> max3(a, b, c)
10475     // min(a, min(b, c)) -> min3(a, b, c)
10476     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
10477       SDLoc DL(N);
10478       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10479                          DL,
10480                          N->getValueType(0),
10481                          Op0,
10482                          Op1.getOperand(0),
10483                          Op1.getOperand(1));
10484     }
10485   }
10486 
10487   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
10488   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
10489     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
10490       return Med3;
10491   }
10492 
10493   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
10494     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
10495       return Med3;
10496   }
10497 
10498   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
10499   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
10500        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
10501        (Opc == AMDGPUISD::FMIN_LEGACY &&
10502         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
10503       (VT == MVT::f32 || VT == MVT::f64 ||
10504        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
10505        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
10506       Op0.hasOneUse()) {
10507     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
10508       return Res;
10509   }
10510 
10511   return SDValue();
10512 }
10513 
10514 static bool isClampZeroToOne(SDValue A, SDValue B) {
10515   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
10516     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
10517       // FIXME: Should this be allowing -0.0?
10518       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
10519              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
10520     }
10521   }
10522 
10523   return false;
10524 }
10525 
10526 // FIXME: Should only worry about snans for version with chain.
10527 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
10528                                               DAGCombinerInfo &DCI) const {
10529   EVT VT = N->getValueType(0);
10530   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
10531   // NaNs. With a NaN input, the order of the operands may change the result.
10532 
10533   SelectionDAG &DAG = DCI.DAG;
10534   SDLoc SL(N);
10535 
10536   SDValue Src0 = N->getOperand(0);
10537   SDValue Src1 = N->getOperand(1);
10538   SDValue Src2 = N->getOperand(2);
10539 
10540   if (isClampZeroToOne(Src0, Src1)) {
10541     // const_a, const_b, x -> clamp is safe in all cases including signaling
10542     // nans.
10543     // FIXME: Should this be allowing -0.0?
10544     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
10545   }
10546 
10547   const MachineFunction &MF = DAG.getMachineFunction();
10548   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10549 
10550   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
10551   // handling no dx10-clamp?
10552   if (Info->getMode().DX10Clamp) {
10553     // If NaNs is clamped to 0, we are free to reorder the inputs.
10554 
10555     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10556       std::swap(Src0, Src1);
10557 
10558     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10559       std::swap(Src1, Src2);
10560 
10561     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10562       std::swap(Src0, Src1);
10563 
10564     if (isClampZeroToOne(Src1, Src2))
10565       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10566   }
10567 
10568   return SDValue();
10569 }
10570 
10571 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10572                                                  DAGCombinerInfo &DCI) const {
10573   SDValue Src0 = N->getOperand(0);
10574   SDValue Src1 = N->getOperand(1);
10575   if (Src0.isUndef() && Src1.isUndef())
10576     return DCI.DAG.getUNDEF(N->getValueType(0));
10577   return SDValue();
10578 }
10579 
10580 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10581 // expanded into a set of cmp/select instructions.
10582 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10583                                                 unsigned NumElem,
10584                                                 bool IsDivergentIdx,
10585                                                 const GCNSubtarget *Subtarget) {
10586   if (UseDivergentRegisterIndexing)
10587     return false;
10588 
10589   unsigned VecSize = EltSize * NumElem;
10590 
10591   // Sub-dword vectors of size 2 dword or less have better implementation.
10592   if (VecSize <= 64 && EltSize < 32)
10593     return false;
10594 
10595   // Always expand the rest of sub-dword instructions, otherwise it will be
10596   // lowered via memory.
10597   if (EltSize < 32)
10598     return true;
10599 
10600   // Always do this if var-idx is divergent, otherwise it will become a loop.
10601   if (IsDivergentIdx)
10602     return true;
10603 
10604   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10605   unsigned NumInsts = NumElem /* Number of compares */ +
10606                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10607 
10608   // On some architectures (GFX9) movrel is not available and it's better
10609   // to expand.
10610   if (!Subtarget->hasMovrel())
10611     return NumInsts <= 16;
10612 
10613   // If movrel is available, use it instead of expanding for vector of 8
10614   // elements.
10615   return NumInsts <= 15;
10616 }
10617 
10618 bool SITargetLowering::shouldExpandVectorDynExt(SDNode *N) const {
10619   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10620   if (isa<ConstantSDNode>(Idx))
10621     return false;
10622 
10623   SDValue Vec = N->getOperand(0);
10624   EVT VecVT = Vec.getValueType();
10625   EVT EltVT = VecVT.getVectorElementType();
10626   unsigned EltSize = EltVT.getSizeInBits();
10627   unsigned NumElem = VecVT.getVectorNumElements();
10628 
10629   return SITargetLowering::shouldExpandVectorDynExt(
10630       EltSize, NumElem, Idx->isDivergent(), getSubtarget());
10631 }
10632 
10633 SDValue SITargetLowering::performExtractVectorEltCombine(
10634   SDNode *N, DAGCombinerInfo &DCI) const {
10635   SDValue Vec = N->getOperand(0);
10636   SelectionDAG &DAG = DCI.DAG;
10637 
10638   EVT VecVT = Vec.getValueType();
10639   EVT EltVT = VecVT.getVectorElementType();
10640 
10641   if ((Vec.getOpcode() == ISD::FNEG ||
10642        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10643     SDLoc SL(N);
10644     EVT EltVT = N->getValueType(0);
10645     SDValue Idx = N->getOperand(1);
10646     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10647                               Vec.getOperand(0), Idx);
10648     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10649   }
10650 
10651   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10652   //    =>
10653   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10654   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10655   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10656   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10657     SDLoc SL(N);
10658     EVT EltVT = N->getValueType(0);
10659     SDValue Idx = N->getOperand(1);
10660     unsigned Opc = Vec.getOpcode();
10661 
10662     switch(Opc) {
10663     default:
10664       break;
10665       // TODO: Support other binary operations.
10666     case ISD::FADD:
10667     case ISD::FSUB:
10668     case ISD::FMUL:
10669     case ISD::ADD:
10670     case ISD::UMIN:
10671     case ISD::UMAX:
10672     case ISD::SMIN:
10673     case ISD::SMAX:
10674     case ISD::FMAXNUM:
10675     case ISD::FMINNUM:
10676     case ISD::FMAXNUM_IEEE:
10677     case ISD::FMINNUM_IEEE: {
10678       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10679                                  Vec.getOperand(0), Idx);
10680       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10681                                  Vec.getOperand(1), Idx);
10682 
10683       DCI.AddToWorklist(Elt0.getNode());
10684       DCI.AddToWorklist(Elt1.getNode());
10685       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10686     }
10687     }
10688   }
10689 
10690   unsigned VecSize = VecVT.getSizeInBits();
10691   unsigned EltSize = EltVT.getSizeInBits();
10692 
10693   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10694   if (shouldExpandVectorDynExt(N)) {
10695     SDLoc SL(N);
10696     SDValue Idx = N->getOperand(1);
10697     SDValue V;
10698     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10699       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10700       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10701       if (I == 0)
10702         V = Elt;
10703       else
10704         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10705     }
10706     return V;
10707   }
10708 
10709   if (!DCI.isBeforeLegalize())
10710     return SDValue();
10711 
10712   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10713   // elements. This exposes more load reduction opportunities by replacing
10714   // multiple small extract_vector_elements with a single 32-bit extract.
10715   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10716   if (isa<MemSDNode>(Vec) &&
10717       EltSize <= 16 &&
10718       EltVT.isByteSized() &&
10719       VecSize > 32 &&
10720       VecSize % 32 == 0 &&
10721       Idx) {
10722     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10723 
10724     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10725     unsigned EltIdx = BitIndex / 32;
10726     unsigned LeftoverBitIdx = BitIndex % 32;
10727     SDLoc SL(N);
10728 
10729     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10730     DCI.AddToWorklist(Cast.getNode());
10731 
10732     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10733                               DAG.getConstant(EltIdx, SL, MVT::i32));
10734     DCI.AddToWorklist(Elt.getNode());
10735     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10736                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10737     DCI.AddToWorklist(Srl.getNode());
10738 
10739     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10740     DCI.AddToWorklist(Trunc.getNode());
10741     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10742   }
10743 
10744   return SDValue();
10745 }
10746 
10747 SDValue
10748 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10749                                                 DAGCombinerInfo &DCI) const {
10750   SDValue Vec = N->getOperand(0);
10751   SDValue Idx = N->getOperand(2);
10752   EVT VecVT = Vec.getValueType();
10753   EVT EltVT = VecVT.getVectorElementType();
10754 
10755   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10756   // => BUILD_VECTOR n x select (e, const-idx)
10757   if (!shouldExpandVectorDynExt(N))
10758     return SDValue();
10759 
10760   SelectionDAG &DAG = DCI.DAG;
10761   SDLoc SL(N);
10762   SDValue Ins = N->getOperand(1);
10763   EVT IdxVT = Idx.getValueType();
10764 
10765   SmallVector<SDValue, 16> Ops;
10766   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10767     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10768     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10769     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10770     Ops.push_back(V);
10771   }
10772 
10773   return DAG.getBuildVector(VecVT, SL, Ops);
10774 }
10775 
10776 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10777                                           const SDNode *N0,
10778                                           const SDNode *N1) const {
10779   EVT VT = N0->getValueType(0);
10780 
10781   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10782   // support denormals ever.
10783   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10784        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10785         getSubtarget()->hasMadF16())) &&
10786        isOperationLegal(ISD::FMAD, VT))
10787     return ISD::FMAD;
10788 
10789   const TargetOptions &Options = DAG.getTarget().Options;
10790   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10791        (N0->getFlags().hasAllowContract() &&
10792         N1->getFlags().hasAllowContract())) &&
10793       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10794     return ISD::FMA;
10795   }
10796 
10797   return 0;
10798 }
10799 
10800 // For a reassociatable opcode perform:
10801 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10802 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10803                                                SelectionDAG &DAG) const {
10804   EVT VT = N->getValueType(0);
10805   if (VT != MVT::i32 && VT != MVT::i64)
10806     return SDValue();
10807 
10808   if (DAG.isBaseWithConstantOffset(SDValue(N, 0)))
10809     return SDValue();
10810 
10811   unsigned Opc = N->getOpcode();
10812   SDValue Op0 = N->getOperand(0);
10813   SDValue Op1 = N->getOperand(1);
10814 
10815   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10816     return SDValue();
10817 
10818   if (Op0->isDivergent())
10819     std::swap(Op0, Op1);
10820 
10821   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10822     return SDValue();
10823 
10824   SDValue Op2 = Op1.getOperand(1);
10825   Op1 = Op1.getOperand(0);
10826   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10827     return SDValue();
10828 
10829   if (Op1->isDivergent())
10830     std::swap(Op1, Op2);
10831 
10832   SDLoc SL(N);
10833   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10834   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10835 }
10836 
10837 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10838                            EVT VT,
10839                            SDValue N0, SDValue N1, SDValue N2,
10840                            bool Signed) {
10841   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10842   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10843   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10844   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10845 }
10846 
10847 // Fold (add (mul x, y), z) --> (mad_[iu]64_[iu]32 x, y, z) plus high
10848 // multiplies, if any.
10849 //
10850 // Full 64-bit multiplies that feed into an addition are lowered here instead
10851 // of using the generic expansion. The generic expansion ends up with
10852 // a tree of ADD nodes that prevents us from using the "add" part of the
10853 // MAD instruction. The expansion produced here results in a chain of ADDs
10854 // instead of a tree.
10855 SDValue SITargetLowering::tryFoldToMad64_32(SDNode *N,
10856                                             DAGCombinerInfo &DCI) const {
10857   assert(N->getOpcode() == ISD::ADD);
10858 
10859   SelectionDAG &DAG = DCI.DAG;
10860   EVT VT = N->getValueType(0);
10861   SDLoc SL(N);
10862   SDValue LHS = N->getOperand(0);
10863   SDValue RHS = N->getOperand(1);
10864 
10865   if (VT.isVector())
10866     return SDValue();
10867 
10868   // S_MUL_HI_[IU]32 was added in gfx9, which allows us to keep the overall
10869   // result in scalar registers for uniform values.
10870   if (!N->isDivergent() && Subtarget->hasSMulHi())
10871     return SDValue();
10872 
10873   unsigned NumBits = VT.getScalarSizeInBits();
10874   if (NumBits <= 32 || NumBits > 64)
10875     return SDValue();
10876 
10877   if (LHS.getOpcode() != ISD::MUL) {
10878     assert(RHS.getOpcode() == ISD::MUL);
10879     std::swap(LHS, RHS);
10880   }
10881 
10882   // Avoid the fold if it would unduly increase the number of multiplies due to
10883   // multiple uses, except on hardware with full-rate multiply-add (which is
10884   // part of full-rate 64-bit ops).
10885   if (!Subtarget->hasFullRate64Ops()) {
10886     unsigned NumUsers = 0;
10887     for (SDNode *Use : LHS->uses()) {
10888       // There is a use that does not feed into addition, so the multiply can't
10889       // be removed. We prefer MUL + ADD + ADDC over MAD + MUL.
10890       if (Use->getOpcode() != ISD::ADD)
10891         return SDValue();
10892 
10893       // We prefer 2xMAD over MUL + 2xADD + 2xADDC (code density), and prefer
10894       // MUL + 3xADD + 3xADDC over 3xMAD.
10895       ++NumUsers;
10896       if (NumUsers >= 3)
10897         return SDValue();
10898     }
10899   }
10900 
10901   SDValue MulLHS = LHS.getOperand(0);
10902   SDValue MulRHS = LHS.getOperand(1);
10903   SDValue AddRHS = RHS;
10904 
10905   // Always check whether operands are small unsigned values, since that
10906   // knowledge is useful in more cases. Check for small signed values only if
10907   // doing so can unlock a shorter code sequence.
10908   bool MulLHSUnsigned32 = numBitsUnsigned(MulLHS, DAG) <= 32;
10909   bool MulRHSUnsigned32 = numBitsUnsigned(MulRHS, DAG) <= 32;
10910 
10911   bool MulSignedLo = false;
10912   if (!MulLHSUnsigned32 || !MulRHSUnsigned32) {
10913     MulSignedLo = numBitsSigned(MulLHS, DAG) <= 32 &&
10914                   numBitsSigned(MulRHS, DAG) <= 32;
10915   }
10916 
10917   // The operands and final result all have the same number of bits. If
10918   // operands need to be extended, they can be extended with garbage. The
10919   // resulting garbage in the high bits of the mad_[iu]64_[iu]32 result is
10920   // truncated away in the end.
10921   if (VT != MVT::i64) {
10922     MulLHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulLHS);
10923     MulRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulRHS);
10924     AddRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, AddRHS);
10925   }
10926 
10927   // The basic code generated is conceptually straightforward. Pseudo code:
10928   //
10929   //   accum = mad_64_32 lhs.lo, rhs.lo, accum
10930   //   accum.hi = add (mul lhs.hi, rhs.lo), accum.hi
10931   //   accum.hi = add (mul lhs.lo, rhs.hi), accum.hi
10932   //
10933   // The second and third lines are optional, depending on whether the factors
10934   // are {sign,zero}-extended or not.
10935   //
10936   // The actual DAG is noisier than the pseudo code, but only due to
10937   // instructions that disassemble values into low and high parts, and
10938   // assemble the final result.
10939   SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
10940   SDValue One = DAG.getConstant(1, SL, MVT::i32);
10941 
10942   auto MulLHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulLHS);
10943   auto MulRHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulRHS);
10944   SDValue Accum =
10945       getMad64_32(DAG, SL, MVT::i64, MulLHSLo, MulRHSLo, AddRHS, MulSignedLo);
10946 
10947   if (!MulSignedLo && (!MulLHSUnsigned32 || !MulRHSUnsigned32)) {
10948     auto AccumLo = DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, Accum, Zero);
10949     auto AccumHi = DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, Accum, One);
10950 
10951     if (!MulLHSUnsigned32) {
10952       auto MulLHSHi =
10953           DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulLHS, One);
10954       SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSHi, MulRHSLo);
10955       AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi);
10956     }
10957 
10958     if (!MulRHSUnsigned32) {
10959       auto MulRHSHi =
10960           DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulRHS, One);
10961       SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSLo, MulRHSHi);
10962       AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi);
10963     }
10964 
10965     Accum = DAG.getBuildVector(MVT::v2i32, SL, {AccumLo, AccumHi});
10966     Accum = DAG.getBitcast(MVT::i64, Accum);
10967   }
10968 
10969   if (VT != MVT::i64)
10970     Accum = DAG.getNode(ISD::TRUNCATE, SL, VT, Accum);
10971   return Accum;
10972 }
10973 
10974 SDValue SITargetLowering::performAddCombine(SDNode *N,
10975                                             DAGCombinerInfo &DCI) const {
10976   SelectionDAG &DAG = DCI.DAG;
10977   EVT VT = N->getValueType(0);
10978   SDLoc SL(N);
10979   SDValue LHS = N->getOperand(0);
10980   SDValue RHS = N->getOperand(1);
10981 
10982   if (LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) {
10983     if (Subtarget->hasMad64_32()) {
10984       if (SDValue Folded = tryFoldToMad64_32(N, DCI))
10985         return Folded;
10986     }
10987 
10988     return SDValue();
10989   }
10990 
10991   if (SDValue V = reassociateScalarOps(N, DAG)) {
10992     return V;
10993   }
10994 
10995   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10996     return SDValue();
10997 
10998   // add x, zext (setcc) => addcarry x, 0, setcc
10999   // add x, sext (setcc) => subcarry x, 0, setcc
11000   unsigned Opc = LHS.getOpcode();
11001   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
11002       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
11003     std::swap(RHS, LHS);
11004 
11005   Opc = RHS.getOpcode();
11006   switch (Opc) {
11007   default: break;
11008   case ISD::ZERO_EXTEND:
11009   case ISD::SIGN_EXTEND:
11010   case ISD::ANY_EXTEND: {
11011     auto Cond = RHS.getOperand(0);
11012     // If this won't be a real VOPC output, we would still need to insert an
11013     // extra instruction anyway.
11014     if (!isBoolSGPR(Cond))
11015       break;
11016     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
11017     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
11018     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
11019     return DAG.getNode(Opc, SL, VTList, Args);
11020   }
11021   case ISD::ADDCARRY: {
11022     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
11023     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
11024     if (!C || C->getZExtValue() != 0) break;
11025     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
11026     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
11027   }
11028   }
11029   return SDValue();
11030 }
11031 
11032 SDValue SITargetLowering::performSubCombine(SDNode *N,
11033                                             DAGCombinerInfo &DCI) const {
11034   SelectionDAG &DAG = DCI.DAG;
11035   EVT VT = N->getValueType(0);
11036 
11037   if (VT != MVT::i32)
11038     return SDValue();
11039 
11040   SDLoc SL(N);
11041   SDValue LHS = N->getOperand(0);
11042   SDValue RHS = N->getOperand(1);
11043 
11044   // sub x, zext (setcc) => subcarry x, 0, setcc
11045   // sub x, sext (setcc) => addcarry x, 0, setcc
11046   unsigned Opc = RHS.getOpcode();
11047   switch (Opc) {
11048   default: break;
11049   case ISD::ZERO_EXTEND:
11050   case ISD::SIGN_EXTEND:
11051   case ISD::ANY_EXTEND: {
11052     auto Cond = RHS.getOperand(0);
11053     // If this won't be a real VOPC output, we would still need to insert an
11054     // extra instruction anyway.
11055     if (!isBoolSGPR(Cond))
11056       break;
11057     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
11058     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
11059     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
11060     return DAG.getNode(Opc, SL, VTList, Args);
11061   }
11062   }
11063 
11064   if (LHS.getOpcode() == ISD::SUBCARRY) {
11065     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
11066     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
11067     if (!C || !C->isZero())
11068       return SDValue();
11069     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
11070     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
11071   }
11072   return SDValue();
11073 }
11074 
11075 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
11076   DAGCombinerInfo &DCI) const {
11077 
11078   if (N->getValueType(0) != MVT::i32)
11079     return SDValue();
11080 
11081   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11082   if (!C || C->getZExtValue() != 0)
11083     return SDValue();
11084 
11085   SelectionDAG &DAG = DCI.DAG;
11086   SDValue LHS = N->getOperand(0);
11087 
11088   // addcarry (add x, y), 0, cc => addcarry x, y, cc
11089   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
11090   unsigned LHSOpc = LHS.getOpcode();
11091   unsigned Opc = N->getOpcode();
11092   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
11093       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
11094     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
11095     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
11096   }
11097   return SDValue();
11098 }
11099 
11100 SDValue SITargetLowering::performFAddCombine(SDNode *N,
11101                                              DAGCombinerInfo &DCI) const {
11102   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
11103     return SDValue();
11104 
11105   SelectionDAG &DAG = DCI.DAG;
11106   EVT VT = N->getValueType(0);
11107 
11108   SDLoc SL(N);
11109   SDValue LHS = N->getOperand(0);
11110   SDValue RHS = N->getOperand(1);
11111 
11112   // These should really be instruction patterns, but writing patterns with
11113   // source modifiers is a pain.
11114 
11115   // fadd (fadd (a, a), b) -> mad 2.0, a, b
11116   if (LHS.getOpcode() == ISD::FADD) {
11117     SDValue A = LHS.getOperand(0);
11118     if (A == LHS.getOperand(1)) {
11119       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
11120       if (FusedOp != 0) {
11121         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
11122         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
11123       }
11124     }
11125   }
11126 
11127   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
11128   if (RHS.getOpcode() == ISD::FADD) {
11129     SDValue A = RHS.getOperand(0);
11130     if (A == RHS.getOperand(1)) {
11131       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
11132       if (FusedOp != 0) {
11133         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
11134         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
11135       }
11136     }
11137   }
11138 
11139   return SDValue();
11140 }
11141 
11142 SDValue SITargetLowering::performFSubCombine(SDNode *N,
11143                                              DAGCombinerInfo &DCI) const {
11144   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
11145     return SDValue();
11146 
11147   SelectionDAG &DAG = DCI.DAG;
11148   SDLoc SL(N);
11149   EVT VT = N->getValueType(0);
11150   assert(!VT.isVector());
11151 
11152   // Try to get the fneg to fold into the source modifier. This undoes generic
11153   // DAG combines and folds them into the mad.
11154   //
11155   // Only do this if we are not trying to support denormals. v_mad_f32 does
11156   // not support denormals ever.
11157   SDValue LHS = N->getOperand(0);
11158   SDValue RHS = N->getOperand(1);
11159   if (LHS.getOpcode() == ISD::FADD) {
11160     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
11161     SDValue A = LHS.getOperand(0);
11162     if (A == LHS.getOperand(1)) {
11163       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
11164       if (FusedOp != 0){
11165         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
11166         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
11167 
11168         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
11169       }
11170     }
11171   }
11172 
11173   if (RHS.getOpcode() == ISD::FADD) {
11174     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
11175 
11176     SDValue A = RHS.getOperand(0);
11177     if (A == RHS.getOperand(1)) {
11178       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
11179       if (FusedOp != 0){
11180         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
11181         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
11182       }
11183     }
11184   }
11185 
11186   return SDValue();
11187 }
11188 
11189 SDValue SITargetLowering::performFMACombine(SDNode *N,
11190                                             DAGCombinerInfo &DCI) const {
11191   SelectionDAG &DAG = DCI.DAG;
11192   EVT VT = N->getValueType(0);
11193   SDLoc SL(N);
11194 
11195   if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
11196     return SDValue();
11197 
11198   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
11199   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
11200   SDValue Op1 = N->getOperand(0);
11201   SDValue Op2 = N->getOperand(1);
11202   SDValue FMA = N->getOperand(2);
11203 
11204   if (FMA.getOpcode() != ISD::FMA ||
11205       Op1.getOpcode() != ISD::FP_EXTEND ||
11206       Op2.getOpcode() != ISD::FP_EXTEND)
11207     return SDValue();
11208 
11209   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
11210   // regardless of the denorm mode setting. Therefore,
11211   // unsafe-fp-math/fp-contract is sufficient to allow generating fdot2.
11212   const TargetOptions &Options = DAG.getTarget().Options;
11213   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
11214       (N->getFlags().hasAllowContract() &&
11215        FMA->getFlags().hasAllowContract())) {
11216     Op1 = Op1.getOperand(0);
11217     Op2 = Op2.getOperand(0);
11218     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11219         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11220       return SDValue();
11221 
11222     SDValue Vec1 = Op1.getOperand(0);
11223     SDValue Idx1 = Op1.getOperand(1);
11224     SDValue Vec2 = Op2.getOperand(0);
11225 
11226     SDValue FMAOp1 = FMA.getOperand(0);
11227     SDValue FMAOp2 = FMA.getOperand(1);
11228     SDValue FMAAcc = FMA.getOperand(2);
11229 
11230     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
11231         FMAOp2.getOpcode() != ISD::FP_EXTEND)
11232       return SDValue();
11233 
11234     FMAOp1 = FMAOp1.getOperand(0);
11235     FMAOp2 = FMAOp2.getOperand(0);
11236     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11237         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11238       return SDValue();
11239 
11240     SDValue Vec3 = FMAOp1.getOperand(0);
11241     SDValue Vec4 = FMAOp2.getOperand(0);
11242     SDValue Idx2 = FMAOp1.getOperand(1);
11243 
11244     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
11245         // Idx1 and Idx2 cannot be the same.
11246         Idx1 == Idx2)
11247       return SDValue();
11248 
11249     if (Vec1 == Vec2 || Vec3 == Vec4)
11250       return SDValue();
11251 
11252     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
11253       return SDValue();
11254 
11255     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
11256         (Vec1 == Vec4 && Vec2 == Vec3)) {
11257       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
11258                          DAG.getTargetConstant(0, SL, MVT::i1));
11259     }
11260   }
11261   return SDValue();
11262 }
11263 
11264 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
11265                                               DAGCombinerInfo &DCI) const {
11266   SelectionDAG &DAG = DCI.DAG;
11267   SDLoc SL(N);
11268 
11269   SDValue LHS = N->getOperand(0);
11270   SDValue RHS = N->getOperand(1);
11271   EVT VT = LHS.getValueType();
11272   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
11273 
11274   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
11275   if (!CRHS) {
11276     CRHS = dyn_cast<ConstantSDNode>(LHS);
11277     if (CRHS) {
11278       std::swap(LHS, RHS);
11279       CC = getSetCCSwappedOperands(CC);
11280     }
11281   }
11282 
11283   if (CRHS) {
11284     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
11285         isBoolSGPR(LHS.getOperand(0))) {
11286       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
11287       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
11288       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
11289       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
11290       if ((CRHS->isAllOnes() &&
11291            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
11292           (CRHS->isZero() &&
11293            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
11294         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
11295                            DAG.getConstant(-1, SL, MVT::i1));
11296       if ((CRHS->isAllOnes() &&
11297            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
11298           (CRHS->isZero() &&
11299            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
11300         return LHS.getOperand(0);
11301     }
11302 
11303     const APInt &CRHSVal = CRHS->getAPIntValue();
11304     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
11305         LHS.getOpcode() == ISD::SELECT &&
11306         isa<ConstantSDNode>(LHS.getOperand(1)) &&
11307         isa<ConstantSDNode>(LHS.getOperand(2)) &&
11308         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
11309         isBoolSGPR(LHS.getOperand(0))) {
11310       // Given CT != FT:
11311       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
11312       // setcc (select cc, CT, CF), CF, ne => cc
11313       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
11314       // setcc (select cc, CT, CF), CT, eq => cc
11315       const APInt &CT = LHS.getConstantOperandAPInt(1);
11316       const APInt &CF = LHS.getConstantOperandAPInt(2);
11317 
11318       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
11319           (CT == CRHSVal && CC == ISD::SETNE))
11320         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
11321                            DAG.getConstant(-1, SL, MVT::i1));
11322       if ((CF == CRHSVal && CC == ISD::SETNE) ||
11323           (CT == CRHSVal && CC == ISD::SETEQ))
11324         return LHS.getOperand(0);
11325     }
11326   }
11327 
11328   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
11329                                            VT != MVT::f16))
11330     return SDValue();
11331 
11332   // Match isinf/isfinite pattern
11333   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
11334   // (fcmp one (fabs x), inf) -> (fp_class x,
11335   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
11336   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
11337     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
11338     if (!CRHS)
11339       return SDValue();
11340 
11341     const APFloat &APF = CRHS->getValueAPF();
11342     if (APF.isInfinity() && !APF.isNegative()) {
11343       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
11344                                  SIInstrFlags::N_INFINITY;
11345       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
11346                                     SIInstrFlags::P_ZERO |
11347                                     SIInstrFlags::N_NORMAL |
11348                                     SIInstrFlags::P_NORMAL |
11349                                     SIInstrFlags::N_SUBNORMAL |
11350                                     SIInstrFlags::P_SUBNORMAL;
11351       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
11352       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
11353                          DAG.getConstant(Mask, SL, MVT::i32));
11354     }
11355   }
11356 
11357   return SDValue();
11358 }
11359 
11360 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
11361                                                      DAGCombinerInfo &DCI) const {
11362   SelectionDAG &DAG = DCI.DAG;
11363   SDLoc SL(N);
11364   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
11365 
11366   SDValue Src = N->getOperand(0);
11367   SDValue Shift = N->getOperand(0);
11368 
11369   // TODO: Extend type shouldn't matter (assuming legal types).
11370   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
11371     Shift = Shift.getOperand(0);
11372 
11373   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
11374     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
11375     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
11376     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
11377     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
11378     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
11379     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
11380       SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0),
11381                                  SDLoc(Shift.getOperand(0)), MVT::i32);
11382 
11383       unsigned ShiftOffset = 8 * Offset;
11384       if (Shift.getOpcode() == ISD::SHL)
11385         ShiftOffset -= C->getZExtValue();
11386       else
11387         ShiftOffset += C->getZExtValue();
11388 
11389       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
11390         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
11391                            MVT::f32, Shifted);
11392       }
11393     }
11394   }
11395 
11396   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11397   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
11398   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
11399     // We simplified Src. If this node is not dead, visit it again so it is
11400     // folded properly.
11401     if (N->getOpcode() != ISD::DELETED_NODE)
11402       DCI.AddToWorklist(N);
11403     return SDValue(N, 0);
11404   }
11405 
11406   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
11407   if (SDValue DemandedSrc =
11408           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
11409     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
11410 
11411   return SDValue();
11412 }
11413 
11414 SDValue SITargetLowering::performClampCombine(SDNode *N,
11415                                               DAGCombinerInfo &DCI) const {
11416   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
11417   if (!CSrc)
11418     return SDValue();
11419 
11420   const MachineFunction &MF = DCI.DAG.getMachineFunction();
11421   const APFloat &F = CSrc->getValueAPF();
11422   APFloat Zero = APFloat::getZero(F.getSemantics());
11423   if (F < Zero ||
11424       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
11425     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
11426   }
11427 
11428   APFloat One(F.getSemantics(), "1.0");
11429   if (F > One)
11430     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
11431 
11432   return SDValue(CSrc, 0);
11433 }
11434 
11435 
11436 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
11437                                             DAGCombinerInfo &DCI) const {
11438   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
11439     return SDValue();
11440   switch (N->getOpcode()) {
11441   case ISD::ADD:
11442     return performAddCombine(N, DCI);
11443   case ISD::SUB:
11444     return performSubCombine(N, DCI);
11445   case ISD::ADDCARRY:
11446   case ISD::SUBCARRY:
11447     return performAddCarrySubCarryCombine(N, DCI);
11448   case ISD::FADD:
11449     return performFAddCombine(N, DCI);
11450   case ISD::FSUB:
11451     return performFSubCombine(N, DCI);
11452   case ISD::SETCC:
11453     return performSetCCCombine(N, DCI);
11454   case ISD::FMAXNUM:
11455   case ISD::FMINNUM:
11456   case ISD::FMAXNUM_IEEE:
11457   case ISD::FMINNUM_IEEE:
11458   case ISD::SMAX:
11459   case ISD::SMIN:
11460   case ISD::UMAX:
11461   case ISD::UMIN:
11462   case AMDGPUISD::FMIN_LEGACY:
11463   case AMDGPUISD::FMAX_LEGACY:
11464     return performMinMaxCombine(N, DCI);
11465   case ISD::FMA:
11466     return performFMACombine(N, DCI);
11467   case ISD::AND:
11468     return performAndCombine(N, DCI);
11469   case ISD::OR:
11470     return performOrCombine(N, DCI);
11471   case ISD::XOR:
11472     return performXorCombine(N, DCI);
11473   case ISD::ZERO_EXTEND:
11474     return performZeroExtendCombine(N, DCI);
11475   case ISD::SIGN_EXTEND_INREG:
11476     return performSignExtendInRegCombine(N , DCI);
11477   case AMDGPUISD::FP_CLASS:
11478     return performClassCombine(N, DCI);
11479   case ISD::FCANONICALIZE:
11480     return performFCanonicalizeCombine(N, DCI);
11481   case AMDGPUISD::RCP:
11482     return performRcpCombine(N, DCI);
11483   case AMDGPUISD::FRACT:
11484   case AMDGPUISD::RSQ:
11485   case AMDGPUISD::RCP_LEGACY:
11486   case AMDGPUISD::RCP_IFLAG:
11487   case AMDGPUISD::RSQ_CLAMP:
11488   case AMDGPUISD::LDEXP: {
11489     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
11490     SDValue Src = N->getOperand(0);
11491     if (Src.isUndef())
11492       return Src;
11493     break;
11494   }
11495   case ISD::SINT_TO_FP:
11496   case ISD::UINT_TO_FP:
11497     return performUCharToFloatCombine(N, DCI);
11498   case AMDGPUISD::CVT_F32_UBYTE0:
11499   case AMDGPUISD::CVT_F32_UBYTE1:
11500   case AMDGPUISD::CVT_F32_UBYTE2:
11501   case AMDGPUISD::CVT_F32_UBYTE3:
11502     return performCvtF32UByteNCombine(N, DCI);
11503   case AMDGPUISD::FMED3:
11504     return performFMed3Combine(N, DCI);
11505   case AMDGPUISD::CVT_PKRTZ_F16_F32:
11506     return performCvtPkRTZCombine(N, DCI);
11507   case AMDGPUISD::CLAMP:
11508     return performClampCombine(N, DCI);
11509   case ISD::SCALAR_TO_VECTOR: {
11510     SelectionDAG &DAG = DCI.DAG;
11511     EVT VT = N->getValueType(0);
11512 
11513     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
11514     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
11515       SDLoc SL(N);
11516       SDValue Src = N->getOperand(0);
11517       EVT EltVT = Src.getValueType();
11518       if (EltVT == MVT::f16)
11519         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
11520 
11521       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
11522       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
11523     }
11524 
11525     break;
11526   }
11527   case ISD::EXTRACT_VECTOR_ELT:
11528     return performExtractVectorEltCombine(N, DCI);
11529   case ISD::INSERT_VECTOR_ELT:
11530     return performInsertVectorEltCombine(N, DCI);
11531   case ISD::LOAD: {
11532     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
11533       return Widended;
11534     LLVM_FALLTHROUGH;
11535   }
11536   default: {
11537     if (!DCI.isBeforeLegalize()) {
11538       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
11539         return performMemSDNodeCombine(MemNode, DCI);
11540     }
11541 
11542     break;
11543   }
11544   }
11545 
11546   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
11547 }
11548 
11549 /// Helper function for adjustWritemask
11550 static unsigned SubIdx2Lane(unsigned Idx) {
11551   switch (Idx) {
11552   default: return ~0u;
11553   case AMDGPU::sub0: return 0;
11554   case AMDGPU::sub1: return 1;
11555   case AMDGPU::sub2: return 2;
11556   case AMDGPU::sub3: return 3;
11557   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
11558   }
11559 }
11560 
11561 /// Adjust the writemask of MIMG instructions
11562 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
11563                                           SelectionDAG &DAG) const {
11564   unsigned Opcode = Node->getMachineOpcode();
11565 
11566   // Subtract 1 because the vdata output is not a MachineSDNode operand.
11567   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
11568   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
11569     return Node; // not implemented for D16
11570 
11571   SDNode *Users[5] = { nullptr };
11572   unsigned Lane = 0;
11573   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
11574   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
11575   unsigned NewDmask = 0;
11576   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
11577   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
11578   bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
11579                   Node->getConstantOperandVal(LWEIdx))
11580                      ? true
11581                      : false;
11582   unsigned TFCLane = 0;
11583   bool HasChain = Node->getNumValues() > 1;
11584 
11585   if (OldDmask == 0) {
11586     // These are folded out, but on the chance it happens don't assert.
11587     return Node;
11588   }
11589 
11590   unsigned OldBitsSet = countPopulation(OldDmask);
11591   // Work out which is the TFE/LWE lane if that is enabled.
11592   if (UsesTFC) {
11593     TFCLane = OldBitsSet;
11594   }
11595 
11596   // Try to figure out the used register components
11597   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
11598        I != E; ++I) {
11599 
11600     // Don't look at users of the chain.
11601     if (I.getUse().getResNo() != 0)
11602       continue;
11603 
11604     // Abort if we can't understand the usage
11605     if (!I->isMachineOpcode() ||
11606         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
11607       return Node;
11608 
11609     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
11610     // Note that subregs are packed, i.e. Lane==0 is the first bit set
11611     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
11612     // set, etc.
11613     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
11614     if (Lane == ~0u)
11615       return Node;
11616 
11617     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
11618     if (UsesTFC && Lane == TFCLane) {
11619       Users[Lane] = *I;
11620     } else {
11621       // Set which texture component corresponds to the lane.
11622       unsigned Comp;
11623       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
11624         Comp = countTrailingZeros(Dmask);
11625         Dmask &= ~(1 << Comp);
11626       }
11627 
11628       // Abort if we have more than one user per component.
11629       if (Users[Lane])
11630         return Node;
11631 
11632       Users[Lane] = *I;
11633       NewDmask |= 1 << Comp;
11634     }
11635   }
11636 
11637   // Don't allow 0 dmask, as hardware assumes one channel enabled.
11638   bool NoChannels = !NewDmask;
11639   if (NoChannels) {
11640     if (!UsesTFC) {
11641       // No uses of the result and not using TFC. Then do nothing.
11642       return Node;
11643     }
11644     // If the original dmask has one channel - then nothing to do
11645     if (OldBitsSet == 1)
11646       return Node;
11647     // Use an arbitrary dmask - required for the instruction to work
11648     NewDmask = 1;
11649   }
11650   // Abort if there's no change
11651   if (NewDmask == OldDmask)
11652     return Node;
11653 
11654   unsigned BitsSet = countPopulation(NewDmask);
11655 
11656   // Check for TFE or LWE - increase the number of channels by one to account
11657   // for the extra return value
11658   // This will need adjustment for D16 if this is also included in
11659   // adjustWriteMask (this function) but at present D16 are excluded.
11660   unsigned NewChannels = BitsSet + UsesTFC;
11661 
11662   int NewOpcode =
11663       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
11664   assert(NewOpcode != -1 &&
11665          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
11666          "failed to find equivalent MIMG op");
11667 
11668   // Adjust the writemask in the node
11669   SmallVector<SDValue, 12> Ops;
11670   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
11671   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
11672   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11673 
11674   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11675 
11676   MVT ResultVT = NewChannels == 1 ?
11677     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11678                            NewChannels == 5 ? 8 : NewChannels);
11679   SDVTList NewVTList = HasChain ?
11680     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11681 
11682 
11683   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11684                                               NewVTList, Ops);
11685 
11686   if (HasChain) {
11687     // Update chain.
11688     DAG.setNodeMemRefs(NewNode, Node->memoperands());
11689     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11690   }
11691 
11692   if (NewChannels == 1) {
11693     assert(Node->hasNUsesOfValue(1, 0));
11694     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11695                                       SDLoc(Node), Users[Lane]->getValueType(0),
11696                                       SDValue(NewNode, 0));
11697     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11698     return nullptr;
11699   }
11700 
11701   // Update the users of the node with the new indices
11702   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11703     SDNode *User = Users[i];
11704     if (!User) {
11705       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11706       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11707       if (i || !NoChannels)
11708         continue;
11709     } else {
11710       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11711       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11712     }
11713 
11714     switch (Idx) {
11715     default: break;
11716     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11717     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11718     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11719     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11720     }
11721   }
11722 
11723   DAG.RemoveDeadNode(Node);
11724   return nullptr;
11725 }
11726 
11727 static bool isFrameIndexOp(SDValue Op) {
11728   if (Op.getOpcode() == ISD::AssertZext)
11729     Op = Op.getOperand(0);
11730 
11731   return isa<FrameIndexSDNode>(Op);
11732 }
11733 
11734 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11735 /// with frame index operands.
11736 /// LLVM assumes that inputs are to these instructions are registers.
11737 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11738                                                         SelectionDAG &DAG) const {
11739   if (Node->getOpcode() == ISD::CopyToReg) {
11740     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11741     SDValue SrcVal = Node->getOperand(2);
11742 
11743     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11744     // to try understanding copies to physical registers.
11745     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11746       SDLoc SL(Node);
11747       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11748       SDValue VReg = DAG.getRegister(
11749         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11750 
11751       SDNode *Glued = Node->getGluedNode();
11752       SDValue ToVReg
11753         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11754                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11755       SDValue ToResultReg
11756         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11757                            VReg, ToVReg.getValue(1));
11758       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11759       DAG.RemoveDeadNode(Node);
11760       return ToResultReg.getNode();
11761     }
11762   }
11763 
11764   SmallVector<SDValue, 8> Ops;
11765   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11766     if (!isFrameIndexOp(Node->getOperand(i))) {
11767       Ops.push_back(Node->getOperand(i));
11768       continue;
11769     }
11770 
11771     SDLoc DL(Node);
11772     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11773                                      Node->getOperand(i).getValueType(),
11774                                      Node->getOperand(i)), 0));
11775   }
11776 
11777   return DAG.UpdateNodeOperands(Node, Ops);
11778 }
11779 
11780 /// Fold the instructions after selecting them.
11781 /// Returns null if users were already updated.
11782 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11783                                           SelectionDAG &DAG) const {
11784   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11785   unsigned Opcode = Node->getMachineOpcode();
11786 
11787   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11788       !TII->isGather4(Opcode) &&
11789       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11790     return adjustWritemask(Node, DAG);
11791   }
11792 
11793   if (Opcode == AMDGPU::INSERT_SUBREG ||
11794       Opcode == AMDGPU::REG_SEQUENCE) {
11795     legalizeTargetIndependentNode(Node, DAG);
11796     return Node;
11797   }
11798 
11799   switch (Opcode) {
11800   case AMDGPU::V_DIV_SCALE_F32_e64:
11801   case AMDGPU::V_DIV_SCALE_F64_e64: {
11802     // Satisfy the operand register constraint when one of the inputs is
11803     // undefined. Ordinarily each undef value will have its own implicit_def of
11804     // a vreg, so force these to use a single register.
11805     SDValue Src0 = Node->getOperand(1);
11806     SDValue Src1 = Node->getOperand(3);
11807     SDValue Src2 = Node->getOperand(5);
11808 
11809     if ((Src0.isMachineOpcode() &&
11810          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11811         (Src0 == Src1 || Src0 == Src2))
11812       break;
11813 
11814     MVT VT = Src0.getValueType().getSimpleVT();
11815     const TargetRegisterClass *RC =
11816         getRegClassFor(VT, Src0.getNode()->isDivergent());
11817 
11818     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11819     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11820 
11821     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11822                                       UndefReg, Src0, SDValue());
11823 
11824     // src0 must be the same register as src1 or src2, even if the value is
11825     // undefined, so make sure we don't violate this constraint.
11826     if (Src0.isMachineOpcode() &&
11827         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11828       if (Src1.isMachineOpcode() &&
11829           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11830         Src0 = Src1;
11831       else if (Src2.isMachineOpcode() &&
11832                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11833         Src0 = Src2;
11834       else {
11835         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11836         Src0 = UndefReg;
11837         Src1 = UndefReg;
11838       }
11839     } else
11840       break;
11841 
11842     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11843     Ops[1] = Src0;
11844     Ops[3] = Src1;
11845     Ops[5] = Src2;
11846     Ops.push_back(ImpDef.getValue(1));
11847     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11848   }
11849   default:
11850     break;
11851   }
11852 
11853   return Node;
11854 }
11855 
11856 // Any MIMG instructions that use tfe or lwe require an initialization of the
11857 // result register that will be written in the case of a memory access failure.
11858 // The required code is also added to tie this init code to the result of the
11859 // img instruction.
11860 void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
11861   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11862   const SIRegisterInfo &TRI = TII->getRegisterInfo();
11863   MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11864   MachineBasicBlock &MBB = *MI.getParent();
11865 
11866   MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
11867   MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
11868   MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
11869 
11870   if (!TFE && !LWE) // intersect_ray
11871     return;
11872 
11873   unsigned TFEVal = TFE ? TFE->getImm() : 0;
11874   unsigned LWEVal = LWE->getImm();
11875   unsigned D16Val = D16 ? D16->getImm() : 0;
11876 
11877   if (!TFEVal && !LWEVal)
11878     return;
11879 
11880   // At least one of TFE or LWE are non-zero
11881   // We have to insert a suitable initialization of the result value and
11882   // tie this to the dest of the image instruction.
11883 
11884   const DebugLoc &DL = MI.getDebugLoc();
11885 
11886   int DstIdx =
11887       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
11888 
11889   // Calculate which dword we have to initialize to 0.
11890   MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
11891 
11892   // check that dmask operand is found.
11893   assert(MO_Dmask && "Expected dmask operand in instruction");
11894 
11895   unsigned dmask = MO_Dmask->getImm();
11896   // Determine the number of active lanes taking into account the
11897   // Gather4 special case
11898   unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask);
11899 
11900   bool Packed = !Subtarget->hasUnpackedD16VMem();
11901 
11902   unsigned InitIdx =
11903       D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
11904 
11905   // Abandon attempt if the dst size isn't large enough
11906   // - this is in fact an error but this is picked up elsewhere and
11907   // reported correctly.
11908   uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
11909   if (DstSize < InitIdx)
11910     return;
11911 
11912   // Create a register for the initialization value.
11913   Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11914   unsigned NewDst = 0; // Final initialized value will be in here
11915 
11916   // If PRTStrictNull feature is enabled (the default) then initialize
11917   // all the result registers to 0, otherwise just the error indication
11918   // register (VGPRn+1)
11919   unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
11920   unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
11921 
11922   BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
11923   for (; SizeLeft; SizeLeft--, CurrIdx++) {
11924     NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11925     // Initialize dword
11926     Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
11927     BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
11928       .addImm(0);
11929     // Insert into the super-reg
11930     BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
11931       .addReg(PrevDst)
11932       .addReg(SubReg)
11933       .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
11934 
11935     PrevDst = NewDst;
11936   }
11937 
11938   // Add as an implicit operand
11939   MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
11940 
11941   // Tie the just added implicit operand to the dst
11942   MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
11943 }
11944 
11945 /// Assign the register class depending on the number of
11946 /// bits set in the writemask
11947 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11948                                                      SDNode *Node) const {
11949   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11950 
11951   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11952 
11953   if (TII->isVOP3(MI.getOpcode())) {
11954     // Make sure constant bus requirements are respected.
11955     TII->legalizeOperandsVOP3(MRI, MI);
11956 
11957     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11958     // This saves a chain-copy of registers and better balance register
11959     // use between vgpr and agpr as agpr tuples tend to be big.
11960     if (MI.getDesc().OpInfo) {
11961       unsigned Opc = MI.getOpcode();
11962       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11963       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11964                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11965         if (I == -1)
11966           break;
11967         MachineOperand &Op = MI.getOperand(I);
11968         if (!Op.isReg() || !Op.getReg().isVirtual())
11969           continue;
11970         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11971         if (!TRI->hasAGPRs(RC))
11972           continue;
11973         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11974         if (!Src || !Src->isCopy() ||
11975             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11976           continue;
11977         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11978         // All uses of agpr64 and agpr32 can also accept vgpr except for
11979         // v_accvgpr_read, but we do not produce agpr reads during selection,
11980         // so no use checks are needed.
11981         MRI.setRegClass(Op.getReg(), NewRC);
11982       }
11983 
11984       // Resolve the rest of AV operands to AGPRs.
11985       if (auto *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2)) {
11986         if (Src2->isReg() && Src2->getReg().isVirtual()) {
11987           auto *RC = TRI->getRegClassForReg(MRI, Src2->getReg());
11988           if (TRI->isVectorSuperClass(RC)) {
11989             auto *NewRC = TRI->getEquivalentAGPRClass(RC);
11990             MRI.setRegClass(Src2->getReg(), NewRC);
11991             if (Src2->isTied())
11992               MRI.setRegClass(MI.getOperand(0).getReg(), NewRC);
11993           }
11994         }
11995       }
11996     }
11997 
11998     return;
11999   }
12000 
12001   if (TII->isMIMG(MI)) {
12002     if (!MI.mayStore())
12003       AddIMGInit(MI);
12004     TII->enforceOperandRCAlignment(MI, AMDGPU::OpName::vaddr);
12005   }
12006 }
12007 
12008 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
12009                               uint64_t Val) {
12010   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
12011   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
12012 }
12013 
12014 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
12015                                                 const SDLoc &DL,
12016                                                 SDValue Ptr) const {
12017   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12018 
12019   // Build the half of the subregister with the constants before building the
12020   // full 128-bit register. If we are building multiple resource descriptors,
12021   // this will allow CSEing of the 2-component register.
12022   const SDValue Ops0[] = {
12023     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
12024     buildSMovImm32(DAG, DL, 0),
12025     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
12026     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
12027     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
12028   };
12029 
12030   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
12031                                                 MVT::v2i32, Ops0), 0);
12032 
12033   // Combine the constants and the pointer.
12034   const SDValue Ops1[] = {
12035     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
12036     Ptr,
12037     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
12038     SubRegHi,
12039     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
12040   };
12041 
12042   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
12043 }
12044 
12045 /// Return a resource descriptor with the 'Add TID' bit enabled
12046 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
12047 ///        of the resource descriptor) to create an offset, which is added to
12048 ///        the resource pointer.
12049 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
12050                                            SDValue Ptr, uint32_t RsrcDword1,
12051                                            uint64_t RsrcDword2And3) const {
12052   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
12053   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
12054   if (RsrcDword1) {
12055     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
12056                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
12057                     0);
12058   }
12059 
12060   SDValue DataLo = buildSMovImm32(DAG, DL,
12061                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
12062   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
12063 
12064   const SDValue Ops[] = {
12065     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
12066     PtrLo,
12067     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
12068     PtrHi,
12069     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
12070     DataLo,
12071     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
12072     DataHi,
12073     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
12074   };
12075 
12076   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
12077 }
12078 
12079 //===----------------------------------------------------------------------===//
12080 //                         SI Inline Assembly Support
12081 //===----------------------------------------------------------------------===//
12082 
12083 std::pair<unsigned, const TargetRegisterClass *>
12084 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
12085                                                StringRef Constraint,
12086                                                MVT VT) const {
12087   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
12088 
12089   const TargetRegisterClass *RC = nullptr;
12090   if (Constraint.size() == 1) {
12091     const unsigned BitWidth = VT.getSizeInBits();
12092     switch (Constraint[0]) {
12093     default:
12094       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
12095     case 's':
12096     case 'r':
12097       switch (BitWidth) {
12098       case 16:
12099         RC = &AMDGPU::SReg_32RegClass;
12100         break;
12101       case 64:
12102         RC = &AMDGPU::SGPR_64RegClass;
12103         break;
12104       default:
12105         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
12106         if (!RC)
12107           return std::make_pair(0U, nullptr);
12108         break;
12109       }
12110       break;
12111     case 'v':
12112       switch (BitWidth) {
12113       case 16:
12114         RC = &AMDGPU::VGPR_32RegClass;
12115         break;
12116       default:
12117         RC = TRI->getVGPRClassForBitWidth(BitWidth);
12118         if (!RC)
12119           return std::make_pair(0U, nullptr);
12120         break;
12121       }
12122       break;
12123     case 'a':
12124       if (!Subtarget->hasMAIInsts())
12125         break;
12126       switch (BitWidth) {
12127       case 16:
12128         RC = &AMDGPU::AGPR_32RegClass;
12129         break;
12130       default:
12131         RC = TRI->getAGPRClassForBitWidth(BitWidth);
12132         if (!RC)
12133           return std::make_pair(0U, nullptr);
12134         break;
12135       }
12136       break;
12137     }
12138     // We actually support i128, i16 and f16 as inline parameters
12139     // even if they are not reported as legal
12140     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
12141                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
12142       return std::make_pair(0U, RC);
12143   }
12144 
12145   if (Constraint.startswith("{") && Constraint.endswith("}")) {
12146     StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
12147     if (RegName.consume_front("v")) {
12148       RC = &AMDGPU::VGPR_32RegClass;
12149     } else if (RegName.consume_front("s")) {
12150       RC = &AMDGPU::SGPR_32RegClass;
12151     } else if (RegName.consume_front("a")) {
12152       RC = &AMDGPU::AGPR_32RegClass;
12153     }
12154 
12155     if (RC) {
12156       uint32_t Idx;
12157       if (RegName.consume_front("[")) {
12158         uint32_t End;
12159         bool Failed = RegName.consumeInteger(10, Idx);
12160         Failed |= !RegName.consume_front(":");
12161         Failed |= RegName.consumeInteger(10, End);
12162         Failed |= !RegName.consume_back("]");
12163         if (!Failed) {
12164           uint32_t Width = (End - Idx + 1) * 32;
12165           MCRegister Reg = RC->getRegister(Idx);
12166           if (SIRegisterInfo::isVGPRClass(RC))
12167             RC = TRI->getVGPRClassForBitWidth(Width);
12168           else if (SIRegisterInfo::isSGPRClass(RC))
12169             RC = TRI->getSGPRClassForBitWidth(Width);
12170           else if (SIRegisterInfo::isAGPRClass(RC))
12171             RC = TRI->getAGPRClassForBitWidth(Width);
12172           if (RC) {
12173             Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC);
12174             return std::make_pair(Reg, RC);
12175           }
12176         }
12177       } else {
12178         bool Failed = RegName.getAsInteger(10, Idx);
12179         if (!Failed && Idx < RC->getNumRegs())
12180           return std::make_pair(RC->getRegister(Idx), RC);
12181       }
12182     }
12183   }
12184 
12185   auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
12186   if (Ret.first)
12187     Ret.second = TRI->getPhysRegClass(Ret.first);
12188 
12189   return Ret;
12190 }
12191 
12192 static bool isImmConstraint(StringRef Constraint) {
12193   if (Constraint.size() == 1) {
12194     switch (Constraint[0]) {
12195     default: break;
12196     case 'I':
12197     case 'J':
12198     case 'A':
12199     case 'B':
12200     case 'C':
12201       return true;
12202     }
12203   } else if (Constraint == "DA" ||
12204              Constraint == "DB") {
12205     return true;
12206   }
12207   return false;
12208 }
12209 
12210 SITargetLowering::ConstraintType
12211 SITargetLowering::getConstraintType(StringRef Constraint) const {
12212   if (Constraint.size() == 1) {
12213     switch (Constraint[0]) {
12214     default: break;
12215     case 's':
12216     case 'v':
12217     case 'a':
12218       return C_RegisterClass;
12219     }
12220   }
12221   if (isImmConstraint(Constraint)) {
12222     return C_Other;
12223   }
12224   return TargetLowering::getConstraintType(Constraint);
12225 }
12226 
12227 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
12228   if (!AMDGPU::isInlinableIntLiteral(Val)) {
12229     Val = Val & maskTrailingOnes<uint64_t>(Size);
12230   }
12231   return Val;
12232 }
12233 
12234 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12235                                                     std::string &Constraint,
12236                                                     std::vector<SDValue> &Ops,
12237                                                     SelectionDAG &DAG) const {
12238   if (isImmConstraint(Constraint)) {
12239     uint64_t Val;
12240     if (getAsmOperandConstVal(Op, Val) &&
12241         checkAsmConstraintVal(Op, Constraint, Val)) {
12242       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
12243       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
12244     }
12245   } else {
12246     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12247   }
12248 }
12249 
12250 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
12251   unsigned Size = Op.getScalarValueSizeInBits();
12252   if (Size > 64)
12253     return false;
12254 
12255   if (Size == 16 && !Subtarget->has16BitInsts())
12256     return false;
12257 
12258   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12259     Val = C->getSExtValue();
12260     return true;
12261   }
12262   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
12263     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
12264     return true;
12265   }
12266   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
12267     if (Size != 16 || Op.getNumOperands() != 2)
12268       return false;
12269     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
12270       return false;
12271     if (ConstantSDNode *C = V->getConstantSplatNode()) {
12272       Val = C->getSExtValue();
12273       return true;
12274     }
12275     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
12276       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
12277       return true;
12278     }
12279   }
12280 
12281   return false;
12282 }
12283 
12284 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
12285                                              const std::string &Constraint,
12286                                              uint64_t Val) const {
12287   if (Constraint.size() == 1) {
12288     switch (Constraint[0]) {
12289     case 'I':
12290       return AMDGPU::isInlinableIntLiteral(Val);
12291     case 'J':
12292       return isInt<16>(Val);
12293     case 'A':
12294       return checkAsmConstraintValA(Op, Val);
12295     case 'B':
12296       return isInt<32>(Val);
12297     case 'C':
12298       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
12299              AMDGPU::isInlinableIntLiteral(Val);
12300     default:
12301       break;
12302     }
12303   } else if (Constraint.size() == 2) {
12304     if (Constraint == "DA") {
12305       int64_t HiBits = static_cast<int32_t>(Val >> 32);
12306       int64_t LoBits = static_cast<int32_t>(Val);
12307       return checkAsmConstraintValA(Op, HiBits, 32) &&
12308              checkAsmConstraintValA(Op, LoBits, 32);
12309     }
12310     if (Constraint == "DB") {
12311       return true;
12312     }
12313   }
12314   llvm_unreachable("Invalid asm constraint");
12315 }
12316 
12317 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
12318                                               uint64_t Val,
12319                                               unsigned MaxSize) const {
12320   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
12321   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
12322   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
12323       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
12324       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
12325     return true;
12326   }
12327   return false;
12328 }
12329 
12330 static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
12331   switch (UnalignedClassID) {
12332   case AMDGPU::VReg_64RegClassID:
12333     return AMDGPU::VReg_64_Align2RegClassID;
12334   case AMDGPU::VReg_96RegClassID:
12335     return AMDGPU::VReg_96_Align2RegClassID;
12336   case AMDGPU::VReg_128RegClassID:
12337     return AMDGPU::VReg_128_Align2RegClassID;
12338   case AMDGPU::VReg_160RegClassID:
12339     return AMDGPU::VReg_160_Align2RegClassID;
12340   case AMDGPU::VReg_192RegClassID:
12341     return AMDGPU::VReg_192_Align2RegClassID;
12342   case AMDGPU::VReg_224RegClassID:
12343     return AMDGPU::VReg_224_Align2RegClassID;
12344   case AMDGPU::VReg_256RegClassID:
12345     return AMDGPU::VReg_256_Align2RegClassID;
12346   case AMDGPU::VReg_512RegClassID:
12347     return AMDGPU::VReg_512_Align2RegClassID;
12348   case AMDGPU::VReg_1024RegClassID:
12349     return AMDGPU::VReg_1024_Align2RegClassID;
12350   case AMDGPU::AReg_64RegClassID:
12351     return AMDGPU::AReg_64_Align2RegClassID;
12352   case AMDGPU::AReg_96RegClassID:
12353     return AMDGPU::AReg_96_Align2RegClassID;
12354   case AMDGPU::AReg_128RegClassID:
12355     return AMDGPU::AReg_128_Align2RegClassID;
12356   case AMDGPU::AReg_160RegClassID:
12357     return AMDGPU::AReg_160_Align2RegClassID;
12358   case AMDGPU::AReg_192RegClassID:
12359     return AMDGPU::AReg_192_Align2RegClassID;
12360   case AMDGPU::AReg_256RegClassID:
12361     return AMDGPU::AReg_256_Align2RegClassID;
12362   case AMDGPU::AReg_512RegClassID:
12363     return AMDGPU::AReg_512_Align2RegClassID;
12364   case AMDGPU::AReg_1024RegClassID:
12365     return AMDGPU::AReg_1024_Align2RegClassID;
12366   default:
12367     return -1;
12368   }
12369 }
12370 
12371 // Figure out which registers should be reserved for stack access. Only after
12372 // the function is legalized do we know all of the non-spill stack objects or if
12373 // calls are present.
12374 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
12375   MachineRegisterInfo &MRI = MF.getRegInfo();
12376   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12377   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
12378   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12379   const SIInstrInfo *TII = ST.getInstrInfo();
12380 
12381   if (Info->isEntryFunction()) {
12382     // Callable functions have fixed registers used for stack access.
12383     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
12384   }
12385 
12386   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
12387                              Info->getStackPtrOffsetReg()));
12388   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
12389     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
12390 
12391   // We need to worry about replacing the default register with itself in case
12392   // of MIR testcases missing the MFI.
12393   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
12394     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
12395 
12396   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
12397     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
12398 
12399   Info->limitOccupancy(MF);
12400 
12401   if (ST.isWave32() && !MF.empty()) {
12402     for (auto &MBB : MF) {
12403       for (auto &MI : MBB) {
12404         TII->fixImplicitOperands(MI);
12405       }
12406     }
12407   }
12408 
12409   // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
12410   // classes if required. Ideally the register class constraints would differ
12411   // per-subtarget, but there's no easy way to achieve that right now. This is
12412   // not a problem for VGPRs because the correctly aligned VGPR class is implied
12413   // from using them as the register class for legal types.
12414   if (ST.needsAlignedVGPRs()) {
12415     for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
12416       const Register Reg = Register::index2VirtReg(I);
12417       const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
12418       if (!RC)
12419         continue;
12420       int NewClassID = getAlignedAGPRClassID(RC->getID());
12421       if (NewClassID != -1)
12422         MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
12423     }
12424   }
12425 
12426   TargetLoweringBase::finalizeLowering(MF);
12427 }
12428 
12429 void SITargetLowering::computeKnownBitsForFrameIndex(
12430   const int FI, KnownBits &Known, const MachineFunction &MF) const {
12431   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
12432 
12433   // Set the high bits to zero based on the maximum allowed scratch size per
12434   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
12435   // calculation won't overflow, so assume the sign bit is never set.
12436   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
12437 }
12438 
12439 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
12440                                    KnownBits &Known, unsigned Dim) {
12441   unsigned MaxValue =
12442       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
12443   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
12444 }
12445 
12446 void SITargetLowering::computeKnownBitsForTargetInstr(
12447     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
12448     const MachineRegisterInfo &MRI, unsigned Depth) const {
12449   const MachineInstr *MI = MRI.getVRegDef(R);
12450   switch (MI->getOpcode()) {
12451   case AMDGPU::G_INTRINSIC: {
12452     switch (MI->getIntrinsicID()) {
12453     case Intrinsic::amdgcn_workitem_id_x:
12454       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
12455       break;
12456     case Intrinsic::amdgcn_workitem_id_y:
12457       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
12458       break;
12459     case Intrinsic::amdgcn_workitem_id_z:
12460       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
12461       break;
12462     case Intrinsic::amdgcn_mbcnt_lo:
12463     case Intrinsic::amdgcn_mbcnt_hi: {
12464       // These return at most the wavefront size - 1.
12465       unsigned Size = MRI.getType(R).getSizeInBits();
12466       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
12467       break;
12468     }
12469     case Intrinsic::amdgcn_groupstaticsize: {
12470       // We can report everything over the maximum size as 0. We can't report
12471       // based on the actual size because we don't know if it's accurate or not
12472       // at any given point.
12473       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
12474       break;
12475     }
12476     }
12477     break;
12478   }
12479   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
12480     Known.Zero.setHighBits(24);
12481     break;
12482   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
12483     Known.Zero.setHighBits(16);
12484     break;
12485   }
12486 }
12487 
12488 Align SITargetLowering::computeKnownAlignForTargetInstr(
12489   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
12490   unsigned Depth) const {
12491   const MachineInstr *MI = MRI.getVRegDef(R);
12492   switch (MI->getOpcode()) {
12493   case AMDGPU::G_INTRINSIC:
12494   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
12495     // FIXME: Can this move to generic code? What about the case where the call
12496     // site specifies a lower alignment?
12497     Intrinsic::ID IID = MI->getIntrinsicID();
12498     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
12499     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
12500     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
12501       return *RetAlign;
12502     return Align(1);
12503   }
12504   default:
12505     return Align(1);
12506   }
12507 }
12508 
12509 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12510   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
12511   const Align CacheLineAlign = Align(64);
12512 
12513   // Pre-GFX10 target did not benefit from loop alignment
12514   if (!ML || DisableLoopAlignment ||
12515       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
12516       getSubtarget()->hasInstFwdPrefetchBug())
12517     return PrefAlign;
12518 
12519   // On GFX10 I$ is 4 x 64 bytes cache lines.
12520   // By default prefetcher keeps one cache line behind and reads two ahead.
12521   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
12522   // behind and one ahead.
12523   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
12524   // If loop fits 64 bytes it always spans no more than two cache lines and
12525   // does not need an alignment.
12526   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
12527   // Else if loop is less or equal 192 bytes we need two lines behind.
12528 
12529   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12530   const MachineBasicBlock *Header = ML->getHeader();
12531   if (Header->getAlignment() != PrefAlign)
12532     return Header->getAlignment(); // Already processed.
12533 
12534   unsigned LoopSize = 0;
12535   for (const MachineBasicBlock *MBB : ML->blocks()) {
12536     // If inner loop block is aligned assume in average half of the alignment
12537     // size to be added as nops.
12538     if (MBB != Header)
12539       LoopSize += MBB->getAlignment().value() / 2;
12540 
12541     for (const MachineInstr &MI : *MBB) {
12542       LoopSize += TII->getInstSizeInBytes(MI);
12543       if (LoopSize > 192)
12544         return PrefAlign;
12545     }
12546   }
12547 
12548   if (LoopSize <= 64)
12549     return PrefAlign;
12550 
12551   if (LoopSize <= 128)
12552     return CacheLineAlign;
12553 
12554   // If any of parent loops is surrounded by prefetch instructions do not
12555   // insert new for inner loop, which would reset parent's settings.
12556   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
12557     if (MachineBasicBlock *Exit = P->getExitBlock()) {
12558       auto I = Exit->getFirstNonDebugInstr();
12559       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
12560         return CacheLineAlign;
12561     }
12562   }
12563 
12564   MachineBasicBlock *Pre = ML->getLoopPreheader();
12565   MachineBasicBlock *Exit = ML->getExitBlock();
12566 
12567   if (Pre && Exit) {
12568     auto PreTerm = Pre->getFirstTerminator();
12569     if (PreTerm == Pre->begin() ||
12570         std::prev(PreTerm)->getOpcode() != AMDGPU::S_INST_PREFETCH)
12571       BuildMI(*Pre, PreTerm, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH))
12572           .addImm(1); // prefetch 2 lines behind PC
12573 
12574     auto ExitHead = Exit->getFirstNonDebugInstr();
12575     if (ExitHead == Exit->end() ||
12576         ExitHead->getOpcode() != AMDGPU::S_INST_PREFETCH)
12577       BuildMI(*Exit, ExitHead, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH))
12578           .addImm(2); // prefetch 1 line behind PC
12579   }
12580 
12581   return CacheLineAlign;
12582 }
12583 
12584 LLVM_ATTRIBUTE_UNUSED
12585 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
12586   assert(N->getOpcode() == ISD::CopyFromReg);
12587   do {
12588     // Follow the chain until we find an INLINEASM node.
12589     N = N->getOperand(0).getNode();
12590     if (N->getOpcode() == ISD::INLINEASM ||
12591         N->getOpcode() == ISD::INLINEASM_BR)
12592       return true;
12593   } while (N->getOpcode() == ISD::CopyFromReg);
12594   return false;
12595 }
12596 
12597 bool SITargetLowering::isSDNodeSourceOfDivergence(
12598     const SDNode *N, FunctionLoweringInfo *FLI,
12599     LegacyDivergenceAnalysis *KDA) const {
12600   switch (N->getOpcode()) {
12601   case ISD::CopyFromReg: {
12602     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
12603     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
12604     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12605     Register Reg = R->getReg();
12606 
12607     // FIXME: Why does this need to consider isLiveIn?
12608     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
12609       return !TRI->isSGPRReg(MRI, Reg);
12610 
12611     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
12612       return KDA->isDivergent(V);
12613 
12614     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
12615     return !TRI->isSGPRReg(MRI, Reg);
12616   }
12617   case ISD::LOAD: {
12618     const LoadSDNode *L = cast<LoadSDNode>(N);
12619     unsigned AS = L->getAddressSpace();
12620     // A flat load may access private memory.
12621     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
12622   }
12623   case ISD::CALLSEQ_END:
12624     return true;
12625   case ISD::INTRINSIC_WO_CHAIN:
12626     return AMDGPU::isIntrinsicSourceOfDivergence(
12627         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
12628   case ISD::INTRINSIC_W_CHAIN:
12629     return AMDGPU::isIntrinsicSourceOfDivergence(
12630         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
12631   case AMDGPUISD::ATOMIC_CMP_SWAP:
12632   case AMDGPUISD::ATOMIC_INC:
12633   case AMDGPUISD::ATOMIC_DEC:
12634   case AMDGPUISD::ATOMIC_LOAD_FMIN:
12635   case AMDGPUISD::ATOMIC_LOAD_FMAX:
12636   case AMDGPUISD::BUFFER_ATOMIC_SWAP:
12637   case AMDGPUISD::BUFFER_ATOMIC_ADD:
12638   case AMDGPUISD::BUFFER_ATOMIC_SUB:
12639   case AMDGPUISD::BUFFER_ATOMIC_SMIN:
12640   case AMDGPUISD::BUFFER_ATOMIC_UMIN:
12641   case AMDGPUISD::BUFFER_ATOMIC_SMAX:
12642   case AMDGPUISD::BUFFER_ATOMIC_UMAX:
12643   case AMDGPUISD::BUFFER_ATOMIC_AND:
12644   case AMDGPUISD::BUFFER_ATOMIC_OR:
12645   case AMDGPUISD::BUFFER_ATOMIC_XOR:
12646   case AMDGPUISD::BUFFER_ATOMIC_INC:
12647   case AMDGPUISD::BUFFER_ATOMIC_DEC:
12648   case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
12649   case AMDGPUISD::BUFFER_ATOMIC_CSUB:
12650   case AMDGPUISD::BUFFER_ATOMIC_FADD:
12651   case AMDGPUISD::BUFFER_ATOMIC_FMIN:
12652   case AMDGPUISD::BUFFER_ATOMIC_FMAX:
12653     // Target-specific read-modify-write atomics are sources of divergence.
12654     return true;
12655   default:
12656     if (auto *A = dyn_cast<AtomicSDNode>(N)) {
12657       // Generic read-modify-write atomics are sources of divergence.
12658       return A->readMem() && A->writeMem();
12659     }
12660     return false;
12661   }
12662 }
12663 
12664 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
12665                                                EVT VT) const {
12666   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
12667   case MVT::f32:
12668     return hasFP32Denormals(DAG.getMachineFunction());
12669   case MVT::f64:
12670   case MVT::f16:
12671     return hasFP64FP16Denormals(DAG.getMachineFunction());
12672   default:
12673     return false;
12674   }
12675 }
12676 
12677 bool SITargetLowering::denormalsEnabledForType(LLT Ty,
12678                                                MachineFunction &MF) const {
12679   switch (Ty.getScalarSizeInBits()) {
12680   case 32:
12681     return hasFP32Denormals(MF);
12682   case 64:
12683   case 16:
12684     return hasFP64FP16Denormals(MF);
12685   default:
12686     return false;
12687   }
12688 }
12689 
12690 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
12691                                                     const SelectionDAG &DAG,
12692                                                     bool SNaN,
12693                                                     unsigned Depth) const {
12694   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
12695     const MachineFunction &MF = DAG.getMachineFunction();
12696     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12697 
12698     if (Info->getMode().DX10Clamp)
12699       return true; // Clamped to 0.
12700     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
12701   }
12702 
12703   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
12704                                                             SNaN, Depth);
12705 }
12706 
12707 // Global FP atomic instructions have a hardcoded FP mode and do not support
12708 // FP32 denormals, and only support v2f16 denormals.
12709 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
12710   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
12711   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
12712   if (&Flt == &APFloat::IEEEsingle())
12713     return DenormMode == DenormalMode::getPreserveSign();
12714   return DenormMode == DenormalMode::getIEEE();
12715 }
12716 
12717 TargetLowering::AtomicExpansionKind
12718 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
12719   unsigned AS = RMW->getPointerAddressSpace();
12720   if (AS == AMDGPUAS::PRIVATE_ADDRESS)
12721     return AtomicExpansionKind::NotAtomic;
12722 
12723   auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) {
12724     OptimizationRemarkEmitter ORE(RMW->getFunction());
12725     LLVMContext &Ctx = RMW->getFunction()->getContext();
12726     SmallVector<StringRef> SSNs;
12727     Ctx.getSyncScopeNames(SSNs);
12728     auto MemScope = SSNs[RMW->getSyncScopeID()].empty()
12729                         ? "system"
12730                         : SSNs[RMW->getSyncScopeID()];
12731     ORE.emit([&]() {
12732       return OptimizationRemark(DEBUG_TYPE, "Passed", RMW)
12733              << "Hardware instruction generated for atomic "
12734              << RMW->getOperationName(RMW->getOperation())
12735              << " operation at memory scope " << MemScope
12736              << " due to an unsafe request.";
12737     });
12738     return Kind;
12739   };
12740 
12741   switch (RMW->getOperation()) {
12742   case AtomicRMWInst::FAdd: {
12743     Type *Ty = RMW->getType();
12744 
12745     // We don't have a way to support 16-bit atomics now, so just leave them
12746     // as-is.
12747     if (Ty->isHalfTy())
12748       return AtomicExpansionKind::None;
12749 
12750     if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
12751       return AtomicExpansionKind::CmpXChg;
12752 
12753     if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) &&
12754         Subtarget->hasAtomicFaddNoRtnInsts()) {
12755       if (Subtarget->hasGFX940Insts())
12756         return AtomicExpansionKind::None;
12757 
12758       // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
12759       // floating point atomic instructions. May generate more efficient code,
12760       // but may not respect rounding and denormal modes, and may give incorrect
12761       // results for certain memory destinations.
12762       if (RMW->getFunction()
12763               ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12764               .getValueAsString() != "true")
12765         return AtomicExpansionKind::CmpXChg;
12766 
12767       if (Subtarget->hasGFX90AInsts()) {
12768         if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS)
12769           return AtomicExpansionKind::CmpXChg;
12770 
12771         auto SSID = RMW->getSyncScopeID();
12772         if (SSID == SyncScope::System ||
12773             SSID == RMW->getContext().getOrInsertSyncScopeID("one-as"))
12774           return AtomicExpansionKind::CmpXChg;
12775 
12776         return ReportUnsafeHWInst(AtomicExpansionKind::None);
12777       }
12778 
12779       if (AS == AMDGPUAS::FLAT_ADDRESS)
12780         return AtomicExpansionKind::CmpXChg;
12781 
12782       return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12783                               : AtomicExpansionKind::CmpXChg;
12784     }
12785 
12786     // DS FP atomics do respect the denormal mode, but the rounding mode is
12787     // fixed to round-to-nearest-even.
12788     // The only exception is DS_ADD_F64 which never flushes regardless of mode.
12789     if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) {
12790       if (!Ty->isDoubleTy())
12791         return AtomicExpansionKind::None;
12792 
12793       if (fpModeMatchesGlobalFPAtomicMode(RMW))
12794         return AtomicExpansionKind::None;
12795 
12796       return RMW->getFunction()
12797                          ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12798                          .getValueAsString() == "true"
12799                  ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12800                  : AtomicExpansionKind::CmpXChg;
12801     }
12802 
12803     return AtomicExpansionKind::CmpXChg;
12804   }
12805   default:
12806     break;
12807   }
12808 
12809   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
12810 }
12811 
12812 TargetLowering::AtomicExpansionKind
12813 SITargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
12814   return LI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12815              ? AtomicExpansionKind::NotAtomic
12816              : AtomicExpansionKind::None;
12817 }
12818 
12819 TargetLowering::AtomicExpansionKind
12820 SITargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
12821   return SI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12822              ? AtomicExpansionKind::NotAtomic
12823              : AtomicExpansionKind::None;
12824 }
12825 
12826 TargetLowering::AtomicExpansionKind
12827 SITargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *CmpX) const {
12828   return CmpX->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12829              ? AtomicExpansionKind::NotAtomic
12830              : AtomicExpansionKind::None;
12831 }
12832 
12833 const TargetRegisterClass *
12834 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
12835   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
12836   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12837   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
12838     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
12839                                                : &AMDGPU::SReg_32RegClass;
12840   if (!TRI->isSGPRClass(RC) && !isDivergent)
12841     return TRI->getEquivalentSGPRClass(RC);
12842   else if (TRI->isSGPRClass(RC) && isDivergent)
12843     return TRI->getEquivalentVGPRClass(RC);
12844 
12845   return RC;
12846 }
12847 
12848 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
12849 // uniform values (as produced by the mask results of control flow intrinsics)
12850 // used outside of divergent blocks. The phi users need to also be treated as
12851 // always uniform.
12852 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
12853                       unsigned WaveSize) {
12854   // FIXME: We assume we never cast the mask results of a control flow
12855   // intrinsic.
12856   // Early exit if the type won't be consistent as a compile time hack.
12857   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
12858   if (!IT || IT->getBitWidth() != WaveSize)
12859     return false;
12860 
12861   if (!isa<Instruction>(V))
12862     return false;
12863   if (!Visited.insert(V).second)
12864     return false;
12865   bool Result = false;
12866   for (auto U : V->users()) {
12867     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
12868       if (V == U->getOperand(1)) {
12869         switch (Intrinsic->getIntrinsicID()) {
12870         default:
12871           Result = false;
12872           break;
12873         case Intrinsic::amdgcn_if_break:
12874         case Intrinsic::amdgcn_if:
12875         case Intrinsic::amdgcn_else:
12876           Result = true;
12877           break;
12878         }
12879       }
12880       if (V == U->getOperand(0)) {
12881         switch (Intrinsic->getIntrinsicID()) {
12882         default:
12883           Result = false;
12884           break;
12885         case Intrinsic::amdgcn_end_cf:
12886         case Intrinsic::amdgcn_loop:
12887           Result = true;
12888           break;
12889         }
12890       }
12891     } else {
12892       Result = hasCFUser(U, Visited, WaveSize);
12893     }
12894     if (Result)
12895       break;
12896   }
12897   return Result;
12898 }
12899 
12900 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
12901                                                const Value *V) const {
12902   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
12903     if (CI->isInlineAsm()) {
12904       // FIXME: This cannot give a correct answer. This should only trigger in
12905       // the case where inline asm returns mixed SGPR and VGPR results, used
12906       // outside the defining block. We don't have a specific result to
12907       // consider, so this assumes if any value is SGPR, the overall register
12908       // also needs to be SGPR.
12909       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
12910       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
12911           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
12912       for (auto &TC : TargetConstraints) {
12913         if (TC.Type == InlineAsm::isOutput) {
12914           ComputeConstraintToUse(TC, SDValue());
12915           const TargetRegisterClass *RC = getRegForInlineAsmConstraint(
12916               SIRI, TC.ConstraintCode, TC.ConstraintVT).second;
12917           if (RC && SIRI->isSGPRClass(RC))
12918             return true;
12919         }
12920       }
12921     }
12922   }
12923   SmallPtrSet<const Value *, 16> Visited;
12924   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
12925 }
12926 
12927 std::pair<InstructionCost, MVT>
12928 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
12929                                           Type *Ty) const {
12930   std::pair<InstructionCost, MVT> Cost =
12931       TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
12932   auto Size = DL.getTypeSizeInBits(Ty);
12933   // Maximum load or store can handle 8 dwords for scalar and 4 for
12934   // vector ALU. Let's assume anything above 8 dwords is expensive
12935   // even if legal.
12936   if (Size <= 256)
12937     return Cost;
12938 
12939   Cost.first += (Size + 255) / 256;
12940   return Cost;
12941 }
12942 
12943 bool SITargetLowering::hasMemSDNodeUser(SDNode *N) const {
12944   SDNode::use_iterator I = N->use_begin(), E = N->use_end();
12945   for (; I != E; ++I) {
12946     if (MemSDNode *M = dyn_cast<MemSDNode>(*I)) {
12947       if (getBasePtrIndex(M) == I.getOperandNo())
12948         return true;
12949     }
12950   }
12951   return false;
12952 }
12953 
12954 bool SITargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0,
12955                                            SDValue N1) const {
12956   if (!N0.hasOneUse())
12957     return false;
12958   // Take care of the opportunity to keep N0 uniform
12959   if (N0->isDivergent() || !N1->isDivergent())
12960     return true;
12961   // Check if we have a good chance to form the memory access pattern with the
12962   // base and offset
12963   return (DAG.isBaseWithConstantOffset(N0) &&
12964           hasMemSDNodeUser(*N0->use_begin()));
12965 }
12966 
12967 MachineMemOperand::Flags
12968 SITargetLowering::getTargetMMOFlags(const Instruction &I) const {
12969   // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load.
12970   if (I.getMetadata("amdgpu.noclobber"))
12971     return MONoClobber;
12972   return MachineMemOperand::MONone;
12973 }
12974