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   }
142 
143   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
144   addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024));
145 
146   computeRegisterProperties(Subtarget->getRegisterInfo());
147 
148   // The boolean content concept here is too inflexible. Compares only ever
149   // really produce a 1-bit result. Any copy/extend from these will turn into a
150   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
151   // it's what most targets use.
152   setBooleanContents(ZeroOrOneBooleanContent);
153   setBooleanVectorContents(ZeroOrOneBooleanContent);
154 
155   // We need to custom lower vector stores from local memory
156   setOperationAction(ISD::LOAD,
157                      {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32,
158                       MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v16i32, MVT::i1,
159                       MVT::v32i32},
160                      Custom);
161 
162   setOperationAction(ISD::STORE,
163                      {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32,
164                       MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v16i32, MVT::i1,
165                       MVT::v32i32},
166                      Custom);
167 
168   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
169   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
170   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
171   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
172   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
173   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
174   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
175   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
176   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
177   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
178   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
179   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
180   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
181   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
182   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
183   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
184 
185   setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand);
186   setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand);
187   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
188   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
189   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
190   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
191   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
192 
193   setOperationAction(ISD::GlobalAddress, {MVT::i32, MVT::i64}, Custom);
194 
195   setOperationAction(ISD::SELECT, MVT::i1, Promote);
196   setOperationAction(ISD::SELECT, MVT::i64, Custom);
197   setOperationAction(ISD::SELECT, MVT::f64, Promote);
198   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
199 
200   setOperationAction(ISD::SELECT_CC,
201                      {MVT::f32, MVT::i32, MVT::i64, MVT::f64, MVT::i1}, Expand);
202 
203   setOperationAction(ISD::SETCC, MVT::i1, Promote);
204   setOperationAction(ISD::SETCC, {MVT::v2i1, MVT::v4i1}, Expand);
205   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
206 
207   setOperationAction(ISD::TRUNCATE,
208                      {MVT::v2i32, MVT::v3i32, MVT::v4i32, MVT::v5i32,
209                       MVT::v6i32, MVT::v7i32, MVT::v8i32, MVT::v16i32},
210                      Expand);
211   setOperationAction(ISD::FP_ROUND,
212                      {MVT::v2f32, MVT::v3f32, MVT::v4f32, MVT::v5f32,
213                       MVT::v6f32, MVT::v7f32, MVT::v8f32, MVT::v16f32},
214                      Expand);
215 
216   setOperationAction(ISD::SIGN_EXTEND_INREG,
217                      {MVT::v2i1, MVT::v4i1, MVT::v2i8, MVT::v4i8, MVT::v2i16,
218                       MVT::v3i16, MVT::v4i16, MVT::Other},
219                      Custom);
220 
221   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
222   setOperationAction(ISD::BR_CC,
223                      {MVT::i1, MVT::i32, MVT::i64, MVT::f32, MVT::f64}, Expand);
224 
225   setOperationAction({ISD::UADDO, ISD::USUBO}, MVT::i32, Legal);
226 
227   setOperationAction({ISD::ADDCARRY, ISD::SUBCARRY}, MVT::i32, Legal);
228 
229   setOperationAction({ISD::SHL_PARTS, ISD::SRA_PARTS, ISD::SRL_PARTS}, MVT::i64,
230                      Expand);
231 
232 #if 0
233   setOperationAction({ISD::ADDCARRY, ISD::SUBCARRY}, MVT::i64, Legal);
234 #endif
235 
236   // We only support LOAD/STORE and vector manipulation ops for vectors
237   // with > 4 elements.
238   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
239                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
240                   MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32,
241                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
242                   MVT::v8i16, MVT::v8f16, MVT::v16i64, MVT::v16f64,
243                   MVT::v32i32, MVT::v32f32 }) {
244     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
245       switch (Op) {
246       case ISD::LOAD:
247       case ISD::STORE:
248       case ISD::BUILD_VECTOR:
249       case ISD::BITCAST:
250       case ISD::EXTRACT_VECTOR_ELT:
251       case ISD::INSERT_VECTOR_ELT:
252       case ISD::EXTRACT_SUBVECTOR:
253       case ISD::SCALAR_TO_VECTOR:
254         break;
255       case ISD::INSERT_SUBVECTOR:
256       case ISD::CONCAT_VECTORS:
257         setOperationAction(Op, VT, Custom);
258         break;
259       default:
260         setOperationAction(Op, VT, Expand);
261         break;
262       }
263     }
264   }
265 
266   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
267 
268   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
269   // is expanded to avoid having two separate loops in case the index is a VGPR.
270 
271   // Most operations are naturally 32-bit vector operations. We only support
272   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
273   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
274     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
275     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
276 
277     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
278     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
279 
280     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
281     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
282 
283     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
284     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
285   }
286 
287   for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) {
288     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
289     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32);
290 
291     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
292     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32);
293 
294     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
295     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32);
296 
297     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
298     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32);
299   }
300 
301   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
302     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
303     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
304 
305     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
306     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
307 
308     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
309     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
310 
311     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
312     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
313   }
314 
315   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
316     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
317     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
318 
319     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
320     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
321 
322     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
323     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
324 
325     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
326     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
327   }
328 
329   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
330     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
331     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
332 
333     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
334     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
335 
336     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
337     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
338 
339     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
340     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
341   }
342 
343   setOperationAction(ISD::VECTOR_SHUFFLE,
344                      {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32},
345                      Expand);
346 
347   setOperationAction(ISD::BUILD_VECTOR, {MVT::v4f16, MVT::v4i16}, Custom);
348 
349   // Avoid stack access for these.
350   // TODO: Generalize to more vector types.
351   setOperationAction({ISD::EXTRACT_VECTOR_ELT, ISD::INSERT_VECTOR_ELT},
352                      {MVT::v2i16, MVT::v2f16, MVT::v2i8, MVT::v4i8, MVT::v8i8,
353                       MVT::v4i16, MVT::v4f16},
354                      Custom);
355 
356   // Deal with vec3 vector operations when widened to vec4.
357   setOperationAction(ISD::INSERT_SUBVECTOR,
358                      {MVT::v3i32, MVT::v3f32, MVT::v4i32, MVT::v4f32}, Custom);
359 
360   // Deal with vec5/6/7 vector operations when widened to vec8.
361   setOperationAction(ISD::INSERT_SUBVECTOR,
362                      {MVT::v5i32, MVT::v5f32, MVT::v6i32, MVT::v6f32,
363                       MVT::v7i32, MVT::v7f32, MVT::v8i32, MVT::v8f32},
364                      Custom);
365 
366   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
367   // and output demarshalling
368   setOperationAction(ISD::ATOMIC_CMP_SWAP, {MVT::i32, MVT::i64}, Custom);
369 
370   // We can't return success/failure, only the old value,
371   // let LLVM add the comparison
372   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, {MVT::i32, MVT::i64},
373                      Expand);
374 
375   if (Subtarget->hasFlatAddressSpace())
376     setOperationAction(ISD::ADDRSPACECAST, {MVT::i32, MVT::i64}, Custom);
377 
378   setOperationAction(ISD::BITREVERSE, {MVT::i32, MVT::i64}, Legal);
379 
380   // FIXME: This should be narrowed to i32, but that only happens if i64 is
381   // illegal.
382   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
383   setOperationAction(ISD::BSWAP, {MVT::i64, MVT::i32}, Legal);
384 
385   // On SI this is s_memtime and s_memrealtime on VI.
386   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
387   setOperationAction({ISD::TRAP, ISD::DEBUGTRAP}, MVT::Other, Custom);
388 
389   if (Subtarget->has16BitInsts()) {
390     setOperationAction({ISD::FPOW, ISD::FPOWI}, MVT::f16, Promote);
391     setOperationAction({ISD::FLOG, ISD::FEXP, ISD::FLOG10}, MVT::f16, Custom);
392   }
393 
394   if (Subtarget->hasMadMacF32Insts())
395     setOperationAction(ISD::FMAD, MVT::f32, Legal);
396 
397   if (!Subtarget->hasBFI())
398     // fcopysign can be done in a single instruction with BFI.
399     setOperationAction(ISD::FCOPYSIGN, {MVT::f32, MVT::f64}, Expand);
400 
401   if (!Subtarget->hasBCNT(32))
402     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
403 
404   if (!Subtarget->hasBCNT(64))
405     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
406 
407   if (Subtarget->hasFFBH())
408     setOperationAction({ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF}, MVT::i32, Custom);
409 
410   if (Subtarget->hasFFBL())
411     setOperationAction({ISD::CTTZ, ISD::CTTZ_ZERO_UNDEF}, MVT::i32, Custom);
412 
413   // We only really have 32-bit BFE instructions (and 16-bit on VI).
414   //
415   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
416   // effort to match them now. We want this to be false for i64 cases when the
417   // extraction isn't restricted to the upper or lower half. Ideally we would
418   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
419   // span the midpoint are probably relatively rare, so don't worry about them
420   // for now.
421   if (Subtarget->hasBFE())
422     setHasExtractBitsInsn(true);
423 
424   // Clamp modifier on add/sub
425   if (Subtarget->hasIntClamp())
426     setOperationAction({ISD::UADDSAT, ISD::USUBSAT}, MVT::i32, Legal);
427 
428   if (Subtarget->hasAddNoCarry())
429     setOperationAction({ISD::SADDSAT, ISD::SSUBSAT}, {MVT::i16, MVT::i32},
430                        Legal);
431 
432   setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, {MVT::f32, MVT::f64},
433                      Custom);
434 
435   // These are really only legal for ieee_mode functions. We should be avoiding
436   // them for functions that don't have ieee_mode enabled, so just say they are
437   // legal.
438   setOperationAction({ISD::FMINNUM_IEEE, ISD::FMAXNUM_IEEE},
439                      {MVT::f32, MVT::f64}, Legal);
440 
441   if (Subtarget->haveRoundOpsF64())
442     setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FRINT}, MVT::f64, Legal);
443   else
444     setOperationAction({ISD::FCEIL, ISD::FTRUNC, ISD::FRINT, ISD::FFLOOR},
445                        MVT::f64, Custom);
446 
447   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
448 
449   setOperationAction({ISD::FSIN, ISD::FCOS, ISD::FDIV}, MVT::f32, Custom);
450   setOperationAction(ISD::FDIV, MVT::f64, Custom);
451 
452   if (Subtarget->has16BitInsts()) {
453     setOperationAction({ISD::Constant, ISD::SMIN, ISD::SMAX, ISD::UMIN,
454                         ISD::UMAX, ISD::UADDSAT, ISD::USUBSAT},
455                        MVT::i16, Legal);
456 
457     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
458 
459     setOperationAction({ISD::ROTR, ISD::ROTL, ISD::SELECT_CC, ISD::BR_CC},
460                        MVT::i16, Expand);
461 
462     setOperationAction({ISD::SIGN_EXTEND, ISD::SDIV, ISD::UDIV, ISD::SREM,
463                         ISD::UREM, ISD::BITREVERSE, ISD::CTTZ,
464                         ISD::CTTZ_ZERO_UNDEF, ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF,
465                         ISD::CTPOP},
466                        MVT::i16, Promote);
467 
468     setOperationAction(ISD::LOAD, MVT::i16, Custom);
469 
470     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
471 
472     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
473     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
474     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
475     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
476 
477     setOperationAction({ISD::FP_TO_SINT, ISD::FP_TO_UINT}, MVT::i16, Custom);
478 
479     // F16 - Constant Actions.
480     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
481 
482     // F16 - Load/Store Actions.
483     setOperationAction(ISD::LOAD, MVT::f16, Promote);
484     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
485     setOperationAction(ISD::STORE, MVT::f16, Promote);
486     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
487 
488     // F16 - VOP1 Actions.
489     setOperationAction(
490         {ISD::FP_ROUND, ISD::FCOS, ISD::FSIN, ISD::FROUND, ISD::FPTRUNC_ROUND},
491         MVT::f16, Custom);
492 
493     setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP}, MVT::i16, Custom);
494 
495     setOperationAction(
496         {ISD::FP_TO_SINT, ISD::FP_TO_UINT, ISD::SINT_TO_FP, ISD::UINT_TO_FP},
497         MVT::f16, Promote);
498 
499     // F16 - VOP2 Actions.
500     setOperationAction({ISD::BR_CC, ISD::SELECT_CC}, MVT::f16, Expand);
501 
502     setOperationAction(ISD::FDIV, MVT::f16, Custom);
503 
504     // F16 - VOP3 Actions.
505     setOperationAction(ISD::FMA, MVT::f16, Legal);
506     if (STI.hasMadF16())
507       setOperationAction(ISD::FMAD, MVT::f16, Legal);
508 
509     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16, MVT::v8i16,
510                    MVT::v8f16}) {
511       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
512         switch (Op) {
513         case ISD::LOAD:
514         case ISD::STORE:
515         case ISD::BUILD_VECTOR:
516         case ISD::BITCAST:
517         case ISD::EXTRACT_VECTOR_ELT:
518         case ISD::INSERT_VECTOR_ELT:
519         case ISD::INSERT_SUBVECTOR:
520         case ISD::EXTRACT_SUBVECTOR:
521         case ISD::SCALAR_TO_VECTOR:
522           break;
523         case ISD::CONCAT_VECTORS:
524           setOperationAction(Op, VT, Custom);
525           break;
526         default:
527           setOperationAction(Op, VT, Expand);
528           break;
529         }
530       }
531     }
532 
533     // v_perm_b32 can handle either of these.
534     setOperationAction(ISD::BSWAP, {MVT::i16, MVT::v2i16}, Legal);
535     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
536 
537     // XXX - Do these do anything? Vector constants turn into build_vector.
538     setOperationAction(ISD::Constant, {MVT::v2i16, MVT::v2f16}, Legal);
539 
540     setOperationAction(ISD::UNDEF, {MVT::v2i16, MVT::v2f16}, Legal);
541 
542     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
543     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
544     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
545     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
546 
547     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
548     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
549     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
550     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
551 
552     setOperationAction(ISD::AND, MVT::v2i16, Promote);
553     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
554     setOperationAction(ISD::OR, MVT::v2i16, Promote);
555     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
556     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
557     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
558 
559     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
560     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
561     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
562     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
563 
564     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
565     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
566     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
567     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
568 
569     setOperationAction(ISD::LOAD, MVT::v8i16, Promote);
570     AddPromotedToType(ISD::LOAD, MVT::v8i16, MVT::v4i32);
571     setOperationAction(ISD::LOAD, MVT::v8f16, Promote);
572     AddPromotedToType(ISD::LOAD, MVT::v8f16, MVT::v4i32);
573 
574     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
575     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
576     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
577     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
578 
579     setOperationAction(ISD::STORE, MVT::v8i16, Promote);
580     AddPromotedToType(ISD::STORE, MVT::v8i16, MVT::v4i32);
581     setOperationAction(ISD::STORE, MVT::v8f16, Promote);
582     AddPromotedToType(ISD::STORE, MVT::v8f16, MVT::v4i32);
583 
584     setOperationAction({ISD::ANY_EXTEND, ISD::ZERO_EXTEND, ISD::SIGN_EXTEND},
585                        MVT::v2i32, Expand);
586     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
587 
588     setOperationAction({ISD::ANY_EXTEND, ISD::ZERO_EXTEND, ISD::SIGN_EXTEND},
589                        MVT::v4i32, Expand);
590 
591     setOperationAction({ISD::ANY_EXTEND, ISD::ZERO_EXTEND, ISD::SIGN_EXTEND},
592                        MVT::v8i32, Expand);
593 
594     if (!Subtarget->hasVOP3PInsts())
595       setOperationAction(ISD::BUILD_VECTOR, {MVT::v2i16, MVT::v2f16}, Custom);
596 
597     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
598     // This isn't really legal, but this avoids the legalizer unrolling it (and
599     // allows matching fneg (fabs x) patterns)
600     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
601 
602     setOperationAction({ISD::FMAXNUM, ISD::FMINNUM}, MVT::f16, Custom);
603     setOperationAction({ISD::FMAXNUM_IEEE, ISD::FMINNUM_IEEE}, MVT::f16, Legal);
604 
605     setOperationAction({ISD::FMINNUM_IEEE, ISD::FMAXNUM_IEEE},
606                        {MVT::v4f16, MVT::v8f16}, Custom);
607 
608     setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, {MVT::v4f16, MVT::v8f16},
609                        Expand);
610 
611     for (MVT Vec16 : { MVT::v8i16, MVT::v8f16 }) {
612       setOperationAction(
613           {ISD::BUILD_VECTOR, ISD::EXTRACT_VECTOR_ELT, ISD::SCALAR_TO_VECTOR},
614           Vec16, Custom);
615       setOperationAction(ISD::INSERT_VECTOR_ELT, Vec16, Expand);
616     }
617   }
618 
619   if (Subtarget->hasVOP3PInsts()) {
620     setOperationAction({ISD::ADD, ISD::SUB, ISD::MUL, ISD::SHL, ISD::SRL,
621                         ISD::SRA, ISD::SMIN, ISD::UMIN, ISD::SMAX, ISD::UMAX,
622                         ISD::UADDSAT, ISD::USUBSAT, ISD::SADDSAT, ISD::SSUBSAT},
623                        MVT::v2i16, Legal);
624 
625     setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA, ISD::FMINNUM_IEEE,
626                         ISD::FMAXNUM_IEEE, ISD::FCANONICALIZE},
627                        MVT::v2f16, Legal);
628 
629     setOperationAction(ISD::EXTRACT_VECTOR_ELT, {MVT::v2i16, MVT::v2f16},
630                        Custom);
631 
632     setOperationAction(ISD::VECTOR_SHUFFLE,
633                        {MVT::v4f16, MVT::v4i16, MVT::v8f16, MVT::v8i16},
634                        Custom);
635 
636     for (MVT VT : {MVT::v4i16, MVT::v8i16})
637       // Split vector operations.
638       setOperationAction({ISD::SHL, ISD::SRA, ISD::SRL, ISD::ADD, ISD::SUB,
639                           ISD::MUL, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX,
640                           ISD::UADDSAT, ISD::SADDSAT, ISD::USUBSAT,
641                           ISD::SSUBSAT},
642                          VT, Custom);
643 
644     for (MVT VT : {MVT::v4f16, MVT::v8f16})
645       // Split vector operations.
646       setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA, ISD::FCANONICALIZE},
647                          VT, Custom);
648 
649     setOperationAction({ISD::FMAXNUM, ISD::FMINNUM}, {MVT::v2f16, MVT::v4f16},
650                        Custom);
651 
652     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
653     setOperationAction(ISD::SELECT, {MVT::v4i16, MVT::v4f16}, Custom);
654 
655     if (Subtarget->hasPackedFP32Ops()) {
656       setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA, ISD::FNEG},
657                          MVT::v2f32, Legal);
658       setOperationAction({ISD::FADD, ISD::FMUL, ISD::FMA},
659                          {MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32},
660                          Custom);
661     }
662   }
663 
664   setOperationAction({ISD::FNEG, ISD::FABS}, MVT::v4f16, Custom);
665 
666   if (Subtarget->has16BitInsts()) {
667     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
668     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
669     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
670     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
671   } else {
672     // Legalization hack.
673     setOperationAction(ISD::SELECT, {MVT::v2i16, MVT::v2f16}, Custom);
674 
675     setOperationAction({ISD::FNEG, ISD::FABS}, MVT::v2f16, Custom);
676   }
677 
678   setOperationAction(ISD::SELECT,
679                      {MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8,
680                       MVT::v8i16, MVT::v8f16},
681                      Custom);
682 
683   setOperationAction({ISD::SMULO, ISD::UMULO}, MVT::i64, Custom);
684 
685   if (Subtarget->hasMad64_32())
686     setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, MVT::i32, Custom);
687 
688   setOperationAction(ISD::INTRINSIC_WO_CHAIN,
689                      {MVT::Other, MVT::f32, MVT::v4f32, MVT::i16, MVT::f16,
690                       MVT::v2i16, MVT::v2f16},
691                      Custom);
692 
693   setOperationAction(ISD::INTRINSIC_W_CHAIN,
694                      {MVT::v2f16, MVT::v2i16, MVT::v3f16, MVT::v3i16,
695                       MVT::v4f16, MVT::v4i16, MVT::v8f16, MVT::Other, MVT::f16,
696                       MVT::i16, MVT::i8},
697                      Custom);
698 
699   setOperationAction(ISD::INTRINSIC_VOID,
700                      {MVT::Other, MVT::v2i16, MVT::v2f16, MVT::v3i16,
701                       MVT::v3f16, MVT::v4f16, MVT::v4i16, MVT::f16, MVT::i16,
702                       MVT::i8},
703                      Custom);
704 
705   setTargetDAGCombine({ISD::ADD,
706                        ISD::ADDCARRY,
707                        ISD::SUB,
708                        ISD::SUBCARRY,
709                        ISD::FADD,
710                        ISD::FSUB,
711                        ISD::FMINNUM,
712                        ISD::FMAXNUM,
713                        ISD::FMINNUM_IEEE,
714                        ISD::FMAXNUM_IEEE,
715                        ISD::FMA,
716                        ISD::SMIN,
717                        ISD::SMAX,
718                        ISD::UMIN,
719                        ISD::UMAX,
720                        ISD::SETCC,
721                        ISD::AND,
722                        ISD::OR,
723                        ISD::XOR,
724                        ISD::SINT_TO_FP,
725                        ISD::UINT_TO_FP,
726                        ISD::FCANONICALIZE,
727                        ISD::SCALAR_TO_VECTOR,
728                        ISD::ZERO_EXTEND,
729                        ISD::SIGN_EXTEND_INREG,
730                        ISD::EXTRACT_VECTOR_ELT,
731                        ISD::INSERT_VECTOR_ELT});
732 
733   // All memory operations. Some folding on the pointer operand is done to help
734   // matching the constant offsets in the addressing modes.
735   setTargetDAGCombine({ISD::LOAD,
736                        ISD::STORE,
737                        ISD::ATOMIC_LOAD,
738                        ISD::ATOMIC_STORE,
739                        ISD::ATOMIC_CMP_SWAP,
740                        ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
741                        ISD::ATOMIC_SWAP,
742                        ISD::ATOMIC_LOAD_ADD,
743                        ISD::ATOMIC_LOAD_SUB,
744                        ISD::ATOMIC_LOAD_AND,
745                        ISD::ATOMIC_LOAD_OR,
746                        ISD::ATOMIC_LOAD_XOR,
747                        ISD::ATOMIC_LOAD_NAND,
748                        ISD::ATOMIC_LOAD_MIN,
749                        ISD::ATOMIC_LOAD_MAX,
750                        ISD::ATOMIC_LOAD_UMIN,
751                        ISD::ATOMIC_LOAD_UMAX,
752                        ISD::ATOMIC_LOAD_FADD,
753                        ISD::INTRINSIC_VOID,
754                        ISD::INTRINSIC_W_CHAIN});
755 
756   // FIXME: In other contexts we pretend this is a per-function property.
757   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
758 
759   setSchedulingPreference(Sched::RegPressure);
760 }
761 
762 const GCNSubtarget *SITargetLowering::getSubtarget() const {
763   return Subtarget;
764 }
765 
766 //===----------------------------------------------------------------------===//
767 // TargetLowering queries
768 //===----------------------------------------------------------------------===//
769 
770 // v_mad_mix* support a conversion from f16 to f32.
771 //
772 // There is only one special case when denormals are enabled we don't currently,
773 // where this is OK to use.
774 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
775                                        EVT DestVT, EVT SrcVT) const {
776   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
777           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
778     DestVT.getScalarType() == MVT::f32 &&
779     SrcVT.getScalarType() == MVT::f16 &&
780     // TODO: This probably only requires no input flushing?
781     !hasFP32Denormals(DAG.getMachineFunction());
782 }
783 
784 bool SITargetLowering::isFPExtFoldable(const MachineInstr &MI, unsigned Opcode,
785                                        LLT DestTy, LLT SrcTy) const {
786   return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) ||
787           (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) &&
788          DestTy.getScalarSizeInBits() == 32 &&
789          SrcTy.getScalarSizeInBits() == 16 &&
790          // TODO: This probably only requires no input flushing?
791          !hasFP32Denormals(*MI.getMF());
792 }
793 
794 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
795   // SI has some legal vector types, but no legal vector operations. Say no
796   // shuffles are legal in order to prefer scalarizing some vector operations.
797   return false;
798 }
799 
800 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
801                                                     CallingConv::ID CC,
802                                                     EVT VT) const {
803   if (CC == CallingConv::AMDGPU_KERNEL)
804     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
805 
806   if (VT.isVector()) {
807     EVT ScalarVT = VT.getScalarType();
808     unsigned Size = ScalarVT.getSizeInBits();
809     if (Size == 16) {
810       if (Subtarget->has16BitInsts())
811         return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
812       return VT.isInteger() ? MVT::i32 : MVT::f32;
813     }
814 
815     if (Size < 16)
816       return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
817     return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
818   }
819 
820   if (VT.getSizeInBits() > 32)
821     return MVT::i32;
822 
823   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
824 }
825 
826 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
827                                                          CallingConv::ID CC,
828                                                          EVT VT) const {
829   if (CC == CallingConv::AMDGPU_KERNEL)
830     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
831 
832   if (VT.isVector()) {
833     unsigned NumElts = VT.getVectorNumElements();
834     EVT ScalarVT = VT.getScalarType();
835     unsigned Size = ScalarVT.getSizeInBits();
836 
837     // FIXME: Should probably promote 8-bit vectors to i16.
838     if (Size == 16 && Subtarget->has16BitInsts())
839       return (NumElts + 1) / 2;
840 
841     if (Size <= 32)
842       return NumElts;
843 
844     if (Size > 32)
845       return NumElts * ((Size + 31) / 32);
846   } else if (VT.getSizeInBits() > 32)
847     return (VT.getSizeInBits() + 31) / 32;
848 
849   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
850 }
851 
852 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
853   LLVMContext &Context, CallingConv::ID CC,
854   EVT VT, EVT &IntermediateVT,
855   unsigned &NumIntermediates, MVT &RegisterVT) const {
856   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
857     unsigned NumElts = VT.getVectorNumElements();
858     EVT ScalarVT = VT.getScalarType();
859     unsigned Size = ScalarVT.getSizeInBits();
860     // FIXME: We should fix the ABI to be the same on targets without 16-bit
861     // support, but unless we can properly handle 3-vectors, it will be still be
862     // inconsistent.
863     if (Size == 16 && Subtarget->has16BitInsts()) {
864       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
865       IntermediateVT = RegisterVT;
866       NumIntermediates = (NumElts + 1) / 2;
867       return NumIntermediates;
868     }
869 
870     if (Size == 32) {
871       RegisterVT = ScalarVT.getSimpleVT();
872       IntermediateVT = RegisterVT;
873       NumIntermediates = NumElts;
874       return NumIntermediates;
875     }
876 
877     if (Size < 16 && Subtarget->has16BitInsts()) {
878       // FIXME: Should probably form v2i16 pieces
879       RegisterVT = MVT::i16;
880       IntermediateVT = ScalarVT;
881       NumIntermediates = NumElts;
882       return NumIntermediates;
883     }
884 
885 
886     if (Size != 16 && Size <= 32) {
887       RegisterVT = MVT::i32;
888       IntermediateVT = ScalarVT;
889       NumIntermediates = NumElts;
890       return NumIntermediates;
891     }
892 
893     if (Size > 32) {
894       RegisterVT = MVT::i32;
895       IntermediateVT = RegisterVT;
896       NumIntermediates = NumElts * ((Size + 31) / 32);
897       return NumIntermediates;
898     }
899   }
900 
901   return TargetLowering::getVectorTypeBreakdownForCallingConv(
902     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
903 }
904 
905 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
906   assert(DMaskLanes != 0);
907 
908   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
909     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
910     return EVT::getVectorVT(Ty->getContext(),
911                             EVT::getEVT(VT->getElementType()),
912                             NumElts);
913   }
914 
915   return EVT::getEVT(Ty);
916 }
917 
918 // Peek through TFE struct returns to only use the data size.
919 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
920   auto *ST = dyn_cast<StructType>(Ty);
921   if (!ST)
922     return memVTFromImageData(Ty, DMaskLanes);
923 
924   // Some intrinsics return an aggregate type - special case to work out the
925   // correct memVT.
926   //
927   // Only limited forms of aggregate type currently expected.
928   if (ST->getNumContainedTypes() != 2 ||
929       !ST->getContainedType(1)->isIntegerTy(32))
930     return EVT();
931   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
932 }
933 
934 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
935                                           const CallInst &CI,
936                                           MachineFunction &MF,
937                                           unsigned IntrID) const {
938   Info.flags = MachineMemOperand::MONone;
939   if (CI.hasMetadata(LLVMContext::MD_invariant_load))
940     Info.flags |= MachineMemOperand::MOInvariant;
941 
942   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
943           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
944     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
945                                                   (Intrinsic::ID)IntrID);
946     if (Attr.hasFnAttr(Attribute::ReadNone))
947       return false;
948 
949     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
950 
951     if (RsrcIntr->IsImage) {
952       Info.ptrVal =
953           MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
954       Info.align.reset();
955     } else {
956       Info.ptrVal =
957           MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
958     }
959 
960     Info.flags |= MachineMemOperand::MODereferenceable;
961     if (Attr.hasFnAttr(Attribute::ReadOnly)) {
962       unsigned DMaskLanes = 4;
963 
964       if (RsrcIntr->IsImage) {
965         const AMDGPU::ImageDimIntrinsicInfo *Intr
966           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
967         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
968           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
969 
970         if (!BaseOpcode->Gather4) {
971           // If this isn't a gather, we may have excess loaded elements in the
972           // IR type. Check the dmask for the real number of elements loaded.
973           unsigned DMask
974             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
975           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
976         }
977 
978         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
979       } else
980         Info.memVT = EVT::getEVT(CI.getType());
981 
982       // FIXME: What does alignment mean for an image?
983       Info.opc = ISD::INTRINSIC_W_CHAIN;
984       Info.flags |= MachineMemOperand::MOLoad;
985     } else if (Attr.hasFnAttr(Attribute::WriteOnly)) {
986       Info.opc = ISD::INTRINSIC_VOID;
987 
988       Type *DataTy = CI.getArgOperand(0)->getType();
989       if (RsrcIntr->IsImage) {
990         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
991         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
992         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
993       } else
994         Info.memVT = EVT::getEVT(DataTy);
995 
996       Info.flags |= MachineMemOperand::MOStore;
997     } else {
998       // Atomic
999       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1000                                             ISD::INTRINSIC_W_CHAIN;
1001       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1002       Info.flags |= MachineMemOperand::MOLoad |
1003                     MachineMemOperand::MOStore |
1004                     MachineMemOperand::MODereferenceable;
1005 
1006       // XXX - Should this be volatile without known ordering?
1007       Info.flags |= MachineMemOperand::MOVolatile;
1008 
1009       switch (IntrID) {
1010       default:
1011         break;
1012       case Intrinsic::amdgcn_raw_buffer_load_lds:
1013       case Intrinsic::amdgcn_struct_buffer_load_lds: {
1014         unsigned Width = cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue();
1015         Info.memVT = EVT::getIntegerVT(CI.getContext(), Width * 8);
1016         return true;
1017       }
1018       }
1019     }
1020     return true;
1021   }
1022 
1023   switch (IntrID) {
1024   case Intrinsic::amdgcn_atomic_inc:
1025   case Intrinsic::amdgcn_atomic_dec:
1026   case Intrinsic::amdgcn_ds_ordered_add:
1027   case Intrinsic::amdgcn_ds_ordered_swap:
1028   case Intrinsic::amdgcn_ds_fadd:
1029   case Intrinsic::amdgcn_ds_fmin:
1030   case Intrinsic::amdgcn_ds_fmax: {
1031     Info.opc = ISD::INTRINSIC_W_CHAIN;
1032     Info.memVT = MVT::getVT(CI.getType());
1033     Info.ptrVal = CI.getOperand(0);
1034     Info.align.reset();
1035     Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1036 
1037     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1038     if (!Vol->isZero())
1039       Info.flags |= MachineMemOperand::MOVolatile;
1040 
1041     return true;
1042   }
1043   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1044     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1045 
1046     Info.opc = ISD::INTRINSIC_W_CHAIN;
1047     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1048     Info.ptrVal =
1049         MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1050     Info.align.reset();
1051     Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1052 
1053     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1054     if (!Vol || !Vol->isZero())
1055       Info.flags |= MachineMemOperand::MOVolatile;
1056 
1057     return true;
1058   }
1059   case Intrinsic::amdgcn_ds_append:
1060   case Intrinsic::amdgcn_ds_consume: {
1061     Info.opc = ISD::INTRINSIC_W_CHAIN;
1062     Info.memVT = MVT::getVT(CI.getType());
1063     Info.ptrVal = CI.getOperand(0);
1064     Info.align.reset();
1065     Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1066 
1067     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1068     if (!Vol->isZero())
1069       Info.flags |= MachineMemOperand::MOVolatile;
1070 
1071     return true;
1072   }
1073   case Intrinsic::amdgcn_global_atomic_csub: {
1074     Info.opc = ISD::INTRINSIC_W_CHAIN;
1075     Info.memVT = MVT::getVT(CI.getType());
1076     Info.ptrVal = CI.getOperand(0);
1077     Info.align.reset();
1078     Info.flags |= MachineMemOperand::MOLoad |
1079                   MachineMemOperand::MOStore |
1080                   MachineMemOperand::MOVolatile;
1081     return true;
1082   }
1083   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1084     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1085     Info.opc = ISD::INTRINSIC_W_CHAIN;
1086     Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1087     Info.ptrVal =
1088         MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1089     Info.align.reset();
1090     Info.flags |= MachineMemOperand::MOLoad |
1091                   MachineMemOperand::MODereferenceable;
1092     return true;
1093   }
1094   case Intrinsic::amdgcn_global_atomic_fadd:
1095   case Intrinsic::amdgcn_global_atomic_fmin:
1096   case Intrinsic::amdgcn_global_atomic_fmax:
1097   case Intrinsic::amdgcn_flat_atomic_fadd:
1098   case Intrinsic::amdgcn_flat_atomic_fmin:
1099   case Intrinsic::amdgcn_flat_atomic_fmax:
1100   case Intrinsic::amdgcn_global_atomic_fadd_v2bf16:
1101   case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16: {
1102     Info.opc = ISD::INTRINSIC_W_CHAIN;
1103     Info.memVT = MVT::getVT(CI.getType());
1104     Info.ptrVal = CI.getOperand(0);
1105     Info.align.reset();
1106     Info.flags |= MachineMemOperand::MOLoad |
1107                   MachineMemOperand::MOStore |
1108                   MachineMemOperand::MODereferenceable |
1109                   MachineMemOperand::MOVolatile;
1110     return true;
1111   }
1112   case Intrinsic::amdgcn_ds_gws_init:
1113   case Intrinsic::amdgcn_ds_gws_barrier:
1114   case Intrinsic::amdgcn_ds_gws_sema_v:
1115   case Intrinsic::amdgcn_ds_gws_sema_br:
1116   case Intrinsic::amdgcn_ds_gws_sema_p:
1117   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1118     Info.opc = ISD::INTRINSIC_VOID;
1119 
1120     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1121     Info.ptrVal =
1122         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1123 
1124     // This is an abstract access, but we need to specify a type and size.
1125     Info.memVT = MVT::i32;
1126     Info.size = 4;
1127     Info.align = Align(4);
1128 
1129     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1130       Info.flags |= MachineMemOperand::MOLoad;
1131     else
1132       Info.flags |= MachineMemOperand::MOStore;
1133     return true;
1134   }
1135   case Intrinsic::amdgcn_global_load_lds: {
1136     Info.opc = ISD::INTRINSIC_VOID;
1137     unsigned Width = cast<ConstantInt>(CI.getArgOperand(2))->getZExtValue();
1138     Info.memVT = EVT::getIntegerVT(CI.getContext(), Width * 8);
1139     Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1140                   MachineMemOperand::MOVolatile;
1141     return true;
1142   }
1143   default:
1144     return false;
1145   }
1146 }
1147 
1148 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1149                                             SmallVectorImpl<Value*> &Ops,
1150                                             Type *&AccessTy) const {
1151   switch (II->getIntrinsicID()) {
1152   case Intrinsic::amdgcn_atomic_inc:
1153   case Intrinsic::amdgcn_atomic_dec:
1154   case Intrinsic::amdgcn_ds_ordered_add:
1155   case Intrinsic::amdgcn_ds_ordered_swap:
1156   case Intrinsic::amdgcn_ds_append:
1157   case Intrinsic::amdgcn_ds_consume:
1158   case Intrinsic::amdgcn_ds_fadd:
1159   case Intrinsic::amdgcn_ds_fmin:
1160   case Intrinsic::amdgcn_ds_fmax:
1161   case Intrinsic::amdgcn_global_atomic_fadd:
1162   case Intrinsic::amdgcn_flat_atomic_fadd:
1163   case Intrinsic::amdgcn_flat_atomic_fmin:
1164   case Intrinsic::amdgcn_flat_atomic_fmax:
1165   case Intrinsic::amdgcn_global_atomic_fadd_v2bf16:
1166   case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16:
1167   case Intrinsic::amdgcn_global_atomic_csub: {
1168     Value *Ptr = II->getArgOperand(0);
1169     AccessTy = II->getType();
1170     Ops.push_back(Ptr);
1171     return true;
1172   }
1173   default:
1174     return false;
1175   }
1176 }
1177 
1178 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1179   if (!Subtarget->hasFlatInstOffsets()) {
1180     // Flat instructions do not have offsets, and only have the register
1181     // address.
1182     return AM.BaseOffs == 0 && AM.Scale == 0;
1183   }
1184 
1185   return AM.Scale == 0 &&
1186          (AM.BaseOffs == 0 ||
1187           Subtarget->getInstrInfo()->isLegalFLATOffset(
1188               AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT));
1189 }
1190 
1191 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1192   if (Subtarget->hasFlatGlobalInsts())
1193     return AM.Scale == 0 &&
1194            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1195                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1196                                     SIInstrFlags::FlatGlobal));
1197 
1198   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1199       // Assume the we will use FLAT for all global memory accesses
1200       // on VI.
1201       // FIXME: This assumption is currently wrong.  On VI we still use
1202       // MUBUF instructions for the r + i addressing mode.  As currently
1203       // implemented, the MUBUF instructions only work on buffer < 4GB.
1204       // It may be possible to support > 4GB buffers with MUBUF instructions,
1205       // by setting the stride value in the resource descriptor which would
1206       // increase the size limit to (stride * 4GB).  However, this is risky,
1207       // because it has never been validated.
1208     return isLegalFlatAddressingMode(AM);
1209   }
1210 
1211   return isLegalMUBUFAddressingMode(AM);
1212 }
1213 
1214 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1215   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1216   // additionally can do r + r + i with addr64. 32-bit has more addressing
1217   // mode options. Depending on the resource constant, it can also do
1218   // (i64 r0) + (i32 r1) * (i14 i).
1219   //
1220   // Private arrays end up using a scratch buffer most of the time, so also
1221   // assume those use MUBUF instructions. Scratch loads / stores are currently
1222   // implemented as mubuf instructions with offen bit set, so slightly
1223   // different than the normal addr64.
1224   if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1225     return false;
1226 
1227   // FIXME: Since we can split immediate into soffset and immediate offset,
1228   // would it make sense to allow any immediate?
1229 
1230   switch (AM.Scale) {
1231   case 0: // r + i or just i, depending on HasBaseReg.
1232     return true;
1233   case 1:
1234     return true; // We have r + r or r + i.
1235   case 2:
1236     if (AM.HasBaseReg) {
1237       // Reject 2 * r + r.
1238       return false;
1239     }
1240 
1241     // Allow 2 * r as r + r
1242     // Or  2 * r + i is allowed as r + r + i.
1243     return true;
1244   default: // Don't allow n * r
1245     return false;
1246   }
1247 }
1248 
1249 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1250                                              const AddrMode &AM, Type *Ty,
1251                                              unsigned AS, Instruction *I) const {
1252   // No global is ever allowed as a base.
1253   if (AM.BaseGV)
1254     return false;
1255 
1256   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1257     return isLegalGlobalAddressingMode(AM);
1258 
1259   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1260       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1261       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1262     // If the offset isn't a multiple of 4, it probably isn't going to be
1263     // correctly aligned.
1264     // FIXME: Can we get the real alignment here?
1265     if (AM.BaseOffs % 4 != 0)
1266       return isLegalMUBUFAddressingMode(AM);
1267 
1268     // There are no SMRD extloads, so if we have to do a small type access we
1269     // will use a MUBUF load.
1270     // FIXME?: We also need to do this if unaligned, but we don't know the
1271     // alignment here.
1272     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1273       return isLegalGlobalAddressingMode(AM);
1274 
1275     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1276       // SMRD instructions have an 8-bit, dword offset on SI.
1277       if (!isUInt<8>(AM.BaseOffs / 4))
1278         return false;
1279     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1280       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1281       // in 8-bits, it can use a smaller encoding.
1282       if (!isUInt<32>(AM.BaseOffs / 4))
1283         return false;
1284     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1285       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1286       if (!isUInt<20>(AM.BaseOffs))
1287         return false;
1288     } else
1289       llvm_unreachable("unhandled generation");
1290 
1291     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1292       return true;
1293 
1294     if (AM.Scale == 1 && AM.HasBaseReg)
1295       return true;
1296 
1297     return false;
1298 
1299   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1300     return isLegalMUBUFAddressingMode(AM);
1301   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1302              AS == AMDGPUAS::REGION_ADDRESS) {
1303     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1304     // field.
1305     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1306     // an 8-bit dword offset but we don't know the alignment here.
1307     if (!isUInt<16>(AM.BaseOffs))
1308       return false;
1309 
1310     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1311       return true;
1312 
1313     if (AM.Scale == 1 && AM.HasBaseReg)
1314       return true;
1315 
1316     return false;
1317   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1318              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1319     // For an unknown address space, this usually means that this is for some
1320     // reason being used for pure arithmetic, and not based on some addressing
1321     // computation. We don't have instructions that compute pointers with any
1322     // addressing modes, so treat them as having no offset like flat
1323     // instructions.
1324     return isLegalFlatAddressingMode(AM);
1325   }
1326 
1327   // Assume a user alias of global for unknown address spaces.
1328   return isLegalGlobalAddressingMode(AM);
1329 }
1330 
1331 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1332                                         const MachineFunction &MF) const {
1333   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1334     return (MemVT.getSizeInBits() <= 4 * 32);
1335   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1336     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1337     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1338   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1339     return (MemVT.getSizeInBits() <= 2 * 32);
1340   }
1341   return true;
1342 }
1343 
1344 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1345     unsigned Size, unsigned AddrSpace, Align Alignment,
1346     MachineMemOperand::Flags Flags, bool *IsFast) const {
1347   if (IsFast)
1348     *IsFast = false;
1349 
1350   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1351       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1352     // Check if alignment requirements for ds_read/write instructions are
1353     // disabled.
1354     if (!Subtarget->hasUnalignedDSAccessEnabled() && Alignment < Align(4))
1355       return false;
1356 
1357     Align RequiredAlignment(PowerOf2Ceil(Size/8)); // Natural alignment.
1358     if (Subtarget->hasLDSMisalignedBug() && Size > 32 &&
1359         Alignment < RequiredAlignment)
1360       return false;
1361 
1362     // Either, the alignment requirements are "enabled", or there is an
1363     // unaligned LDS access related hardware bug though alignment requirements
1364     // are "disabled". In either case, we need to check for proper alignment
1365     // requirements.
1366     //
1367     switch (Size) {
1368     case 64:
1369       // SI has a hardware bug in the LDS / GDS bounds checking: if the base
1370       // address is negative, then the instruction is incorrectly treated as
1371       // out-of-bounds even if base + offsets is in bounds. Split vectorized
1372       // loads here to avoid emitting ds_read2_b32. We may re-combine the
1373       // load later in the SILoadStoreOptimizer.
1374       if (!Subtarget->hasUsableDSOffset() && Alignment < Align(8))
1375         return false;
1376 
1377       // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
1378       // can do a 4 byte aligned, 8 byte access in a single operation using
1379       // ds_read2/write2_b32 with adjacent offsets.
1380       RequiredAlignment = Align(4);
1381 
1382       if (Subtarget->hasUnalignedDSAccessEnabled()) {
1383         // We will either select ds_read_b64/ds_write_b64 or ds_read2_b32/
1384         // ds_write2_b32 depending on the alignment. In either case with either
1385         // alignment there is no faster way of doing this.
1386         if (IsFast)
1387           *IsFast = true;
1388         return true;
1389       }
1390 
1391       break;
1392     case 96:
1393       if (!Subtarget->hasDS96AndDS128())
1394         return false;
1395 
1396       // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
1397       // gfx8 and older.
1398 
1399       if (Subtarget->hasUnalignedDSAccessEnabled()) {
1400         // Naturally aligned access is fastest. However, also report it is Fast
1401         // if memory is aligned less than DWORD. A narrow load or store will be
1402         // be equally slow as a single ds_read_b96/ds_write_b96, but there will
1403         // be more of them, so overall we will pay less penalty issuing a single
1404         // instruction.
1405         if (IsFast)
1406           *IsFast = Alignment >= RequiredAlignment || Alignment < Align(4);
1407         return true;
1408       }
1409 
1410       break;
1411     case 128:
1412       if (!Subtarget->hasDS96AndDS128() || !Subtarget->useDS128())
1413         return false;
1414 
1415       // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
1416       // gfx8 and older, but  we can do a 8 byte aligned, 16 byte access in a
1417       // single operation using ds_read2/write2_b64.
1418       RequiredAlignment = Align(8);
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_b128/ds_write_b128, but there
1424         // will be more of them, so overall we will pay less penalty issuing a
1425         // single instruction.
1426         if (IsFast)
1427           *IsFast = Alignment >= RequiredAlignment || Alignment < Align(4);
1428         return true;
1429       }
1430 
1431       break;
1432     default:
1433       if (Size > 32)
1434         return false;
1435 
1436       break;
1437     }
1438 
1439     if (IsFast)
1440       *IsFast = Alignment >= RequiredAlignment;
1441 
1442     return Alignment >= RequiredAlignment ||
1443            Subtarget->hasUnalignedDSAccessEnabled();
1444   }
1445 
1446   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1447     bool AlignedBy4 = Alignment >= Align(4);
1448     if (IsFast)
1449       *IsFast = AlignedBy4;
1450 
1451     return AlignedBy4 ||
1452            Subtarget->enableFlatScratch() ||
1453            Subtarget->hasUnalignedScratchAccess();
1454   }
1455 
1456   // FIXME: We have to be conservative here and assume that flat operations
1457   // will access scratch.  If we had access to the IR function, then we
1458   // could determine if any private memory was used in the function.
1459   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1460       !Subtarget->hasUnalignedScratchAccess()) {
1461     bool AlignedBy4 = Alignment >= Align(4);
1462     if (IsFast)
1463       *IsFast = AlignedBy4;
1464 
1465     return AlignedBy4;
1466   }
1467 
1468   if (Subtarget->hasUnalignedBufferAccessEnabled()) {
1469     // If we have a uniform constant load, it still requires using a slow
1470     // buffer instruction if unaligned.
1471     if (IsFast) {
1472       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1473       // 2-byte alignment is worse than 1 unless doing a 2-byte access.
1474       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1475                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1476         Alignment >= Align(4) : Alignment != Align(2);
1477     }
1478 
1479     return true;
1480   }
1481 
1482   // Smaller than dword value must be aligned.
1483   if (Size < 32)
1484     return false;
1485 
1486   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1487   // byte-address are ignored, thus forcing Dword alignment.
1488   // This applies to private, global, and constant memory.
1489   if (IsFast)
1490     *IsFast = true;
1491 
1492   return Size >= 32 && Alignment >= Align(4);
1493 }
1494 
1495 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1496     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1497     bool *IsFast) const {
1498   bool Allow = allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1499                                                   Alignment, Flags, IsFast);
1500 
1501   if (Allow && IsFast && Subtarget->hasUnalignedDSAccessEnabled() &&
1502       (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1503        AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1504     // Lie it is fast if +unaligned-access-mode is passed so that DS accesses
1505     // get vectorized. We could use ds_read2_b*/ds_write2_b* instructions on a
1506     // misaligned data which is faster than a pair of ds_read_b*/ds_write_b*
1507     // which would be equally misaligned.
1508     // This is only used by the common passes, selection always calls the
1509     // allowsMisalignedMemoryAccessesImpl version.
1510     *IsFast = true;
1511   }
1512 
1513   return Allow;
1514 }
1515 
1516 EVT SITargetLowering::getOptimalMemOpType(
1517     const MemOp &Op, const AttributeList &FuncAttributes) const {
1518   // FIXME: Should account for address space here.
1519 
1520   // The default fallback uses the private pointer size as a guess for a type to
1521   // use. Make sure we switch these to 64-bit accesses.
1522 
1523   if (Op.size() >= 16 &&
1524       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1525     return MVT::v4i32;
1526 
1527   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1528     return MVT::v2i32;
1529 
1530   // Use the default.
1531   return MVT::Other;
1532 }
1533 
1534 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1535   const MemSDNode *MemNode = cast<MemSDNode>(N);
1536   return MemNode->getMemOperand()->getFlags() & MONoClobber;
1537 }
1538 
1539 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1540   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1541          AS == AMDGPUAS::PRIVATE_ADDRESS;
1542 }
1543 
1544 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1545                                            unsigned DestAS) const {
1546   // Flat -> private/local is a simple truncate.
1547   // Flat -> global is no-op
1548   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1549     return true;
1550 
1551   const GCNTargetMachine &TM =
1552       static_cast<const GCNTargetMachine &>(getTargetMachine());
1553   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1554 }
1555 
1556 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1557   const MemSDNode *MemNode = cast<MemSDNode>(N);
1558 
1559   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1560 }
1561 
1562 TargetLoweringBase::LegalizeTypeAction
1563 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1564   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1565       VT.getScalarType().bitsLE(MVT::i16))
1566     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1567   return TargetLoweringBase::getPreferredVectorAction(VT);
1568 }
1569 
1570 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1571                                                          Type *Ty) const {
1572   // FIXME: Could be smarter if called for vector constants.
1573   return true;
1574 }
1575 
1576 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1577   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1578     switch (Op) {
1579     case ISD::LOAD:
1580     case ISD::STORE:
1581 
1582     // These operations are done with 32-bit instructions anyway.
1583     case ISD::AND:
1584     case ISD::OR:
1585     case ISD::XOR:
1586     case ISD::SELECT:
1587       // TODO: Extensions?
1588       return true;
1589     default:
1590       return false;
1591     }
1592   }
1593 
1594   // SimplifySetCC uses this function to determine whether or not it should
1595   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1596   if (VT == MVT::i1 && Op == ISD::SETCC)
1597     return false;
1598 
1599   return TargetLowering::isTypeDesirableForOp(Op, VT);
1600 }
1601 
1602 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1603                                                    const SDLoc &SL,
1604                                                    SDValue Chain,
1605                                                    uint64_t Offset) const {
1606   const DataLayout &DL = DAG.getDataLayout();
1607   MachineFunction &MF = DAG.getMachineFunction();
1608   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1609 
1610   const ArgDescriptor *InputPtrReg;
1611   const TargetRegisterClass *RC;
1612   LLT ArgTy;
1613   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1614 
1615   std::tie(InputPtrReg, RC, ArgTy) =
1616       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1617 
1618   // We may not have the kernarg segment argument if we have no kernel
1619   // arguments.
1620   if (!InputPtrReg)
1621     return DAG.getConstant(0, SL, PtrVT);
1622 
1623   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1624   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1625     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1626 
1627   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1628 }
1629 
1630 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1631                                             const SDLoc &SL) const {
1632   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1633                                                FIRST_IMPLICIT);
1634   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1635 }
1636 
1637 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1638                                          const SDLoc &SL, SDValue Val,
1639                                          bool Signed,
1640                                          const ISD::InputArg *Arg) const {
1641   // First, if it is a widened vector, narrow it.
1642   if (VT.isVector() &&
1643       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1644     EVT NarrowedVT =
1645         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1646                          VT.getVectorNumElements());
1647     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1648                       DAG.getConstant(0, SL, MVT::i32));
1649   }
1650 
1651   // Then convert the vector elements or scalar value.
1652   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1653       VT.bitsLT(MemVT)) {
1654     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1655     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1656   }
1657 
1658   if (MemVT.isFloatingPoint())
1659     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1660   else if (Signed)
1661     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1662   else
1663     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1664 
1665   return Val;
1666 }
1667 
1668 SDValue SITargetLowering::lowerKernargMemParameter(
1669     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1670     uint64_t Offset, Align Alignment, bool Signed,
1671     const ISD::InputArg *Arg) const {
1672   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1673 
1674   // Try to avoid using an extload by loading earlier than the argument address,
1675   // and extracting the relevant bits. The load should hopefully be merged with
1676   // the previous argument.
1677   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1678     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1679     int64_t AlignDownOffset = alignDown(Offset, 4);
1680     int64_t OffsetDiff = Offset - AlignDownOffset;
1681 
1682     EVT IntVT = MemVT.changeTypeToInteger();
1683 
1684     // TODO: If we passed in the base kernel offset we could have a better
1685     // alignment than 4, but we don't really need it.
1686     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1687     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1688                                MachineMemOperand::MODereferenceable |
1689                                    MachineMemOperand::MOInvariant);
1690 
1691     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1692     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1693 
1694     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1695     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1696     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1697 
1698 
1699     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1700   }
1701 
1702   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1703   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1704                              MachineMemOperand::MODereferenceable |
1705                                  MachineMemOperand::MOInvariant);
1706 
1707   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1708   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1709 }
1710 
1711 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1712                                               const SDLoc &SL, SDValue Chain,
1713                                               const ISD::InputArg &Arg) const {
1714   MachineFunction &MF = DAG.getMachineFunction();
1715   MachineFrameInfo &MFI = MF.getFrameInfo();
1716 
1717   if (Arg.Flags.isByVal()) {
1718     unsigned Size = Arg.Flags.getByValSize();
1719     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1720     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1721   }
1722 
1723   unsigned ArgOffset = VA.getLocMemOffset();
1724   unsigned ArgSize = VA.getValVT().getStoreSize();
1725 
1726   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1727 
1728   // Create load nodes to retrieve arguments from the stack.
1729   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1730   SDValue ArgValue;
1731 
1732   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1733   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1734   MVT MemVT = VA.getValVT();
1735 
1736   switch (VA.getLocInfo()) {
1737   default:
1738     break;
1739   case CCValAssign::BCvt:
1740     MemVT = VA.getLocVT();
1741     break;
1742   case CCValAssign::SExt:
1743     ExtType = ISD::SEXTLOAD;
1744     break;
1745   case CCValAssign::ZExt:
1746     ExtType = ISD::ZEXTLOAD;
1747     break;
1748   case CCValAssign::AExt:
1749     ExtType = ISD::EXTLOAD;
1750     break;
1751   }
1752 
1753   ArgValue = DAG.getExtLoad(
1754     ExtType, SL, VA.getLocVT(), Chain, FIN,
1755     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1756     MemVT);
1757   return ArgValue;
1758 }
1759 
1760 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1761   const SIMachineFunctionInfo &MFI,
1762   EVT VT,
1763   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1764   const ArgDescriptor *Reg;
1765   const TargetRegisterClass *RC;
1766   LLT Ty;
1767 
1768   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1769   if (!Reg) {
1770     if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) {
1771       // It's possible for a kernarg intrinsic call to appear in a kernel with
1772       // no allocated segment, in which case we do not add the user sgpr
1773       // argument, so just return null.
1774       return DAG.getConstant(0, SDLoc(), VT);
1775     }
1776 
1777     // It's undefined behavior if a function marked with the amdgpu-no-*
1778     // attributes uses the corresponding intrinsic.
1779     return DAG.getUNDEF(VT);
1780   }
1781 
1782   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1783 }
1784 
1785 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1786                                CallingConv::ID CallConv,
1787                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1788                                FunctionType *FType,
1789                                SIMachineFunctionInfo *Info) {
1790   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1791     const ISD::InputArg *Arg = &Ins[I];
1792 
1793     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1794            "vector type argument should have been split");
1795 
1796     // First check if it's a PS input addr.
1797     if (CallConv == CallingConv::AMDGPU_PS &&
1798         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1799       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1800 
1801       // Inconveniently only the first part of the split is marked as isSplit,
1802       // so skip to the end. We only want to increment PSInputNum once for the
1803       // entire split argument.
1804       if (Arg->Flags.isSplit()) {
1805         while (!Arg->Flags.isSplitEnd()) {
1806           assert((!Arg->VT.isVector() ||
1807                   Arg->VT.getScalarSizeInBits() == 16) &&
1808                  "unexpected vector split in ps argument type");
1809           if (!SkipArg)
1810             Splits.push_back(*Arg);
1811           Arg = &Ins[++I];
1812         }
1813       }
1814 
1815       if (SkipArg) {
1816         // We can safely skip PS inputs.
1817         Skipped.set(Arg->getOrigArgIndex());
1818         ++PSInputNum;
1819         continue;
1820       }
1821 
1822       Info->markPSInputAllocated(PSInputNum);
1823       if (Arg->Used)
1824         Info->markPSInputEnabled(PSInputNum);
1825 
1826       ++PSInputNum;
1827     }
1828 
1829     Splits.push_back(*Arg);
1830   }
1831 }
1832 
1833 // Allocate special inputs passed in VGPRs.
1834 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1835                                                       MachineFunction &MF,
1836                                                       const SIRegisterInfo &TRI,
1837                                                       SIMachineFunctionInfo &Info) const {
1838   const LLT S32 = LLT::scalar(32);
1839   MachineRegisterInfo &MRI = MF.getRegInfo();
1840 
1841   if (Info.hasWorkItemIDX()) {
1842     Register Reg = AMDGPU::VGPR0;
1843     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1844 
1845     CCInfo.AllocateReg(Reg);
1846     unsigned Mask = (Subtarget->hasPackedTID() &&
1847                      Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
1848     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1849   }
1850 
1851   if (Info.hasWorkItemIDY()) {
1852     assert(Info.hasWorkItemIDX());
1853     if (Subtarget->hasPackedTID()) {
1854       Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1855                                                         0x3ff << 10));
1856     } else {
1857       unsigned Reg = AMDGPU::VGPR1;
1858       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1859 
1860       CCInfo.AllocateReg(Reg);
1861       Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1862     }
1863   }
1864 
1865   if (Info.hasWorkItemIDZ()) {
1866     assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
1867     if (Subtarget->hasPackedTID()) {
1868       Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1869                                                         0x3ff << 20));
1870     } else {
1871       unsigned Reg = AMDGPU::VGPR2;
1872       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1873 
1874       CCInfo.AllocateReg(Reg);
1875       Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1876     }
1877   }
1878 }
1879 
1880 // Try to allocate a VGPR at the end of the argument list, or if no argument
1881 // VGPRs are left allocating a stack slot.
1882 // If \p Mask is is given it indicates bitfield position in the register.
1883 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1884 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1885                                          ArgDescriptor Arg = ArgDescriptor()) {
1886   if (Arg.isSet())
1887     return ArgDescriptor::createArg(Arg, Mask);
1888 
1889   ArrayRef<MCPhysReg> ArgVGPRs
1890     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1891   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1892   if (RegIdx == ArgVGPRs.size()) {
1893     // Spill to stack required.
1894     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1895 
1896     return ArgDescriptor::createStack(Offset, Mask);
1897   }
1898 
1899   unsigned Reg = ArgVGPRs[RegIdx];
1900   Reg = CCInfo.AllocateReg(Reg);
1901   assert(Reg != AMDGPU::NoRegister);
1902 
1903   MachineFunction &MF = CCInfo.getMachineFunction();
1904   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1905   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1906   return ArgDescriptor::createRegister(Reg, Mask);
1907 }
1908 
1909 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1910                                              const TargetRegisterClass *RC,
1911                                              unsigned NumArgRegs) {
1912   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1913   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1914   if (RegIdx == ArgSGPRs.size())
1915     report_fatal_error("ran out of SGPRs for arguments");
1916 
1917   unsigned Reg = ArgSGPRs[RegIdx];
1918   Reg = CCInfo.AllocateReg(Reg);
1919   assert(Reg != AMDGPU::NoRegister);
1920 
1921   MachineFunction &MF = CCInfo.getMachineFunction();
1922   MF.addLiveIn(Reg, RC);
1923   return ArgDescriptor::createRegister(Reg);
1924 }
1925 
1926 // If this has a fixed position, we still should allocate the register in the
1927 // CCInfo state. Technically we could get away with this for values passed
1928 // outside of the normal argument range.
1929 static void allocateFixedSGPRInputImpl(CCState &CCInfo,
1930                                        const TargetRegisterClass *RC,
1931                                        MCRegister Reg) {
1932   Reg = CCInfo.AllocateReg(Reg);
1933   assert(Reg != AMDGPU::NoRegister);
1934   MachineFunction &MF = CCInfo.getMachineFunction();
1935   MF.addLiveIn(Reg, RC);
1936 }
1937 
1938 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
1939   if (Arg) {
1940     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
1941                                Arg.getRegister());
1942   } else
1943     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1944 }
1945 
1946 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
1947   if (Arg) {
1948     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
1949                                Arg.getRegister());
1950   } else
1951     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1952 }
1953 
1954 /// Allocate implicit function VGPR arguments at the end of allocated user
1955 /// arguments.
1956 void SITargetLowering::allocateSpecialInputVGPRs(
1957   CCState &CCInfo, MachineFunction &MF,
1958   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1959   const unsigned Mask = 0x3ff;
1960   ArgDescriptor Arg;
1961 
1962   if (Info.hasWorkItemIDX()) {
1963     Arg = allocateVGPR32Input(CCInfo, Mask);
1964     Info.setWorkItemIDX(Arg);
1965   }
1966 
1967   if (Info.hasWorkItemIDY()) {
1968     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1969     Info.setWorkItemIDY(Arg);
1970   }
1971 
1972   if (Info.hasWorkItemIDZ())
1973     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1974 }
1975 
1976 /// Allocate implicit function VGPR arguments in fixed registers.
1977 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1978   CCState &CCInfo, MachineFunction &MF,
1979   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1980   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1981   if (!Reg)
1982     report_fatal_error("failed to allocated VGPR for implicit arguments");
1983 
1984   const unsigned Mask = 0x3ff;
1985   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1986   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1987   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1988 }
1989 
1990 void SITargetLowering::allocateSpecialInputSGPRs(
1991   CCState &CCInfo,
1992   MachineFunction &MF,
1993   const SIRegisterInfo &TRI,
1994   SIMachineFunctionInfo &Info) const {
1995   auto &ArgInfo = Info.getArgInfo();
1996 
1997   // TODO: Unify handling with private memory pointers.
1998   if (Info.hasDispatchPtr())
1999     allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
2000 
2001   if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5)
2002     allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
2003 
2004   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
2005   // constant offset from the kernarg segment.
2006   if (Info.hasImplicitArgPtr())
2007     allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
2008 
2009   if (Info.hasDispatchID())
2010     allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2011 
2012   // flat_scratch_init is not applicable for non-kernel functions.
2013 
2014   if (Info.hasWorkGroupIDX())
2015     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2016 
2017   if (Info.hasWorkGroupIDY())
2018     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2019 
2020   if (Info.hasWorkGroupIDZ())
2021     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2022 }
2023 
2024 // Allocate special inputs passed in user SGPRs.
2025 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2026                                             MachineFunction &MF,
2027                                             const SIRegisterInfo &TRI,
2028                                             SIMachineFunctionInfo &Info) const {
2029   if (Info.hasImplicitBufferPtr()) {
2030     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2031     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2032     CCInfo.AllocateReg(ImplicitBufferPtrReg);
2033   }
2034 
2035   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2036   if (Info.hasPrivateSegmentBuffer()) {
2037     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2038     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2039     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2040   }
2041 
2042   if (Info.hasDispatchPtr()) {
2043     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2044     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2045     CCInfo.AllocateReg(DispatchPtrReg);
2046   }
2047 
2048   if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) {
2049     Register QueuePtrReg = Info.addQueuePtr(TRI);
2050     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2051     CCInfo.AllocateReg(QueuePtrReg);
2052   }
2053 
2054   if (Info.hasKernargSegmentPtr()) {
2055     MachineRegisterInfo &MRI = MF.getRegInfo();
2056     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2057     CCInfo.AllocateReg(InputPtrReg);
2058 
2059     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2060     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2061   }
2062 
2063   if (Info.hasDispatchID()) {
2064     Register DispatchIDReg = Info.addDispatchID(TRI);
2065     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2066     CCInfo.AllocateReg(DispatchIDReg);
2067   }
2068 
2069   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2070     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2071     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2072     CCInfo.AllocateReg(FlatScratchInitReg);
2073   }
2074 
2075   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2076   // these from the dispatch pointer.
2077 }
2078 
2079 // Allocate special input registers that are initialized per-wave.
2080 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2081                                            MachineFunction &MF,
2082                                            SIMachineFunctionInfo &Info,
2083                                            CallingConv::ID CallConv,
2084                                            bool IsShader) const {
2085   if (Info.hasWorkGroupIDX()) {
2086     Register Reg = Info.addWorkGroupIDX();
2087     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2088     CCInfo.AllocateReg(Reg);
2089   }
2090 
2091   if (Info.hasWorkGroupIDY()) {
2092     Register Reg = Info.addWorkGroupIDY();
2093     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2094     CCInfo.AllocateReg(Reg);
2095   }
2096 
2097   if (Info.hasWorkGroupIDZ()) {
2098     Register Reg = Info.addWorkGroupIDZ();
2099     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2100     CCInfo.AllocateReg(Reg);
2101   }
2102 
2103   if (Info.hasWorkGroupInfo()) {
2104     Register Reg = Info.addWorkGroupInfo();
2105     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2106     CCInfo.AllocateReg(Reg);
2107   }
2108 
2109   if (Info.hasPrivateSegmentWaveByteOffset()) {
2110     // Scratch wave offset passed in system SGPR.
2111     unsigned PrivateSegmentWaveByteOffsetReg;
2112 
2113     if (IsShader) {
2114       PrivateSegmentWaveByteOffsetReg =
2115         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2116 
2117       // This is true if the scratch wave byte offset doesn't have a fixed
2118       // location.
2119       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2120         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2121         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2122       }
2123     } else
2124       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2125 
2126     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2127     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2128   }
2129 }
2130 
2131 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2132                                      MachineFunction &MF,
2133                                      const SIRegisterInfo &TRI,
2134                                      SIMachineFunctionInfo &Info) {
2135   // Now that we've figured out where the scratch register inputs are, see if
2136   // should reserve the arguments and use them directly.
2137   MachineFrameInfo &MFI = MF.getFrameInfo();
2138   bool HasStackObjects = MFI.hasStackObjects();
2139   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2140 
2141   // Record that we know we have non-spill stack objects so we don't need to
2142   // check all stack objects later.
2143   if (HasStackObjects)
2144     Info.setHasNonSpillStackObjects(true);
2145 
2146   // Everything live out of a block is spilled with fast regalloc, so it's
2147   // almost certain that spilling will be required.
2148   if (TM.getOptLevel() == CodeGenOpt::None)
2149     HasStackObjects = true;
2150 
2151   // For now assume stack access is needed in any callee functions, so we need
2152   // the scratch registers to pass in.
2153   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2154 
2155   if (!ST.enableFlatScratch()) {
2156     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2157       // If we have stack objects, we unquestionably need the private buffer
2158       // resource. For the Code Object V2 ABI, this will be the first 4 user
2159       // SGPR inputs. We can reserve those and use them directly.
2160 
2161       Register PrivateSegmentBufferReg =
2162           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2163       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2164     } else {
2165       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2166       // We tentatively reserve the last registers (skipping the last registers
2167       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2168       // we'll replace these with the ones immediately after those which were
2169       // really allocated. In the prologue copies will be inserted from the
2170       // argument to these reserved registers.
2171 
2172       // Without HSA, relocations are used for the scratch pointer and the
2173       // buffer resource setup is always inserted in the prologue. Scratch wave
2174       // offset is still in an input SGPR.
2175       Info.setScratchRSrcReg(ReservedBufferReg);
2176     }
2177   }
2178 
2179   MachineRegisterInfo &MRI = MF.getRegInfo();
2180 
2181   // For entry functions we have to set up the stack pointer if we use it,
2182   // whereas non-entry functions get this "for free". This means there is no
2183   // intrinsic advantage to using S32 over S34 in cases where we do not have
2184   // calls but do need a frame pointer (i.e. if we are requested to have one
2185   // because frame pointer elimination is disabled). To keep things simple we
2186   // only ever use S32 as the call ABI stack pointer, and so using it does not
2187   // imply we need a separate frame pointer.
2188   //
2189   // Try to use s32 as the SP, but move it if it would interfere with input
2190   // arguments. This won't work with calls though.
2191   //
2192   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2193   // registers.
2194   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2195     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2196   } else {
2197     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2198 
2199     if (MFI.hasCalls())
2200       report_fatal_error("call in graphics shader with too many input SGPRs");
2201 
2202     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2203       if (!MRI.isLiveIn(Reg)) {
2204         Info.setStackPtrOffsetReg(Reg);
2205         break;
2206       }
2207     }
2208 
2209     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2210       report_fatal_error("failed to find register for SP");
2211   }
2212 
2213   // hasFP should be accurate for entry functions even before the frame is
2214   // finalized, because it does not rely on the known stack size, only
2215   // properties like whether variable sized objects are present.
2216   if (ST.getFrameLowering()->hasFP(MF)) {
2217     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2218   }
2219 }
2220 
2221 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2222   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2223   return !Info->isEntryFunction();
2224 }
2225 
2226 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2227 
2228 }
2229 
2230 void SITargetLowering::insertCopiesSplitCSR(
2231   MachineBasicBlock *Entry,
2232   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2233   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2234 
2235   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2236   if (!IStart)
2237     return;
2238 
2239   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2240   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2241   MachineBasicBlock::iterator MBBI = Entry->begin();
2242   for (const MCPhysReg *I = IStart; *I; ++I) {
2243     const TargetRegisterClass *RC = nullptr;
2244     if (AMDGPU::SReg_64RegClass.contains(*I))
2245       RC = &AMDGPU::SGPR_64RegClass;
2246     else if (AMDGPU::SReg_32RegClass.contains(*I))
2247       RC = &AMDGPU::SGPR_32RegClass;
2248     else
2249       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2250 
2251     Register NewVR = MRI->createVirtualRegister(RC);
2252     // Create copy from CSR to a virtual register.
2253     Entry->addLiveIn(*I);
2254     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2255       .addReg(*I);
2256 
2257     // Insert the copy-back instructions right before the terminator.
2258     for (auto *Exit : Exits)
2259       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2260               TII->get(TargetOpcode::COPY), *I)
2261         .addReg(NewVR);
2262   }
2263 }
2264 
2265 SDValue SITargetLowering::LowerFormalArguments(
2266     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2267     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2268     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2269   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2270 
2271   MachineFunction &MF = DAG.getMachineFunction();
2272   const Function &Fn = MF.getFunction();
2273   FunctionType *FType = MF.getFunction().getFunctionType();
2274   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2275 
2276   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2277     DiagnosticInfoUnsupported NoGraphicsHSA(
2278         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2279     DAG.getContext()->diagnose(NoGraphicsHSA);
2280     return DAG.getEntryNode();
2281   }
2282 
2283   Info->allocateModuleLDSGlobal(Fn);
2284 
2285   SmallVector<ISD::InputArg, 16> Splits;
2286   SmallVector<CCValAssign, 16> ArgLocs;
2287   BitVector Skipped(Ins.size());
2288   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2289                  *DAG.getContext());
2290 
2291   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2292   bool IsKernel = AMDGPU::isKernel(CallConv);
2293   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2294 
2295   if (IsGraphics) {
2296     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2297            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2298            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2299            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2300            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2301            !Info->hasWorkItemIDZ());
2302   }
2303 
2304   if (CallConv == CallingConv::AMDGPU_PS) {
2305     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2306 
2307     // At least one interpolation mode must be enabled or else the GPU will
2308     // hang.
2309     //
2310     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2311     // set PSInputAddr, the user wants to enable some bits after the compilation
2312     // based on run-time states. Since we can't know what the final PSInputEna
2313     // will look like, so we shouldn't do anything here and the user should take
2314     // responsibility for the correct programming.
2315     //
2316     // Otherwise, the following restrictions apply:
2317     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2318     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2319     //   enabled too.
2320     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2321         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2322       CCInfo.AllocateReg(AMDGPU::VGPR0);
2323       CCInfo.AllocateReg(AMDGPU::VGPR1);
2324       Info->markPSInputAllocated(0);
2325       Info->markPSInputEnabled(0);
2326     }
2327     if (Subtarget->isAmdPalOS()) {
2328       // For isAmdPalOS, the user does not enable some bits after compilation
2329       // based on run-time states; the register values being generated here are
2330       // the final ones set in hardware. Therefore we need to apply the
2331       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2332       // a bit is set in PSInputAddr but not PSInputEnable is where the
2333       // frontend set up an input arg for a particular interpolation mode, but
2334       // nothing uses that input arg. Really we should have an earlier pass
2335       // that removes such an arg.)
2336       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2337       if ((PsInputBits & 0x7F) == 0 ||
2338           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2339         Info->markPSInputEnabled(
2340             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2341     }
2342   } else if (IsKernel) {
2343     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2344   } else {
2345     Splits.append(Ins.begin(), Ins.end());
2346   }
2347 
2348   if (IsEntryFunc) {
2349     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2350     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2351   } else if (!IsGraphics) {
2352     // For the fixed ABI, pass workitem IDs in the last argument register.
2353     allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2354   }
2355 
2356   if (IsKernel) {
2357     analyzeFormalArgumentsCompute(CCInfo, Ins);
2358   } else {
2359     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2360     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2361   }
2362 
2363   SmallVector<SDValue, 16> Chains;
2364 
2365   // FIXME: This is the minimum kernel argument alignment. We should improve
2366   // this to the maximum alignment of the arguments.
2367   //
2368   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2369   // kern arg offset.
2370   const Align KernelArgBaseAlign = Align(16);
2371 
2372   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2373     const ISD::InputArg &Arg = Ins[i];
2374     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2375       InVals.push_back(DAG.getUNDEF(Arg.VT));
2376       continue;
2377     }
2378 
2379     CCValAssign &VA = ArgLocs[ArgIdx++];
2380     MVT VT = VA.getLocVT();
2381 
2382     if (IsEntryFunc && VA.isMemLoc()) {
2383       VT = Ins[i].VT;
2384       EVT MemVT = VA.getLocVT();
2385 
2386       const uint64_t Offset = VA.getLocMemOffset();
2387       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2388 
2389       if (Arg.Flags.isByRef()) {
2390         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2391 
2392         const GCNTargetMachine &TM =
2393             static_cast<const GCNTargetMachine &>(getTargetMachine());
2394         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2395                                     Arg.Flags.getPointerAddrSpace())) {
2396           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2397                                      Arg.Flags.getPointerAddrSpace());
2398         }
2399 
2400         InVals.push_back(Ptr);
2401         continue;
2402       }
2403 
2404       SDValue Arg = lowerKernargMemParameter(
2405         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2406       Chains.push_back(Arg.getValue(1));
2407 
2408       auto *ParamTy =
2409         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2410       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2411           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2412                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2413         // On SI local pointers are just offsets into LDS, so they are always
2414         // less than 16-bits.  On CI and newer they could potentially be
2415         // real pointers, so we can't guarantee their size.
2416         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2417                           DAG.getValueType(MVT::i16));
2418       }
2419 
2420       InVals.push_back(Arg);
2421       continue;
2422     } else if (!IsEntryFunc && VA.isMemLoc()) {
2423       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2424       InVals.push_back(Val);
2425       if (!Arg.Flags.isByVal())
2426         Chains.push_back(Val.getValue(1));
2427       continue;
2428     }
2429 
2430     assert(VA.isRegLoc() && "Parameter must be in a register!");
2431 
2432     Register Reg = VA.getLocReg();
2433     const TargetRegisterClass *RC = nullptr;
2434     if (AMDGPU::VGPR_32RegClass.contains(Reg))
2435       RC = &AMDGPU::VGPR_32RegClass;
2436     else if (AMDGPU::SGPR_32RegClass.contains(Reg))
2437       RC = &AMDGPU::SGPR_32RegClass;
2438     else
2439       llvm_unreachable("Unexpected register class in LowerFormalArguments!");
2440     EVT ValVT = VA.getValVT();
2441 
2442     Reg = MF.addLiveIn(Reg, RC);
2443     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2444 
2445     if (Arg.Flags.isSRet()) {
2446       // The return object should be reasonably addressable.
2447 
2448       // FIXME: This helps when the return is a real sret. If it is a
2449       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2450       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2451       unsigned NumBits
2452         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2453       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2454         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2455     }
2456 
2457     // If this is an 8 or 16-bit value, it is really passed promoted
2458     // to 32 bits. Insert an assert[sz]ext to capture this, then
2459     // truncate to the right size.
2460     switch (VA.getLocInfo()) {
2461     case CCValAssign::Full:
2462       break;
2463     case CCValAssign::BCvt:
2464       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2465       break;
2466     case CCValAssign::SExt:
2467       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2468                         DAG.getValueType(ValVT));
2469       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2470       break;
2471     case CCValAssign::ZExt:
2472       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2473                         DAG.getValueType(ValVT));
2474       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2475       break;
2476     case CCValAssign::AExt:
2477       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2478       break;
2479     default:
2480       llvm_unreachable("Unknown loc info!");
2481     }
2482 
2483     InVals.push_back(Val);
2484   }
2485 
2486   // Start adding system SGPRs.
2487   if (IsEntryFunc) {
2488     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2489   } else {
2490     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2491     if (!IsGraphics)
2492       allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2493   }
2494 
2495   auto &ArgUsageInfo =
2496     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2497   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2498 
2499   unsigned StackArgSize = CCInfo.getNextStackOffset();
2500   Info->setBytesInStackArgArea(StackArgSize);
2501 
2502   return Chains.empty() ? Chain :
2503     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2504 }
2505 
2506 // TODO: If return values can't fit in registers, we should return as many as
2507 // possible in registers before passing on stack.
2508 bool SITargetLowering::CanLowerReturn(
2509   CallingConv::ID CallConv,
2510   MachineFunction &MF, bool IsVarArg,
2511   const SmallVectorImpl<ISD::OutputArg> &Outs,
2512   LLVMContext &Context) const {
2513   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2514   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2515   // for shaders. Vector types should be explicitly handled by CC.
2516   if (AMDGPU::isEntryFunctionCC(CallConv))
2517     return true;
2518 
2519   SmallVector<CCValAssign, 16> RVLocs;
2520   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2521   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2522 }
2523 
2524 SDValue
2525 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2526                               bool isVarArg,
2527                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2528                               const SmallVectorImpl<SDValue> &OutVals,
2529                               const SDLoc &DL, SelectionDAG &DAG) const {
2530   MachineFunction &MF = DAG.getMachineFunction();
2531   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2532 
2533   if (AMDGPU::isKernel(CallConv)) {
2534     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2535                                              OutVals, DL, DAG);
2536   }
2537 
2538   bool IsShader = AMDGPU::isShader(CallConv);
2539 
2540   Info->setIfReturnsVoid(Outs.empty());
2541   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2542 
2543   // CCValAssign - represent the assignment of the return value to a location.
2544   SmallVector<CCValAssign, 48> RVLocs;
2545   SmallVector<ISD::OutputArg, 48> Splits;
2546 
2547   // CCState - Info about the registers and stack slots.
2548   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2549                  *DAG.getContext());
2550 
2551   // Analyze outgoing return values.
2552   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2553 
2554   SDValue Flag;
2555   SmallVector<SDValue, 48> RetOps;
2556   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2557 
2558   // Copy the result values into the output registers.
2559   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2560        ++I, ++RealRVLocIdx) {
2561     CCValAssign &VA = RVLocs[I];
2562     assert(VA.isRegLoc() && "Can only return in registers!");
2563     // TODO: Partially return in registers if return values don't fit.
2564     SDValue Arg = OutVals[RealRVLocIdx];
2565 
2566     // Copied from other backends.
2567     switch (VA.getLocInfo()) {
2568     case CCValAssign::Full:
2569       break;
2570     case CCValAssign::BCvt:
2571       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2572       break;
2573     case CCValAssign::SExt:
2574       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2575       break;
2576     case CCValAssign::ZExt:
2577       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2578       break;
2579     case CCValAssign::AExt:
2580       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2581       break;
2582     default:
2583       llvm_unreachable("Unknown loc info!");
2584     }
2585 
2586     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2587     Flag = Chain.getValue(1);
2588     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2589   }
2590 
2591   // FIXME: Does sret work properly?
2592   if (!Info->isEntryFunction()) {
2593     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2594     const MCPhysReg *I =
2595       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2596     if (I) {
2597       for (; *I; ++I) {
2598         if (AMDGPU::SReg_64RegClass.contains(*I))
2599           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2600         else if (AMDGPU::SReg_32RegClass.contains(*I))
2601           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2602         else
2603           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2604       }
2605     }
2606   }
2607 
2608   // Update chain and glue.
2609   RetOps[0] = Chain;
2610   if (Flag.getNode())
2611     RetOps.push_back(Flag);
2612 
2613   unsigned Opc = AMDGPUISD::ENDPGM;
2614   if (!IsWaveEnd)
2615     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2616   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2617 }
2618 
2619 SDValue SITargetLowering::LowerCallResult(
2620     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2621     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2622     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2623     SDValue ThisVal) const {
2624   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2625 
2626   // Assign locations to each value returned by this call.
2627   SmallVector<CCValAssign, 16> RVLocs;
2628   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2629                  *DAG.getContext());
2630   CCInfo.AnalyzeCallResult(Ins, RetCC);
2631 
2632   // Copy all of the result registers out of their specified physreg.
2633   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2634     CCValAssign VA = RVLocs[i];
2635     SDValue Val;
2636 
2637     if (VA.isRegLoc()) {
2638       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2639       Chain = Val.getValue(1);
2640       InFlag = Val.getValue(2);
2641     } else if (VA.isMemLoc()) {
2642       report_fatal_error("TODO: return values in memory");
2643     } else
2644       llvm_unreachable("unknown argument location type");
2645 
2646     switch (VA.getLocInfo()) {
2647     case CCValAssign::Full:
2648       break;
2649     case CCValAssign::BCvt:
2650       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2651       break;
2652     case CCValAssign::ZExt:
2653       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2654                         DAG.getValueType(VA.getValVT()));
2655       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2656       break;
2657     case CCValAssign::SExt:
2658       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2659                         DAG.getValueType(VA.getValVT()));
2660       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2661       break;
2662     case CCValAssign::AExt:
2663       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2664       break;
2665     default:
2666       llvm_unreachable("Unknown loc info!");
2667     }
2668 
2669     InVals.push_back(Val);
2670   }
2671 
2672   return Chain;
2673 }
2674 
2675 // Add code to pass special inputs required depending on used features separate
2676 // from the explicit user arguments present in the IR.
2677 void SITargetLowering::passSpecialInputs(
2678     CallLoweringInfo &CLI,
2679     CCState &CCInfo,
2680     const SIMachineFunctionInfo &Info,
2681     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2682     SmallVectorImpl<SDValue> &MemOpChains,
2683     SDValue Chain) const {
2684   // If we don't have a call site, this was a call inserted by
2685   // legalization. These can never use special inputs.
2686   if (!CLI.CB)
2687     return;
2688 
2689   SelectionDAG &DAG = CLI.DAG;
2690   const SDLoc &DL = CLI.DL;
2691   const Function &F = DAG.getMachineFunction().getFunction();
2692 
2693   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2694   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2695 
2696   const AMDGPUFunctionArgInfo *CalleeArgInfo
2697     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2698   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2699     auto &ArgUsageInfo =
2700       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2701     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2702   }
2703 
2704   // TODO: Unify with private memory register handling. This is complicated by
2705   // the fact that at least in kernels, the input argument is not necessarily
2706   // in the same location as the input.
2707   static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
2708                              StringLiteral> ImplicitAttrs[] = {
2709     {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"},
2710     {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" },
2711     {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"},
2712     {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"},
2713     {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"},
2714     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"},
2715     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"}
2716   };
2717 
2718   for (auto Attr : ImplicitAttrs) {
2719     const ArgDescriptor *OutgoingArg;
2720     const TargetRegisterClass *ArgRC;
2721     LLT ArgTy;
2722 
2723     AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first;
2724 
2725     // If the callee does not use the attribute value, skip copying the value.
2726     if (CLI.CB->hasFnAttr(Attr.second))
2727       continue;
2728 
2729     std::tie(OutgoingArg, ArgRC, ArgTy) =
2730         CalleeArgInfo->getPreloadedValue(InputID);
2731     if (!OutgoingArg)
2732       continue;
2733 
2734     const ArgDescriptor *IncomingArg;
2735     const TargetRegisterClass *IncomingArgRC;
2736     LLT Ty;
2737     std::tie(IncomingArg, IncomingArgRC, Ty) =
2738         CallerArgInfo.getPreloadedValue(InputID);
2739     assert(IncomingArgRC == ArgRC);
2740 
2741     // All special arguments are ints for now.
2742     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2743     SDValue InputReg;
2744 
2745     if (IncomingArg) {
2746       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2747     } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
2748       // The implicit arg ptr is special because it doesn't have a corresponding
2749       // input for kernels, and is computed from the kernarg segment pointer.
2750       InputReg = getImplicitArgPtr(DAG, DL);
2751     } else {
2752       // We may have proven the input wasn't needed, although the ABI is
2753       // requiring it. We just need to allocate the register appropriately.
2754       InputReg = DAG.getUNDEF(ArgVT);
2755     }
2756 
2757     if (OutgoingArg->isRegister()) {
2758       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2759       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2760         report_fatal_error("failed to allocate implicit input argument");
2761     } else {
2762       unsigned SpecialArgOffset =
2763           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2764       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2765                                               SpecialArgOffset);
2766       MemOpChains.push_back(ArgStore);
2767     }
2768   }
2769 
2770   // Pack workitem IDs into a single register or pass it as is if already
2771   // packed.
2772   const ArgDescriptor *OutgoingArg;
2773   const TargetRegisterClass *ArgRC;
2774   LLT Ty;
2775 
2776   std::tie(OutgoingArg, ArgRC, Ty) =
2777       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2778   if (!OutgoingArg)
2779     std::tie(OutgoingArg, ArgRC, Ty) =
2780         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2781   if (!OutgoingArg)
2782     std::tie(OutgoingArg, ArgRC, Ty) =
2783         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2784   if (!OutgoingArg)
2785     return;
2786 
2787   const ArgDescriptor *IncomingArgX = std::get<0>(
2788       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2789   const ArgDescriptor *IncomingArgY = std::get<0>(
2790       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2791   const ArgDescriptor *IncomingArgZ = std::get<0>(
2792       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2793 
2794   SDValue InputReg;
2795   SDLoc SL;
2796 
2797   const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
2798   const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
2799   const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
2800 
2801   // If incoming ids are not packed we need to pack them.
2802   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
2803       NeedWorkItemIDX) {
2804     if (Subtarget->getMaxWorkitemID(F, 0) != 0) {
2805       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2806     } else {
2807       InputReg = DAG.getConstant(0, DL, MVT::i32);
2808     }
2809   }
2810 
2811   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
2812       NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) {
2813     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2814     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2815                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2816     InputReg = InputReg.getNode() ?
2817                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2818   }
2819 
2820   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
2821       NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) {
2822     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2823     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2824                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2825     InputReg = InputReg.getNode() ?
2826                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2827   }
2828 
2829   if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
2830     if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) {
2831       // We're in a situation where the outgoing function requires the workitem
2832       // ID, but the calling function does not have it (e.g a graphics function
2833       // calling a C calling convention function). This is illegal, but we need
2834       // to produce something.
2835       InputReg = DAG.getUNDEF(MVT::i32);
2836     } else {
2837       // Workitem ids are already packed, any of present incoming arguments
2838       // will carry all required fields.
2839       ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2840         IncomingArgX ? *IncomingArgX :
2841         IncomingArgY ? *IncomingArgY :
2842         *IncomingArgZ, ~0u);
2843       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2844     }
2845   }
2846 
2847   if (OutgoingArg->isRegister()) {
2848     if (InputReg)
2849       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2850 
2851     CCInfo.AllocateReg(OutgoingArg->getRegister());
2852   } else {
2853     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2854     if (InputReg) {
2855       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2856                                               SpecialArgOffset);
2857       MemOpChains.push_back(ArgStore);
2858     }
2859   }
2860 }
2861 
2862 static bool canGuaranteeTCO(CallingConv::ID CC) {
2863   return CC == CallingConv::Fast;
2864 }
2865 
2866 /// Return true if we might ever do TCO for calls with this calling convention.
2867 static bool mayTailCallThisCC(CallingConv::ID CC) {
2868   switch (CC) {
2869   case CallingConv::C:
2870   case CallingConv::AMDGPU_Gfx:
2871     return true;
2872   default:
2873     return canGuaranteeTCO(CC);
2874   }
2875 }
2876 
2877 bool SITargetLowering::isEligibleForTailCallOptimization(
2878     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2879     const SmallVectorImpl<ISD::OutputArg> &Outs,
2880     const SmallVectorImpl<SDValue> &OutVals,
2881     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2882   if (!mayTailCallThisCC(CalleeCC))
2883     return false;
2884 
2885   // For a divergent call target, we need to do a waterfall loop over the
2886   // possible callees which precludes us from using a simple jump.
2887   if (Callee->isDivergent())
2888     return false;
2889 
2890   MachineFunction &MF = DAG.getMachineFunction();
2891   const Function &CallerF = MF.getFunction();
2892   CallingConv::ID CallerCC = CallerF.getCallingConv();
2893   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2894   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2895 
2896   // Kernels aren't callable, and don't have a live in return address so it
2897   // doesn't make sense to do a tail call with entry functions.
2898   if (!CallerPreserved)
2899     return false;
2900 
2901   bool CCMatch = CallerCC == CalleeCC;
2902 
2903   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2904     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2905       return true;
2906     return false;
2907   }
2908 
2909   // TODO: Can we handle var args?
2910   if (IsVarArg)
2911     return false;
2912 
2913   for (const Argument &Arg : CallerF.args()) {
2914     if (Arg.hasByValAttr())
2915       return false;
2916   }
2917 
2918   LLVMContext &Ctx = *DAG.getContext();
2919 
2920   // Check that the call results are passed in the same way.
2921   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2922                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2923                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2924     return false;
2925 
2926   // The callee has to preserve all registers the caller needs to preserve.
2927   if (!CCMatch) {
2928     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2929     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2930       return false;
2931   }
2932 
2933   // Nothing more to check if the callee is taking no arguments.
2934   if (Outs.empty())
2935     return true;
2936 
2937   SmallVector<CCValAssign, 16> ArgLocs;
2938   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2939 
2940   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2941 
2942   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2943   // If the stack arguments for this call do not fit into our own save area then
2944   // the call cannot be made tail.
2945   // TODO: Is this really necessary?
2946   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2947     return false;
2948 
2949   const MachineRegisterInfo &MRI = MF.getRegInfo();
2950   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2951 }
2952 
2953 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2954   if (!CI->isTailCall())
2955     return false;
2956 
2957   const Function *ParentFn = CI->getParent()->getParent();
2958   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2959     return false;
2960   return true;
2961 }
2962 
2963 // The wave scratch offset register is used as the global base pointer.
2964 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2965                                     SmallVectorImpl<SDValue> &InVals) const {
2966   SelectionDAG &DAG = CLI.DAG;
2967   const SDLoc &DL = CLI.DL;
2968   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2969   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2970   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2971   SDValue Chain = CLI.Chain;
2972   SDValue Callee = CLI.Callee;
2973   bool &IsTailCall = CLI.IsTailCall;
2974   CallingConv::ID CallConv = CLI.CallConv;
2975   bool IsVarArg = CLI.IsVarArg;
2976   bool IsSibCall = false;
2977   bool IsThisReturn = false;
2978   MachineFunction &MF = DAG.getMachineFunction();
2979 
2980   if (Callee.isUndef() || isNullConstant(Callee)) {
2981     if (!CLI.IsTailCall) {
2982       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2983         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2984     }
2985 
2986     return Chain;
2987   }
2988 
2989   if (IsVarArg) {
2990     return lowerUnhandledCall(CLI, InVals,
2991                               "unsupported call to variadic function ");
2992   }
2993 
2994   if (!CLI.CB)
2995     report_fatal_error("unsupported libcall legalization");
2996 
2997   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2998     return lowerUnhandledCall(CLI, InVals,
2999                               "unsupported required tail call to function ");
3000   }
3001 
3002   if (AMDGPU::isShader(CallConv)) {
3003     // Note the issue is with the CC of the called function, not of the call
3004     // itself.
3005     return lowerUnhandledCall(CLI, InVals,
3006                               "unsupported call to a shader function ");
3007   }
3008 
3009   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
3010       CallConv != CallingConv::AMDGPU_Gfx) {
3011     // Only allow calls with specific calling conventions.
3012     return lowerUnhandledCall(CLI, InVals,
3013                               "unsupported calling convention for call from "
3014                               "graphics shader of function ");
3015   }
3016 
3017   if (IsTailCall) {
3018     IsTailCall = isEligibleForTailCallOptimization(
3019       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3020     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
3021       report_fatal_error("failed to perform tail call elimination on a call "
3022                          "site marked musttail");
3023     }
3024 
3025     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3026 
3027     // A sibling call is one where we're under the usual C ABI and not planning
3028     // to change that but can still do a tail call:
3029     if (!TailCallOpt && IsTailCall)
3030       IsSibCall = true;
3031 
3032     if (IsTailCall)
3033       ++NumTailCalls;
3034   }
3035 
3036   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3037   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3038   SmallVector<SDValue, 8> MemOpChains;
3039 
3040   // Analyze operands of the call, assigning locations to each operand.
3041   SmallVector<CCValAssign, 16> ArgLocs;
3042   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3043   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3044 
3045   if (CallConv != CallingConv::AMDGPU_Gfx) {
3046     // With a fixed ABI, allocate fixed registers before user arguments.
3047     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3048   }
3049 
3050   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3051 
3052   // Get a count of how many bytes are to be pushed on the stack.
3053   unsigned NumBytes = CCInfo.getNextStackOffset();
3054 
3055   if (IsSibCall) {
3056     // Since we're not changing the ABI to make this a tail call, the memory
3057     // operands are already available in the caller's incoming argument space.
3058     NumBytes = 0;
3059   }
3060 
3061   // FPDiff is the byte offset of the call's argument area from the callee's.
3062   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3063   // by this amount for a tail call. In a sibling call it must be 0 because the
3064   // caller will deallocate the entire stack and the callee still expects its
3065   // arguments to begin at SP+0. Completely unused for non-tail calls.
3066   int32_t FPDiff = 0;
3067   MachineFrameInfo &MFI = MF.getFrameInfo();
3068 
3069   // Adjust the stack pointer for the new arguments...
3070   // These operations are automatically eliminated by the prolog/epilog pass
3071   if (!IsSibCall) {
3072     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3073 
3074     if (!Subtarget->enableFlatScratch()) {
3075       SmallVector<SDValue, 4> CopyFromChains;
3076 
3077       // In the HSA case, this should be an identity copy.
3078       SDValue ScratchRSrcReg
3079         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3080       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3081       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3082       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3083     }
3084   }
3085 
3086   MVT PtrVT = MVT::i32;
3087 
3088   // Walk the register/memloc assignments, inserting copies/loads.
3089   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3090     CCValAssign &VA = ArgLocs[i];
3091     SDValue Arg = OutVals[i];
3092 
3093     // Promote the value if needed.
3094     switch (VA.getLocInfo()) {
3095     case CCValAssign::Full:
3096       break;
3097     case CCValAssign::BCvt:
3098       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3099       break;
3100     case CCValAssign::ZExt:
3101       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3102       break;
3103     case CCValAssign::SExt:
3104       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3105       break;
3106     case CCValAssign::AExt:
3107       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3108       break;
3109     case CCValAssign::FPExt:
3110       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3111       break;
3112     default:
3113       llvm_unreachable("Unknown loc info!");
3114     }
3115 
3116     if (VA.isRegLoc()) {
3117       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3118     } else {
3119       assert(VA.isMemLoc());
3120 
3121       SDValue DstAddr;
3122       MachinePointerInfo DstInfo;
3123 
3124       unsigned LocMemOffset = VA.getLocMemOffset();
3125       int32_t Offset = LocMemOffset;
3126 
3127       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3128       MaybeAlign Alignment;
3129 
3130       if (IsTailCall) {
3131         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3132         unsigned OpSize = Flags.isByVal() ?
3133           Flags.getByValSize() : VA.getValVT().getStoreSize();
3134 
3135         // FIXME: We can have better than the minimum byval required alignment.
3136         Alignment =
3137             Flags.isByVal()
3138                 ? Flags.getNonZeroByValAlign()
3139                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3140 
3141         Offset = Offset + FPDiff;
3142         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3143 
3144         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3145         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3146 
3147         // Make sure any stack arguments overlapping with where we're storing
3148         // are loaded before this eventual operation. Otherwise they'll be
3149         // clobbered.
3150 
3151         // FIXME: Why is this really necessary? This seems to just result in a
3152         // lot of code to copy the stack and write them back to the same
3153         // locations, which are supposed to be immutable?
3154         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3155       } else {
3156         // Stores to the argument stack area are relative to the stack pointer.
3157         SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3158                                         MVT::i32);
3159         DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3160         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3161         Alignment =
3162             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3163       }
3164 
3165       if (Outs[i].Flags.isByVal()) {
3166         SDValue SizeNode =
3167             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3168         SDValue Cpy =
3169             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3170                           Outs[i].Flags.getNonZeroByValAlign(),
3171                           /*isVol = */ false, /*AlwaysInline = */ true,
3172                           /*isTailCall = */ false, DstInfo,
3173                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3174 
3175         MemOpChains.push_back(Cpy);
3176       } else {
3177         SDValue Store =
3178             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3179         MemOpChains.push_back(Store);
3180       }
3181     }
3182   }
3183 
3184   if (!MemOpChains.empty())
3185     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3186 
3187   // Build a sequence of copy-to-reg nodes chained together with token chain
3188   // and flag operands which copy the outgoing args into the appropriate regs.
3189   SDValue InFlag;
3190   for (auto &RegToPass : RegsToPass) {
3191     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3192                              RegToPass.second, InFlag);
3193     InFlag = Chain.getValue(1);
3194   }
3195 
3196 
3197   // We don't usually want to end the call-sequence here because we would tidy
3198   // the frame up *after* the call, however in the ABI-changing tail-call case
3199   // we've carefully laid out the parameters so that when sp is reset they'll be
3200   // in the correct location.
3201   if (IsTailCall && !IsSibCall) {
3202     Chain = DAG.getCALLSEQ_END(Chain,
3203                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3204                                DAG.getTargetConstant(0, DL, MVT::i32),
3205                                InFlag, DL);
3206     InFlag = Chain.getValue(1);
3207   }
3208 
3209   std::vector<SDValue> Ops;
3210   Ops.push_back(Chain);
3211   Ops.push_back(Callee);
3212   // Add a redundant copy of the callee global which will not be legalized, as
3213   // we need direct access to the callee later.
3214   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3215     const GlobalValue *GV = GSD->getGlobal();
3216     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3217   } else {
3218     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3219   }
3220 
3221   if (IsTailCall) {
3222     // Each tail call may have to adjust the stack by a different amount, so
3223     // this information must travel along with the operation for eventual
3224     // consumption by emitEpilogue.
3225     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3226   }
3227 
3228   // Add argument registers to the end of the list so that they are known live
3229   // into the call.
3230   for (auto &RegToPass : RegsToPass) {
3231     Ops.push_back(DAG.getRegister(RegToPass.first,
3232                                   RegToPass.second.getValueType()));
3233   }
3234 
3235   // Add a register mask operand representing the call-preserved registers.
3236 
3237   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3238   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3239   assert(Mask && "Missing call preserved mask for calling convention");
3240   Ops.push_back(DAG.getRegisterMask(Mask));
3241 
3242   if (InFlag.getNode())
3243     Ops.push_back(InFlag);
3244 
3245   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3246 
3247   // If we're doing a tall call, use a TC_RETURN here rather than an
3248   // actual call instruction.
3249   if (IsTailCall) {
3250     MFI.setHasTailCall();
3251     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3252   }
3253 
3254   // Returns a chain and a flag for retval copy to use.
3255   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3256   Chain = Call.getValue(0);
3257   InFlag = Call.getValue(1);
3258 
3259   uint64_t CalleePopBytes = NumBytes;
3260   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3261                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3262                              InFlag, DL);
3263   if (!Ins.empty())
3264     InFlag = Chain.getValue(1);
3265 
3266   // Handle result values, copying them out of physregs into vregs that we
3267   // return.
3268   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3269                          InVals, IsThisReturn,
3270                          IsThisReturn ? OutVals[0] : SDValue());
3271 }
3272 
3273 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3274 // except for applying the wave size scale to the increment amount.
3275 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3276     SDValue Op, SelectionDAG &DAG) const {
3277   const MachineFunction &MF = DAG.getMachineFunction();
3278   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3279 
3280   SDLoc dl(Op);
3281   EVT VT = Op.getValueType();
3282   SDValue Tmp1 = Op;
3283   SDValue Tmp2 = Op.getValue(1);
3284   SDValue Tmp3 = Op.getOperand(2);
3285   SDValue Chain = Tmp1.getOperand(0);
3286 
3287   Register SPReg = Info->getStackPtrOffsetReg();
3288 
3289   // Chain the dynamic stack allocation so that it doesn't modify the stack
3290   // pointer when other instructions are using the stack.
3291   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3292 
3293   SDValue Size  = Tmp2.getOperand(1);
3294   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3295   Chain = SP.getValue(1);
3296   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3297   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3298   const TargetFrameLowering *TFL = ST.getFrameLowering();
3299   unsigned Opc =
3300     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3301     ISD::ADD : ISD::SUB;
3302 
3303   SDValue ScaledSize = DAG.getNode(
3304       ISD::SHL, dl, VT, Size,
3305       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3306 
3307   Align StackAlign = TFL->getStackAlign();
3308   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3309   if (Alignment && *Alignment > StackAlign) {
3310     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3311                        DAG.getConstant(-(uint64_t)Alignment->value()
3312                                            << ST.getWavefrontSizeLog2(),
3313                                        dl, VT));
3314   }
3315 
3316   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3317   Tmp2 = DAG.getCALLSEQ_END(
3318       Chain, DAG.getIntPtrConstant(0, dl, true),
3319       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3320 
3321   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3322 }
3323 
3324 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3325                                                   SelectionDAG &DAG) const {
3326   // We only handle constant sizes here to allow non-entry block, static sized
3327   // allocas. A truly dynamic value is more difficult to support because we
3328   // don't know if the size value is uniform or not. If the size isn't uniform,
3329   // we would need to do a wave reduction to get the maximum size to know how
3330   // much to increment the uniform stack pointer.
3331   SDValue Size = Op.getOperand(1);
3332   if (isa<ConstantSDNode>(Size))
3333       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3334 
3335   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3336 }
3337 
3338 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3339                                              const MachineFunction &MF) const {
3340   Register Reg = StringSwitch<Register>(RegName)
3341     .Case("m0", AMDGPU::M0)
3342     .Case("exec", AMDGPU::EXEC)
3343     .Case("exec_lo", AMDGPU::EXEC_LO)
3344     .Case("exec_hi", AMDGPU::EXEC_HI)
3345     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3346     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3347     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3348     .Default(Register());
3349 
3350   if (Reg == AMDGPU::NoRegister) {
3351     report_fatal_error(Twine("invalid register name \""
3352                              + StringRef(RegName)  + "\"."));
3353 
3354   }
3355 
3356   if (!Subtarget->hasFlatScrRegister() &&
3357        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3358     report_fatal_error(Twine("invalid register \""
3359                              + StringRef(RegName)  + "\" for subtarget."));
3360   }
3361 
3362   switch (Reg) {
3363   case AMDGPU::M0:
3364   case AMDGPU::EXEC_LO:
3365   case AMDGPU::EXEC_HI:
3366   case AMDGPU::FLAT_SCR_LO:
3367   case AMDGPU::FLAT_SCR_HI:
3368     if (VT.getSizeInBits() == 32)
3369       return Reg;
3370     break;
3371   case AMDGPU::EXEC:
3372   case AMDGPU::FLAT_SCR:
3373     if (VT.getSizeInBits() == 64)
3374       return Reg;
3375     break;
3376   default:
3377     llvm_unreachable("missing register type checking");
3378   }
3379 
3380   report_fatal_error(Twine("invalid type for register \""
3381                            + StringRef(RegName) + "\"."));
3382 }
3383 
3384 // If kill is not the last instruction, split the block so kill is always a
3385 // proper terminator.
3386 MachineBasicBlock *
3387 SITargetLowering::splitKillBlock(MachineInstr &MI,
3388                                  MachineBasicBlock *BB) const {
3389   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3390   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3391   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3392   return SplitBB;
3393 }
3394 
3395 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3396 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3397 // be the first instruction in the remainder block.
3398 //
3399 /// \returns { LoopBody, Remainder }
3400 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3401 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3402   MachineFunction *MF = MBB.getParent();
3403   MachineBasicBlock::iterator I(&MI);
3404 
3405   // To insert the loop we need to split the block. Move everything after this
3406   // point to a new block, and insert a new empty block between the two.
3407   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3408   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3409   MachineFunction::iterator MBBI(MBB);
3410   ++MBBI;
3411 
3412   MF->insert(MBBI, LoopBB);
3413   MF->insert(MBBI, RemainderBB);
3414 
3415   LoopBB->addSuccessor(LoopBB);
3416   LoopBB->addSuccessor(RemainderBB);
3417 
3418   // Move the rest of the block into a new block.
3419   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3420 
3421   if (InstInLoop) {
3422     auto Next = std::next(I);
3423 
3424     // Move instruction to loop body.
3425     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3426 
3427     // Move the rest of the block.
3428     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3429   } else {
3430     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3431   }
3432 
3433   MBB.addSuccessor(LoopBB);
3434 
3435   return std::make_pair(LoopBB, RemainderBB);
3436 }
3437 
3438 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3439 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3440   MachineBasicBlock *MBB = MI.getParent();
3441   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3442   auto I = MI.getIterator();
3443   auto E = std::next(I);
3444 
3445   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3446     .addImm(0);
3447 
3448   MIBundleBuilder Bundler(*MBB, I, E);
3449   finalizeBundle(*MBB, Bundler.begin());
3450 }
3451 
3452 MachineBasicBlock *
3453 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3454                                          MachineBasicBlock *BB) const {
3455   const DebugLoc &DL = MI.getDebugLoc();
3456 
3457   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3458 
3459   MachineBasicBlock *LoopBB;
3460   MachineBasicBlock *RemainderBB;
3461   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3462 
3463   // Apparently kill flags are only valid if the def is in the same block?
3464   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3465     Src->setIsKill(false);
3466 
3467   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3468 
3469   MachineBasicBlock::iterator I = LoopBB->end();
3470 
3471   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3472     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3473 
3474   // Clear TRAP_STS.MEM_VIOL
3475   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3476     .addImm(0)
3477     .addImm(EncodedReg);
3478 
3479   bundleInstWithWaitcnt(MI);
3480 
3481   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3482 
3483   // Load and check TRAP_STS.MEM_VIOL
3484   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3485     .addImm(EncodedReg);
3486 
3487   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3488   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3489     .addReg(Reg, RegState::Kill)
3490     .addImm(0);
3491   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3492     .addMBB(LoopBB);
3493 
3494   return RemainderBB;
3495 }
3496 
3497 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3498 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3499 // will only do one iteration. In the worst case, this will loop 64 times.
3500 //
3501 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3502 static MachineBasicBlock::iterator
3503 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3504                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3505                        const DebugLoc &DL, const MachineOperand &Idx,
3506                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3507                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3508                        Register &SGPRIdxReg) {
3509 
3510   MachineFunction *MF = OrigBB.getParent();
3511   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3512   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3513   MachineBasicBlock::iterator I = LoopBB.begin();
3514 
3515   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3516   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3517   Register NewExec = MRI.createVirtualRegister(BoolRC);
3518   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3519   Register CondReg = MRI.createVirtualRegister(BoolRC);
3520 
3521   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3522     .addReg(InitReg)
3523     .addMBB(&OrigBB)
3524     .addReg(ResultReg)
3525     .addMBB(&LoopBB);
3526 
3527   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3528     .addReg(InitSaveExecReg)
3529     .addMBB(&OrigBB)
3530     .addReg(NewExec)
3531     .addMBB(&LoopBB);
3532 
3533   // Read the next variant <- also loop target.
3534   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3535       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3536 
3537   // Compare the just read M0 value to all possible Idx values.
3538   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3539       .addReg(CurrentIdxReg)
3540       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3541 
3542   // Update EXEC, save the original EXEC value to VCC.
3543   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3544                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3545           NewExec)
3546     .addReg(CondReg, RegState::Kill);
3547 
3548   MRI.setSimpleHint(NewExec, CondReg);
3549 
3550   if (UseGPRIdxMode) {
3551     if (Offset == 0) {
3552       SGPRIdxReg = CurrentIdxReg;
3553     } else {
3554       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3555       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3556           .addReg(CurrentIdxReg, RegState::Kill)
3557           .addImm(Offset);
3558     }
3559   } else {
3560     // Move index from VCC into M0
3561     if (Offset == 0) {
3562       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3563         .addReg(CurrentIdxReg, RegState::Kill);
3564     } else {
3565       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3566         .addReg(CurrentIdxReg, RegState::Kill)
3567         .addImm(Offset);
3568     }
3569   }
3570 
3571   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3572   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3573   MachineInstr *InsertPt =
3574     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3575                                                   : AMDGPU::S_XOR_B64_term), Exec)
3576       .addReg(Exec)
3577       .addReg(NewExec);
3578 
3579   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3580   // s_cbranch_scc0?
3581 
3582   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3583   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3584     .addMBB(&LoopBB);
3585 
3586   return InsertPt->getIterator();
3587 }
3588 
3589 // This has slightly sub-optimal regalloc when the source vector is killed by
3590 // the read. The register allocator does not understand that the kill is
3591 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3592 // subregister from it, using 1 more VGPR than necessary. This was saved when
3593 // this was expanded after register allocation.
3594 static MachineBasicBlock::iterator
3595 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3596                unsigned InitResultReg, unsigned PhiReg, int Offset,
3597                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3598   MachineFunction *MF = MBB.getParent();
3599   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3600   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3601   MachineRegisterInfo &MRI = MF->getRegInfo();
3602   const DebugLoc &DL = MI.getDebugLoc();
3603   MachineBasicBlock::iterator I(&MI);
3604 
3605   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3606   Register DstReg = MI.getOperand(0).getReg();
3607   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3608   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3609   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3610   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3611 
3612   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3613 
3614   // Save the EXEC mask
3615   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3616     .addReg(Exec);
3617 
3618   MachineBasicBlock *LoopBB;
3619   MachineBasicBlock *RemainderBB;
3620   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3621 
3622   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3623 
3624   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3625                                       InitResultReg, DstReg, PhiReg, TmpExec,
3626                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3627 
3628   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3629   MachineFunction::iterator MBBI(LoopBB);
3630   ++MBBI;
3631   MF->insert(MBBI, LandingPad);
3632   LoopBB->removeSuccessor(RemainderBB);
3633   LandingPad->addSuccessor(RemainderBB);
3634   LoopBB->addSuccessor(LandingPad);
3635   MachineBasicBlock::iterator First = LandingPad->begin();
3636   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3637     .addReg(SaveExec);
3638 
3639   return InsPt;
3640 }
3641 
3642 // Returns subreg index, offset
3643 static std::pair<unsigned, int>
3644 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3645                             const TargetRegisterClass *SuperRC,
3646                             unsigned VecReg,
3647                             int Offset) {
3648   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3649 
3650   // Skip out of bounds offsets, or else we would end up using an undefined
3651   // register.
3652   if (Offset >= NumElts || Offset < 0)
3653     return std::make_pair(AMDGPU::sub0, Offset);
3654 
3655   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3656 }
3657 
3658 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3659                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3660                                  int Offset) {
3661   MachineBasicBlock *MBB = MI.getParent();
3662   const DebugLoc &DL = MI.getDebugLoc();
3663   MachineBasicBlock::iterator I(&MI);
3664 
3665   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3666 
3667   assert(Idx->getReg() != AMDGPU::NoRegister);
3668 
3669   if (Offset == 0) {
3670     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3671   } else {
3672     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3673         .add(*Idx)
3674         .addImm(Offset);
3675   }
3676 }
3677 
3678 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3679                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3680                                    int Offset) {
3681   MachineBasicBlock *MBB = MI.getParent();
3682   const DebugLoc &DL = MI.getDebugLoc();
3683   MachineBasicBlock::iterator I(&MI);
3684 
3685   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3686 
3687   if (Offset == 0)
3688     return Idx->getReg();
3689 
3690   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3691   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3692       .add(*Idx)
3693       .addImm(Offset);
3694   return Tmp;
3695 }
3696 
3697 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3698                                           MachineBasicBlock &MBB,
3699                                           const GCNSubtarget &ST) {
3700   const SIInstrInfo *TII = ST.getInstrInfo();
3701   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3702   MachineFunction *MF = MBB.getParent();
3703   MachineRegisterInfo &MRI = MF->getRegInfo();
3704 
3705   Register Dst = MI.getOperand(0).getReg();
3706   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3707   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3708   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3709 
3710   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3711   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3712 
3713   unsigned SubReg;
3714   std::tie(SubReg, Offset)
3715     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3716 
3717   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3718 
3719   // Check for a SGPR index.
3720   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3721     MachineBasicBlock::iterator I(&MI);
3722     const DebugLoc &DL = MI.getDebugLoc();
3723 
3724     if (UseGPRIdxMode) {
3725       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3726       // to avoid interfering with other uses, so probably requires a new
3727       // optimization pass.
3728       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3729 
3730       const MCInstrDesc &GPRIDXDesc =
3731           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3732       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3733           .addReg(SrcReg)
3734           .addReg(Idx)
3735           .addImm(SubReg);
3736     } else {
3737       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3738 
3739       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3740         .addReg(SrcReg, 0, SubReg)
3741         .addReg(SrcReg, RegState::Implicit);
3742     }
3743 
3744     MI.eraseFromParent();
3745 
3746     return &MBB;
3747   }
3748 
3749   // Control flow needs to be inserted if indexing with a VGPR.
3750   const DebugLoc &DL = MI.getDebugLoc();
3751   MachineBasicBlock::iterator I(&MI);
3752 
3753   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3754   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3755 
3756   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3757 
3758   Register SGPRIdxReg;
3759   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3760                               UseGPRIdxMode, SGPRIdxReg);
3761 
3762   MachineBasicBlock *LoopBB = InsPt->getParent();
3763 
3764   if (UseGPRIdxMode) {
3765     const MCInstrDesc &GPRIDXDesc =
3766         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3767 
3768     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3769         .addReg(SrcReg)
3770         .addReg(SGPRIdxReg)
3771         .addImm(SubReg);
3772   } else {
3773     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3774       .addReg(SrcReg, 0, SubReg)
3775       .addReg(SrcReg, RegState::Implicit);
3776   }
3777 
3778   MI.eraseFromParent();
3779 
3780   return LoopBB;
3781 }
3782 
3783 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3784                                           MachineBasicBlock &MBB,
3785                                           const GCNSubtarget &ST) {
3786   const SIInstrInfo *TII = ST.getInstrInfo();
3787   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3788   MachineFunction *MF = MBB.getParent();
3789   MachineRegisterInfo &MRI = MF->getRegInfo();
3790 
3791   Register Dst = MI.getOperand(0).getReg();
3792   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3793   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3794   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3795   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3796   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3797   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3798 
3799   // This can be an immediate, but will be folded later.
3800   assert(Val->getReg());
3801 
3802   unsigned SubReg;
3803   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3804                                                          SrcVec->getReg(),
3805                                                          Offset);
3806   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3807 
3808   if (Idx->getReg() == AMDGPU::NoRegister) {
3809     MachineBasicBlock::iterator I(&MI);
3810     const DebugLoc &DL = MI.getDebugLoc();
3811 
3812     assert(Offset == 0);
3813 
3814     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3815         .add(*SrcVec)
3816         .add(*Val)
3817         .addImm(SubReg);
3818 
3819     MI.eraseFromParent();
3820     return &MBB;
3821   }
3822 
3823   // Check for a SGPR index.
3824   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3825     MachineBasicBlock::iterator I(&MI);
3826     const DebugLoc &DL = MI.getDebugLoc();
3827 
3828     if (UseGPRIdxMode) {
3829       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3830 
3831       const MCInstrDesc &GPRIDXDesc =
3832           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3833       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3834           .addReg(SrcVec->getReg())
3835           .add(*Val)
3836           .addReg(Idx)
3837           .addImm(SubReg);
3838     } else {
3839       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3840 
3841       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3842           TRI.getRegSizeInBits(*VecRC), 32, false);
3843       BuildMI(MBB, I, DL, MovRelDesc, Dst)
3844           .addReg(SrcVec->getReg())
3845           .add(*Val)
3846           .addImm(SubReg);
3847     }
3848     MI.eraseFromParent();
3849     return &MBB;
3850   }
3851 
3852   // Control flow needs to be inserted if indexing with a VGPR.
3853   if (Val->isReg())
3854     MRI.clearKillFlags(Val->getReg());
3855 
3856   const DebugLoc &DL = MI.getDebugLoc();
3857 
3858   Register PhiReg = MRI.createVirtualRegister(VecRC);
3859 
3860   Register SGPRIdxReg;
3861   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
3862                               UseGPRIdxMode, SGPRIdxReg);
3863   MachineBasicBlock *LoopBB = InsPt->getParent();
3864 
3865   if (UseGPRIdxMode) {
3866     const MCInstrDesc &GPRIDXDesc =
3867         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3868 
3869     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3870         .addReg(PhiReg)
3871         .add(*Val)
3872         .addReg(SGPRIdxReg)
3873         .addImm(AMDGPU::sub0);
3874   } else {
3875     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3876         TRI.getRegSizeInBits(*VecRC), 32, false);
3877     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3878         .addReg(PhiReg)
3879         .add(*Val)
3880         .addImm(AMDGPU::sub0);
3881   }
3882 
3883   MI.eraseFromParent();
3884   return LoopBB;
3885 }
3886 
3887 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3888   MachineInstr &MI, MachineBasicBlock *BB) const {
3889 
3890   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3891   MachineFunction *MF = BB->getParent();
3892   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3893 
3894   switch (MI.getOpcode()) {
3895   case AMDGPU::S_UADDO_PSEUDO:
3896   case AMDGPU::S_USUBO_PSEUDO: {
3897     const DebugLoc &DL = MI.getDebugLoc();
3898     MachineOperand &Dest0 = MI.getOperand(0);
3899     MachineOperand &Dest1 = MI.getOperand(1);
3900     MachineOperand &Src0 = MI.getOperand(2);
3901     MachineOperand &Src1 = MI.getOperand(3);
3902 
3903     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3904                        ? AMDGPU::S_ADD_I32
3905                        : AMDGPU::S_SUB_I32;
3906     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3907 
3908     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3909         .addImm(1)
3910         .addImm(0);
3911 
3912     MI.eraseFromParent();
3913     return BB;
3914   }
3915   case AMDGPU::S_ADD_U64_PSEUDO:
3916   case AMDGPU::S_SUB_U64_PSEUDO: {
3917     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3918     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3919     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3920     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3921     const DebugLoc &DL = MI.getDebugLoc();
3922 
3923     MachineOperand &Dest = MI.getOperand(0);
3924     MachineOperand &Src0 = MI.getOperand(1);
3925     MachineOperand &Src1 = MI.getOperand(2);
3926 
3927     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3928     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3929 
3930     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3931         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3932     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3933         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3934 
3935     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3936         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3937     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3938         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3939 
3940     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3941 
3942     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3943     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3944     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3945     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3946     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3947         .addReg(DestSub0)
3948         .addImm(AMDGPU::sub0)
3949         .addReg(DestSub1)
3950         .addImm(AMDGPU::sub1);
3951     MI.eraseFromParent();
3952     return BB;
3953   }
3954   case AMDGPU::V_ADD_U64_PSEUDO:
3955   case AMDGPU::V_SUB_U64_PSEUDO: {
3956     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3957     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3958     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3959     const DebugLoc &DL = MI.getDebugLoc();
3960 
3961     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
3962 
3963     MachineOperand &Dest = MI.getOperand(0);
3964     MachineOperand &Src0 = MI.getOperand(1);
3965     MachineOperand &Src1 = MI.getOperand(2);
3966 
3967     if (IsAdd && ST.hasLshlAddB64()) {
3968       auto Add = BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_LSHL_ADD_U64_e64),
3969                          Dest.getReg())
3970                      .add(Src0)
3971                      .addImm(0)
3972                      .add(Src1);
3973       TII->legalizeOperands(*Add);
3974       MI.eraseFromParent();
3975       return BB;
3976     }
3977 
3978     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3979 
3980     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3981     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3982 
3983     Register CarryReg = MRI.createVirtualRegister(CarryRC);
3984     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
3985 
3986     const TargetRegisterClass *Src0RC = Src0.isReg()
3987                                             ? MRI.getRegClass(Src0.getReg())
3988                                             : &AMDGPU::VReg_64RegClass;
3989     const TargetRegisterClass *Src1RC = Src1.isReg()
3990                                             ? MRI.getRegClass(Src1.getReg())
3991                                             : &AMDGPU::VReg_64RegClass;
3992 
3993     const TargetRegisterClass *Src0SubRC =
3994         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
3995     const TargetRegisterClass *Src1SubRC =
3996         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
3997 
3998     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
3999         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
4000     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
4001         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
4002 
4003     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
4004         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
4005     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
4006         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
4007 
4008     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
4009     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
4010                                .addReg(CarryReg, RegState::Define)
4011                                .add(SrcReg0Sub0)
4012                                .add(SrcReg1Sub0)
4013                                .addImm(0); // clamp bit
4014 
4015     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
4016     MachineInstr *HiHalf =
4017         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4018             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4019             .add(SrcReg0Sub1)
4020             .add(SrcReg1Sub1)
4021             .addReg(CarryReg, RegState::Kill)
4022             .addImm(0); // clamp bit
4023 
4024     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4025         .addReg(DestSub0)
4026         .addImm(AMDGPU::sub0)
4027         .addReg(DestSub1)
4028         .addImm(AMDGPU::sub1);
4029     TII->legalizeOperands(*LoHalf);
4030     TII->legalizeOperands(*HiHalf);
4031     MI.eraseFromParent();
4032     return BB;
4033   }
4034   case AMDGPU::S_ADD_CO_PSEUDO:
4035   case AMDGPU::S_SUB_CO_PSEUDO: {
4036     // This pseudo has a chance to be selected
4037     // only from uniform add/subcarry node. All the VGPR operands
4038     // therefore assumed to be splat vectors.
4039     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4040     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4041     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4042     MachineBasicBlock::iterator MII = MI;
4043     const DebugLoc &DL = MI.getDebugLoc();
4044     MachineOperand &Dest = MI.getOperand(0);
4045     MachineOperand &CarryDest = MI.getOperand(1);
4046     MachineOperand &Src0 = MI.getOperand(2);
4047     MachineOperand &Src1 = MI.getOperand(3);
4048     MachineOperand &Src2 = MI.getOperand(4);
4049     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4050                        ? AMDGPU::S_ADDC_U32
4051                        : AMDGPU::S_SUBB_U32;
4052     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4053       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4054       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4055           .addReg(Src0.getReg());
4056       Src0.setReg(RegOp0);
4057     }
4058     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4059       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4060       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4061           .addReg(Src1.getReg());
4062       Src1.setReg(RegOp1);
4063     }
4064     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4065     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4066       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4067           .addReg(Src2.getReg());
4068       Src2.setReg(RegOp2);
4069     }
4070 
4071     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4072     unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC);
4073     assert(WaveSize == 64 || WaveSize == 32);
4074 
4075     if (WaveSize == 64) {
4076       if (ST.hasScalarCompareEq64()) {
4077         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4078             .addReg(Src2.getReg())
4079             .addImm(0);
4080       } else {
4081         const TargetRegisterClass *SubRC =
4082             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4083         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4084             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4085         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4086             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4087         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4088 
4089         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4090             .add(Src2Sub0)
4091             .add(Src2Sub1);
4092 
4093         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4094             .addReg(Src2_32, RegState::Kill)
4095             .addImm(0);
4096       }
4097     } else {
4098       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4099           .addReg(Src2.getReg())
4100           .addImm(0);
4101     }
4102 
4103     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4104 
4105     unsigned SelOpc =
4106         (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
4107 
4108     BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg())
4109         .addImm(-1)
4110         .addImm(0);
4111 
4112     MI.eraseFromParent();
4113     return BB;
4114   }
4115   case AMDGPU::SI_INIT_M0: {
4116     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4117             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4118         .add(MI.getOperand(0));
4119     MI.eraseFromParent();
4120     return BB;
4121   }
4122   case AMDGPU::GET_GROUPSTATICSIZE: {
4123     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4124            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4125     DebugLoc DL = MI.getDebugLoc();
4126     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4127         .add(MI.getOperand(0))
4128         .addImm(MFI->getLDSSize());
4129     MI.eraseFromParent();
4130     return BB;
4131   }
4132   case AMDGPU::SI_INDIRECT_SRC_V1:
4133   case AMDGPU::SI_INDIRECT_SRC_V2:
4134   case AMDGPU::SI_INDIRECT_SRC_V4:
4135   case AMDGPU::SI_INDIRECT_SRC_V8:
4136   case AMDGPU::SI_INDIRECT_SRC_V16:
4137   case AMDGPU::SI_INDIRECT_SRC_V32:
4138     return emitIndirectSrc(MI, *BB, *getSubtarget());
4139   case AMDGPU::SI_INDIRECT_DST_V1:
4140   case AMDGPU::SI_INDIRECT_DST_V2:
4141   case AMDGPU::SI_INDIRECT_DST_V4:
4142   case AMDGPU::SI_INDIRECT_DST_V8:
4143   case AMDGPU::SI_INDIRECT_DST_V16:
4144   case AMDGPU::SI_INDIRECT_DST_V32:
4145     return emitIndirectDst(MI, *BB, *getSubtarget());
4146   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4147   case AMDGPU::SI_KILL_I1_PSEUDO:
4148     return splitKillBlock(MI, BB);
4149   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4150     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4151     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4152     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4153 
4154     Register Dst = MI.getOperand(0).getReg();
4155     Register Src0 = MI.getOperand(1).getReg();
4156     Register Src1 = MI.getOperand(2).getReg();
4157     const DebugLoc &DL = MI.getDebugLoc();
4158     Register SrcCond = MI.getOperand(3).getReg();
4159 
4160     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4161     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4162     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4163     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4164 
4165     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4166       .addReg(SrcCond);
4167     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4168       .addImm(0)
4169       .addReg(Src0, 0, AMDGPU::sub0)
4170       .addImm(0)
4171       .addReg(Src1, 0, AMDGPU::sub0)
4172       .addReg(SrcCondCopy);
4173     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4174       .addImm(0)
4175       .addReg(Src0, 0, AMDGPU::sub1)
4176       .addImm(0)
4177       .addReg(Src1, 0, AMDGPU::sub1)
4178       .addReg(SrcCondCopy);
4179 
4180     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4181       .addReg(DstLo)
4182       .addImm(AMDGPU::sub0)
4183       .addReg(DstHi)
4184       .addImm(AMDGPU::sub1);
4185     MI.eraseFromParent();
4186     return BB;
4187   }
4188   case AMDGPU::SI_BR_UNDEF: {
4189     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4190     const DebugLoc &DL = MI.getDebugLoc();
4191     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4192                            .add(MI.getOperand(0));
4193     Br->getOperand(1).setIsUndef(true); // read undef SCC
4194     MI.eraseFromParent();
4195     return BB;
4196   }
4197   case AMDGPU::ADJCALLSTACKUP:
4198   case AMDGPU::ADJCALLSTACKDOWN: {
4199     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4200     MachineInstrBuilder MIB(*MF, &MI);
4201     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4202        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4203     return BB;
4204   }
4205   case AMDGPU::SI_CALL_ISEL: {
4206     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4207     const DebugLoc &DL = MI.getDebugLoc();
4208 
4209     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4210 
4211     MachineInstrBuilder MIB;
4212     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4213 
4214     for (const MachineOperand &MO : MI.operands())
4215       MIB.add(MO);
4216 
4217     MIB.cloneMemRefs(MI);
4218     MI.eraseFromParent();
4219     return BB;
4220   }
4221   case AMDGPU::V_ADD_CO_U32_e32:
4222   case AMDGPU::V_SUB_CO_U32_e32:
4223   case AMDGPU::V_SUBREV_CO_U32_e32: {
4224     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4225     const DebugLoc &DL = MI.getDebugLoc();
4226     unsigned Opc = MI.getOpcode();
4227 
4228     bool NeedClampOperand = false;
4229     if (TII->pseudoToMCOpcode(Opc) == -1) {
4230       Opc = AMDGPU::getVOPe64(Opc);
4231       NeedClampOperand = true;
4232     }
4233 
4234     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4235     if (TII->isVOP3(*I)) {
4236       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4237       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4238       I.addReg(TRI->getVCC(), RegState::Define);
4239     }
4240     I.add(MI.getOperand(1))
4241      .add(MI.getOperand(2));
4242     if (NeedClampOperand)
4243       I.addImm(0); // clamp bit for e64 encoding
4244 
4245     TII->legalizeOperands(*I);
4246 
4247     MI.eraseFromParent();
4248     return BB;
4249   }
4250   case AMDGPU::V_ADDC_U32_e32:
4251   case AMDGPU::V_SUBB_U32_e32:
4252   case AMDGPU::V_SUBBREV_U32_e32:
4253     // These instructions have an implicit use of vcc which counts towards the
4254     // constant bus limit.
4255     TII->legalizeOperands(MI);
4256     return BB;
4257   case AMDGPU::DS_GWS_INIT:
4258   case AMDGPU::DS_GWS_SEMA_BR:
4259   case AMDGPU::DS_GWS_BARRIER:
4260     if (Subtarget->needsAlignedVGPRs()) {
4261       // Add implicit aligned super-reg to force alignment on the data operand.
4262       const DebugLoc &DL = MI.getDebugLoc();
4263       MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4264       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
4265       MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0);
4266       Register DataReg = Op->getReg();
4267       bool IsAGPR = TRI->isAGPR(MRI, DataReg);
4268       Register Undef = MRI.createVirtualRegister(
4269           IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass);
4270       BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef);
4271       Register NewVR =
4272           MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass
4273                                            : &AMDGPU::VReg_64_Align2RegClass);
4274       BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR)
4275           .addReg(DataReg, 0, Op->getSubReg())
4276           .addImm(AMDGPU::sub0)
4277           .addReg(Undef)
4278           .addImm(AMDGPU::sub1);
4279       Op->setReg(NewVR);
4280       Op->setSubReg(AMDGPU::sub0);
4281       MI.addOperand(MachineOperand::CreateReg(NewVR, false, true));
4282     }
4283     LLVM_FALLTHROUGH;
4284   case AMDGPU::DS_GWS_SEMA_V:
4285   case AMDGPU::DS_GWS_SEMA_P:
4286   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4287     // A s_waitcnt 0 is required to be the instruction immediately following.
4288     if (getSubtarget()->hasGWSAutoReplay()) {
4289       bundleInstWithWaitcnt(MI);
4290       return BB;
4291     }
4292 
4293     return emitGWSMemViolTestLoop(MI, BB);
4294   case AMDGPU::S_SETREG_B32: {
4295     // Try to optimize cases that only set the denormal mode or rounding mode.
4296     //
4297     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4298     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4299     // instead.
4300     //
4301     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4302     // allow you to have a no side effect instruction in the output of a
4303     // sideeffecting pattern.
4304     unsigned ID, Offset, Width;
4305     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4306     if (ID != AMDGPU::Hwreg::ID_MODE)
4307       return BB;
4308 
4309     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4310     const unsigned SetMask = WidthMask << Offset;
4311 
4312     if (getSubtarget()->hasDenormModeInst()) {
4313       unsigned SetDenormOp = 0;
4314       unsigned SetRoundOp = 0;
4315 
4316       // The dedicated instructions can only set the whole denorm or round mode
4317       // at once, not a subset of bits in either.
4318       if (SetMask ==
4319           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4320         // If this fully sets both the round and denorm mode, emit the two
4321         // dedicated instructions for these.
4322         SetRoundOp = AMDGPU::S_ROUND_MODE;
4323         SetDenormOp = AMDGPU::S_DENORM_MODE;
4324       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4325         SetRoundOp = AMDGPU::S_ROUND_MODE;
4326       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4327         SetDenormOp = AMDGPU::S_DENORM_MODE;
4328       }
4329 
4330       if (SetRoundOp || SetDenormOp) {
4331         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4332         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4333         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4334           unsigned ImmVal = Def->getOperand(1).getImm();
4335           if (SetRoundOp) {
4336             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4337                 .addImm(ImmVal & 0xf);
4338 
4339             // If we also have the denorm mode, get just the denorm mode bits.
4340             ImmVal >>= 4;
4341           }
4342 
4343           if (SetDenormOp) {
4344             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4345                 .addImm(ImmVal & 0xf);
4346           }
4347 
4348           MI.eraseFromParent();
4349           return BB;
4350         }
4351       }
4352     }
4353 
4354     // If only FP bits are touched, used the no side effects pseudo.
4355     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4356                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4357       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4358 
4359     return BB;
4360   }
4361   default:
4362     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4363   }
4364 }
4365 
4366 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4367   return isTypeLegal(VT.getScalarType());
4368 }
4369 
4370 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4371   // This currently forces unfolding various combinations of fsub into fma with
4372   // free fneg'd operands. As long as we have fast FMA (controlled by
4373   // isFMAFasterThanFMulAndFAdd), we should perform these.
4374 
4375   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4376   // most of these combines appear to be cycle neutral but save on instruction
4377   // count / code size.
4378   return true;
4379 }
4380 
4381 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; }
4382 
4383 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4384                                          EVT VT) const {
4385   if (!VT.isVector()) {
4386     return MVT::i1;
4387   }
4388   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4389 }
4390 
4391 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4392   // TODO: Should i16 be used always if legal? For now it would force VALU
4393   // shifts.
4394   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4395 }
4396 
4397 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4398   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4399              ? Ty.changeElementSize(16)
4400              : Ty.changeElementSize(32);
4401 }
4402 
4403 // Answering this is somewhat tricky and depends on the specific device which
4404 // have different rates for fma or all f64 operations.
4405 //
4406 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4407 // regardless of which device (although the number of cycles differs between
4408 // devices), so it is always profitable for f64.
4409 //
4410 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4411 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4412 // which we can always do even without fused FP ops since it returns the same
4413 // result as the separate operations and since it is always full
4414 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4415 // however does not support denormals, so we do report fma as faster if we have
4416 // a fast fma device and require denormals.
4417 //
4418 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4419                                                   EVT VT) const {
4420   VT = VT.getScalarType();
4421 
4422   switch (VT.getSimpleVT().SimpleTy) {
4423   case MVT::f32: {
4424     // If mad is not available this depends only on if f32 fma is full rate.
4425     if (!Subtarget->hasMadMacF32Insts())
4426       return Subtarget->hasFastFMAF32();
4427 
4428     // Otherwise f32 mad is always full rate and returns the same result as
4429     // the separate operations so should be preferred over fma.
4430     // However does not support denormals.
4431     if (hasFP32Denormals(MF))
4432       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4433 
4434     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4435     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4436   }
4437   case MVT::f64:
4438     return true;
4439   case MVT::f16:
4440     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4441   default:
4442     break;
4443   }
4444 
4445   return false;
4446 }
4447 
4448 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4449                                                   LLT Ty) const {
4450   switch (Ty.getScalarSizeInBits()) {
4451   case 16:
4452     return isFMAFasterThanFMulAndFAdd(MF, MVT::f16);
4453   case 32:
4454     return isFMAFasterThanFMulAndFAdd(MF, MVT::f32);
4455   case 64:
4456     return isFMAFasterThanFMulAndFAdd(MF, MVT::f64);
4457   default:
4458     break;
4459   }
4460 
4461   return false;
4462 }
4463 
4464 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const {
4465   if (!Ty.isScalar())
4466     return false;
4467 
4468   if (Ty.getScalarSizeInBits() == 16)
4469     return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF());
4470   if (Ty.getScalarSizeInBits() == 32)
4471     return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF());
4472 
4473   return false;
4474 }
4475 
4476 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4477                                    const SDNode *N) const {
4478   // TODO: Check future ftz flag
4479   // v_mad_f32/v_mac_f32 do not support denormals.
4480   EVT VT = N->getValueType(0);
4481   if (VT == MVT::f32)
4482     return Subtarget->hasMadMacF32Insts() &&
4483            !hasFP32Denormals(DAG.getMachineFunction());
4484   if (VT == MVT::f16) {
4485     return Subtarget->hasMadF16() &&
4486            !hasFP64FP16Denormals(DAG.getMachineFunction());
4487   }
4488 
4489   return false;
4490 }
4491 
4492 //===----------------------------------------------------------------------===//
4493 // Custom DAG Lowering Operations
4494 //===----------------------------------------------------------------------===//
4495 
4496 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4497 // wider vector type is legal.
4498 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4499                                              SelectionDAG &DAG) const {
4500   unsigned Opc = Op.getOpcode();
4501   EVT VT = Op.getValueType();
4502   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4503 
4504   SDValue Lo, Hi;
4505   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4506 
4507   SDLoc SL(Op);
4508   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4509                              Op->getFlags());
4510   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4511                              Op->getFlags());
4512 
4513   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4514 }
4515 
4516 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4517 // wider vector type is legal.
4518 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4519                                               SelectionDAG &DAG) const {
4520   unsigned Opc = Op.getOpcode();
4521   EVT VT = Op.getValueType();
4522   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4523          VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8f32 ||
4524          VT == MVT::v16f32 || VT == MVT::v32f32);
4525 
4526   SDValue Lo0, Hi0;
4527   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4528   SDValue Lo1, Hi1;
4529   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4530 
4531   SDLoc SL(Op);
4532 
4533   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4534                              Op->getFlags());
4535   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4536                              Op->getFlags());
4537 
4538   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4539 }
4540 
4541 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4542                                               SelectionDAG &DAG) const {
4543   unsigned Opc = Op.getOpcode();
4544   EVT VT = Op.getValueType();
4545   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 ||
4546          VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v8f32 ||
4547          VT == MVT::v16f32 || VT == MVT::v32f32);
4548 
4549   SDValue Lo0, Hi0;
4550   SDValue Op0 = Op.getOperand(0);
4551   std::tie(Lo0, Hi0) = Op0.getValueType().isVector()
4552                          ? DAG.SplitVectorOperand(Op.getNode(), 0)
4553                          : std::make_pair(Op0, Op0);
4554   SDValue Lo1, Hi1;
4555   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4556   SDValue Lo2, Hi2;
4557   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4558 
4559   SDLoc SL(Op);
4560   auto ResVT = DAG.GetSplitDestVTs(VT);
4561 
4562   SDValue OpLo = DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2,
4563                              Op->getFlags());
4564   SDValue OpHi = DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2,
4565                              Op->getFlags());
4566 
4567   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4568 }
4569 
4570 
4571 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4572   switch (Op.getOpcode()) {
4573   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4574   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4575   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4576   case ISD::LOAD: {
4577     SDValue Result = LowerLOAD(Op, DAG);
4578     assert((!Result.getNode() ||
4579             Result.getNode()->getNumValues() == 2) &&
4580            "Load should return a value and a chain");
4581     return Result;
4582   }
4583 
4584   case ISD::FSIN:
4585   case ISD::FCOS:
4586     return LowerTrig(Op, DAG);
4587   case ISD::SELECT: return LowerSELECT(Op, DAG);
4588   case ISD::FDIV: return LowerFDIV(Op, DAG);
4589   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4590   case ISD::STORE: return LowerSTORE(Op, DAG);
4591   case ISD::GlobalAddress: {
4592     MachineFunction &MF = DAG.getMachineFunction();
4593     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4594     return LowerGlobalAddress(MFI, Op, DAG);
4595   }
4596   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4597   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4598   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4599   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4600   case ISD::INSERT_SUBVECTOR:
4601     return lowerINSERT_SUBVECTOR(Op, DAG);
4602   case ISD::INSERT_VECTOR_ELT:
4603     return lowerINSERT_VECTOR_ELT(Op, DAG);
4604   case ISD::EXTRACT_VECTOR_ELT:
4605     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4606   case ISD::VECTOR_SHUFFLE:
4607     return lowerVECTOR_SHUFFLE(Op, DAG);
4608   case ISD::SCALAR_TO_VECTOR:
4609     return lowerSCALAR_TO_VECTOR(Op, DAG);
4610   case ISD::BUILD_VECTOR:
4611     return lowerBUILD_VECTOR(Op, DAG);
4612   case ISD::FP_ROUND:
4613     return lowerFP_ROUND(Op, DAG);
4614   case ISD::FPTRUNC_ROUND: {
4615     unsigned Opc;
4616     SDLoc DL(Op);
4617 
4618     if (Op.getOperand(0)->getValueType(0) != MVT::f32)
4619       return SDValue();
4620 
4621     // Get the rounding mode from the last operand
4622     int RoundMode = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4623     if (RoundMode == (int)RoundingMode::TowardPositive)
4624       Opc = AMDGPUISD::FPTRUNC_ROUND_UPWARD;
4625     else if (RoundMode == (int)RoundingMode::TowardNegative)
4626       Opc = AMDGPUISD::FPTRUNC_ROUND_DOWNWARD;
4627     else
4628       return SDValue();
4629 
4630     return DAG.getNode(Opc, DL, Op.getNode()->getVTList(), Op->getOperand(0));
4631   }
4632   case ISD::TRAP:
4633     return lowerTRAP(Op, DAG);
4634   case ISD::DEBUGTRAP:
4635     return lowerDEBUGTRAP(Op, DAG);
4636   case ISD::FABS:
4637   case ISD::FNEG:
4638   case ISD::FCANONICALIZE:
4639   case ISD::BSWAP:
4640     return splitUnaryVectorOp(Op, DAG);
4641   case ISD::FMINNUM:
4642   case ISD::FMAXNUM:
4643     return lowerFMINNUM_FMAXNUM(Op, DAG);
4644   case ISD::FMA:
4645     return splitTernaryVectorOp(Op, DAG);
4646   case ISD::FP_TO_SINT:
4647   case ISD::FP_TO_UINT:
4648     return LowerFP_TO_INT(Op, DAG);
4649   case ISD::SHL:
4650   case ISD::SRA:
4651   case ISD::SRL:
4652   case ISD::ADD:
4653   case ISD::SUB:
4654   case ISD::MUL:
4655   case ISD::SMIN:
4656   case ISD::SMAX:
4657   case ISD::UMIN:
4658   case ISD::UMAX:
4659   case ISD::FADD:
4660   case ISD::FMUL:
4661   case ISD::FMINNUM_IEEE:
4662   case ISD::FMAXNUM_IEEE:
4663   case ISD::UADDSAT:
4664   case ISD::USUBSAT:
4665   case ISD::SADDSAT:
4666   case ISD::SSUBSAT:
4667     return splitBinaryVectorOp(Op, DAG);
4668   case ISD::SMULO:
4669   case ISD::UMULO:
4670     return lowerXMULO(Op, DAG);
4671   case ISD::SMUL_LOHI:
4672   case ISD::UMUL_LOHI:
4673     return lowerXMUL_LOHI(Op, DAG);
4674   case ISD::DYNAMIC_STACKALLOC:
4675     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4676   }
4677   return SDValue();
4678 }
4679 
4680 // Used for D16: Casts the result of an instruction into the right vector,
4681 // packs values if loads return unpacked values.
4682 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4683                                        const SDLoc &DL,
4684                                        SelectionDAG &DAG, bool Unpacked) {
4685   if (!LoadVT.isVector())
4686     return Result;
4687 
4688   // Cast back to the original packed type or to a larger type that is a
4689   // multiple of 32 bit for D16. Widening the return type is a required for
4690   // legalization.
4691   EVT FittingLoadVT = LoadVT;
4692   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4693     FittingLoadVT =
4694         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4695                          LoadVT.getVectorNumElements() + 1);
4696   }
4697 
4698   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4699     // Truncate to v2i16/v4i16.
4700     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4701 
4702     // Workaround legalizer not scalarizing truncate after vector op
4703     // legalization but not creating intermediate vector trunc.
4704     SmallVector<SDValue, 4> Elts;
4705     DAG.ExtractVectorElements(Result, Elts);
4706     for (SDValue &Elt : Elts)
4707       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4708 
4709     // Pad illegal v1i16/v3fi6 to v4i16
4710     if ((LoadVT.getVectorNumElements() % 2) == 1)
4711       Elts.push_back(DAG.getUNDEF(MVT::i16));
4712 
4713     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4714 
4715     // Bitcast to original type (v2f16/v4f16).
4716     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4717   }
4718 
4719   // Cast back to the original packed type.
4720   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4721 }
4722 
4723 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4724                                               MemSDNode *M,
4725                                               SelectionDAG &DAG,
4726                                               ArrayRef<SDValue> Ops,
4727                                               bool IsIntrinsic) const {
4728   SDLoc DL(M);
4729 
4730   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4731   EVT LoadVT = M->getValueType(0);
4732 
4733   EVT EquivLoadVT = LoadVT;
4734   if (LoadVT.isVector()) {
4735     if (Unpacked) {
4736       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4737                                      LoadVT.getVectorNumElements());
4738     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4739       // Widen v3f16 to legal type
4740       EquivLoadVT =
4741           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4742                            LoadVT.getVectorNumElements() + 1);
4743     }
4744   }
4745 
4746   // Change from v4f16/v2f16 to EquivLoadVT.
4747   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4748 
4749   SDValue Load
4750     = DAG.getMemIntrinsicNode(
4751       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4752       VTList, Ops, M->getMemoryVT(),
4753       M->getMemOperand());
4754 
4755   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4756 
4757   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4758 }
4759 
4760 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4761                                              SelectionDAG &DAG,
4762                                              ArrayRef<SDValue> Ops) const {
4763   SDLoc DL(M);
4764   EVT LoadVT = M->getValueType(0);
4765   EVT EltType = LoadVT.getScalarType();
4766   EVT IntVT = LoadVT.changeTypeToInteger();
4767 
4768   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4769 
4770   unsigned Opc =
4771       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4772 
4773   if (IsD16) {
4774     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4775   }
4776 
4777   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4778   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4779     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4780 
4781   if (isTypeLegal(LoadVT)) {
4782     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4783                                M->getMemOperand(), DAG);
4784   }
4785 
4786   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4787   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4788   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4789                                         M->getMemOperand(), DAG);
4790   return DAG.getMergeValues(
4791       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4792       DL);
4793 }
4794 
4795 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4796                                   SDNode *N, SelectionDAG &DAG) {
4797   EVT VT = N->getValueType(0);
4798   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4799   unsigned CondCode = CD->getZExtValue();
4800   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4801     return DAG.getUNDEF(VT);
4802 
4803   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4804 
4805   SDValue LHS = N->getOperand(1);
4806   SDValue RHS = N->getOperand(2);
4807 
4808   SDLoc DL(N);
4809 
4810   EVT CmpVT = LHS.getValueType();
4811   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4812     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4813       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4814     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4815     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4816   }
4817 
4818   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4819 
4820   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4821   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4822 
4823   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4824                               DAG.getCondCode(CCOpcode));
4825   if (VT.bitsEq(CCVT))
4826     return SetCC;
4827   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4828 }
4829 
4830 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4831                                   SDNode *N, SelectionDAG &DAG) {
4832   EVT VT = N->getValueType(0);
4833   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4834 
4835   unsigned CondCode = CD->getZExtValue();
4836   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4837     return DAG.getUNDEF(VT);
4838 
4839   SDValue Src0 = N->getOperand(1);
4840   SDValue Src1 = N->getOperand(2);
4841   EVT CmpVT = Src0.getValueType();
4842   SDLoc SL(N);
4843 
4844   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4845     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4846     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4847   }
4848 
4849   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4850   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4851   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4852   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4853   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4854                               Src1, DAG.getCondCode(CCOpcode));
4855   if (VT.bitsEq(CCVT))
4856     return SetCC;
4857   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4858 }
4859 
4860 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4861                                     SelectionDAG &DAG) {
4862   EVT VT = N->getValueType(0);
4863   SDValue Src = N->getOperand(1);
4864   SDLoc SL(N);
4865 
4866   if (Src.getOpcode() == ISD::SETCC) {
4867     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4868     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4869                        Src.getOperand(1), Src.getOperand(2));
4870   }
4871   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4872     // (ballot 0) -> 0
4873     if (Arg->isZero())
4874       return DAG.getConstant(0, SL, VT);
4875 
4876     // (ballot 1) -> EXEC/EXEC_LO
4877     if (Arg->isOne()) {
4878       Register Exec;
4879       if (VT.getScalarSizeInBits() == 32)
4880         Exec = AMDGPU::EXEC_LO;
4881       else if (VT.getScalarSizeInBits() == 64)
4882         Exec = AMDGPU::EXEC;
4883       else
4884         return SDValue();
4885 
4886       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4887     }
4888   }
4889 
4890   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4891   // ISD::SETNE)
4892   return DAG.getNode(
4893       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4894       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4895 }
4896 
4897 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4898                                           SmallVectorImpl<SDValue> &Results,
4899                                           SelectionDAG &DAG) const {
4900   switch (N->getOpcode()) {
4901   case ISD::INSERT_VECTOR_ELT: {
4902     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4903       Results.push_back(Res);
4904     return;
4905   }
4906   case ISD::EXTRACT_VECTOR_ELT: {
4907     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4908       Results.push_back(Res);
4909     return;
4910   }
4911   case ISD::INTRINSIC_WO_CHAIN: {
4912     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4913     switch (IID) {
4914     case Intrinsic::amdgcn_cvt_pkrtz: {
4915       SDValue Src0 = N->getOperand(1);
4916       SDValue Src1 = N->getOperand(2);
4917       SDLoc SL(N);
4918       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4919                                 Src0, Src1);
4920       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4921       return;
4922     }
4923     case Intrinsic::amdgcn_cvt_pknorm_i16:
4924     case Intrinsic::amdgcn_cvt_pknorm_u16:
4925     case Intrinsic::amdgcn_cvt_pk_i16:
4926     case Intrinsic::amdgcn_cvt_pk_u16: {
4927       SDValue Src0 = N->getOperand(1);
4928       SDValue Src1 = N->getOperand(2);
4929       SDLoc SL(N);
4930       unsigned Opcode;
4931 
4932       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4933         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4934       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4935         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4936       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4937         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4938       else
4939         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4940 
4941       EVT VT = N->getValueType(0);
4942       if (isTypeLegal(VT))
4943         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4944       else {
4945         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4946         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4947       }
4948       return;
4949     }
4950     }
4951     break;
4952   }
4953   case ISD::INTRINSIC_W_CHAIN: {
4954     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4955       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4956         // FIXME: Hacky
4957         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
4958           Results.push_back(Res.getOperand(I));
4959         }
4960       } else {
4961         Results.push_back(Res);
4962         Results.push_back(Res.getValue(1));
4963       }
4964       return;
4965     }
4966 
4967     break;
4968   }
4969   case ISD::SELECT: {
4970     SDLoc SL(N);
4971     EVT VT = N->getValueType(0);
4972     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4973     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4974     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4975 
4976     EVT SelectVT = NewVT;
4977     if (NewVT.bitsLT(MVT::i32)) {
4978       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4979       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4980       SelectVT = MVT::i32;
4981     }
4982 
4983     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4984                                     N->getOperand(0), LHS, RHS);
4985 
4986     if (NewVT != SelectVT)
4987       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4988     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4989     return;
4990   }
4991   case ISD::FNEG: {
4992     if (N->getValueType(0) != MVT::v2f16)
4993       break;
4994 
4995     SDLoc SL(N);
4996     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4997 
4998     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4999                              BC,
5000                              DAG.getConstant(0x80008000, SL, MVT::i32));
5001     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5002     return;
5003   }
5004   case ISD::FABS: {
5005     if (N->getValueType(0) != MVT::v2f16)
5006       break;
5007 
5008     SDLoc SL(N);
5009     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5010 
5011     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
5012                              BC,
5013                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
5014     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5015     return;
5016   }
5017   default:
5018     break;
5019   }
5020 }
5021 
5022 /// Helper function for LowerBRCOND
5023 static SDNode *findUser(SDValue Value, unsigned Opcode) {
5024 
5025   SDNode *Parent = Value.getNode();
5026   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
5027        I != E; ++I) {
5028 
5029     if (I.getUse().get() != Value)
5030       continue;
5031 
5032     if (I->getOpcode() == Opcode)
5033       return *I;
5034   }
5035   return nullptr;
5036 }
5037 
5038 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
5039   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
5040     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
5041     case Intrinsic::amdgcn_if:
5042       return AMDGPUISD::IF;
5043     case Intrinsic::amdgcn_else:
5044       return AMDGPUISD::ELSE;
5045     case Intrinsic::amdgcn_loop:
5046       return AMDGPUISD::LOOP;
5047     case Intrinsic::amdgcn_end_cf:
5048       llvm_unreachable("should not occur");
5049     default:
5050       return 0;
5051     }
5052   }
5053 
5054   // break, if_break, else_break are all only used as inputs to loop, not
5055   // directly as branch conditions.
5056   return 0;
5057 }
5058 
5059 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
5060   const Triple &TT = getTargetMachine().getTargetTriple();
5061   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5062           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5063          AMDGPU::shouldEmitConstantsToTextSection(TT);
5064 }
5065 
5066 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
5067   // FIXME: Either avoid relying on address space here or change the default
5068   // address space for functions to avoid the explicit check.
5069   return (GV->getValueType()->isFunctionTy() ||
5070           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
5071          !shouldEmitFixup(GV) &&
5072          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
5073 }
5074 
5075 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
5076   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
5077 }
5078 
5079 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
5080   if (!GV->hasExternalLinkage())
5081     return true;
5082 
5083   const auto OS = getTargetMachine().getTargetTriple().getOS();
5084   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
5085 }
5086 
5087 /// This transforms the control flow intrinsics to get the branch destination as
5088 /// last parameter, also switches branch target with BR if the need arise
5089 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
5090                                       SelectionDAG &DAG) const {
5091   SDLoc DL(BRCOND);
5092 
5093   SDNode *Intr = BRCOND.getOperand(1).getNode();
5094   SDValue Target = BRCOND.getOperand(2);
5095   SDNode *BR = nullptr;
5096   SDNode *SetCC = nullptr;
5097 
5098   if (Intr->getOpcode() == ISD::SETCC) {
5099     // As long as we negate the condition everything is fine
5100     SetCC = Intr;
5101     Intr = SetCC->getOperand(0).getNode();
5102 
5103   } else {
5104     // Get the target from BR if we don't negate the condition
5105     BR = findUser(BRCOND, ISD::BR);
5106     assert(BR && "brcond missing unconditional branch user");
5107     Target = BR->getOperand(1);
5108   }
5109 
5110   unsigned CFNode = isCFIntrinsic(Intr);
5111   if (CFNode == 0) {
5112     // This is a uniform branch so we don't need to legalize.
5113     return BRCOND;
5114   }
5115 
5116   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5117                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5118 
5119   assert(!SetCC ||
5120         (SetCC->getConstantOperandVal(1) == 1 &&
5121          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5122                                                              ISD::SETNE));
5123 
5124   // operands of the new intrinsic call
5125   SmallVector<SDValue, 4> Ops;
5126   if (HaveChain)
5127     Ops.push_back(BRCOND.getOperand(0));
5128 
5129   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5130   Ops.push_back(Target);
5131 
5132   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5133 
5134   // build the new intrinsic call
5135   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5136 
5137   if (!HaveChain) {
5138     SDValue Ops[] =  {
5139       SDValue(Result, 0),
5140       BRCOND.getOperand(0)
5141     };
5142 
5143     Result = DAG.getMergeValues(Ops, DL).getNode();
5144   }
5145 
5146   if (BR) {
5147     // Give the branch instruction our target
5148     SDValue Ops[] = {
5149       BR->getOperand(0),
5150       BRCOND.getOperand(2)
5151     };
5152     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5153     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5154   }
5155 
5156   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5157 
5158   // Copy the intrinsic results to registers
5159   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5160     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5161     if (!CopyToReg)
5162       continue;
5163 
5164     Chain = DAG.getCopyToReg(
5165       Chain, DL,
5166       CopyToReg->getOperand(1),
5167       SDValue(Result, i - 1),
5168       SDValue());
5169 
5170     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5171   }
5172 
5173   // Remove the old intrinsic from the chain
5174   DAG.ReplaceAllUsesOfValueWith(
5175     SDValue(Intr, Intr->getNumValues() - 1),
5176     Intr->getOperand(0));
5177 
5178   return Chain;
5179 }
5180 
5181 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5182                                           SelectionDAG &DAG) const {
5183   MVT VT = Op.getSimpleValueType();
5184   SDLoc DL(Op);
5185   // Checking the depth
5186   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5187     return DAG.getConstant(0, DL, VT);
5188 
5189   MachineFunction &MF = DAG.getMachineFunction();
5190   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5191   // Check for kernel and shader functions
5192   if (Info->isEntryFunction())
5193     return DAG.getConstant(0, DL, VT);
5194 
5195   MachineFrameInfo &MFI = MF.getFrameInfo();
5196   // There is a call to @llvm.returnaddress in this function
5197   MFI.setReturnAddressIsTaken(true);
5198 
5199   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5200   // Get the return address reg and mark it as an implicit live-in
5201   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5202 
5203   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5204 }
5205 
5206 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5207                                             SDValue Op,
5208                                             const SDLoc &DL,
5209                                             EVT VT) const {
5210   return Op.getValueType().bitsLE(VT) ?
5211       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5212     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5213                 DAG.getTargetConstant(0, DL, MVT::i32));
5214 }
5215 
5216 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5217   assert(Op.getValueType() == MVT::f16 &&
5218          "Do not know how to custom lower FP_ROUND for non-f16 type");
5219 
5220   SDValue Src = Op.getOperand(0);
5221   EVT SrcVT = Src.getValueType();
5222   if (SrcVT != MVT::f64)
5223     return Op;
5224 
5225   SDLoc DL(Op);
5226 
5227   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5228   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5229   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5230 }
5231 
5232 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5233                                                SelectionDAG &DAG) const {
5234   EVT VT = Op.getValueType();
5235   const MachineFunction &MF = DAG.getMachineFunction();
5236   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5237   bool IsIEEEMode = Info->getMode().IEEE;
5238 
5239   // FIXME: Assert during selection that this is only selected for
5240   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5241   // mode functions, but this happens to be OK since it's only done in cases
5242   // where there is known no sNaN.
5243   if (IsIEEEMode)
5244     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5245 
5246   if (VT == MVT::v4f16 || VT == MVT::v8f16)
5247     return splitBinaryVectorOp(Op, DAG);
5248   return Op;
5249 }
5250 
5251 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5252   EVT VT = Op.getValueType();
5253   SDLoc SL(Op);
5254   SDValue LHS = Op.getOperand(0);
5255   SDValue RHS = Op.getOperand(1);
5256   bool isSigned = Op.getOpcode() == ISD::SMULO;
5257 
5258   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5259     const APInt &C = RHSC->getAPIntValue();
5260     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5261     if (C.isPowerOf2()) {
5262       // smulo(x, signed_min) is same as umulo(x, signed_min).
5263       bool UseArithShift = isSigned && !C.isMinSignedValue();
5264       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5265       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5266       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5267           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5268                       SL, VT, Result, ShiftAmt),
5269           LHS, ISD::SETNE);
5270       return DAG.getMergeValues({ Result, Overflow }, SL);
5271     }
5272   }
5273 
5274   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5275   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5276                             SL, VT, LHS, RHS);
5277 
5278   SDValue Sign = isSigned
5279     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5280                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5281     : DAG.getConstant(0, SL, VT);
5282   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5283 
5284   return DAG.getMergeValues({ Result, Overflow }, SL);
5285 }
5286 
5287 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const {
5288   if (Op->isDivergent()) {
5289     // Select to V_MAD_[IU]64_[IU]32.
5290     return Op;
5291   }
5292   if (Subtarget->hasSMulHi()) {
5293     // Expand to S_MUL_I32 + S_MUL_HI_[IU]32.
5294     return SDValue();
5295   }
5296   // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to
5297   // calculate the high part, so we might as well do the whole thing with
5298   // V_MAD_[IU]64_[IU]32.
5299   return Op;
5300 }
5301 
5302 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5303   if (!Subtarget->isTrapHandlerEnabled() ||
5304       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5305     return lowerTrapEndpgm(Op, DAG);
5306 
5307   if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) {
5308     switch (*HsaAbiVer) {
5309     case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
5310     case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
5311       return lowerTrapHsaQueuePtr(Op, DAG);
5312     case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
5313     case ELF::ELFABIVERSION_AMDGPU_HSA_V5:
5314       return Subtarget->supportsGetDoorbellID() ?
5315           lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG);
5316     }
5317   }
5318 
5319   llvm_unreachable("Unknown trap handler");
5320 }
5321 
5322 SDValue SITargetLowering::lowerTrapEndpgm(
5323     SDValue Op, SelectionDAG &DAG) const {
5324   SDLoc SL(Op);
5325   SDValue Chain = Op.getOperand(0);
5326   return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5327 }
5328 
5329 SDValue SITargetLowering::loadImplicitKernelArgument(SelectionDAG &DAG, MVT VT,
5330     const SDLoc &DL, Align Alignment, ImplicitParameter Param) const {
5331   MachineFunction &MF = DAG.getMachineFunction();
5332   uint64_t Offset = getImplicitParameterOffset(MF, Param);
5333   SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), Offset);
5334   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5335   return DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, PtrInfo, Alignment,
5336                      MachineMemOperand::MODereferenceable |
5337                          MachineMemOperand::MOInvariant);
5338 }
5339 
5340 SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5341     SDValue Op, SelectionDAG &DAG) const {
5342   SDLoc SL(Op);
5343   SDValue Chain = Op.getOperand(0);
5344 
5345   SDValue QueuePtr;
5346   // For code object version 5, QueuePtr is passed through implicit kernarg.
5347   if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) {
5348     QueuePtr =
5349         loadImplicitKernelArgument(DAG, MVT::i64, SL, Align(8), QUEUE_PTR);
5350   } else {
5351     MachineFunction &MF = DAG.getMachineFunction();
5352     SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5353     Register UserSGPR = Info->getQueuePtrUserSGPR();
5354 
5355     if (UserSGPR == AMDGPU::NoRegister) {
5356       // We probably are in a function incorrectly marked with
5357       // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the
5358       // trap, so just use a null pointer.
5359       QueuePtr = DAG.getConstant(0, SL, MVT::i64);
5360     } else {
5361       QueuePtr = CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, UserSGPR,
5362                                       MVT::i64);
5363     }
5364   }
5365 
5366   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5367   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5368                                    QueuePtr, SDValue());
5369 
5370   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5371   SDValue Ops[] = {
5372     ToReg,
5373     DAG.getTargetConstant(TrapID, SL, MVT::i16),
5374     SGPR01,
5375     ToReg.getValue(1)
5376   };
5377   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5378 }
5379 
5380 SDValue SITargetLowering::lowerTrapHsa(
5381     SDValue Op, SelectionDAG &DAG) const {
5382   SDLoc SL(Op);
5383   SDValue Chain = Op.getOperand(0);
5384 
5385   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5386   SDValue Ops[] = {
5387     Chain,
5388     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5389   };
5390   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5391 }
5392 
5393 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5394   SDLoc SL(Op);
5395   SDValue Chain = Op.getOperand(0);
5396   MachineFunction &MF = DAG.getMachineFunction();
5397 
5398   if (!Subtarget->isTrapHandlerEnabled() ||
5399       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5400     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5401                                      "debugtrap handler not supported",
5402                                      Op.getDebugLoc(),
5403                                      DS_Warning);
5404     LLVMContext &Ctx = MF.getFunction().getContext();
5405     Ctx.diagnose(NoTrap);
5406     return Chain;
5407   }
5408 
5409   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5410   SDValue Ops[] = {
5411     Chain,
5412     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5413   };
5414   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5415 }
5416 
5417 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5418                                              SelectionDAG &DAG) const {
5419   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5420   if (Subtarget->hasApertureRegs()) {
5421     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5422         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5423         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5424     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5425         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5426         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5427     unsigned Encoding =
5428         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5429         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5430         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5431 
5432     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5433     SDValue ApertureReg = SDValue(
5434         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5435     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5436     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5437   }
5438 
5439   // For code object version 5, private_base and shared_base are passed through
5440   // implicit kernargs.
5441   if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) {
5442     ImplicitParameter Param =
5443         (AS == AMDGPUAS::LOCAL_ADDRESS) ? SHARED_BASE : PRIVATE_BASE;
5444     return loadImplicitKernelArgument(DAG, MVT::i32, DL, Align(4), Param);
5445   }
5446 
5447   MachineFunction &MF = DAG.getMachineFunction();
5448   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5449   Register UserSGPR = Info->getQueuePtrUserSGPR();
5450   if (UserSGPR == AMDGPU::NoRegister) {
5451     // We probably are in a function incorrectly marked with
5452     // amdgpu-no-queue-ptr. This is undefined.
5453     return DAG.getUNDEF(MVT::i32);
5454   }
5455 
5456   SDValue QueuePtr = CreateLiveInRegister(
5457     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5458 
5459   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5460   // private_segment_aperture_base_hi.
5461   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5462 
5463   SDValue Ptr =
5464       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5465 
5466   // TODO: Use custom target PseudoSourceValue.
5467   // TODO: We should use the value from the IR intrinsic call, but it might not
5468   // be available and how do we get it?
5469   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5470   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5471                      commonAlignment(Align(64), StructOffset),
5472                      MachineMemOperand::MODereferenceable |
5473                          MachineMemOperand::MOInvariant);
5474 }
5475 
5476 /// Return true if the value is a known valid address, such that a null check is
5477 /// not necessary.
5478 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG,
5479                            const AMDGPUTargetMachine &TM, unsigned AddrSpace) {
5480   if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) ||
5481       isa<BasicBlockSDNode>(Val))
5482     return true;
5483 
5484   if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val))
5485     return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace);
5486 
5487   // TODO: Search through arithmetic, handle arguments and loads
5488   // marked nonnull.
5489   return false;
5490 }
5491 
5492 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5493                                              SelectionDAG &DAG) const {
5494   SDLoc SL(Op);
5495   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5496 
5497   SDValue Src = ASC->getOperand(0);
5498   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5499   unsigned SrcAS = ASC->getSrcAddressSpace();
5500 
5501   const AMDGPUTargetMachine &TM =
5502     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5503 
5504   // flat -> local/private
5505   if (SrcAS == AMDGPUAS::FLAT_ADDRESS) {
5506     unsigned DestAS = ASC->getDestAddressSpace();
5507 
5508     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5509         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5510       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5511 
5512       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5513         return Ptr;
5514 
5515       unsigned NullVal = TM.getNullPointerValue(DestAS);
5516       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5517       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5518 
5519       return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr,
5520                          SegmentNullPtr);
5521     }
5522   }
5523 
5524   // local/private -> flat
5525   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5526     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5527         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5528 
5529       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5530       SDValue CvtPtr =
5531           DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5532       CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr);
5533 
5534       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5535         return CvtPtr;
5536 
5537       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5538       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5539 
5540       SDValue NonNull
5541         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5542 
5543       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr,
5544                          FlatNullPtr);
5545     }
5546   }
5547 
5548   if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5549       Op.getValueType() == MVT::i64) {
5550     const SIMachineFunctionInfo *Info =
5551         DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>();
5552     SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32);
5553     SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi);
5554     return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
5555   }
5556 
5557   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5558       Src.getValueType() == MVT::i64)
5559     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5560 
5561   // global <-> flat are no-ops and never emitted.
5562 
5563   const MachineFunction &MF = DAG.getMachineFunction();
5564   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5565     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5566   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5567 
5568   return DAG.getUNDEF(ASC->getValueType(0));
5569 }
5570 
5571 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5572 // the small vector and inserting them into the big vector. That is better than
5573 // the default expansion of doing it via a stack slot. Even though the use of
5574 // the stack slot would be optimized away afterwards, the stack slot itself
5575 // remains.
5576 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5577                                                 SelectionDAG &DAG) const {
5578   SDValue Vec = Op.getOperand(0);
5579   SDValue Ins = Op.getOperand(1);
5580   SDValue Idx = Op.getOperand(2);
5581   EVT VecVT = Vec.getValueType();
5582   EVT InsVT = Ins.getValueType();
5583   EVT EltVT = VecVT.getVectorElementType();
5584   unsigned InsNumElts = InsVT.getVectorNumElements();
5585   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5586   SDLoc SL(Op);
5587 
5588   for (unsigned I = 0; I != InsNumElts; ++I) {
5589     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5590                               DAG.getConstant(I, SL, MVT::i32));
5591     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5592                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5593   }
5594   return Vec;
5595 }
5596 
5597 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5598                                                  SelectionDAG &DAG) const {
5599   SDValue Vec = Op.getOperand(0);
5600   SDValue InsVal = Op.getOperand(1);
5601   SDValue Idx = Op.getOperand(2);
5602   EVT VecVT = Vec.getValueType();
5603   EVT EltVT = VecVT.getVectorElementType();
5604   unsigned VecSize = VecVT.getSizeInBits();
5605   unsigned EltSize = EltVT.getSizeInBits();
5606   SDLoc SL(Op);
5607 
5608   // Specially handle the case of v4i16 with static indexing.
5609   unsigned NumElts = VecVT.getVectorNumElements();
5610   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5611   if (NumElts == 4 && EltSize == 16 && KIdx) {
5612     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5613 
5614     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5615                                  DAG.getConstant(0, SL, MVT::i32));
5616     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5617                                  DAG.getConstant(1, SL, MVT::i32));
5618 
5619     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5620     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5621 
5622     unsigned Idx = KIdx->getZExtValue();
5623     bool InsertLo = Idx < 2;
5624     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5625       InsertLo ? LoVec : HiVec,
5626       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5627       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5628 
5629     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5630 
5631     SDValue Concat = InsertLo ?
5632       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5633       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5634 
5635     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5636   }
5637 
5638   // Static indexing does not lower to stack access, and hence there is no need
5639   // for special custom lowering to avoid stack access.
5640   if (isa<ConstantSDNode>(Idx))
5641     return SDValue();
5642 
5643   // Avoid stack access for dynamic indexing by custom lowering to
5644   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5645 
5646   assert(VecSize <= 64 && "Expected target vector size to be <= 64 bits");
5647 
5648   MVT IntVT = MVT::getIntegerVT(VecSize);
5649 
5650   // Convert vector index to bit-index and get the required bit mask.
5651   assert(isPowerOf2_32(EltSize));
5652   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5653   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5654   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5655                             DAG.getConstant(0xffff, SL, IntVT),
5656                             ScaledIdx);
5657 
5658   // 1. Create a congruent vector with the target value in each element.
5659   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5660                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5661 
5662   // 2. Mask off all other indicies except the required index within (1).
5663   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5664 
5665   // 3. Mask off the required index within the target vector.
5666   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5667   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5668                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5669 
5670   // 4. Get (2) and (3) ORed into the target vector.
5671   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5672 
5673   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5674 }
5675 
5676 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5677                                                   SelectionDAG &DAG) const {
5678   SDLoc SL(Op);
5679 
5680   EVT ResultVT = Op.getValueType();
5681   SDValue Vec = Op.getOperand(0);
5682   SDValue Idx = Op.getOperand(1);
5683   EVT VecVT = Vec.getValueType();
5684   unsigned VecSize = VecVT.getSizeInBits();
5685   EVT EltVT = VecVT.getVectorElementType();
5686 
5687   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5688 
5689   // Make sure we do any optimizations that will make it easier to fold
5690   // source modifiers before obscuring it with bit operations.
5691 
5692   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5693   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5694     return Combined;
5695 
5696   if (VecSize == 128) {
5697     SDValue Lo, Hi;
5698     EVT LoVT, HiVT;
5699     SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec);
5700     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5701     Lo =
5702         DAG.getBitcast(LoVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5703                                          V2, DAG.getConstant(0, SL, MVT::i32)));
5704     Hi =
5705         DAG.getBitcast(HiVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5706                                          V2, DAG.getConstant(1, SL, MVT::i32)));
5707     EVT IdxVT = Idx.getValueType();
5708     unsigned NElem = VecVT.getVectorNumElements();
5709     assert(isPowerOf2_32(NElem));
5710     SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT);
5711     SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask);
5712     SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT);
5713     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx);
5714   }
5715 
5716   assert(VecSize <= 64);
5717 
5718   MVT IntVT = MVT::getIntegerVT(VecSize);
5719 
5720   // If Vec is just a SCALAR_TO_VECTOR, then use the scalar integer directly.
5721   SDValue VecBC = peekThroughBitcasts(Vec);
5722   if (VecBC.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5723     SDValue Src = VecBC.getOperand(0);
5724     Src = DAG.getBitcast(Src.getValueType().changeTypeToInteger(), Src);
5725     Vec = DAG.getAnyExtOrTrunc(Src, SL, IntVT);
5726   }
5727 
5728   unsigned EltSize = EltVT.getSizeInBits();
5729   assert(isPowerOf2_32(EltSize));
5730 
5731   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5732 
5733   // Convert vector index to bit-index (* EltSize)
5734   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5735 
5736   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5737   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5738 
5739   if (ResultVT == MVT::f16) {
5740     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5741     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5742   }
5743 
5744   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5745 }
5746 
5747 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5748   assert(Elt % 2 == 0);
5749   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5750 }
5751 
5752 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5753                                               SelectionDAG &DAG) const {
5754   SDLoc SL(Op);
5755   EVT ResultVT = Op.getValueType();
5756   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5757 
5758   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5759   EVT EltVT = PackVT.getVectorElementType();
5760   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5761 
5762   // vector_shuffle <0,1,6,7> lhs, rhs
5763   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5764   //
5765   // vector_shuffle <6,7,2,3> lhs, rhs
5766   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5767   //
5768   // vector_shuffle <6,7,0,1> lhs, rhs
5769   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5770 
5771   // Avoid scalarizing when both halves are reading from consecutive elements.
5772   SmallVector<SDValue, 4> Pieces;
5773   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5774     if (elementPairIsContiguous(SVN->getMask(), I)) {
5775       const int Idx = SVN->getMaskElt(I);
5776       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5777       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5778       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5779                                     PackVT, SVN->getOperand(VecIdx),
5780                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5781       Pieces.push_back(SubVec);
5782     } else {
5783       const int Idx0 = SVN->getMaskElt(I);
5784       const int Idx1 = SVN->getMaskElt(I + 1);
5785       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5786       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5787       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5788       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5789 
5790       SDValue Vec0 = SVN->getOperand(VecIdx0);
5791       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5792                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5793 
5794       SDValue Vec1 = SVN->getOperand(VecIdx1);
5795       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5796                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5797       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5798     }
5799   }
5800 
5801   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5802 }
5803 
5804 SDValue SITargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
5805                                                 SelectionDAG &DAG) const {
5806   SDValue SVal = Op.getOperand(0);
5807   EVT ResultVT = Op.getValueType();
5808   EVT SValVT = SVal.getValueType();
5809   SDValue UndefVal = DAG.getUNDEF(SValVT);
5810   SDLoc SL(Op);
5811 
5812   SmallVector<SDValue, 8> VElts;
5813   VElts.push_back(SVal);
5814   for (int I = 1, E = ResultVT.getVectorNumElements(); I < E; ++I)
5815     VElts.push_back(UndefVal);
5816 
5817   return DAG.getBuildVector(ResultVT, SL, VElts);
5818 }
5819 
5820 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5821                                             SelectionDAG &DAG) const {
5822   SDLoc SL(Op);
5823   EVT VT = Op.getValueType();
5824 
5825   if (VT == MVT::v4i16 || VT == MVT::v4f16 ||
5826       VT == MVT::v8i16 || VT == MVT::v8f16) {
5827     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(),
5828                                   VT.getVectorNumElements() / 2);
5829     MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits());
5830 
5831     // Turn into pair of packed build_vectors.
5832     // TODO: Special case for constants that can be materialized with s_mov_b64.
5833     SmallVector<SDValue, 4> LoOps, HiOps;
5834     for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) {
5835       LoOps.push_back(Op.getOperand(I));
5836       HiOps.push_back(Op.getOperand(I + E));
5837     }
5838     SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps);
5839     SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps);
5840 
5841     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo);
5842     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi);
5843 
5844     SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL,
5845                                        { CastLo, CastHi });
5846     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5847   }
5848 
5849   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5850   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5851 
5852   SDValue Lo = Op.getOperand(0);
5853   SDValue Hi = Op.getOperand(1);
5854 
5855   // Avoid adding defined bits with the zero_extend.
5856   if (Hi.isUndef()) {
5857     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5858     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5859     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5860   }
5861 
5862   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5863   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5864 
5865   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5866                               DAG.getConstant(16, SL, MVT::i32));
5867   if (Lo.isUndef())
5868     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5869 
5870   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5871   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5872 
5873   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5874   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5875 }
5876 
5877 bool
5878 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5879   // We can fold offsets for anything that doesn't require a GOT relocation.
5880   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5881           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5882           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5883          !shouldEmitGOTReloc(GA->getGlobal());
5884 }
5885 
5886 static SDValue
5887 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5888                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5889                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5890   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5891   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5892   // lowered to the following code sequence:
5893   //
5894   // For constant address space:
5895   //   s_getpc_b64 s[0:1]
5896   //   s_add_u32 s0, s0, $symbol
5897   //   s_addc_u32 s1, s1, 0
5898   //
5899   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5900   //   a fixup or relocation is emitted to replace $symbol with a literal
5901   //   constant, which is a pc-relative offset from the encoding of the $symbol
5902   //   operand to the global variable.
5903   //
5904   // For global address space:
5905   //   s_getpc_b64 s[0:1]
5906   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5907   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5908   //
5909   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5910   //   fixups or relocations are emitted to replace $symbol@*@lo and
5911   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5912   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5913   //   operand to the global variable.
5914   //
5915   // What we want here is an offset from the value returned by s_getpc
5916   // (which is the address of the s_add_u32 instruction) to the global
5917   // variable, but since the encoding of $symbol starts 4 bytes after the start
5918   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5919   // small. This requires us to add 4 to the global variable offset in order to
5920   // compute the correct address. Similarly for the s_addc_u32 instruction, the
5921   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
5922   // instruction.
5923   SDValue PtrLo =
5924       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5925   SDValue PtrHi;
5926   if (GAFlags == SIInstrInfo::MO_NONE) {
5927     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5928   } else {
5929     PtrHi =
5930         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
5931   }
5932   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5933 }
5934 
5935 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5936                                              SDValue Op,
5937                                              SelectionDAG &DAG) const {
5938   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5939   SDLoc DL(GSD);
5940   EVT PtrVT = Op.getValueType();
5941 
5942   const GlobalValue *GV = GSD->getGlobal();
5943   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5944        shouldUseLDSConstAddress(GV)) ||
5945       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5946       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
5947     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5948         GV->hasExternalLinkage()) {
5949       Type *Ty = GV->getValueType();
5950       // HIP uses an unsized array `extern __shared__ T s[]` or similar
5951       // zero-sized type in other languages to declare the dynamic shared
5952       // memory which size is not known at the compile time. They will be
5953       // allocated by the runtime and placed directly after the static
5954       // allocated ones. They all share the same offset.
5955       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
5956         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
5957         // Adjust alignment for that dynamic shared memory array.
5958         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
5959         return SDValue(
5960             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
5961       }
5962     }
5963     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5964   }
5965 
5966   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5967     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5968                                             SIInstrInfo::MO_ABS32_LO);
5969     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5970   }
5971 
5972   if (shouldEmitFixup(GV))
5973     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5974   else if (shouldEmitPCReloc(GV))
5975     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5976                                    SIInstrInfo::MO_REL32);
5977 
5978   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5979                                             SIInstrInfo::MO_GOTPCREL32);
5980 
5981   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5982   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5983   const DataLayout &DataLayout = DAG.getDataLayout();
5984   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
5985   MachinePointerInfo PtrInfo
5986     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5987 
5988   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
5989                      MachineMemOperand::MODereferenceable |
5990                          MachineMemOperand::MOInvariant);
5991 }
5992 
5993 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5994                                    const SDLoc &DL, SDValue V) const {
5995   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5996   // the destination register.
5997   //
5998   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5999   // so we will end up with redundant moves to m0.
6000   //
6001   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
6002 
6003   // A Null SDValue creates a glue result.
6004   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
6005                                   V, Chain);
6006   return SDValue(M0, 0);
6007 }
6008 
6009 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
6010                                                  SDValue Op,
6011                                                  MVT VT,
6012                                                  unsigned Offset) const {
6013   SDLoc SL(Op);
6014   SDValue Param = lowerKernargMemParameter(
6015       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
6016   // The local size values will have the hi 16-bits as zero.
6017   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
6018                      DAG.getValueType(VT));
6019 }
6020 
6021 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6022                                         EVT VT) {
6023   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6024                                       "non-hsa intrinsic with hsa target",
6025                                       DL.getDebugLoc());
6026   DAG.getContext()->diagnose(BadIntrin);
6027   return DAG.getUNDEF(VT);
6028 }
6029 
6030 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6031                                          EVT VT) {
6032   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6033                                       "intrinsic not supported on subtarget",
6034                                       DL.getDebugLoc());
6035   DAG.getContext()->diagnose(BadIntrin);
6036   return DAG.getUNDEF(VT);
6037 }
6038 
6039 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
6040                                     ArrayRef<SDValue> Elts) {
6041   assert(!Elts.empty());
6042   MVT Type;
6043   unsigned NumElts = Elts.size();
6044 
6045   if (NumElts <= 8) {
6046     Type = MVT::getVectorVT(MVT::f32, NumElts);
6047   } else {
6048     assert(Elts.size() <= 16);
6049     Type = MVT::v16f32;
6050     NumElts = 16;
6051   }
6052 
6053   SmallVector<SDValue, 16> VecElts(NumElts);
6054   for (unsigned i = 0; i < Elts.size(); ++i) {
6055     SDValue Elt = Elts[i];
6056     if (Elt.getValueType() != MVT::f32)
6057       Elt = DAG.getBitcast(MVT::f32, Elt);
6058     VecElts[i] = Elt;
6059   }
6060   for (unsigned i = Elts.size(); i < NumElts; ++i)
6061     VecElts[i] = DAG.getUNDEF(MVT::f32);
6062 
6063   if (NumElts == 1)
6064     return VecElts[0];
6065   return DAG.getBuildVector(Type, DL, VecElts);
6066 }
6067 
6068 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
6069                               SDValue Src, int ExtraElts) {
6070   EVT SrcVT = Src.getValueType();
6071 
6072   SmallVector<SDValue, 8> Elts;
6073 
6074   if (SrcVT.isVector())
6075     DAG.ExtractVectorElements(Src, Elts);
6076   else
6077     Elts.push_back(Src);
6078 
6079   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
6080   while (ExtraElts--)
6081     Elts.push_back(Undef);
6082 
6083   return DAG.getBuildVector(CastVT, DL, Elts);
6084 }
6085 
6086 // Re-construct the required return value for a image load intrinsic.
6087 // This is more complicated due to the optional use TexFailCtrl which means the required
6088 // return type is an aggregate
6089 static SDValue constructRetValue(SelectionDAG &DAG,
6090                                  MachineSDNode *Result,
6091                                  ArrayRef<EVT> ResultTypes,
6092                                  bool IsTexFail, bool Unpacked, bool IsD16,
6093                                  int DMaskPop, int NumVDataDwords,
6094                                  const SDLoc &DL) {
6095   // Determine the required return type. This is the same regardless of IsTexFail flag
6096   EVT ReqRetVT = ResultTypes[0];
6097   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
6098   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6099     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
6100 
6101   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6102     DMaskPop : (DMaskPop + 1) / 2;
6103 
6104   MVT DataDwordVT = NumDataDwords == 1 ?
6105     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
6106 
6107   MVT MaskPopVT = MaskPopDwords == 1 ?
6108     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
6109 
6110   SDValue Data(Result, 0);
6111   SDValue TexFail;
6112 
6113   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
6114     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
6115     if (MaskPopVT.isVector()) {
6116       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
6117                          SDValue(Result, 0), ZeroIdx);
6118     } else {
6119       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
6120                          SDValue(Result, 0), ZeroIdx);
6121     }
6122   }
6123 
6124   if (DataDwordVT.isVector())
6125     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
6126                           NumDataDwords - MaskPopDwords);
6127 
6128   if (IsD16)
6129     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
6130 
6131   EVT LegalReqRetVT = ReqRetVT;
6132   if (!ReqRetVT.isVector()) {
6133     if (!Data.getValueType().isInteger())
6134       Data = DAG.getNode(ISD::BITCAST, DL,
6135                          Data.getValueType().changeTypeToInteger(), Data);
6136     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
6137   } else {
6138     // We need to widen the return vector to a legal type
6139     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
6140         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
6141       LegalReqRetVT =
6142           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
6143                            ReqRetVT.getVectorNumElements() + 1);
6144     }
6145   }
6146   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
6147 
6148   if (IsTexFail) {
6149     TexFail =
6150         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
6151                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
6152 
6153     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
6154   }
6155 
6156   if (Result->getNumValues() == 1)
6157     return Data;
6158 
6159   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
6160 }
6161 
6162 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
6163                          SDValue *LWE, bool &IsTexFail) {
6164   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
6165 
6166   uint64_t Value = TexFailCtrlConst->getZExtValue();
6167   if (Value) {
6168     IsTexFail = true;
6169   }
6170 
6171   SDLoc DL(TexFailCtrlConst);
6172   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
6173   Value &= ~(uint64_t)0x1;
6174   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
6175   Value &= ~(uint64_t)0x2;
6176 
6177   return Value == 0;
6178 }
6179 
6180 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
6181                                       MVT PackVectorVT,
6182                                       SmallVectorImpl<SDValue> &PackedAddrs,
6183                                       unsigned DimIdx, unsigned EndIdx,
6184                                       unsigned NumGradients) {
6185   SDLoc DL(Op);
6186   for (unsigned I = DimIdx; I < EndIdx; I++) {
6187     SDValue Addr = Op.getOperand(I);
6188 
6189     // Gradients are packed with undef for each coordinate.
6190     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
6191     // 1D: undef,dx/dh; undef,dx/dv
6192     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
6193     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
6194     if (((I + 1) >= EndIdx) ||
6195         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
6196                                          I == DimIdx + NumGradients - 1))) {
6197       if (Addr.getValueType() != MVT::i16)
6198         Addr = DAG.getBitcast(MVT::i16, Addr);
6199       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
6200     } else {
6201       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
6202       I++;
6203     }
6204     Addr = DAG.getBitcast(MVT::f32, Addr);
6205     PackedAddrs.push_back(Addr);
6206   }
6207 }
6208 
6209 SDValue SITargetLowering::lowerImage(SDValue Op,
6210                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
6211                                      SelectionDAG &DAG, bool WithChain) const {
6212   SDLoc DL(Op);
6213   MachineFunction &MF = DAG.getMachineFunction();
6214   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
6215   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
6216       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
6217   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
6218   unsigned IntrOpcode = Intr->BaseOpcode;
6219   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6220 
6221   SmallVector<EVT, 3> ResultTypes(Op->values());
6222   SmallVector<EVT, 3> OrigResultTypes(Op->values());
6223   bool IsD16 = false;
6224   bool IsG16 = false;
6225   bool IsA16 = false;
6226   SDValue VData;
6227   int NumVDataDwords;
6228   bool AdjustRetType = false;
6229 
6230   // Offset of intrinsic arguments
6231   const unsigned ArgOffset = WithChain ? 2 : 1;
6232 
6233   unsigned DMask;
6234   unsigned DMaskLanes = 0;
6235 
6236   if (BaseOpcode->Atomic) {
6237     VData = Op.getOperand(2);
6238 
6239     bool Is64Bit = VData.getValueType() == MVT::i64;
6240     if (BaseOpcode->AtomicX2) {
6241       SDValue VData2 = Op.getOperand(3);
6242       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6243                                  {VData, VData2});
6244       if (Is64Bit)
6245         VData = DAG.getBitcast(MVT::v4i32, VData);
6246 
6247       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6248       DMask = Is64Bit ? 0xf : 0x3;
6249       NumVDataDwords = Is64Bit ? 4 : 2;
6250     } else {
6251       DMask = Is64Bit ? 0x3 : 0x1;
6252       NumVDataDwords = Is64Bit ? 2 : 1;
6253     }
6254   } else {
6255     auto *DMaskConst =
6256         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6257     DMask = DMaskConst->getZExtValue();
6258     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6259 
6260     if (BaseOpcode->Store) {
6261       VData = Op.getOperand(2);
6262 
6263       MVT StoreVT = VData.getSimpleValueType();
6264       if (StoreVT.getScalarType() == MVT::f16) {
6265         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6266           return Op; // D16 is unsupported for this instruction
6267 
6268         IsD16 = true;
6269         VData = handleD16VData(VData, DAG, true);
6270       }
6271 
6272       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6273     } else {
6274       // Work out the num dwords based on the dmask popcount and underlying type
6275       // and whether packing is supported.
6276       MVT LoadVT = ResultTypes[0].getSimpleVT();
6277       if (LoadVT.getScalarType() == MVT::f16) {
6278         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6279           return Op; // D16 is unsupported for this instruction
6280 
6281         IsD16 = true;
6282       }
6283 
6284       // Confirm that the return type is large enough for the dmask specified
6285       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6286           (!LoadVT.isVector() && DMaskLanes > 1))
6287           return Op;
6288 
6289       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6290       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6291       // instructions.
6292       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6293           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6294         NumVDataDwords = (DMaskLanes + 1) / 2;
6295       else
6296         NumVDataDwords = DMaskLanes;
6297 
6298       AdjustRetType = true;
6299     }
6300   }
6301 
6302   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6303   SmallVector<SDValue, 4> VAddrs;
6304 
6305   // Check for 16 bit addresses or derivatives and pack if true.
6306   MVT VAddrVT =
6307       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6308   MVT VAddrScalarVT = VAddrVT.getScalarType();
6309   MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6310   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6311 
6312   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6313   VAddrScalarVT = VAddrVT.getScalarType();
6314   MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6315   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6316 
6317   // Push back extra arguments.
6318   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) {
6319     if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) {
6320       assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument");
6321       // Special handling of bias when A16 is on. Bias is of type half but
6322       // occupies full 32-bit.
6323       SDValue Bias = DAG.getBuildVector(
6324           MVT::v2f16, DL,
6325           {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)});
6326       VAddrs.push_back(Bias);
6327     } else {
6328       assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) &&
6329              "Bias needs to be converted to 16 bit in A16 mode");
6330       VAddrs.push_back(Op.getOperand(ArgOffset + I));
6331     }
6332   }
6333 
6334   if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
6335     // 16 bit gradients are supported, but are tied to the A16 control
6336     // so both gradients and addresses must be 16 bit
6337     LLVM_DEBUG(
6338         dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6339                   "require 16 bit args for both gradients and addresses");
6340     return Op;
6341   }
6342 
6343   if (IsA16) {
6344     if (!ST->hasA16()) {
6345       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6346                            "support 16 bit addresses\n");
6347       return Op;
6348     }
6349   }
6350 
6351   // We've dealt with incorrect input so we know that if IsA16, IsG16
6352   // are set then we have to compress/pack operands (either address,
6353   // gradient or both)
6354   // In the case where a16 and gradients are tied (no G16 support) then we
6355   // have already verified that both IsA16 and IsG16 are true
6356   if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
6357     // Activate g16
6358     const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6359         AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6360     IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6361   }
6362 
6363   // Add gradients (packed or unpacked)
6364   if (IsG16) {
6365     // Pack the gradients
6366     // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6367     packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
6368                               ArgOffset + Intr->GradientStart,
6369                               ArgOffset + Intr->CoordStart, Intr->NumGradients);
6370   } else {
6371     for (unsigned I = ArgOffset + Intr->GradientStart;
6372          I < ArgOffset + Intr->CoordStart; I++)
6373       VAddrs.push_back(Op.getOperand(I));
6374   }
6375 
6376   // Add addresses (packed or unpacked)
6377   if (IsA16) {
6378     packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
6379                               ArgOffset + Intr->CoordStart, VAddrEnd,
6380                               0 /* No gradients */);
6381   } else {
6382     // Add uncompressed address
6383     for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6384       VAddrs.push_back(Op.getOperand(I));
6385   }
6386 
6387   // If the register allocator cannot place the address registers contiguously
6388   // without introducing moves, then using the non-sequential address encoding
6389   // is always preferable, since it saves VALU instructions and is usually a
6390   // wash in terms of code size or even better.
6391   //
6392   // However, we currently have no way of hinting to the register allocator that
6393   // MIMG addresses should be placed contiguously when it is possible to do so,
6394   // so force non-NSA for the common 2-address case as a heuristic.
6395   //
6396   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6397   // allocation when possible.
6398   bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) &&
6399                 VAddrs.size() >= 3 &&
6400                 VAddrs.size() <= (unsigned)ST->getNSAMaxSize();
6401   SDValue VAddr;
6402   if (!UseNSA)
6403     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6404 
6405   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6406   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6407   SDValue Unorm;
6408   if (!BaseOpcode->Sampler) {
6409     Unorm = True;
6410   } else {
6411     auto UnormConst =
6412         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6413 
6414     Unorm = UnormConst->getZExtValue() ? True : False;
6415   }
6416 
6417   SDValue TFE;
6418   SDValue LWE;
6419   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6420   bool IsTexFail = false;
6421   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6422     return Op;
6423 
6424   if (IsTexFail) {
6425     if (!DMaskLanes) {
6426       // Expecting to get an error flag since TFC is on - and dmask is 0
6427       // Force dmask to be at least 1 otherwise the instruction will fail
6428       DMask = 0x1;
6429       DMaskLanes = 1;
6430       NumVDataDwords = 1;
6431     }
6432     NumVDataDwords += 1;
6433     AdjustRetType = true;
6434   }
6435 
6436   // Has something earlier tagged that the return type needs adjusting
6437   // This happens if the instruction is a load or has set TexFailCtrl flags
6438   if (AdjustRetType) {
6439     // NumVDataDwords reflects the true number of dwords required in the return type
6440     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6441       // This is a no-op load. This can be eliminated
6442       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6443       if (isa<MemSDNode>(Op))
6444         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6445       return Undef;
6446     }
6447 
6448     EVT NewVT = NumVDataDwords > 1 ?
6449                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6450                 : MVT::i32;
6451 
6452     ResultTypes[0] = NewVT;
6453     if (ResultTypes.size() == 3) {
6454       // Original result was aggregate type used for TexFailCtrl results
6455       // The actual instruction returns as a vector type which has now been
6456       // created. Remove the aggregate result.
6457       ResultTypes.erase(&ResultTypes[1]);
6458     }
6459   }
6460 
6461   unsigned CPol = cast<ConstantSDNode>(
6462       Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6463   if (BaseOpcode->Atomic)
6464     CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6465   if (CPol & ~AMDGPU::CPol::ALL)
6466     return Op;
6467 
6468   SmallVector<SDValue, 26> Ops;
6469   if (BaseOpcode->Store || BaseOpcode->Atomic)
6470     Ops.push_back(VData); // vdata
6471   if (UseNSA)
6472     append_range(Ops, VAddrs);
6473   else
6474     Ops.push_back(VAddr);
6475   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6476   if (BaseOpcode->Sampler)
6477     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6478   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6479   if (IsGFX10Plus)
6480     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6481   Ops.push_back(Unorm);
6482   Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6483   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6484                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6485   if (IsGFX10Plus)
6486     Ops.push_back(IsA16 ? True : False);
6487   if (!Subtarget->hasGFX90AInsts()) {
6488     Ops.push_back(TFE); //tfe
6489   } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6490     report_fatal_error("TFE is not supported on this GPU");
6491   }
6492   Ops.push_back(LWE); // lwe
6493   if (!IsGFX10Plus)
6494     Ops.push_back(DimInfo->DA ? True : False);
6495   if (BaseOpcode->HasD16)
6496     Ops.push_back(IsD16 ? True : False);
6497   if (isa<MemSDNode>(Op))
6498     Ops.push_back(Op.getOperand(0)); // chain
6499 
6500   int NumVAddrDwords =
6501       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6502   int Opcode = -1;
6503 
6504   if (IsGFX10Plus) {
6505     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6506                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6507                                           : AMDGPU::MIMGEncGfx10Default,
6508                                    NumVDataDwords, NumVAddrDwords);
6509   } else {
6510     if (Subtarget->hasGFX90AInsts()) {
6511       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6512                                      NumVDataDwords, NumVAddrDwords);
6513       if (Opcode == -1)
6514         report_fatal_error(
6515             "requested image instruction is not supported on this GPU");
6516     }
6517     if (Opcode == -1 &&
6518         Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6519       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6520                                      NumVDataDwords, NumVAddrDwords);
6521     if (Opcode == -1)
6522       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6523                                      NumVDataDwords, NumVAddrDwords);
6524   }
6525   assert(Opcode != -1);
6526 
6527   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6528   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6529     MachineMemOperand *MemRef = MemOp->getMemOperand();
6530     DAG.setNodeMemRefs(NewNode, {MemRef});
6531   }
6532 
6533   if (BaseOpcode->AtomicX2) {
6534     SmallVector<SDValue, 1> Elt;
6535     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6536     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6537   }
6538   if (BaseOpcode->Store)
6539     return SDValue(NewNode, 0);
6540   return constructRetValue(DAG, NewNode,
6541                            OrigResultTypes, IsTexFail,
6542                            Subtarget->hasUnpackedD16VMem(), IsD16,
6543                            DMaskLanes, NumVDataDwords, DL);
6544 }
6545 
6546 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6547                                        SDValue Offset, SDValue CachePolicy,
6548                                        SelectionDAG &DAG) const {
6549   MachineFunction &MF = DAG.getMachineFunction();
6550 
6551   const DataLayout &DataLayout = DAG.getDataLayout();
6552   Align Alignment =
6553       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6554 
6555   MachineMemOperand *MMO = MF.getMachineMemOperand(
6556       MachinePointerInfo(),
6557       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6558           MachineMemOperand::MOInvariant,
6559       VT.getStoreSize(), Alignment);
6560 
6561   if (!Offset->isDivergent()) {
6562     SDValue Ops[] = {
6563         Rsrc,
6564         Offset, // Offset
6565         CachePolicy
6566     };
6567 
6568     // Widen vec3 load to vec4.
6569     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6570       EVT WidenedVT =
6571           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6572       auto WidenedOp = DAG.getMemIntrinsicNode(
6573           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6574           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6575       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6576                                    DAG.getVectorIdxConstant(0, DL));
6577       return Subvector;
6578     }
6579 
6580     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6581                                    DAG.getVTList(VT), Ops, VT, MMO);
6582   }
6583 
6584   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6585   // assume that the buffer is unswizzled.
6586   SmallVector<SDValue, 4> Loads;
6587   unsigned NumLoads = 1;
6588   MVT LoadVT = VT.getSimpleVT();
6589   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6590   assert((LoadVT.getScalarType() == MVT::i32 ||
6591           LoadVT.getScalarType() == MVT::f32));
6592 
6593   if (NumElts == 8 || NumElts == 16) {
6594     NumLoads = NumElts / 4;
6595     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6596   }
6597 
6598   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6599   SDValue Ops[] = {
6600       DAG.getEntryNode(),                               // Chain
6601       Rsrc,                                             // rsrc
6602       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6603       {},                                               // voffset
6604       {},                                               // soffset
6605       {},                                               // offset
6606       CachePolicy,                                      // cachepolicy
6607       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6608   };
6609 
6610   // Use the alignment to ensure that the required offsets will fit into the
6611   // immediate offsets.
6612   setBufferOffsets(Offset, DAG, &Ops[3],
6613                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6614 
6615   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6616   for (unsigned i = 0; i < NumLoads; ++i) {
6617     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6618     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6619                                         LoadVT, MMO, DAG));
6620   }
6621 
6622   if (NumElts == 8 || NumElts == 16)
6623     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6624 
6625   return Loads[0];
6626 }
6627 
6628 SDValue SITargetLowering::lowerWorkitemID(SelectionDAG &DAG, SDValue Op,
6629                                           unsigned Dim,
6630                                           const ArgDescriptor &Arg) const {
6631   SDLoc SL(Op);
6632   MachineFunction &MF = DAG.getMachineFunction();
6633   unsigned MaxID = Subtarget->getMaxWorkitemID(MF.getFunction(), Dim);
6634   if (MaxID == 0)
6635     return DAG.getConstant(0, SL, MVT::i32);
6636 
6637   SDValue Val = loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6638                                SDLoc(DAG.getEntryNode()), Arg);
6639 
6640   // Don't bother inserting AssertZext for packed IDs since we're emitting the
6641   // masking operations anyway.
6642   //
6643   // TODO: We could assert the top bit is 0 for the source copy.
6644   if (Arg.isMasked())
6645     return Val;
6646 
6647   // Preserve the known bits after expansion to a copy.
6648   EVT SmallVT =
6649       EVT::getIntegerVT(*DAG.getContext(), 32 - countLeadingZeros(MaxID));
6650   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Val,
6651                      DAG.getValueType(SmallVT));
6652 }
6653 
6654 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6655                                                   SelectionDAG &DAG) const {
6656   MachineFunction &MF = DAG.getMachineFunction();
6657   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6658 
6659   EVT VT = Op.getValueType();
6660   SDLoc DL(Op);
6661   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6662 
6663   // TODO: Should this propagate fast-math-flags?
6664 
6665   switch (IntrinsicID) {
6666   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6667     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6668       return emitNonHSAIntrinsicError(DAG, DL, VT);
6669     return getPreloadedValue(DAG, *MFI, VT,
6670                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6671   }
6672   case Intrinsic::amdgcn_dispatch_ptr:
6673   case Intrinsic::amdgcn_queue_ptr: {
6674     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6675       DiagnosticInfoUnsupported BadIntrin(
6676           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6677           DL.getDebugLoc());
6678       DAG.getContext()->diagnose(BadIntrin);
6679       return DAG.getUNDEF(VT);
6680     }
6681 
6682     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6683       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6684     return getPreloadedValue(DAG, *MFI, VT, RegID);
6685   }
6686   case Intrinsic::amdgcn_implicitarg_ptr: {
6687     if (MFI->isEntryFunction())
6688       return getImplicitArgPtr(DAG, DL);
6689     return getPreloadedValue(DAG, *MFI, VT,
6690                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6691   }
6692   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6693     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6694       // This only makes sense to call in a kernel, so just lower to null.
6695       return DAG.getConstant(0, DL, VT);
6696     }
6697 
6698     return getPreloadedValue(DAG, *MFI, VT,
6699                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6700   }
6701   case Intrinsic::amdgcn_dispatch_id: {
6702     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6703   }
6704   case Intrinsic::amdgcn_rcp:
6705     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6706   case Intrinsic::amdgcn_rsq:
6707     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6708   case Intrinsic::amdgcn_rsq_legacy:
6709     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6710       return emitRemovedIntrinsicError(DAG, DL, VT);
6711     return SDValue();
6712   case Intrinsic::amdgcn_rcp_legacy:
6713     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6714       return emitRemovedIntrinsicError(DAG, DL, VT);
6715     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6716   case Intrinsic::amdgcn_rsq_clamp: {
6717     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6718       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6719 
6720     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6721     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6722     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6723 
6724     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6725     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6726                               DAG.getConstantFP(Max, DL, VT));
6727     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6728                        DAG.getConstantFP(Min, DL, VT));
6729   }
6730   case Intrinsic::r600_read_ngroups_x:
6731     if (Subtarget->isAmdHsaOS())
6732       return emitNonHSAIntrinsicError(DAG, DL, VT);
6733 
6734     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6735                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6736                                     false);
6737   case Intrinsic::r600_read_ngroups_y:
6738     if (Subtarget->isAmdHsaOS())
6739       return emitNonHSAIntrinsicError(DAG, DL, VT);
6740 
6741     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6742                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6743                                     false);
6744   case Intrinsic::r600_read_ngroups_z:
6745     if (Subtarget->isAmdHsaOS())
6746       return emitNonHSAIntrinsicError(DAG, DL, VT);
6747 
6748     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6749                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6750                                     false);
6751   case Intrinsic::r600_read_global_size_x:
6752     if (Subtarget->isAmdHsaOS())
6753       return emitNonHSAIntrinsicError(DAG, DL, VT);
6754 
6755     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6756                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6757                                     Align(4), false);
6758   case Intrinsic::r600_read_global_size_y:
6759     if (Subtarget->isAmdHsaOS())
6760       return emitNonHSAIntrinsicError(DAG, DL, VT);
6761 
6762     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6763                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6764                                     Align(4), false);
6765   case Intrinsic::r600_read_global_size_z:
6766     if (Subtarget->isAmdHsaOS())
6767       return emitNonHSAIntrinsicError(DAG, DL, VT);
6768 
6769     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6770                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6771                                     Align(4), false);
6772   case Intrinsic::r600_read_local_size_x:
6773     if (Subtarget->isAmdHsaOS())
6774       return emitNonHSAIntrinsicError(DAG, DL, VT);
6775 
6776     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6777                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6778   case Intrinsic::r600_read_local_size_y:
6779     if (Subtarget->isAmdHsaOS())
6780       return emitNonHSAIntrinsicError(DAG, DL, VT);
6781 
6782     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6783                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6784   case Intrinsic::r600_read_local_size_z:
6785     if (Subtarget->isAmdHsaOS())
6786       return emitNonHSAIntrinsicError(DAG, DL, VT);
6787 
6788     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6789                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6790   case Intrinsic::amdgcn_workgroup_id_x:
6791     return getPreloadedValue(DAG, *MFI, VT,
6792                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6793   case Intrinsic::amdgcn_workgroup_id_y:
6794     return getPreloadedValue(DAG, *MFI, VT,
6795                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6796   case Intrinsic::amdgcn_workgroup_id_z:
6797     return getPreloadedValue(DAG, *MFI, VT,
6798                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6799   case Intrinsic::amdgcn_workitem_id_x:
6800     return lowerWorkitemID(DAG, Op, 0, MFI->getArgInfo().WorkItemIDX);
6801   case Intrinsic::amdgcn_workitem_id_y:
6802     return lowerWorkitemID(DAG, Op, 1, MFI->getArgInfo().WorkItemIDY);
6803   case Intrinsic::amdgcn_workitem_id_z:
6804     return lowerWorkitemID(DAG, Op, 2, MFI->getArgInfo().WorkItemIDZ);
6805   case Intrinsic::amdgcn_wavefrontsize:
6806     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6807                            SDLoc(Op), MVT::i32);
6808   case Intrinsic::amdgcn_s_buffer_load: {
6809     unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6810     if (CPol & ~AMDGPU::CPol::ALL)
6811       return Op;
6812     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6813                         DAG);
6814   }
6815   case Intrinsic::amdgcn_fdiv_fast:
6816     return lowerFDIV_FAST(Op, DAG);
6817   case Intrinsic::amdgcn_sin:
6818     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6819 
6820   case Intrinsic::amdgcn_cos:
6821     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6822 
6823   case Intrinsic::amdgcn_mul_u24:
6824     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6825   case Intrinsic::amdgcn_mul_i24:
6826     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6827 
6828   case Intrinsic::amdgcn_log_clamp: {
6829     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6830       return SDValue();
6831 
6832     return emitRemovedIntrinsicError(DAG, DL, VT);
6833   }
6834   case Intrinsic::amdgcn_ldexp:
6835     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6836                        Op.getOperand(1), Op.getOperand(2));
6837 
6838   case Intrinsic::amdgcn_fract:
6839     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6840 
6841   case Intrinsic::amdgcn_class:
6842     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6843                        Op.getOperand(1), Op.getOperand(2));
6844   case Intrinsic::amdgcn_div_fmas:
6845     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6846                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6847                        Op.getOperand(4));
6848 
6849   case Intrinsic::amdgcn_div_fixup:
6850     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6851                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6852 
6853   case Intrinsic::amdgcn_div_scale: {
6854     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6855 
6856     // Translate to the operands expected by the machine instruction. The
6857     // first parameter must be the same as the first instruction.
6858     SDValue Numerator = Op.getOperand(1);
6859     SDValue Denominator = Op.getOperand(2);
6860 
6861     // Note this order is opposite of the machine instruction's operations,
6862     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6863     // intrinsic has the numerator as the first operand to match a normal
6864     // division operation.
6865 
6866     SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator;
6867 
6868     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6869                        Denominator, Numerator);
6870   }
6871   case Intrinsic::amdgcn_icmp: {
6872     // There is a Pat that handles this variant, so return it as-is.
6873     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6874         Op.getConstantOperandVal(2) == 0 &&
6875         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6876       return Op;
6877     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6878   }
6879   case Intrinsic::amdgcn_fcmp: {
6880     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6881   }
6882   case Intrinsic::amdgcn_ballot:
6883     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6884   case Intrinsic::amdgcn_fmed3:
6885     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6886                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6887   case Intrinsic::amdgcn_fdot2:
6888     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6889                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6890                        Op.getOperand(4));
6891   case Intrinsic::amdgcn_fmul_legacy:
6892     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6893                        Op.getOperand(1), Op.getOperand(2));
6894   case Intrinsic::amdgcn_sffbh:
6895     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6896   case Intrinsic::amdgcn_sbfe:
6897     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6898                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6899   case Intrinsic::amdgcn_ubfe:
6900     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6901                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6902   case Intrinsic::amdgcn_cvt_pkrtz:
6903   case Intrinsic::amdgcn_cvt_pknorm_i16:
6904   case Intrinsic::amdgcn_cvt_pknorm_u16:
6905   case Intrinsic::amdgcn_cvt_pk_i16:
6906   case Intrinsic::amdgcn_cvt_pk_u16: {
6907     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6908     EVT VT = Op.getValueType();
6909     unsigned Opcode;
6910 
6911     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6912       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6913     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6914       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6915     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6916       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6917     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6918       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6919     else
6920       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6921 
6922     if (isTypeLegal(VT))
6923       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6924 
6925     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6926                                Op.getOperand(1), Op.getOperand(2));
6927     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6928   }
6929   case Intrinsic::amdgcn_fmad_ftz:
6930     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6931                        Op.getOperand(2), Op.getOperand(3));
6932 
6933   case Intrinsic::amdgcn_if_break:
6934     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6935                                       Op->getOperand(1), Op->getOperand(2)), 0);
6936 
6937   case Intrinsic::amdgcn_groupstaticsize: {
6938     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6939     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6940       return Op;
6941 
6942     const Module *M = MF.getFunction().getParent();
6943     const GlobalValue *GV =
6944         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6945     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6946                                             SIInstrInfo::MO_ABS32_LO);
6947     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6948   }
6949   case Intrinsic::amdgcn_is_shared:
6950   case Intrinsic::amdgcn_is_private: {
6951     SDLoc SL(Op);
6952     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6953       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6954     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6955     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6956                                  Op.getOperand(1));
6957 
6958     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6959                                 DAG.getConstant(1, SL, MVT::i32));
6960     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6961   }
6962   case Intrinsic::amdgcn_perm:
6963     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
6964                        Op.getOperand(2), Op.getOperand(3));
6965   case Intrinsic::amdgcn_reloc_constant: {
6966     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6967     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6968     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6969     auto RelocSymbol = cast<GlobalVariable>(
6970         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6971     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6972                                             SIInstrInfo::MO_ABS32_LO);
6973     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6974   }
6975   default:
6976     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6977             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6978       return lowerImage(Op, ImageDimIntr, DAG, false);
6979 
6980     return Op;
6981   }
6982 }
6983 
6984 /// Update \p MMO based on the offset inputs to an intrinsic.
6985 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset,
6986                             SDValue SOffset, SDValue Offset,
6987                             SDValue VIndex = SDValue()) {
6988   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6989       !isa<ConstantSDNode>(Offset)) {
6990     // The combined offset is not known to be constant, so we cannot represent
6991     // it in the MMO. Give up.
6992     MMO->setValue((Value *)nullptr);
6993     return;
6994   }
6995 
6996   if (VIndex && (!isa<ConstantSDNode>(VIndex) ||
6997                  !cast<ConstantSDNode>(VIndex)->isZero())) {
6998     // The strided index component of the address is not known to be zero, so we
6999     // cannot represent it in the MMO. Give up.
7000     MMO->setValue((Value *)nullptr);
7001     return;
7002   }
7003 
7004   MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() +
7005                  cast<ConstantSDNode>(SOffset)->getSExtValue() +
7006                  cast<ConstantSDNode>(Offset)->getSExtValue());
7007 }
7008 
7009 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
7010                                                      SelectionDAG &DAG,
7011                                                      unsigned NewOpcode) const {
7012   SDLoc DL(Op);
7013 
7014   SDValue VData = Op.getOperand(2);
7015   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7016   SDValue Ops[] = {
7017     Op.getOperand(0), // Chain
7018     VData,            // vdata
7019     Op.getOperand(3), // rsrc
7020     DAG.getConstant(0, DL, MVT::i32), // vindex
7021     Offsets.first,    // voffset
7022     Op.getOperand(5), // soffset
7023     Offsets.second,   // offset
7024     Op.getOperand(6), // cachepolicy
7025     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7026   };
7027 
7028   auto *M = cast<MemSDNode>(Op);
7029   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
7030 
7031   EVT MemVT = VData.getValueType();
7032   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7033                                  M->getMemOperand());
7034 }
7035 
7036 // Return a value to use for the idxen operand by examining the vindex operand.
7037 static unsigned getIdxEn(SDValue VIndex) {
7038   if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex))
7039     // No need to set idxen if vindex is known to be zero.
7040     return VIndexC->getZExtValue() != 0;
7041   return 1;
7042 }
7043 
7044 SDValue
7045 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
7046                                                 unsigned NewOpcode) const {
7047   SDLoc DL(Op);
7048 
7049   SDValue VData = Op.getOperand(2);
7050   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7051   SDValue Ops[] = {
7052     Op.getOperand(0), // Chain
7053     VData,            // vdata
7054     Op.getOperand(3), // rsrc
7055     Op.getOperand(4), // vindex
7056     Offsets.first,    // voffset
7057     Op.getOperand(6), // soffset
7058     Offsets.second,   // offset
7059     Op.getOperand(7), // cachepolicy
7060     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7061   };
7062 
7063   auto *M = cast<MemSDNode>(Op);
7064   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7065 
7066   EVT MemVT = VData.getValueType();
7067   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7068                                  M->getMemOperand());
7069 }
7070 
7071 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
7072                                                  SelectionDAG &DAG) const {
7073   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7074   SDLoc DL(Op);
7075 
7076   switch (IntrID) {
7077   case Intrinsic::amdgcn_ds_ordered_add:
7078   case Intrinsic::amdgcn_ds_ordered_swap: {
7079     MemSDNode *M = cast<MemSDNode>(Op);
7080     SDValue Chain = M->getOperand(0);
7081     SDValue M0 = M->getOperand(2);
7082     SDValue Value = M->getOperand(3);
7083     unsigned IndexOperand = M->getConstantOperandVal(7);
7084     unsigned WaveRelease = M->getConstantOperandVal(8);
7085     unsigned WaveDone = M->getConstantOperandVal(9);
7086 
7087     unsigned OrderedCountIndex = IndexOperand & 0x3f;
7088     IndexOperand &= ~0x3f;
7089     unsigned CountDw = 0;
7090 
7091     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
7092       CountDw = (IndexOperand >> 24) & 0xf;
7093       IndexOperand &= ~(0xf << 24);
7094 
7095       if (CountDw < 1 || CountDw > 4) {
7096         report_fatal_error(
7097             "ds_ordered_count: dword count must be between 1 and 4");
7098       }
7099     }
7100 
7101     if (IndexOperand)
7102       report_fatal_error("ds_ordered_count: bad index operand");
7103 
7104     if (WaveDone && !WaveRelease)
7105       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
7106 
7107     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
7108     unsigned ShaderType =
7109         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
7110     unsigned Offset0 = OrderedCountIndex << 2;
7111     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
7112                        (Instruction << 4);
7113 
7114     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
7115       Offset1 |= (CountDw - 1) << 6;
7116 
7117     unsigned Offset = Offset0 | (Offset1 << 8);
7118 
7119     SDValue Ops[] = {
7120       Chain,
7121       Value,
7122       DAG.getTargetConstant(Offset, DL, MVT::i16),
7123       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
7124     };
7125     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
7126                                    M->getVTList(), Ops, M->getMemoryVT(),
7127                                    M->getMemOperand());
7128   }
7129   case Intrinsic::amdgcn_ds_fadd: {
7130     MemSDNode *M = cast<MemSDNode>(Op);
7131     unsigned Opc;
7132     switch (IntrID) {
7133     case Intrinsic::amdgcn_ds_fadd:
7134       Opc = ISD::ATOMIC_LOAD_FADD;
7135       break;
7136     }
7137 
7138     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
7139                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
7140                          M->getMemOperand());
7141   }
7142   case Intrinsic::amdgcn_atomic_inc:
7143   case Intrinsic::amdgcn_atomic_dec:
7144   case Intrinsic::amdgcn_ds_fmin:
7145   case Intrinsic::amdgcn_ds_fmax: {
7146     MemSDNode *M = cast<MemSDNode>(Op);
7147     unsigned Opc;
7148     switch (IntrID) {
7149     case Intrinsic::amdgcn_atomic_inc:
7150       Opc = AMDGPUISD::ATOMIC_INC;
7151       break;
7152     case Intrinsic::amdgcn_atomic_dec:
7153       Opc = AMDGPUISD::ATOMIC_DEC;
7154       break;
7155     case Intrinsic::amdgcn_ds_fmin:
7156       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
7157       break;
7158     case Intrinsic::amdgcn_ds_fmax:
7159       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
7160       break;
7161     default:
7162       llvm_unreachable("Unknown intrinsic!");
7163     }
7164     SDValue Ops[] = {
7165       M->getOperand(0), // Chain
7166       M->getOperand(2), // Ptr
7167       M->getOperand(3)  // Value
7168     };
7169 
7170     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
7171                                    M->getMemoryVT(), M->getMemOperand());
7172   }
7173   case Intrinsic::amdgcn_buffer_load:
7174   case Intrinsic::amdgcn_buffer_load_format: {
7175     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
7176     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7177     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7178     SDValue Ops[] = {
7179       Op.getOperand(0), // Chain
7180       Op.getOperand(2), // rsrc
7181       Op.getOperand(3), // vindex
7182       SDValue(),        // voffset -- will be set by setBufferOffsets
7183       SDValue(),        // soffset -- will be set by setBufferOffsets
7184       SDValue(),        // offset -- will be set by setBufferOffsets
7185       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7186       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7187     };
7188     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
7189 
7190     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
7191         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
7192 
7193     EVT VT = Op.getValueType();
7194     EVT IntVT = VT.changeTypeToInteger();
7195     auto *M = cast<MemSDNode>(Op);
7196     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7197     EVT LoadVT = Op.getValueType();
7198 
7199     if (LoadVT.getScalarType() == MVT::f16)
7200       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
7201                                  M, DAG, Ops);
7202 
7203     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
7204     if (LoadVT.getScalarType() == MVT::i8 ||
7205         LoadVT.getScalarType() == MVT::i16)
7206       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
7207 
7208     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
7209                                M->getMemOperand(), DAG);
7210   }
7211   case Intrinsic::amdgcn_raw_buffer_load:
7212   case Intrinsic::amdgcn_raw_buffer_load_format: {
7213     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
7214 
7215     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7216     SDValue Ops[] = {
7217       Op.getOperand(0), // Chain
7218       Op.getOperand(2), // rsrc
7219       DAG.getConstant(0, DL, MVT::i32), // vindex
7220       Offsets.first,    // voffset
7221       Op.getOperand(4), // soffset
7222       Offsets.second,   // offset
7223       Op.getOperand(5), // cachepolicy, swizzled buffer
7224       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7225     };
7226 
7227     auto *M = cast<MemSDNode>(Op);
7228     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]);
7229     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
7230   }
7231   case Intrinsic::amdgcn_struct_buffer_load:
7232   case Intrinsic::amdgcn_struct_buffer_load_format: {
7233     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
7234 
7235     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7236     SDValue Ops[] = {
7237       Op.getOperand(0), // Chain
7238       Op.getOperand(2), // rsrc
7239       Op.getOperand(3), // vindex
7240       Offsets.first,    // voffset
7241       Op.getOperand(5), // soffset
7242       Offsets.second,   // offset
7243       Op.getOperand(6), // cachepolicy, swizzled buffer
7244       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7245     };
7246 
7247     auto *M = cast<MemSDNode>(Op);
7248     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7249     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7250   }
7251   case Intrinsic::amdgcn_tbuffer_load: {
7252     MemSDNode *M = cast<MemSDNode>(Op);
7253     EVT LoadVT = Op.getValueType();
7254 
7255     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7256     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7257     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7258     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7259     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7260     SDValue Ops[] = {
7261       Op.getOperand(0),  // Chain
7262       Op.getOperand(2),  // rsrc
7263       Op.getOperand(3),  // vindex
7264       Op.getOperand(4),  // voffset
7265       Op.getOperand(5),  // soffset
7266       Op.getOperand(6),  // offset
7267       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7268       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7269       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7270     };
7271 
7272     if (LoadVT.getScalarType() == MVT::f16)
7273       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7274                                  M, DAG, Ops);
7275     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7276                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7277                                DAG);
7278   }
7279   case Intrinsic::amdgcn_raw_tbuffer_load: {
7280     MemSDNode *M = cast<MemSDNode>(Op);
7281     EVT LoadVT = Op.getValueType();
7282     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7283 
7284     SDValue Ops[] = {
7285       Op.getOperand(0),  // Chain
7286       Op.getOperand(2),  // rsrc
7287       DAG.getConstant(0, DL, MVT::i32), // vindex
7288       Offsets.first,     // voffset
7289       Op.getOperand(4),  // soffset
7290       Offsets.second,    // offset
7291       Op.getOperand(5),  // format
7292       Op.getOperand(6),  // cachepolicy, swizzled buffer
7293       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7294     };
7295 
7296     if (LoadVT.getScalarType() == MVT::f16)
7297       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7298                                  M, DAG, Ops);
7299     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7300                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7301                                DAG);
7302   }
7303   case Intrinsic::amdgcn_struct_tbuffer_load: {
7304     MemSDNode *M = cast<MemSDNode>(Op);
7305     EVT LoadVT = Op.getValueType();
7306     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7307 
7308     SDValue Ops[] = {
7309       Op.getOperand(0),  // Chain
7310       Op.getOperand(2),  // rsrc
7311       Op.getOperand(3),  // vindex
7312       Offsets.first,     // voffset
7313       Op.getOperand(5),  // soffset
7314       Offsets.second,    // offset
7315       Op.getOperand(6),  // format
7316       Op.getOperand(7),  // cachepolicy, swizzled buffer
7317       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7318     };
7319 
7320     if (LoadVT.getScalarType() == MVT::f16)
7321       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7322                                  M, DAG, Ops);
7323     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7324                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7325                                DAG);
7326   }
7327   case Intrinsic::amdgcn_buffer_atomic_swap:
7328   case Intrinsic::amdgcn_buffer_atomic_add:
7329   case Intrinsic::amdgcn_buffer_atomic_sub:
7330   case Intrinsic::amdgcn_buffer_atomic_csub:
7331   case Intrinsic::amdgcn_buffer_atomic_smin:
7332   case Intrinsic::amdgcn_buffer_atomic_umin:
7333   case Intrinsic::amdgcn_buffer_atomic_smax:
7334   case Intrinsic::amdgcn_buffer_atomic_umax:
7335   case Intrinsic::amdgcn_buffer_atomic_and:
7336   case Intrinsic::amdgcn_buffer_atomic_or:
7337   case Intrinsic::amdgcn_buffer_atomic_xor:
7338   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7339     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7340     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7341     SDValue Ops[] = {
7342       Op.getOperand(0), // Chain
7343       Op.getOperand(2), // vdata
7344       Op.getOperand(3), // rsrc
7345       Op.getOperand(4), // vindex
7346       SDValue(),        // voffset -- will be set by setBufferOffsets
7347       SDValue(),        // soffset -- will be set by setBufferOffsets
7348       SDValue(),        // offset -- will be set by setBufferOffsets
7349       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7350       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7351     };
7352     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7353 
7354     EVT VT = Op.getValueType();
7355 
7356     auto *M = cast<MemSDNode>(Op);
7357     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7358     unsigned Opcode = 0;
7359 
7360     switch (IntrID) {
7361     case Intrinsic::amdgcn_buffer_atomic_swap:
7362       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7363       break;
7364     case Intrinsic::amdgcn_buffer_atomic_add:
7365       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7366       break;
7367     case Intrinsic::amdgcn_buffer_atomic_sub:
7368       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7369       break;
7370     case Intrinsic::amdgcn_buffer_atomic_csub:
7371       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7372       break;
7373     case Intrinsic::amdgcn_buffer_atomic_smin:
7374       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7375       break;
7376     case Intrinsic::amdgcn_buffer_atomic_umin:
7377       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7378       break;
7379     case Intrinsic::amdgcn_buffer_atomic_smax:
7380       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7381       break;
7382     case Intrinsic::amdgcn_buffer_atomic_umax:
7383       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7384       break;
7385     case Intrinsic::amdgcn_buffer_atomic_and:
7386       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7387       break;
7388     case Intrinsic::amdgcn_buffer_atomic_or:
7389       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7390       break;
7391     case Intrinsic::amdgcn_buffer_atomic_xor:
7392       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7393       break;
7394     case Intrinsic::amdgcn_buffer_atomic_fadd:
7395       if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7396         DiagnosticInfoUnsupported
7397           NoFpRet(DAG.getMachineFunction().getFunction(),
7398                   "return versions of fp atomics not supported",
7399                   DL.getDebugLoc(), DS_Error);
7400         DAG.getContext()->diagnose(NoFpRet);
7401         return SDValue();
7402       }
7403       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7404       break;
7405     default:
7406       llvm_unreachable("unhandled atomic opcode");
7407     }
7408 
7409     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7410                                    M->getMemOperand());
7411   }
7412   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7413     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7414   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7415     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7416   case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7417     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7418   case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7419     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7420   case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7421     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7422   case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7423     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7424   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7425     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7426   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7427     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7428   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7429     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7430   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7431     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7432   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7433     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7434   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7435     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7436   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7437     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7438   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7439     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7440   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7441     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7442   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7443     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7444   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7445     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7446   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7447     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7448   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7449     return lowerStructBufferAtomicIntrin(Op, DAG,
7450                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7451   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7452     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7453   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7454     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7455   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7456     return lowerStructBufferAtomicIntrin(Op, DAG,
7457                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7458   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7459     return lowerStructBufferAtomicIntrin(Op, DAG,
7460                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7461   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7462     return lowerStructBufferAtomicIntrin(Op, DAG,
7463                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7464   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7465     return lowerStructBufferAtomicIntrin(Op, DAG,
7466                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7467   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7468     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7469   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7470     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7471   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7472     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7473   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7474     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7475   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7476     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7477 
7478   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7479     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7480     unsigned IdxEn = getIdxEn(Op.getOperand(5));
7481     SDValue Ops[] = {
7482       Op.getOperand(0), // Chain
7483       Op.getOperand(2), // src
7484       Op.getOperand(3), // cmp
7485       Op.getOperand(4), // rsrc
7486       Op.getOperand(5), // vindex
7487       SDValue(),        // voffset -- will be set by setBufferOffsets
7488       SDValue(),        // soffset -- will be set by setBufferOffsets
7489       SDValue(),        // offset -- will be set by setBufferOffsets
7490       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7491       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7492     };
7493     setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7494 
7495     EVT VT = Op.getValueType();
7496     auto *M = cast<MemSDNode>(Op);
7497     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7498 
7499     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7500                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7501   }
7502   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7503     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7504     SDValue Ops[] = {
7505       Op.getOperand(0), // Chain
7506       Op.getOperand(2), // src
7507       Op.getOperand(3), // cmp
7508       Op.getOperand(4), // rsrc
7509       DAG.getConstant(0, DL, MVT::i32), // vindex
7510       Offsets.first,    // voffset
7511       Op.getOperand(6), // soffset
7512       Offsets.second,   // offset
7513       Op.getOperand(7), // cachepolicy
7514       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7515     };
7516     EVT VT = Op.getValueType();
7517     auto *M = cast<MemSDNode>(Op);
7518     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]);
7519 
7520     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7521                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7522   }
7523   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7524     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7525     SDValue Ops[] = {
7526       Op.getOperand(0), // Chain
7527       Op.getOperand(2), // src
7528       Op.getOperand(3), // cmp
7529       Op.getOperand(4), // rsrc
7530       Op.getOperand(5), // vindex
7531       Offsets.first,    // voffset
7532       Op.getOperand(7), // soffset
7533       Offsets.second,   // offset
7534       Op.getOperand(8), // cachepolicy
7535       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7536     };
7537     EVT VT = Op.getValueType();
7538     auto *M = cast<MemSDNode>(Op);
7539     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7540 
7541     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7542                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7543   }
7544   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7545     MemSDNode *M = cast<MemSDNode>(Op);
7546     SDValue NodePtr = M->getOperand(2);
7547     SDValue RayExtent = M->getOperand(3);
7548     SDValue RayOrigin = M->getOperand(4);
7549     SDValue RayDir = M->getOperand(5);
7550     SDValue RayInvDir = M->getOperand(6);
7551     SDValue TDescr = M->getOperand(7);
7552 
7553     assert(NodePtr.getValueType() == MVT::i32 ||
7554            NodePtr.getValueType() == MVT::i64);
7555     assert(RayDir.getValueType() == MVT::v3f16 ||
7556            RayDir.getValueType() == MVT::v3f32);
7557 
7558     if (!Subtarget->hasGFX10_AEncoding()) {
7559       emitRemovedIntrinsicError(DAG, DL, Op.getValueType());
7560       return SDValue();
7561     }
7562 
7563     const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7564     const bool Is64 = NodePtr.getValueType() == MVT::i64;
7565     const unsigned NumVDataDwords = 4;
7566     const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
7567     const bool UseNSA = Subtarget->hasNSAEncoding() &&
7568                         NumVAddrDwords <= Subtarget->getNSAMaxSize();
7569     const unsigned BaseOpcodes[2][2] = {
7570         {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
7571         {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
7572          AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
7573     int Opcode;
7574     if (UseNSA) {
7575       Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7576                                      AMDGPU::MIMGEncGfx10NSA, NumVDataDwords,
7577                                      NumVAddrDwords);
7578     } else {
7579       Opcode = AMDGPU::getMIMGOpcode(
7580           BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords,
7581           PowerOf2Ceil(NumVAddrDwords));
7582     }
7583     assert(Opcode != -1);
7584 
7585     SmallVector<SDValue, 16> Ops;
7586 
7587     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7588       SmallVector<SDValue, 3> Lanes;
7589       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7590       if (Lanes[0].getValueSizeInBits() == 32) {
7591         for (unsigned I = 0; I < 3; ++I)
7592           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7593       } else {
7594         if (IsAligned) {
7595           Ops.push_back(
7596             DAG.getBitcast(MVT::i32,
7597                            DAG.getBuildVector(MVT::v2f16, DL,
7598                                               { Lanes[0], Lanes[1] })));
7599           Ops.push_back(Lanes[2]);
7600         } else {
7601           SDValue Elt0 = Ops.pop_back_val();
7602           Ops.push_back(
7603             DAG.getBitcast(MVT::i32,
7604                            DAG.getBuildVector(MVT::v2f16, DL,
7605                                               { Elt0, Lanes[0] })));
7606           Ops.push_back(
7607             DAG.getBitcast(MVT::i32,
7608                            DAG.getBuildVector(MVT::v2f16, DL,
7609                                               { Lanes[1], Lanes[2] })));
7610         }
7611       }
7612     };
7613 
7614     if (Is64)
7615       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7616     else
7617       Ops.push_back(NodePtr);
7618 
7619     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7620     packLanes(RayOrigin, true);
7621     packLanes(RayDir, true);
7622     packLanes(RayInvDir, false);
7623 
7624     if (!UseNSA) {
7625       // Build a single vector containing all the operands so far prepared.
7626       if (NumVAddrDwords > 8) {
7627         SDValue Undef = DAG.getUNDEF(MVT::i32);
7628         Ops.append(16 - Ops.size(), Undef);
7629       }
7630       assert(Ops.size() == 8 || Ops.size() == 16);
7631       SDValue MergedOps = DAG.getBuildVector(
7632           Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops);
7633       Ops.clear();
7634       Ops.push_back(MergedOps);
7635     }
7636 
7637     Ops.push_back(TDescr);
7638     if (IsA16)
7639       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7640     Ops.push_back(M->getChain());
7641 
7642     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7643     MachineMemOperand *MemRef = M->getMemOperand();
7644     DAG.setNodeMemRefs(NewNode, {MemRef});
7645     return SDValue(NewNode, 0);
7646   }
7647   case Intrinsic::amdgcn_global_atomic_fadd:
7648     if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7649       DiagnosticInfoUnsupported
7650         NoFpRet(DAG.getMachineFunction().getFunction(),
7651                 "return versions of fp atomics not supported",
7652                 DL.getDebugLoc(), DS_Error);
7653       DAG.getContext()->diagnose(NoFpRet);
7654       return SDValue();
7655     }
7656     LLVM_FALLTHROUGH;
7657   case Intrinsic::amdgcn_global_atomic_fmin:
7658   case Intrinsic::amdgcn_global_atomic_fmax:
7659   case Intrinsic::amdgcn_flat_atomic_fadd:
7660   case Intrinsic::amdgcn_flat_atomic_fmin:
7661   case Intrinsic::amdgcn_flat_atomic_fmax: {
7662     MemSDNode *M = cast<MemSDNode>(Op);
7663     SDValue Ops[] = {
7664       M->getOperand(0), // Chain
7665       M->getOperand(2), // Ptr
7666       M->getOperand(3)  // Value
7667     };
7668     unsigned Opcode = 0;
7669     switch (IntrID) {
7670     case Intrinsic::amdgcn_global_atomic_fadd:
7671     case Intrinsic::amdgcn_flat_atomic_fadd: {
7672       EVT VT = Op.getOperand(3).getValueType();
7673       return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7674                            DAG.getVTList(VT, MVT::Other), Ops,
7675                            M->getMemOperand());
7676     }
7677     case Intrinsic::amdgcn_global_atomic_fmin:
7678     case Intrinsic::amdgcn_flat_atomic_fmin: {
7679       Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7680       break;
7681     }
7682     case Intrinsic::amdgcn_global_atomic_fmax:
7683     case Intrinsic::amdgcn_flat_atomic_fmax: {
7684       Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7685       break;
7686     }
7687     default:
7688       llvm_unreachable("unhandled atomic opcode");
7689     }
7690     return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7691                                    M->getVTList(), Ops, M->getMemoryVT(),
7692                                    M->getMemOperand());
7693   }
7694   default:
7695 
7696     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7697             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7698       return lowerImage(Op, ImageDimIntr, DAG, true);
7699 
7700     return SDValue();
7701   }
7702 }
7703 
7704 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7705 // dwordx4 if on SI.
7706 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7707                                               SDVTList VTList,
7708                                               ArrayRef<SDValue> Ops, EVT MemVT,
7709                                               MachineMemOperand *MMO,
7710                                               SelectionDAG &DAG) const {
7711   EVT VT = VTList.VTs[0];
7712   EVT WidenedVT = VT;
7713   EVT WidenedMemVT = MemVT;
7714   if (!Subtarget->hasDwordx3LoadStores() &&
7715       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7716     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7717                                  WidenedVT.getVectorElementType(), 4);
7718     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7719                                     WidenedMemVT.getVectorElementType(), 4);
7720     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7721   }
7722 
7723   assert(VTList.NumVTs == 2);
7724   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7725 
7726   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7727                                        WidenedMemVT, MMO);
7728   if (WidenedVT != VT) {
7729     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7730                                DAG.getVectorIdxConstant(0, DL));
7731     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7732   }
7733   return NewOp;
7734 }
7735 
7736 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7737                                          bool ImageStore) const {
7738   EVT StoreVT = VData.getValueType();
7739 
7740   // No change for f16 and legal vector D16 types.
7741   if (!StoreVT.isVector())
7742     return VData;
7743 
7744   SDLoc DL(VData);
7745   unsigned NumElements = StoreVT.getVectorNumElements();
7746 
7747   if (Subtarget->hasUnpackedD16VMem()) {
7748     // We need to unpack the packed data to store.
7749     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7750     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7751 
7752     EVT EquivStoreVT =
7753         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7754     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7755     return DAG.UnrollVectorOp(ZExt.getNode());
7756   }
7757 
7758   // The sq block of gfx8.1 does not estimate register use correctly for d16
7759   // image store instructions. The data operand is computed as if it were not a
7760   // d16 image instruction.
7761   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7762     // Bitcast to i16
7763     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7764     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7765 
7766     // Decompose into scalars
7767     SmallVector<SDValue, 4> Elts;
7768     DAG.ExtractVectorElements(IntVData, Elts);
7769 
7770     // Group pairs of i16 into v2i16 and bitcast to i32
7771     SmallVector<SDValue, 4> PackedElts;
7772     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7773       SDValue Pair =
7774           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7775       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7776       PackedElts.push_back(IntPair);
7777     }
7778     if ((NumElements % 2) == 1) {
7779       // Handle v3i16
7780       unsigned I = Elts.size() / 2;
7781       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7782                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7783       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7784       PackedElts.push_back(IntPair);
7785     }
7786 
7787     // Pad using UNDEF
7788     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7789 
7790     // Build final vector
7791     EVT VecVT =
7792         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7793     return DAG.getBuildVector(VecVT, DL, PackedElts);
7794   }
7795 
7796   if (NumElements == 3) {
7797     EVT IntStoreVT =
7798         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7799     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7800 
7801     EVT WidenedStoreVT = EVT::getVectorVT(
7802         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7803     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7804                                          WidenedStoreVT.getStoreSizeInBits());
7805     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7806     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7807   }
7808 
7809   assert(isTypeLegal(StoreVT));
7810   return VData;
7811 }
7812 
7813 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7814                                               SelectionDAG &DAG) const {
7815   SDLoc DL(Op);
7816   SDValue Chain = Op.getOperand(0);
7817   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7818   MachineFunction &MF = DAG.getMachineFunction();
7819 
7820   switch (IntrinsicID) {
7821   case Intrinsic::amdgcn_exp_compr: {
7822     SDValue Src0 = Op.getOperand(4);
7823     SDValue Src1 = Op.getOperand(5);
7824     // Hack around illegal type on SI by directly selecting it.
7825     if (isTypeLegal(Src0.getValueType()))
7826       return SDValue();
7827 
7828     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7829     SDValue Undef = DAG.getUNDEF(MVT::f32);
7830     const SDValue Ops[] = {
7831       Op.getOperand(2), // tgt
7832       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7833       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7834       Undef, // src2
7835       Undef, // src3
7836       Op.getOperand(7), // vm
7837       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7838       Op.getOperand(3), // en
7839       Op.getOperand(0) // Chain
7840     };
7841 
7842     unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7843     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7844   }
7845   case Intrinsic::amdgcn_s_barrier: {
7846     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7847       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7848       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7849       if (WGSize <= ST.getWavefrontSize())
7850         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7851                                           Op.getOperand(0)), 0);
7852     }
7853     return SDValue();
7854   };
7855   case Intrinsic::amdgcn_tbuffer_store: {
7856     SDValue VData = Op.getOperand(2);
7857     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7858     if (IsD16)
7859       VData = handleD16VData(VData, DAG);
7860     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7861     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7862     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7863     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7864     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7865     SDValue Ops[] = {
7866       Chain,
7867       VData,             // vdata
7868       Op.getOperand(3),  // rsrc
7869       Op.getOperand(4),  // vindex
7870       Op.getOperand(5),  // voffset
7871       Op.getOperand(6),  // soffset
7872       Op.getOperand(7),  // offset
7873       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7874       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7875       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7876     };
7877     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7878                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7879     MemSDNode *M = cast<MemSDNode>(Op);
7880     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7881                                    M->getMemoryVT(), M->getMemOperand());
7882   }
7883 
7884   case Intrinsic::amdgcn_struct_tbuffer_store: {
7885     SDValue VData = Op.getOperand(2);
7886     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7887     if (IsD16)
7888       VData = handleD16VData(VData, DAG);
7889     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7890     SDValue Ops[] = {
7891       Chain,
7892       VData,             // vdata
7893       Op.getOperand(3),  // rsrc
7894       Op.getOperand(4),  // vindex
7895       Offsets.first,     // voffset
7896       Op.getOperand(6),  // soffset
7897       Offsets.second,    // offset
7898       Op.getOperand(7),  // format
7899       Op.getOperand(8),  // cachepolicy, swizzled buffer
7900       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7901     };
7902     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7903                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7904     MemSDNode *M = cast<MemSDNode>(Op);
7905     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7906                                    M->getMemoryVT(), M->getMemOperand());
7907   }
7908 
7909   case Intrinsic::amdgcn_raw_tbuffer_store: {
7910     SDValue VData = Op.getOperand(2);
7911     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7912     if (IsD16)
7913       VData = handleD16VData(VData, DAG);
7914     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7915     SDValue Ops[] = {
7916       Chain,
7917       VData,             // vdata
7918       Op.getOperand(3),  // rsrc
7919       DAG.getConstant(0, DL, MVT::i32), // vindex
7920       Offsets.first,     // voffset
7921       Op.getOperand(5),  // soffset
7922       Offsets.second,    // offset
7923       Op.getOperand(6),  // format
7924       Op.getOperand(7),  // cachepolicy, swizzled buffer
7925       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7926     };
7927     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7928                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7929     MemSDNode *M = cast<MemSDNode>(Op);
7930     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7931                                    M->getMemoryVT(), M->getMemOperand());
7932   }
7933 
7934   case Intrinsic::amdgcn_buffer_store:
7935   case Intrinsic::amdgcn_buffer_store_format: {
7936     SDValue VData = Op.getOperand(2);
7937     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7938     if (IsD16)
7939       VData = handleD16VData(VData, DAG);
7940     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7941     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7942     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7943     SDValue Ops[] = {
7944       Chain,
7945       VData,
7946       Op.getOperand(3), // rsrc
7947       Op.getOperand(4), // vindex
7948       SDValue(), // voffset -- will be set by setBufferOffsets
7949       SDValue(), // soffset -- will be set by setBufferOffsets
7950       SDValue(), // offset -- will be set by setBufferOffsets
7951       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7952       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7953     };
7954     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7955 
7956     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7957                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7958     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7959     MemSDNode *M = cast<MemSDNode>(Op);
7960     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7961 
7962     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7963     EVT VDataType = VData.getValueType().getScalarType();
7964     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7965       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7966 
7967     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7968                                    M->getMemoryVT(), M->getMemOperand());
7969   }
7970 
7971   case Intrinsic::amdgcn_raw_buffer_store:
7972   case Intrinsic::amdgcn_raw_buffer_store_format: {
7973     const bool IsFormat =
7974         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7975 
7976     SDValue VData = Op.getOperand(2);
7977     EVT VDataVT = VData.getValueType();
7978     EVT EltType = VDataVT.getScalarType();
7979     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7980     if (IsD16) {
7981       VData = handleD16VData(VData, DAG);
7982       VDataVT = VData.getValueType();
7983     }
7984 
7985     if (!isTypeLegal(VDataVT)) {
7986       VData =
7987           DAG.getNode(ISD::BITCAST, DL,
7988                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7989     }
7990 
7991     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7992     SDValue Ops[] = {
7993       Chain,
7994       VData,
7995       Op.getOperand(3), // rsrc
7996       DAG.getConstant(0, DL, MVT::i32), // vindex
7997       Offsets.first,    // voffset
7998       Op.getOperand(5), // soffset
7999       Offsets.second,   // offset
8000       Op.getOperand(6), // cachepolicy, swizzled buffer
8001       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8002     };
8003     unsigned Opc =
8004         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
8005     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8006     MemSDNode *M = cast<MemSDNode>(Op);
8007     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
8008 
8009     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8010     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8011       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
8012 
8013     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8014                                    M->getMemoryVT(), M->getMemOperand());
8015   }
8016 
8017   case Intrinsic::amdgcn_struct_buffer_store:
8018   case Intrinsic::amdgcn_struct_buffer_store_format: {
8019     const bool IsFormat =
8020         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
8021 
8022     SDValue VData = Op.getOperand(2);
8023     EVT VDataVT = VData.getValueType();
8024     EVT EltType = VDataVT.getScalarType();
8025     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8026 
8027     if (IsD16) {
8028       VData = handleD16VData(VData, DAG);
8029       VDataVT = VData.getValueType();
8030     }
8031 
8032     if (!isTypeLegal(VDataVT)) {
8033       VData =
8034           DAG.getNode(ISD::BITCAST, DL,
8035                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8036     }
8037 
8038     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
8039     SDValue Ops[] = {
8040       Chain,
8041       VData,
8042       Op.getOperand(3), // rsrc
8043       Op.getOperand(4), // vindex
8044       Offsets.first,    // voffset
8045       Op.getOperand(6), // soffset
8046       Offsets.second,   // offset
8047       Op.getOperand(7), // cachepolicy, swizzled buffer
8048       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8049     };
8050     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
8051                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8052     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8053     MemSDNode *M = cast<MemSDNode>(Op);
8054     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8055 
8056     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8057     EVT VDataType = VData.getValueType().getScalarType();
8058     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8059       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8060 
8061     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8062                                    M->getMemoryVT(), M->getMemOperand());
8063   }
8064   case Intrinsic::amdgcn_raw_buffer_load_lds:
8065   case Intrinsic::amdgcn_struct_buffer_load_lds: {
8066     unsigned Opc;
8067     bool HasVIndex = IntrinsicID == Intrinsic::amdgcn_struct_buffer_load_lds;
8068     unsigned OpOffset = HasVIndex ? 1 : 0;
8069     SDValue VOffset = Op.getOperand(5 + OpOffset);
8070     auto CVOffset = dyn_cast<ConstantSDNode>(VOffset);
8071     bool HasVOffset = !CVOffset || !CVOffset->isZero();
8072     unsigned Size = Op->getConstantOperandVal(4);
8073 
8074     switch (Size) {
8075     default:
8076       return SDValue();
8077     case 1:
8078       Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_BOTHEN
8079                                    : AMDGPU::BUFFER_LOAD_UBYTE_LDS_IDXEN
8080                       : HasVOffset ? AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFEN
8081                                    : AMDGPU::BUFFER_LOAD_UBYTE_LDS_OFFSET;
8082       break;
8083     case 2:
8084       Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_BOTHEN
8085                                    : AMDGPU::BUFFER_LOAD_USHORT_LDS_IDXEN
8086                       : HasVOffset ? AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFEN
8087                                    : AMDGPU::BUFFER_LOAD_USHORT_LDS_OFFSET;
8088       break;
8089     case 4:
8090       Opc = HasVIndex ? HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_BOTHEN
8091                                    : AMDGPU::BUFFER_LOAD_DWORD_LDS_IDXEN
8092                       : HasVOffset ? AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFEN
8093                                    : AMDGPU::BUFFER_LOAD_DWORD_LDS_OFFSET;
8094       break;
8095     }
8096 
8097     SDValue M0Val = copyToM0(DAG, Chain, DL, Op.getOperand(3));
8098 
8099     SmallVector<SDValue, 8> Ops;
8100 
8101     if (HasVIndex && HasVOffset)
8102       Ops.push_back(DAG.getBuildVector(MVT::v2i32, DL,
8103                                        { Op.getOperand(5), // VIndex
8104                                          VOffset }));
8105     else if (HasVIndex)
8106       Ops.push_back(Op.getOperand(5));
8107     else if (HasVOffset)
8108       Ops.push_back(VOffset);
8109 
8110     Ops.push_back(Op.getOperand(2));           // rsrc
8111     Ops.push_back(Op.getOperand(6 + OpOffset)); // soffset
8112     Ops.push_back(Op.getOperand(7 + OpOffset)); // imm offset
8113     unsigned Aux = Op.getConstantOperandVal(8 + OpOffset);
8114     Ops.push_back(
8115       DAG.getTargetConstant(Aux & AMDGPU::CPol::ALL, DL, MVT::i8)); // cpol
8116     Ops.push_back(
8117       DAG.getTargetConstant((Aux >> 3) & 1, DL, MVT::i8));          // swz
8118     Ops.push_back(M0Val.getValue(0)); // Chain
8119     Ops.push_back(M0Val.getValue(1)); // Glue
8120 
8121     auto *M = cast<MemSDNode>(Op);
8122     MachineMemOperand *LoadMMO = M->getMemOperand();
8123     MachinePointerInfo LoadPtrI = LoadMMO->getPointerInfo();
8124     LoadPtrI.Offset = Op->getConstantOperandVal(7 + OpOffset);
8125     MachinePointerInfo StorePtrI = LoadPtrI;
8126     StorePtrI.V = nullptr;
8127     StorePtrI.AddrSpace = AMDGPUAS::LOCAL_ADDRESS;
8128 
8129     auto F = LoadMMO->getFlags() &
8130              ~(MachineMemOperand::MOStore | MachineMemOperand::MOLoad);
8131     LoadMMO = MF.getMachineMemOperand(LoadPtrI, F | MachineMemOperand::MOLoad,
8132                                       Size, LoadMMO->getBaseAlign());
8133 
8134     MachineMemOperand *StoreMMO =
8135         MF.getMachineMemOperand(StorePtrI, F | MachineMemOperand::MOStore,
8136                                 sizeof(int32_t), LoadMMO->getBaseAlign());
8137 
8138     auto Load = DAG.getMachineNode(Opc, DL, M->getVTList(), Ops);
8139     DAG.setNodeMemRefs(Load, {LoadMMO, StoreMMO});
8140 
8141     return SDValue(Load, 0);
8142   }
8143   case Intrinsic::amdgcn_global_load_lds: {
8144     unsigned Opc;
8145     unsigned Size = Op->getConstantOperandVal(4);
8146     switch (Size) {
8147     default:
8148       return SDValue();
8149     case 1:
8150       Opc = AMDGPU::GLOBAL_LOAD_LDS_UBYTE;
8151       break;
8152     case 2:
8153       Opc = AMDGPU::GLOBAL_LOAD_LDS_USHORT;
8154       break;
8155     case 4:
8156       Opc = AMDGPU::GLOBAL_LOAD_LDS_DWORD;
8157       break;
8158     }
8159 
8160     auto *M = cast<MemSDNode>(Op);
8161     SDValue M0Val = copyToM0(DAG, Chain, DL, Op.getOperand(3));
8162 
8163     SmallVector<SDValue, 6> Ops;
8164 
8165     SDValue Addr = Op.getOperand(2); // Global ptr
8166     SDValue VOffset;
8167     // Try to split SAddr and VOffset. Global and LDS pointers share the same
8168     // immediate offset, so we cannot use a regular SelectGlobalSAddr().
8169     if (Addr->isDivergent() && Addr.getOpcode() == ISD::ADD) {
8170       SDValue LHS = Addr.getOperand(0);
8171       SDValue RHS = Addr.getOperand(1);
8172 
8173       if (LHS->isDivergent())
8174         std::swap(LHS, RHS);
8175 
8176       if (!LHS->isDivergent() && RHS.getOpcode() == ISD::ZERO_EXTEND &&
8177           RHS.getOperand(0).getValueType() == MVT::i32) {
8178         // add (i64 sgpr), (zero_extend (i32 vgpr))
8179         Addr = LHS;
8180         VOffset = RHS.getOperand(0);
8181       }
8182     }
8183 
8184     Ops.push_back(Addr);
8185     if (!Addr->isDivergent()) {
8186       Opc = AMDGPU::getGlobalSaddrOp(Opc);
8187       if (!VOffset)
8188         VOffset = SDValue(
8189             DAG.getMachineNode(AMDGPU::V_MOV_B32_e32, DL, MVT::i32,
8190                                DAG.getTargetConstant(0, DL, MVT::i32)), 0);
8191       Ops.push_back(VOffset);
8192     }
8193 
8194     Ops.push_back(Op.getOperand(5));  // Offset
8195     Ops.push_back(Op.getOperand(6));  // CPol
8196     Ops.push_back(M0Val.getValue(0)); // Chain
8197     Ops.push_back(M0Val.getValue(1)); // Glue
8198 
8199     MachineMemOperand *LoadMMO = M->getMemOperand();
8200     MachinePointerInfo LoadPtrI = LoadMMO->getPointerInfo();
8201     LoadPtrI.Offset = Op->getConstantOperandVal(5);
8202     MachinePointerInfo StorePtrI = LoadPtrI;
8203     LoadPtrI.AddrSpace = AMDGPUAS::GLOBAL_ADDRESS;
8204     StorePtrI.AddrSpace = AMDGPUAS::LOCAL_ADDRESS;
8205     auto F = LoadMMO->getFlags() &
8206              ~(MachineMemOperand::MOStore | MachineMemOperand::MOLoad);
8207     LoadMMO = MF.getMachineMemOperand(LoadPtrI, F | MachineMemOperand::MOLoad,
8208                                       Size, LoadMMO->getBaseAlign());
8209     MachineMemOperand *StoreMMO =
8210         MF.getMachineMemOperand(StorePtrI, F | MachineMemOperand::MOStore,
8211                                 sizeof(int32_t), Align(4));
8212 
8213     auto Load = DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops);
8214     DAG.setNodeMemRefs(Load, {LoadMMO, StoreMMO});
8215 
8216     return SDValue(Load, 0);
8217   }
8218   case Intrinsic::amdgcn_end_cf:
8219     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
8220                                       Op->getOperand(2), Chain), 0);
8221 
8222   default: {
8223     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
8224             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
8225       return lowerImage(Op, ImageDimIntr, DAG, true);
8226 
8227     return Op;
8228   }
8229   }
8230 }
8231 
8232 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
8233 // offset (the offset that is included in bounds checking and swizzling, to be
8234 // split between the instruction's voffset and immoffset fields) and soffset
8235 // (the offset that is excluded from bounds checking and swizzling, to go in
8236 // the instruction's soffset field).  This function takes the first kind of
8237 // offset and figures out how to split it between voffset and immoffset.
8238 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
8239     SDValue Offset, SelectionDAG &DAG) const {
8240   SDLoc DL(Offset);
8241   const unsigned MaxImm = 4095;
8242   SDValue N0 = Offset;
8243   ConstantSDNode *C1 = nullptr;
8244 
8245   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
8246     N0 = SDValue();
8247   else if (DAG.isBaseWithConstantOffset(N0)) {
8248     C1 = cast<ConstantSDNode>(N0.getOperand(1));
8249     N0 = N0.getOperand(0);
8250   }
8251 
8252   if (C1) {
8253     unsigned ImmOffset = C1->getZExtValue();
8254     // If the immediate value is too big for the immoffset field, put the value
8255     // and -4096 into the immoffset field so that the value that is copied/added
8256     // for the voffset field is a multiple of 4096, and it stands more chance
8257     // of being CSEd with the copy/add for another similar load/store.
8258     // However, do not do that rounding down to a multiple of 4096 if that is a
8259     // negative number, as it appears to be illegal to have a negative offset
8260     // in the vgpr, even if adding the immediate offset makes it positive.
8261     unsigned Overflow = ImmOffset & ~MaxImm;
8262     ImmOffset -= Overflow;
8263     if ((int32_t)Overflow < 0) {
8264       Overflow += ImmOffset;
8265       ImmOffset = 0;
8266     }
8267     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
8268     if (Overflow) {
8269       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
8270       if (!N0)
8271         N0 = OverflowVal;
8272       else {
8273         SDValue Ops[] = { N0, OverflowVal };
8274         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
8275       }
8276     }
8277   }
8278   if (!N0)
8279     N0 = DAG.getConstant(0, DL, MVT::i32);
8280   if (!C1)
8281     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
8282   return {N0, SDValue(C1, 0)};
8283 }
8284 
8285 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
8286 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
8287 // pointed to by Offsets.
8288 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
8289                                         SelectionDAG &DAG, SDValue *Offsets,
8290                                         Align Alignment) const {
8291   SDLoc DL(CombinedOffset);
8292   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
8293     uint32_t Imm = C->getZExtValue();
8294     uint32_t SOffset, ImmOffset;
8295     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
8296                                  Alignment)) {
8297       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
8298       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8299       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8300       return;
8301     }
8302   }
8303   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
8304     SDValue N0 = CombinedOffset.getOperand(0);
8305     SDValue N1 = CombinedOffset.getOperand(1);
8306     uint32_t SOffset, ImmOffset;
8307     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
8308     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
8309                                                 Subtarget, Alignment)) {
8310       Offsets[0] = N0;
8311       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8312       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8313       return;
8314     }
8315   }
8316   Offsets[0] = CombinedOffset;
8317   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
8318   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
8319 }
8320 
8321 // Handle 8 bit and 16 bit buffer loads
8322 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
8323                                                      EVT LoadVT, SDLoc DL,
8324                                                      ArrayRef<SDValue> Ops,
8325                                                      MemSDNode *M) const {
8326   EVT IntVT = LoadVT.changeTypeToInteger();
8327   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
8328          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
8329 
8330   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
8331   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
8332                                                Ops, IntVT,
8333                                                M->getMemOperand());
8334   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
8335   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
8336 
8337   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
8338 }
8339 
8340 // Handle 8 bit and 16 bit buffer stores
8341 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
8342                                                       EVT VDataType, SDLoc DL,
8343                                                       SDValue Ops[],
8344                                                       MemSDNode *M) const {
8345   if (VDataType == MVT::f16)
8346     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
8347 
8348   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
8349   Ops[1] = BufferStoreExt;
8350   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
8351                                  AMDGPUISD::BUFFER_STORE_SHORT;
8352   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
8353   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
8354                                      M->getMemOperand());
8355 }
8356 
8357 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
8358                                  ISD::LoadExtType ExtType, SDValue Op,
8359                                  const SDLoc &SL, EVT VT) {
8360   if (VT.bitsLT(Op.getValueType()))
8361     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
8362 
8363   switch (ExtType) {
8364   case ISD::SEXTLOAD:
8365     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
8366   case ISD::ZEXTLOAD:
8367     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
8368   case ISD::EXTLOAD:
8369     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
8370   case ISD::NON_EXTLOAD:
8371     return Op;
8372   }
8373 
8374   llvm_unreachable("invalid ext type");
8375 }
8376 
8377 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
8378   SelectionDAG &DAG = DCI.DAG;
8379   if (Ld->getAlignment() < 4 || Ld->isDivergent())
8380     return SDValue();
8381 
8382   // FIXME: Constant loads should all be marked invariant.
8383   unsigned AS = Ld->getAddressSpace();
8384   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
8385       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
8386       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
8387     return SDValue();
8388 
8389   // Don't do this early, since it may interfere with adjacent load merging for
8390   // illegal types. We can avoid losing alignment information for exotic types
8391   // pre-legalize.
8392   EVT MemVT = Ld->getMemoryVT();
8393   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
8394       MemVT.getSizeInBits() >= 32)
8395     return SDValue();
8396 
8397   SDLoc SL(Ld);
8398 
8399   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
8400          "unexpected vector extload");
8401 
8402   // TODO: Drop only high part of range.
8403   SDValue Ptr = Ld->getBasePtr();
8404   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
8405                                 MVT::i32, SL, Ld->getChain(), Ptr,
8406                                 Ld->getOffset(),
8407                                 Ld->getPointerInfo(), MVT::i32,
8408                                 Ld->getAlignment(),
8409                                 Ld->getMemOperand()->getFlags(),
8410                                 Ld->getAAInfo(),
8411                                 nullptr); // Drop ranges
8412 
8413   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
8414   if (MemVT.isFloatingPoint()) {
8415     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
8416            "unexpected fp extload");
8417     TruncVT = MemVT.changeTypeToInteger();
8418   }
8419 
8420   SDValue Cvt = NewLoad;
8421   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
8422     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
8423                       DAG.getValueType(TruncVT));
8424   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
8425              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
8426     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
8427   } else {
8428     assert(Ld->getExtensionType() == ISD::EXTLOAD);
8429   }
8430 
8431   EVT VT = Ld->getValueType(0);
8432   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8433 
8434   DCI.AddToWorklist(Cvt.getNode());
8435 
8436   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
8437   // the appropriate extension from the 32-bit load.
8438   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
8439   DCI.AddToWorklist(Cvt.getNode());
8440 
8441   // Handle conversion back to floating point if necessary.
8442   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8443 
8444   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8445 }
8446 
8447 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8448   SDLoc DL(Op);
8449   LoadSDNode *Load = cast<LoadSDNode>(Op);
8450   ISD::LoadExtType ExtType = Load->getExtensionType();
8451   EVT MemVT = Load->getMemoryVT();
8452 
8453   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8454     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8455       return SDValue();
8456 
8457     // FIXME: Copied from PPC
8458     // First, load into 32 bits, then truncate to 1 bit.
8459 
8460     SDValue Chain = Load->getChain();
8461     SDValue BasePtr = Load->getBasePtr();
8462     MachineMemOperand *MMO = Load->getMemOperand();
8463 
8464     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8465 
8466     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8467                                    BasePtr, RealMemVT, MMO);
8468 
8469     if (!MemVT.isVector()) {
8470       SDValue Ops[] = {
8471         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8472         NewLD.getValue(1)
8473       };
8474 
8475       return DAG.getMergeValues(Ops, DL);
8476     }
8477 
8478     SmallVector<SDValue, 3> Elts;
8479     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8480       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8481                                 DAG.getConstant(I, DL, MVT::i32));
8482 
8483       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8484     }
8485 
8486     SDValue Ops[] = {
8487       DAG.getBuildVector(MemVT, DL, Elts),
8488       NewLD.getValue(1)
8489     };
8490 
8491     return DAG.getMergeValues(Ops, DL);
8492   }
8493 
8494   if (!MemVT.isVector())
8495     return SDValue();
8496 
8497   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8498          "Custom lowering for non-i32 vectors hasn't been implemented.");
8499 
8500   unsigned Alignment = Load->getAlignment();
8501   unsigned AS = Load->getAddressSpace();
8502   if (Subtarget->hasLDSMisalignedBug() &&
8503       AS == AMDGPUAS::FLAT_ADDRESS &&
8504       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8505     return SplitVectorLoad(Op, DAG);
8506   }
8507 
8508   MachineFunction &MF = DAG.getMachineFunction();
8509   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8510   // If there is a possibility that flat instruction access scratch memory
8511   // then we need to use the same legalization rules we use for private.
8512   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8513       !Subtarget->hasMultiDwordFlatScratchAddressing())
8514     AS = MFI->hasFlatScratchInit() ?
8515          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8516 
8517   unsigned NumElements = MemVT.getVectorNumElements();
8518 
8519   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8520       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8521     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8522       if (MemVT.isPow2VectorType())
8523         return SDValue();
8524       return WidenOrSplitVectorLoad(Op, DAG);
8525     }
8526     // Non-uniform loads will be selected to MUBUF instructions, so they
8527     // have the same legalization requirements as global and private
8528     // loads.
8529     //
8530   }
8531 
8532   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8533       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8534       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8535     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8536         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8537         Alignment >= 4 && NumElements < 32) {
8538       if (MemVT.isPow2VectorType())
8539         return SDValue();
8540       return WidenOrSplitVectorLoad(Op, DAG);
8541     }
8542     // Non-uniform loads will be selected to MUBUF instructions, so they
8543     // have the same legalization requirements as global and private
8544     // loads.
8545     //
8546   }
8547   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8548       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8549       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8550       AS == AMDGPUAS::FLAT_ADDRESS) {
8551     if (NumElements > 4)
8552       return SplitVectorLoad(Op, DAG);
8553     // v3 loads not supported on SI.
8554     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8555       return WidenOrSplitVectorLoad(Op, DAG);
8556 
8557     // v3 and v4 loads are supported for private and global memory.
8558     return SDValue();
8559   }
8560   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8561     // Depending on the setting of the private_element_size field in the
8562     // resource descriptor, we can only make private accesses up to a certain
8563     // size.
8564     switch (Subtarget->getMaxPrivateElementSize()) {
8565     case 4: {
8566       SDValue Ops[2];
8567       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8568       return DAG.getMergeValues(Ops, DL);
8569     }
8570     case 8:
8571       if (NumElements > 2)
8572         return SplitVectorLoad(Op, DAG);
8573       return SDValue();
8574     case 16:
8575       // Same as global/flat
8576       if (NumElements > 4)
8577         return SplitVectorLoad(Op, DAG);
8578       // v3 loads not supported on SI.
8579       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8580         return WidenOrSplitVectorLoad(Op, DAG);
8581 
8582       return SDValue();
8583     default:
8584       llvm_unreachable("unsupported private_element_size");
8585     }
8586   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8587     bool Fast = false;
8588     auto Flags = Load->getMemOperand()->getFlags();
8589     if (allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8590                                            Load->getAlign(), Flags, &Fast) &&
8591         Fast)
8592       return SDValue();
8593 
8594     if (MemVT.isVector())
8595       return SplitVectorLoad(Op, DAG);
8596   }
8597 
8598   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8599                                       MemVT, *Load->getMemOperand())) {
8600     SDValue Ops[2];
8601     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8602     return DAG.getMergeValues(Ops, DL);
8603   }
8604 
8605   return SDValue();
8606 }
8607 
8608 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8609   EVT VT = Op.getValueType();
8610   if (VT.getSizeInBits() == 128)
8611     return splitTernaryVectorOp(Op, DAG);
8612 
8613   assert(VT.getSizeInBits() == 64);
8614 
8615   SDLoc DL(Op);
8616   SDValue Cond = Op.getOperand(0);
8617 
8618   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8619   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8620 
8621   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8622   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8623 
8624   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8625   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8626 
8627   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8628 
8629   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8630   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8631 
8632   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8633 
8634   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8635   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8636 }
8637 
8638 // Catch division cases where we can use shortcuts with rcp and rsq
8639 // instructions.
8640 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8641                                               SelectionDAG &DAG) const {
8642   SDLoc SL(Op);
8643   SDValue LHS = Op.getOperand(0);
8644   SDValue RHS = Op.getOperand(1);
8645   EVT VT = Op.getValueType();
8646   const SDNodeFlags Flags = Op->getFlags();
8647 
8648   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8649 
8650   // Without !fpmath accuracy information, we can't do more because we don't
8651   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8652   if (!AllowInaccurateRcp)
8653     return SDValue();
8654 
8655   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8656     if (CLHS->isExactlyValue(1.0)) {
8657       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8658       // the CI documentation has a worst case error of 1 ulp.
8659       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8660       // use it as long as we aren't trying to use denormals.
8661       //
8662       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8663 
8664       // 1.0 / sqrt(x) -> rsq(x)
8665 
8666       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8667       // error seems really high at 2^29 ULP.
8668       if (RHS.getOpcode() == ISD::FSQRT)
8669         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8670 
8671       // 1.0 / x -> rcp(x)
8672       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8673     }
8674 
8675     // Same as for 1.0, but expand the sign out of the constant.
8676     if (CLHS->isExactlyValue(-1.0)) {
8677       // -1.0 / x -> rcp (fneg x)
8678       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8679       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8680     }
8681   }
8682 
8683   // Turn into multiply by the reciprocal.
8684   // x / y -> x * (1.0 / y)
8685   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8686   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8687 }
8688 
8689 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8690                                                 SelectionDAG &DAG) const {
8691   SDLoc SL(Op);
8692   SDValue X = Op.getOperand(0);
8693   SDValue Y = Op.getOperand(1);
8694   EVT VT = Op.getValueType();
8695   const SDNodeFlags Flags = Op->getFlags();
8696 
8697   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8698                             DAG.getTarget().Options.UnsafeFPMath;
8699   if (!AllowInaccurateDiv)
8700     return SDValue();
8701 
8702   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8703   SDValue One = DAG.getConstantFP(1.0, SL, VT);
8704 
8705   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8706   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8707 
8708   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8709   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8710   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8711   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8712   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8713   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8714 }
8715 
8716 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8717                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8718                           SDNodeFlags Flags) {
8719   if (GlueChain->getNumValues() <= 1) {
8720     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8721   }
8722 
8723   assert(GlueChain->getNumValues() == 3);
8724 
8725   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8726   switch (Opcode) {
8727   default: llvm_unreachable("no chain equivalent for opcode");
8728   case ISD::FMUL:
8729     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8730     break;
8731   }
8732 
8733   return DAG.getNode(Opcode, SL, VTList,
8734                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8735                      Flags);
8736 }
8737 
8738 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8739                            EVT VT, SDValue A, SDValue B, SDValue C,
8740                            SDValue GlueChain, SDNodeFlags Flags) {
8741   if (GlueChain->getNumValues() <= 1) {
8742     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8743   }
8744 
8745   assert(GlueChain->getNumValues() == 3);
8746 
8747   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8748   switch (Opcode) {
8749   default: llvm_unreachable("no chain equivalent for opcode");
8750   case ISD::FMA:
8751     Opcode = AMDGPUISD::FMA_W_CHAIN;
8752     break;
8753   }
8754 
8755   return DAG.getNode(Opcode, SL, VTList,
8756                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8757                      Flags);
8758 }
8759 
8760 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8761   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8762     return FastLowered;
8763 
8764   SDLoc SL(Op);
8765   SDValue Src0 = Op.getOperand(0);
8766   SDValue Src1 = Op.getOperand(1);
8767 
8768   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8769   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8770 
8771   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8772   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8773 
8774   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8775   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8776 
8777   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8778 }
8779 
8780 // Faster 2.5 ULP division that does not support denormals.
8781 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8782   SDLoc SL(Op);
8783   SDValue LHS = Op.getOperand(1);
8784   SDValue RHS = Op.getOperand(2);
8785 
8786   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8787 
8788   const APFloat K0Val(BitsToFloat(0x6f800000));
8789   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8790 
8791   const APFloat K1Val(BitsToFloat(0x2f800000));
8792   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8793 
8794   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8795 
8796   EVT SetCCVT =
8797     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8798 
8799   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8800 
8801   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8802 
8803   // TODO: Should this propagate fast-math-flags?
8804   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8805 
8806   // rcp does not support denormals.
8807   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8808 
8809   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8810 
8811   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8812 }
8813 
8814 // Returns immediate value for setting the F32 denorm mode when using the
8815 // S_DENORM_MODE instruction.
8816 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8817                                     const SDLoc &SL, const GCNSubtarget *ST) {
8818   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8819   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8820                                 ? FP_DENORM_FLUSH_NONE
8821                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8822 
8823   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8824   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8825 }
8826 
8827 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8828   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8829     return FastLowered;
8830 
8831   // The selection matcher assumes anything with a chain selecting to a
8832   // mayRaiseFPException machine instruction. Since we're introducing a chain
8833   // here, we need to explicitly report nofpexcept for the regular fdiv
8834   // lowering.
8835   SDNodeFlags Flags = Op->getFlags();
8836   Flags.setNoFPExcept(true);
8837 
8838   SDLoc SL(Op);
8839   SDValue LHS = Op.getOperand(0);
8840   SDValue RHS = Op.getOperand(1);
8841 
8842   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8843 
8844   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8845 
8846   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8847                                           {RHS, RHS, LHS}, Flags);
8848   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8849                                         {LHS, RHS, LHS}, Flags);
8850 
8851   // Denominator is scaled to not be denormal, so using rcp is ok.
8852   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8853                                   DenominatorScaled, Flags);
8854   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8855                                      DenominatorScaled, Flags);
8856 
8857   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8858                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8859                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8860   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8861 
8862   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8863 
8864   if (!HasFP32Denormals) {
8865     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8866     // lowering. The chain dependence is insufficient, and we need glue. We do
8867     // not need the glue variants in a strictfp function.
8868 
8869     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8870 
8871     SDNode *EnableDenorm;
8872     if (Subtarget->hasDenormModeInst()) {
8873       const SDValue EnableDenormValue =
8874           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8875 
8876       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8877                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8878     } else {
8879       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8880                                                         SL, MVT::i32);
8881       EnableDenorm =
8882           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8883                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8884     }
8885 
8886     SDValue Ops[3] = {
8887       NegDivScale0,
8888       SDValue(EnableDenorm, 0),
8889       SDValue(EnableDenorm, 1)
8890     };
8891 
8892     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8893   }
8894 
8895   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8896                              ApproxRcp, One, NegDivScale0, Flags);
8897 
8898   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8899                              ApproxRcp, Fma0, Flags);
8900 
8901   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8902                            Fma1, Fma1, Flags);
8903 
8904   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8905                              NumeratorScaled, Mul, Flags);
8906 
8907   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8908                              Fma2, Fma1, Mul, Fma2, Flags);
8909 
8910   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8911                              NumeratorScaled, Fma3, Flags);
8912 
8913   if (!HasFP32Denormals) {
8914     SDNode *DisableDenorm;
8915     if (Subtarget->hasDenormModeInst()) {
8916       const SDValue DisableDenormValue =
8917           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8918 
8919       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8920                                   Fma4.getValue(1), DisableDenormValue,
8921                                   Fma4.getValue(2)).getNode();
8922     } else {
8923       const SDValue DisableDenormValue =
8924           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8925 
8926       DisableDenorm = DAG.getMachineNode(
8927           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8928           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8929     }
8930 
8931     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8932                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8933     DAG.setRoot(OutputChain);
8934   }
8935 
8936   SDValue Scale = NumeratorScaled.getValue(1);
8937   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8938                              {Fma4, Fma1, Fma3, Scale}, Flags);
8939 
8940   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8941 }
8942 
8943 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8944   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
8945     return FastLowered;
8946 
8947   SDLoc SL(Op);
8948   SDValue X = Op.getOperand(0);
8949   SDValue Y = Op.getOperand(1);
8950 
8951   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8952 
8953   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8954 
8955   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8956 
8957   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8958 
8959   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8960 
8961   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8962 
8963   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8964 
8965   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8966 
8967   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8968 
8969   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8970   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8971 
8972   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8973                              NegDivScale0, Mul, DivScale1);
8974 
8975   SDValue Scale;
8976 
8977   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8978     // Workaround a hardware bug on SI where the condition output from div_scale
8979     // is not usable.
8980 
8981     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8982 
8983     // Figure out if the scale to use for div_fmas.
8984     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8985     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8986     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8987     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8988 
8989     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8990     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8991 
8992     SDValue Scale0Hi
8993       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8994     SDValue Scale1Hi
8995       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8996 
8997     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8998     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8999     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
9000   } else {
9001     Scale = DivScale1.getValue(1);
9002   }
9003 
9004   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
9005                              Fma4, Fma3, Mul, Scale);
9006 
9007   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
9008 }
9009 
9010 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
9011   EVT VT = Op.getValueType();
9012 
9013   if (VT == MVT::f32)
9014     return LowerFDIV32(Op, DAG);
9015 
9016   if (VT == MVT::f64)
9017     return LowerFDIV64(Op, DAG);
9018 
9019   if (VT == MVT::f16)
9020     return LowerFDIV16(Op, DAG);
9021 
9022   llvm_unreachable("Unexpected type for fdiv");
9023 }
9024 
9025 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
9026   SDLoc DL(Op);
9027   StoreSDNode *Store = cast<StoreSDNode>(Op);
9028   EVT VT = Store->getMemoryVT();
9029 
9030   if (VT == MVT::i1) {
9031     return DAG.getTruncStore(Store->getChain(), DL,
9032        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
9033        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
9034   }
9035 
9036   assert(VT.isVector() &&
9037          Store->getValue().getValueType().getScalarType() == MVT::i32);
9038 
9039   unsigned AS = Store->getAddressSpace();
9040   if (Subtarget->hasLDSMisalignedBug() &&
9041       AS == AMDGPUAS::FLAT_ADDRESS &&
9042       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
9043     return SplitVectorStore(Op, DAG);
9044   }
9045 
9046   MachineFunction &MF = DAG.getMachineFunction();
9047   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
9048   // If there is a possibility that flat instruction access scratch memory
9049   // then we need to use the same legalization rules we use for private.
9050   if (AS == AMDGPUAS::FLAT_ADDRESS &&
9051       !Subtarget->hasMultiDwordFlatScratchAddressing())
9052     AS = MFI->hasFlatScratchInit() ?
9053          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
9054 
9055   unsigned NumElements = VT.getVectorNumElements();
9056   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
9057       AS == AMDGPUAS::FLAT_ADDRESS) {
9058     if (NumElements > 4)
9059       return SplitVectorStore(Op, DAG);
9060     // v3 stores not supported on SI.
9061     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
9062       return SplitVectorStore(Op, DAG);
9063 
9064     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
9065                                         VT, *Store->getMemOperand()))
9066       return expandUnalignedStore(Store, DAG);
9067 
9068     return SDValue();
9069   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
9070     switch (Subtarget->getMaxPrivateElementSize()) {
9071     case 4:
9072       return scalarizeVectorStore(Store, DAG);
9073     case 8:
9074       if (NumElements > 2)
9075         return SplitVectorStore(Op, DAG);
9076       return SDValue();
9077     case 16:
9078       if (NumElements > 4 ||
9079           (NumElements == 3 && !Subtarget->enableFlatScratch()))
9080         return SplitVectorStore(Op, DAG);
9081       return SDValue();
9082     default:
9083       llvm_unreachable("unsupported private_element_size");
9084     }
9085   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
9086     bool Fast = false;
9087     auto Flags = Store->getMemOperand()->getFlags();
9088     if (allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
9089                                            Store->getAlign(), Flags, &Fast) &&
9090         Fast)
9091       return SDValue();
9092 
9093     if (VT.isVector())
9094       return SplitVectorStore(Op, DAG);
9095 
9096     return expandUnalignedStore(Store, DAG);
9097   }
9098 
9099   // Probably an invalid store. If so we'll end up emitting a selection error.
9100   return SDValue();
9101 }
9102 
9103 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
9104   SDLoc DL(Op);
9105   EVT VT = Op.getValueType();
9106   SDValue Arg = Op.getOperand(0);
9107   SDValue TrigVal;
9108 
9109   // Propagate fast-math flags so that the multiply we introduce can be folded
9110   // if Arg is already the result of a multiply by constant.
9111   auto Flags = Op->getFlags();
9112 
9113   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
9114 
9115   if (Subtarget->hasTrigReducedRange()) {
9116     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9117     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
9118   } else {
9119     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9120   }
9121 
9122   switch (Op.getOpcode()) {
9123   case ISD::FCOS:
9124     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
9125   case ISD::FSIN:
9126     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
9127   default:
9128     llvm_unreachable("Wrong trig opcode");
9129   }
9130 }
9131 
9132 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9133   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
9134   assert(AtomicNode->isCompareAndSwap());
9135   unsigned AS = AtomicNode->getAddressSpace();
9136 
9137   // No custom lowering required for local address space
9138   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
9139     return Op;
9140 
9141   // Non-local address space requires custom lowering for atomic compare
9142   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
9143   SDLoc DL(Op);
9144   SDValue ChainIn = Op.getOperand(0);
9145   SDValue Addr = Op.getOperand(1);
9146   SDValue Old = Op.getOperand(2);
9147   SDValue New = Op.getOperand(3);
9148   EVT VT = Op.getValueType();
9149   MVT SimpleVT = VT.getSimpleVT();
9150   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
9151 
9152   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
9153   SDValue Ops[] = { ChainIn, Addr, NewOld };
9154 
9155   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
9156                                  Ops, VT, AtomicNode->getMemOperand());
9157 }
9158 
9159 //===----------------------------------------------------------------------===//
9160 // Custom DAG optimizations
9161 //===----------------------------------------------------------------------===//
9162 
9163 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
9164                                                      DAGCombinerInfo &DCI) const {
9165   EVT VT = N->getValueType(0);
9166   EVT ScalarVT = VT.getScalarType();
9167   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
9168     return SDValue();
9169 
9170   SelectionDAG &DAG = DCI.DAG;
9171   SDLoc DL(N);
9172 
9173   SDValue Src = N->getOperand(0);
9174   EVT SrcVT = Src.getValueType();
9175 
9176   // TODO: We could try to match extracting the higher bytes, which would be
9177   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
9178   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
9179   // about in practice.
9180   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
9181     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
9182       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
9183       DCI.AddToWorklist(Cvt.getNode());
9184 
9185       // For the f16 case, fold to a cast to f32 and then cast back to f16.
9186       if (ScalarVT != MVT::f32) {
9187         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
9188                           DAG.getTargetConstant(0, DL, MVT::i32));
9189       }
9190       return Cvt;
9191     }
9192   }
9193 
9194   return SDValue();
9195 }
9196 
9197 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
9198 
9199 // This is a variant of
9200 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
9201 //
9202 // The normal DAG combiner will do this, but only if the add has one use since
9203 // that would increase the number of instructions.
9204 //
9205 // This prevents us from seeing a constant offset that can be folded into a
9206 // memory instruction's addressing mode. If we know the resulting add offset of
9207 // a pointer can be folded into an addressing offset, we can replace the pointer
9208 // operand with the add of new constant offset. This eliminates one of the uses,
9209 // and may allow the remaining use to also be simplified.
9210 //
9211 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
9212                                                unsigned AddrSpace,
9213                                                EVT MemVT,
9214                                                DAGCombinerInfo &DCI) const {
9215   SDValue N0 = N->getOperand(0);
9216   SDValue N1 = N->getOperand(1);
9217 
9218   // We only do this to handle cases where it's profitable when there are
9219   // multiple uses of the add, so defer to the standard combine.
9220   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
9221       N0->hasOneUse())
9222     return SDValue();
9223 
9224   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
9225   if (!CN1)
9226     return SDValue();
9227 
9228   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9229   if (!CAdd)
9230     return SDValue();
9231 
9232   // If the resulting offset is too large, we can't fold it into the addressing
9233   // mode offset.
9234   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
9235   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
9236 
9237   AddrMode AM;
9238   AM.HasBaseReg = true;
9239   AM.BaseOffs = Offset.getSExtValue();
9240   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
9241     return SDValue();
9242 
9243   SelectionDAG &DAG = DCI.DAG;
9244   SDLoc SL(N);
9245   EVT VT = N->getValueType(0);
9246 
9247   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
9248   SDValue COffset = DAG.getConstant(Offset, SL, VT);
9249 
9250   SDNodeFlags Flags;
9251   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
9252                           (N0.getOpcode() == ISD::OR ||
9253                            N0->getFlags().hasNoUnsignedWrap()));
9254 
9255   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
9256 }
9257 
9258 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
9259 /// by the chain and intrinsic ID. Theoretically we would also need to check the
9260 /// specific intrinsic, but they all place the pointer operand first.
9261 static unsigned getBasePtrIndex(const MemSDNode *N) {
9262   switch (N->getOpcode()) {
9263   case ISD::STORE:
9264   case ISD::INTRINSIC_W_CHAIN:
9265   case ISD::INTRINSIC_VOID:
9266     return 2;
9267   default:
9268     return 1;
9269   }
9270 }
9271 
9272 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
9273                                                   DAGCombinerInfo &DCI) const {
9274   SelectionDAG &DAG = DCI.DAG;
9275   SDLoc SL(N);
9276 
9277   unsigned PtrIdx = getBasePtrIndex(N);
9278   SDValue Ptr = N->getOperand(PtrIdx);
9279 
9280   // TODO: We could also do this for multiplies.
9281   if (Ptr.getOpcode() == ISD::SHL) {
9282     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
9283                                           N->getMemoryVT(), DCI);
9284     if (NewPtr) {
9285       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
9286 
9287       NewOps[PtrIdx] = NewPtr;
9288       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
9289     }
9290   }
9291 
9292   return SDValue();
9293 }
9294 
9295 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
9296   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
9297          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
9298          (Opc == ISD::XOR && Val == 0);
9299 }
9300 
9301 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
9302 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
9303 // integer combine opportunities since most 64-bit operations are decomposed
9304 // this way.  TODO: We won't want this for SALU especially if it is an inline
9305 // immediate.
9306 SDValue SITargetLowering::splitBinaryBitConstantOp(
9307   DAGCombinerInfo &DCI,
9308   const SDLoc &SL,
9309   unsigned Opc, SDValue LHS,
9310   const ConstantSDNode *CRHS) const {
9311   uint64_t Val = CRHS->getZExtValue();
9312   uint32_t ValLo = Lo_32(Val);
9313   uint32_t ValHi = Hi_32(Val);
9314   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9315 
9316     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
9317          bitOpWithConstantIsReducible(Opc, ValHi)) ||
9318         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
9319     // If we need to materialize a 64-bit immediate, it will be split up later
9320     // anyway. Avoid creating the harder to understand 64-bit immediate
9321     // materialization.
9322     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
9323   }
9324 
9325   return SDValue();
9326 }
9327 
9328 // Returns true if argument is a boolean value which is not serialized into
9329 // memory or argument and does not require v_cndmask_b32 to be deserialized.
9330 static bool isBoolSGPR(SDValue V) {
9331   if (V.getValueType() != MVT::i1)
9332     return false;
9333   switch (V.getOpcode()) {
9334   default:
9335     break;
9336   case ISD::SETCC:
9337   case AMDGPUISD::FP_CLASS:
9338     return true;
9339   case ISD::AND:
9340   case ISD::OR:
9341   case ISD::XOR:
9342     return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
9343   }
9344   return false;
9345 }
9346 
9347 // If a constant has all zeroes or all ones within each byte return it.
9348 // Otherwise return 0.
9349 static uint32_t getConstantPermuteMask(uint32_t C) {
9350   // 0xff for any zero byte in the mask
9351   uint32_t ZeroByteMask = 0;
9352   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
9353   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
9354   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
9355   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
9356   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
9357   if ((NonZeroByteMask & C) != NonZeroByteMask)
9358     return 0; // Partial bytes selected.
9359   return C;
9360 }
9361 
9362 // Check if a node selects whole bytes from its operand 0 starting at a byte
9363 // boundary while masking the rest. Returns select mask as in the v_perm_b32
9364 // or -1 if not succeeded.
9365 // Note byte select encoding:
9366 // value 0-3 selects corresponding source byte;
9367 // value 0xc selects zero;
9368 // value 0xff selects 0xff.
9369 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
9370   assert(V.getValueSizeInBits() == 32);
9371 
9372   if (V.getNumOperands() != 2)
9373     return ~0;
9374 
9375   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
9376   if (!N1)
9377     return ~0;
9378 
9379   uint32_t C = N1->getZExtValue();
9380 
9381   switch (V.getOpcode()) {
9382   default:
9383     break;
9384   case ISD::AND:
9385     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9386       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
9387     }
9388     break;
9389 
9390   case ISD::OR:
9391     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9392       return (0x03020100 & ~ConstMask) | ConstMask;
9393     }
9394     break;
9395 
9396   case ISD::SHL:
9397     if (C % 8)
9398       return ~0;
9399 
9400     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
9401 
9402   case ISD::SRL:
9403     if (C % 8)
9404       return ~0;
9405 
9406     return uint32_t(0x0c0c0c0c03020100ull >> C);
9407   }
9408 
9409   return ~0;
9410 }
9411 
9412 SDValue SITargetLowering::performAndCombine(SDNode *N,
9413                                             DAGCombinerInfo &DCI) const {
9414   if (DCI.isBeforeLegalize())
9415     return SDValue();
9416 
9417   SelectionDAG &DAG = DCI.DAG;
9418   EVT VT = N->getValueType(0);
9419   SDValue LHS = N->getOperand(0);
9420   SDValue RHS = N->getOperand(1);
9421 
9422 
9423   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9424   if (VT == MVT::i64 && CRHS) {
9425     if (SDValue Split
9426         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9427       return Split;
9428   }
9429 
9430   if (CRHS && VT == MVT::i32) {
9431     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9432     // nb = number of trailing zeroes in mask
9433     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9434     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9435     uint64_t Mask = CRHS->getZExtValue();
9436     unsigned Bits = countPopulation(Mask);
9437     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9438         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9439       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9440         unsigned Shift = CShift->getZExtValue();
9441         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9442         unsigned Offset = NB + Shift;
9443         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9444           SDLoc SL(N);
9445           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9446                                     LHS->getOperand(0),
9447                                     DAG.getConstant(Offset, SL, MVT::i32),
9448                                     DAG.getConstant(Bits, SL, MVT::i32));
9449           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9450           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9451                                     DAG.getValueType(NarrowVT));
9452           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9453                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9454           return Shl;
9455         }
9456       }
9457     }
9458 
9459     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9460     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9461         isa<ConstantSDNode>(LHS.getOperand(2))) {
9462       uint32_t Sel = getConstantPermuteMask(Mask);
9463       if (!Sel)
9464         return SDValue();
9465 
9466       // Select 0xc for all zero bytes
9467       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9468       SDLoc DL(N);
9469       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9470                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9471     }
9472   }
9473 
9474   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9475   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9476   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9477     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9478     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9479 
9480     SDValue X = LHS.getOperand(0);
9481     SDValue Y = RHS.getOperand(0);
9482     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9483       return SDValue();
9484 
9485     if (LCC == ISD::SETO) {
9486       if (X != LHS.getOperand(1))
9487         return SDValue();
9488 
9489       if (RCC == ISD::SETUNE) {
9490         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9491         if (!C1 || !C1->isInfinity() || C1->isNegative())
9492           return SDValue();
9493 
9494         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9495                               SIInstrFlags::N_SUBNORMAL |
9496                               SIInstrFlags::N_ZERO |
9497                               SIInstrFlags::P_ZERO |
9498                               SIInstrFlags::P_SUBNORMAL |
9499                               SIInstrFlags::P_NORMAL;
9500 
9501         static_assert(((~(SIInstrFlags::S_NAN |
9502                           SIInstrFlags::Q_NAN |
9503                           SIInstrFlags::N_INFINITY |
9504                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9505                       "mask not equal");
9506 
9507         SDLoc DL(N);
9508         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9509                            X, DAG.getConstant(Mask, DL, MVT::i32));
9510       }
9511     }
9512   }
9513 
9514   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9515     std::swap(LHS, RHS);
9516 
9517   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9518       RHS.hasOneUse()) {
9519     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9520     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9521     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9522     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9523     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9524         (RHS.getOperand(0) == LHS.getOperand(0) &&
9525          LHS.getOperand(0) == LHS.getOperand(1))) {
9526       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9527       unsigned NewMask = LCC == ISD::SETO ?
9528         Mask->getZExtValue() & ~OrdMask :
9529         Mask->getZExtValue() & OrdMask;
9530 
9531       SDLoc DL(N);
9532       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9533                          DAG.getConstant(NewMask, DL, MVT::i32));
9534     }
9535   }
9536 
9537   if (VT == MVT::i32 &&
9538       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9539     // and x, (sext cc from i1) => select cc, x, 0
9540     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9541       std::swap(LHS, RHS);
9542     if (isBoolSGPR(RHS.getOperand(0)))
9543       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9544                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9545   }
9546 
9547   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9548   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9549   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9550       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9551     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9552     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9553     if (LHSMask != ~0u && RHSMask != ~0u) {
9554       // Canonicalize the expression in an attempt to have fewer unique masks
9555       // and therefore fewer registers used to hold the masks.
9556       if (LHSMask > RHSMask) {
9557         std::swap(LHSMask, RHSMask);
9558         std::swap(LHS, RHS);
9559       }
9560 
9561       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9562       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9563       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9564       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9565 
9566       // Check of we need to combine values from two sources within a byte.
9567       if (!(LHSUsedLanes & RHSUsedLanes) &&
9568           // If we select high and lower word keep it for SDWA.
9569           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9570           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9571         // Each byte in each mask is either selector mask 0-3, or has higher
9572         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9573         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9574         // mask which is not 0xff wins. By anding both masks we have a correct
9575         // result except that 0x0c shall be corrected to give 0x0c only.
9576         uint32_t Mask = LHSMask & RHSMask;
9577         for (unsigned I = 0; I < 32; I += 8) {
9578           uint32_t ByteSel = 0xff << I;
9579           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9580             Mask &= (0x0c << I) & 0xffffffff;
9581         }
9582 
9583         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9584         // or 0x0c.
9585         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9586         SDLoc DL(N);
9587 
9588         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9589                            LHS.getOperand(0), RHS.getOperand(0),
9590                            DAG.getConstant(Sel, DL, MVT::i32));
9591       }
9592     }
9593   }
9594 
9595   return SDValue();
9596 }
9597 
9598 SDValue SITargetLowering::performOrCombine(SDNode *N,
9599                                            DAGCombinerInfo &DCI) const {
9600   SelectionDAG &DAG = DCI.DAG;
9601   SDValue LHS = N->getOperand(0);
9602   SDValue RHS = N->getOperand(1);
9603 
9604   EVT VT = N->getValueType(0);
9605   if (VT == MVT::i1) {
9606     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9607     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9608         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9609       SDValue Src = LHS.getOperand(0);
9610       if (Src != RHS.getOperand(0))
9611         return SDValue();
9612 
9613       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9614       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9615       if (!CLHS || !CRHS)
9616         return SDValue();
9617 
9618       // Only 10 bits are used.
9619       static const uint32_t MaxMask = 0x3ff;
9620 
9621       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9622       SDLoc DL(N);
9623       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9624                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9625     }
9626 
9627     return SDValue();
9628   }
9629 
9630   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9631   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9632       LHS.getOpcode() == AMDGPUISD::PERM &&
9633       isa<ConstantSDNode>(LHS.getOperand(2))) {
9634     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9635     if (!Sel)
9636       return SDValue();
9637 
9638     Sel |= LHS.getConstantOperandVal(2);
9639     SDLoc DL(N);
9640     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9641                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9642   }
9643 
9644   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9645   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9646   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9647       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9648     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9649     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9650     if (LHSMask != ~0u && RHSMask != ~0u) {
9651       // Canonicalize the expression in an attempt to have fewer unique masks
9652       // and therefore fewer registers used to hold the masks.
9653       if (LHSMask > RHSMask) {
9654         std::swap(LHSMask, RHSMask);
9655         std::swap(LHS, RHS);
9656       }
9657 
9658       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9659       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9660       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9661       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9662 
9663       // Check of we need to combine values from two sources within a byte.
9664       if (!(LHSUsedLanes & RHSUsedLanes) &&
9665           // If we select high and lower word keep it for SDWA.
9666           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9667           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9668         // Kill zero bytes selected by other mask. Zero value is 0xc.
9669         LHSMask &= ~RHSUsedLanes;
9670         RHSMask &= ~LHSUsedLanes;
9671         // Add 4 to each active LHS lane
9672         LHSMask |= LHSUsedLanes & 0x04040404;
9673         // Combine masks
9674         uint32_t Sel = LHSMask | RHSMask;
9675         SDLoc DL(N);
9676 
9677         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9678                            LHS.getOperand(0), RHS.getOperand(0),
9679                            DAG.getConstant(Sel, DL, MVT::i32));
9680       }
9681     }
9682   }
9683 
9684   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9685     return SDValue();
9686 
9687   // TODO: This could be a generic combine with a predicate for extracting the
9688   // high half of an integer being free.
9689 
9690   // (or i64:x, (zero_extend i32:y)) ->
9691   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9692   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9693       RHS.getOpcode() != ISD::ZERO_EXTEND)
9694     std::swap(LHS, RHS);
9695 
9696   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9697     SDValue ExtSrc = RHS.getOperand(0);
9698     EVT SrcVT = ExtSrc.getValueType();
9699     if (SrcVT == MVT::i32) {
9700       SDLoc SL(N);
9701       SDValue LowLHS, HiBits;
9702       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9703       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9704 
9705       DCI.AddToWorklist(LowOr.getNode());
9706       DCI.AddToWorklist(HiBits.getNode());
9707 
9708       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9709                                 LowOr, HiBits);
9710       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9711     }
9712   }
9713 
9714   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9715   if (CRHS) {
9716     if (SDValue Split
9717           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR,
9718                                      N->getOperand(0), CRHS))
9719       return Split;
9720   }
9721 
9722   return SDValue();
9723 }
9724 
9725 SDValue SITargetLowering::performXorCombine(SDNode *N,
9726                                             DAGCombinerInfo &DCI) const {
9727   if (SDValue RV = reassociateScalarOps(N, DCI.DAG))
9728     return RV;
9729 
9730   EVT VT = N->getValueType(0);
9731   if (VT != MVT::i64)
9732     return SDValue();
9733 
9734   SDValue LHS = N->getOperand(0);
9735   SDValue RHS = N->getOperand(1);
9736 
9737   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9738   if (CRHS) {
9739     if (SDValue Split
9740           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9741       return Split;
9742   }
9743 
9744   return SDValue();
9745 }
9746 
9747 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9748                                                    DAGCombinerInfo &DCI) const {
9749   if (!Subtarget->has16BitInsts() ||
9750       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9751     return SDValue();
9752 
9753   EVT VT = N->getValueType(0);
9754   if (VT != MVT::i32)
9755     return SDValue();
9756 
9757   SDValue Src = N->getOperand(0);
9758   if (Src.getValueType() != MVT::i16)
9759     return SDValue();
9760 
9761   return SDValue();
9762 }
9763 
9764 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9765                                                         DAGCombinerInfo &DCI)
9766                                                         const {
9767   SDValue Src = N->getOperand(0);
9768   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9769 
9770   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9771       VTSign->getVT() == MVT::i8) ||
9772       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9773       VTSign->getVT() == MVT::i16)) &&
9774       Src.hasOneUse()) {
9775     auto *M = cast<MemSDNode>(Src);
9776     SDValue Ops[] = {
9777       Src.getOperand(0), // Chain
9778       Src.getOperand(1), // rsrc
9779       Src.getOperand(2), // vindex
9780       Src.getOperand(3), // voffset
9781       Src.getOperand(4), // soffset
9782       Src.getOperand(5), // offset
9783       Src.getOperand(6),
9784       Src.getOperand(7)
9785     };
9786     // replace with BUFFER_LOAD_BYTE/SHORT
9787     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9788                                          Src.getOperand(0).getValueType());
9789     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9790                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9791     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9792                                                           ResList,
9793                                                           Ops, M->getMemoryVT(),
9794                                                           M->getMemOperand());
9795     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9796                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9797   }
9798   return SDValue();
9799 }
9800 
9801 SDValue SITargetLowering::performClassCombine(SDNode *N,
9802                                               DAGCombinerInfo &DCI) const {
9803   SelectionDAG &DAG = DCI.DAG;
9804   SDValue Mask = N->getOperand(1);
9805 
9806   // fp_class x, 0 -> false
9807   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9808     if (CMask->isZero())
9809       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9810   }
9811 
9812   if (N->getOperand(0).isUndef())
9813     return DAG.getUNDEF(MVT::i1);
9814 
9815   return SDValue();
9816 }
9817 
9818 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9819                                             DAGCombinerInfo &DCI) const {
9820   EVT VT = N->getValueType(0);
9821   SDValue N0 = N->getOperand(0);
9822 
9823   if (N0.isUndef())
9824     return N0;
9825 
9826   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9827                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9828     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9829                            N->getFlags());
9830   }
9831 
9832   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9833     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9834                            N0.getOperand(0), N->getFlags());
9835   }
9836 
9837   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9838 }
9839 
9840 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9841                                        unsigned MaxDepth) const {
9842   unsigned Opcode = Op.getOpcode();
9843   if (Opcode == ISD::FCANONICALIZE)
9844     return true;
9845 
9846   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9847     auto F = CFP->getValueAPF();
9848     if (F.isNaN() && F.isSignaling())
9849       return false;
9850     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9851   }
9852 
9853   // If source is a result of another standard FP operation it is already in
9854   // canonical form.
9855   if (MaxDepth == 0)
9856     return false;
9857 
9858   switch (Opcode) {
9859   // These will flush denorms if required.
9860   case ISD::FADD:
9861   case ISD::FSUB:
9862   case ISD::FMUL:
9863   case ISD::FCEIL:
9864   case ISD::FFLOOR:
9865   case ISD::FMA:
9866   case ISD::FMAD:
9867   case ISD::FSQRT:
9868   case ISD::FDIV:
9869   case ISD::FREM:
9870   case ISD::FP_ROUND:
9871   case ISD::FP_EXTEND:
9872   case AMDGPUISD::FMUL_LEGACY:
9873   case AMDGPUISD::FMAD_FTZ:
9874   case AMDGPUISD::RCP:
9875   case AMDGPUISD::RSQ:
9876   case AMDGPUISD::RSQ_CLAMP:
9877   case AMDGPUISD::RCP_LEGACY:
9878   case AMDGPUISD::RCP_IFLAG:
9879   case AMDGPUISD::DIV_SCALE:
9880   case AMDGPUISD::DIV_FMAS:
9881   case AMDGPUISD::DIV_FIXUP:
9882   case AMDGPUISD::FRACT:
9883   case AMDGPUISD::LDEXP:
9884   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9885   case AMDGPUISD::CVT_F32_UBYTE0:
9886   case AMDGPUISD::CVT_F32_UBYTE1:
9887   case AMDGPUISD::CVT_F32_UBYTE2:
9888   case AMDGPUISD::CVT_F32_UBYTE3:
9889     return true;
9890 
9891   // It can/will be lowered or combined as a bit operation.
9892   // Need to check their input recursively to handle.
9893   case ISD::FNEG:
9894   case ISD::FABS:
9895   case ISD::FCOPYSIGN:
9896     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9897 
9898   case ISD::FSIN:
9899   case ISD::FCOS:
9900   case ISD::FSINCOS:
9901     return Op.getValueType().getScalarType() != MVT::f16;
9902 
9903   case ISD::FMINNUM:
9904   case ISD::FMAXNUM:
9905   case ISD::FMINNUM_IEEE:
9906   case ISD::FMAXNUM_IEEE:
9907   case AMDGPUISD::CLAMP:
9908   case AMDGPUISD::FMED3:
9909   case AMDGPUISD::FMAX3:
9910   case AMDGPUISD::FMIN3: {
9911     // FIXME: Shouldn't treat the generic operations different based these.
9912     // However, we aren't really required to flush the result from
9913     // minnum/maxnum..
9914 
9915     // snans will be quieted, so we only need to worry about denormals.
9916     if (Subtarget->supportsMinMaxDenormModes() ||
9917         denormalsEnabledForType(DAG, Op.getValueType()))
9918       return true;
9919 
9920     // Flushing may be required.
9921     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9922     // targets need to check their input recursively.
9923 
9924     // FIXME: Does this apply with clamp? It's implemented with max.
9925     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9926       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9927         return false;
9928     }
9929 
9930     return true;
9931   }
9932   case ISD::SELECT: {
9933     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9934            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9935   }
9936   case ISD::BUILD_VECTOR: {
9937     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9938       SDValue SrcOp = Op.getOperand(i);
9939       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9940         return false;
9941     }
9942 
9943     return true;
9944   }
9945   case ISD::EXTRACT_VECTOR_ELT:
9946   case ISD::EXTRACT_SUBVECTOR: {
9947     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9948   }
9949   case ISD::INSERT_VECTOR_ELT: {
9950     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9951            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9952   }
9953   case ISD::UNDEF:
9954     // Could be anything.
9955     return false;
9956 
9957   case ISD::BITCAST:
9958     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9959   case ISD::TRUNCATE: {
9960     // Hack round the mess we make when legalizing extract_vector_elt
9961     if (Op.getValueType() == MVT::i16) {
9962       SDValue TruncSrc = Op.getOperand(0);
9963       if (TruncSrc.getValueType() == MVT::i32 &&
9964           TruncSrc.getOpcode() == ISD::BITCAST &&
9965           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9966         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9967       }
9968     }
9969     return false;
9970   }
9971   case ISD::INTRINSIC_WO_CHAIN: {
9972     unsigned IntrinsicID
9973       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9974     // TODO: Handle more intrinsics
9975     switch (IntrinsicID) {
9976     case Intrinsic::amdgcn_cvt_pkrtz:
9977     case Intrinsic::amdgcn_cubeid:
9978     case Intrinsic::amdgcn_frexp_mant:
9979     case Intrinsic::amdgcn_fdot2:
9980     case Intrinsic::amdgcn_rcp:
9981     case Intrinsic::amdgcn_rsq:
9982     case Intrinsic::amdgcn_rsq_clamp:
9983     case Intrinsic::amdgcn_rcp_legacy:
9984     case Intrinsic::amdgcn_rsq_legacy:
9985     case Intrinsic::amdgcn_trig_preop:
9986       return true;
9987     default:
9988       break;
9989     }
9990 
9991     LLVM_FALLTHROUGH;
9992   }
9993   default:
9994     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9995            DAG.isKnownNeverSNaN(Op);
9996   }
9997 
9998   llvm_unreachable("invalid operation");
9999 }
10000 
10001 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
10002                                        unsigned MaxDepth) const {
10003   MachineRegisterInfo &MRI = MF.getRegInfo();
10004   MachineInstr *MI = MRI.getVRegDef(Reg);
10005   unsigned Opcode = MI->getOpcode();
10006 
10007   if (Opcode == AMDGPU::G_FCANONICALIZE)
10008     return true;
10009 
10010   Optional<FPValueAndVReg> FCR;
10011   // Constant splat (can be padded with undef) or scalar constant.
10012   if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) {
10013     if (FCR->Value.isSignaling())
10014       return false;
10015     return !FCR->Value.isDenormal() ||
10016            denormalsEnabledForType(MRI.getType(FCR->VReg), MF);
10017   }
10018 
10019   if (MaxDepth == 0)
10020     return false;
10021 
10022   switch (Opcode) {
10023   case AMDGPU::G_FMINNUM_IEEE:
10024   case AMDGPU::G_FMAXNUM_IEEE: {
10025     if (Subtarget->supportsMinMaxDenormModes() ||
10026         denormalsEnabledForType(MRI.getType(Reg), MF))
10027       return true;
10028     for (const MachineOperand &MO : llvm::drop_begin(MI->operands()))
10029       if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1))
10030         return false;
10031     return true;
10032   }
10033   default:
10034     return denormalsEnabledForType(MRI.getType(Reg), MF) &&
10035            isKnownNeverSNaN(Reg, MRI);
10036   }
10037 
10038   llvm_unreachable("invalid operation");
10039 }
10040 
10041 // Constant fold canonicalize.
10042 SDValue SITargetLowering::getCanonicalConstantFP(
10043   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
10044   // Flush denormals to 0 if not enabled.
10045   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
10046     return DAG.getConstantFP(0.0, SL, VT);
10047 
10048   if (C.isNaN()) {
10049     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
10050     if (C.isSignaling()) {
10051       // Quiet a signaling NaN.
10052       // FIXME: Is this supposed to preserve payload bits?
10053       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
10054     }
10055 
10056     // Make sure it is the canonical NaN bitpattern.
10057     //
10058     // TODO: Can we use -1 as the canonical NaN value since it's an inline
10059     // immediate?
10060     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
10061       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
10062   }
10063 
10064   // Already canonical.
10065   return DAG.getConstantFP(C, SL, VT);
10066 }
10067 
10068 static bool vectorEltWillFoldAway(SDValue Op) {
10069   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
10070 }
10071 
10072 SDValue SITargetLowering::performFCanonicalizeCombine(
10073   SDNode *N,
10074   DAGCombinerInfo &DCI) const {
10075   SelectionDAG &DAG = DCI.DAG;
10076   SDValue N0 = N->getOperand(0);
10077   EVT VT = N->getValueType(0);
10078 
10079   // fcanonicalize undef -> qnan
10080   if (N0.isUndef()) {
10081     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
10082     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
10083   }
10084 
10085   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
10086     EVT VT = N->getValueType(0);
10087     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
10088   }
10089 
10090   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
10091   //                                                   (fcanonicalize k)
10092   //
10093   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
10094 
10095   // TODO: This could be better with wider vectors that will be split to v2f16,
10096   // and to consider uses since there aren't that many packed operations.
10097   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
10098       isTypeLegal(MVT::v2f16)) {
10099     SDLoc SL(N);
10100     SDValue NewElts[2];
10101     SDValue Lo = N0.getOperand(0);
10102     SDValue Hi = N0.getOperand(1);
10103     EVT EltVT = Lo.getValueType();
10104 
10105     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
10106       for (unsigned I = 0; I != 2; ++I) {
10107         SDValue Op = N0.getOperand(I);
10108         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
10109           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
10110                                               CFP->getValueAPF());
10111         } else if (Op.isUndef()) {
10112           // Handled below based on what the other operand is.
10113           NewElts[I] = Op;
10114         } else {
10115           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
10116         }
10117       }
10118 
10119       // If one half is undef, and one is constant, prefer a splat vector rather
10120       // than the normal qNaN. If it's a register, prefer 0.0 since that's
10121       // cheaper to use and may be free with a packed operation.
10122       if (NewElts[0].isUndef()) {
10123         if (isa<ConstantFPSDNode>(NewElts[1]))
10124           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
10125             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
10126       }
10127 
10128       if (NewElts[1].isUndef()) {
10129         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
10130           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
10131       }
10132 
10133       return DAG.getBuildVector(VT, SL, NewElts);
10134     }
10135   }
10136 
10137   unsigned SrcOpc = N0.getOpcode();
10138 
10139   // If it's free to do so, push canonicalizes further up the source, which may
10140   // find a canonical source.
10141   //
10142   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
10143   // sNaNs.
10144   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
10145     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10146     if (CRHS && N0.hasOneUse()) {
10147       SDLoc SL(N);
10148       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
10149                                    N0.getOperand(0));
10150       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
10151       DCI.AddToWorklist(Canon0.getNode());
10152 
10153       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
10154     }
10155   }
10156 
10157   return isCanonicalized(DAG, N0) ? N0 : SDValue();
10158 }
10159 
10160 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
10161   switch (Opc) {
10162   case ISD::FMAXNUM:
10163   case ISD::FMAXNUM_IEEE:
10164     return AMDGPUISD::FMAX3;
10165   case ISD::SMAX:
10166     return AMDGPUISD::SMAX3;
10167   case ISD::UMAX:
10168     return AMDGPUISD::UMAX3;
10169   case ISD::FMINNUM:
10170   case ISD::FMINNUM_IEEE:
10171     return AMDGPUISD::FMIN3;
10172   case ISD::SMIN:
10173     return AMDGPUISD::SMIN3;
10174   case ISD::UMIN:
10175     return AMDGPUISD::UMIN3;
10176   default:
10177     llvm_unreachable("Not a min/max opcode");
10178   }
10179 }
10180 
10181 SDValue SITargetLowering::performIntMed3ImmCombine(
10182   SelectionDAG &DAG, const SDLoc &SL,
10183   SDValue Op0, SDValue Op1, bool Signed) const {
10184   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
10185   if (!K1)
10186     return SDValue();
10187 
10188   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
10189   if (!K0)
10190     return SDValue();
10191 
10192   if (Signed) {
10193     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
10194       return SDValue();
10195   } else {
10196     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
10197       return SDValue();
10198   }
10199 
10200   EVT VT = K0->getValueType(0);
10201   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
10202   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
10203     return DAG.getNode(Med3Opc, SL, VT,
10204                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
10205   }
10206 
10207   // If there isn't a 16-bit med3 operation, convert to 32-bit.
10208   if (VT == MVT::i16) {
10209     MVT NVT = MVT::i32;
10210     unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
10211 
10212     SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
10213     SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
10214     SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
10215 
10216     SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
10217     return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
10218   }
10219 
10220   return SDValue();
10221 }
10222 
10223 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
10224   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
10225     return C;
10226 
10227   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
10228     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
10229       return C;
10230   }
10231 
10232   return nullptr;
10233 }
10234 
10235 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
10236                                                   const SDLoc &SL,
10237                                                   SDValue Op0,
10238                                                   SDValue Op1) const {
10239   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
10240   if (!K1)
10241     return SDValue();
10242 
10243   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
10244   if (!K0)
10245     return SDValue();
10246 
10247   // Ordered >= (although NaN inputs should have folded away by now).
10248   if (K0->getValueAPF() > K1->getValueAPF())
10249     return SDValue();
10250 
10251   const MachineFunction &MF = DAG.getMachineFunction();
10252   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10253 
10254   // TODO: Check IEEE bit enabled?
10255   EVT VT = Op0.getValueType();
10256   if (Info->getMode().DX10Clamp) {
10257     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
10258     // hardware fmed3 behavior converting to a min.
10259     // FIXME: Should this be allowing -0.0?
10260     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
10261       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
10262   }
10263 
10264   // med3 for f16 is only available on gfx9+, and not available for v2f16.
10265   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
10266     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
10267     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
10268     // then give the other result, which is different from med3 with a NaN
10269     // input.
10270     SDValue Var = Op0.getOperand(0);
10271     if (!DAG.isKnownNeverSNaN(Var))
10272       return SDValue();
10273 
10274     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10275 
10276     if ((!K0->hasOneUse() ||
10277          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
10278         (!K1->hasOneUse() ||
10279          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
10280       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
10281                          Var, SDValue(K0, 0), SDValue(K1, 0));
10282     }
10283   }
10284 
10285   return SDValue();
10286 }
10287 
10288 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
10289                                                DAGCombinerInfo &DCI) const {
10290   SelectionDAG &DAG = DCI.DAG;
10291 
10292   EVT VT = N->getValueType(0);
10293   unsigned Opc = N->getOpcode();
10294   SDValue Op0 = N->getOperand(0);
10295   SDValue Op1 = N->getOperand(1);
10296 
10297   // Only do this if the inner op has one use since this will just increases
10298   // register pressure for no benefit.
10299 
10300   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
10301       !VT.isVector() &&
10302       (VT == MVT::i32 || VT == MVT::f32 ||
10303        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
10304     // max(max(a, b), c) -> max3(a, b, c)
10305     // min(min(a, b), c) -> min3(a, b, c)
10306     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
10307       SDLoc DL(N);
10308       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10309                          DL,
10310                          N->getValueType(0),
10311                          Op0.getOperand(0),
10312                          Op0.getOperand(1),
10313                          Op1);
10314     }
10315 
10316     // Try commuted.
10317     // max(a, max(b, c)) -> max3(a, b, c)
10318     // min(a, min(b, c)) -> min3(a, b, c)
10319     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
10320       SDLoc DL(N);
10321       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10322                          DL,
10323                          N->getValueType(0),
10324                          Op0,
10325                          Op1.getOperand(0),
10326                          Op1.getOperand(1));
10327     }
10328   }
10329 
10330   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
10331   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
10332     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
10333       return Med3;
10334   }
10335 
10336   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
10337     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
10338       return Med3;
10339   }
10340 
10341   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
10342   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
10343        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
10344        (Opc == AMDGPUISD::FMIN_LEGACY &&
10345         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
10346       (VT == MVT::f32 || VT == MVT::f64 ||
10347        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
10348        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
10349       Op0.hasOneUse()) {
10350     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
10351       return Res;
10352   }
10353 
10354   return SDValue();
10355 }
10356 
10357 static bool isClampZeroToOne(SDValue A, SDValue B) {
10358   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
10359     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
10360       // FIXME: Should this be allowing -0.0?
10361       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
10362              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
10363     }
10364   }
10365 
10366   return false;
10367 }
10368 
10369 // FIXME: Should only worry about snans for version with chain.
10370 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
10371                                               DAGCombinerInfo &DCI) const {
10372   EVT VT = N->getValueType(0);
10373   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
10374   // NaNs. With a NaN input, the order of the operands may change the result.
10375 
10376   SelectionDAG &DAG = DCI.DAG;
10377   SDLoc SL(N);
10378 
10379   SDValue Src0 = N->getOperand(0);
10380   SDValue Src1 = N->getOperand(1);
10381   SDValue Src2 = N->getOperand(2);
10382 
10383   if (isClampZeroToOne(Src0, Src1)) {
10384     // const_a, const_b, x -> clamp is safe in all cases including signaling
10385     // nans.
10386     // FIXME: Should this be allowing -0.0?
10387     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
10388   }
10389 
10390   const MachineFunction &MF = DAG.getMachineFunction();
10391   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10392 
10393   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
10394   // handling no dx10-clamp?
10395   if (Info->getMode().DX10Clamp) {
10396     // If NaNs is clamped to 0, we are free to reorder the inputs.
10397 
10398     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10399       std::swap(Src0, Src1);
10400 
10401     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10402       std::swap(Src1, Src2);
10403 
10404     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10405       std::swap(Src0, Src1);
10406 
10407     if (isClampZeroToOne(Src1, Src2))
10408       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10409   }
10410 
10411   return SDValue();
10412 }
10413 
10414 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10415                                                  DAGCombinerInfo &DCI) const {
10416   SDValue Src0 = N->getOperand(0);
10417   SDValue Src1 = N->getOperand(1);
10418   if (Src0.isUndef() && Src1.isUndef())
10419     return DCI.DAG.getUNDEF(N->getValueType(0));
10420   return SDValue();
10421 }
10422 
10423 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10424 // expanded into a set of cmp/select instructions.
10425 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10426                                                 unsigned NumElem,
10427                                                 bool IsDivergentIdx) {
10428   if (UseDivergentRegisterIndexing)
10429     return false;
10430 
10431   unsigned VecSize = EltSize * NumElem;
10432 
10433   // Sub-dword vectors of size 2 dword or less have better implementation.
10434   if (VecSize <= 64 && EltSize < 32)
10435     return false;
10436 
10437   // Always expand the rest of sub-dword instructions, otherwise it will be
10438   // lowered via memory.
10439   if (EltSize < 32)
10440     return true;
10441 
10442   // Always do this if var-idx is divergent, otherwise it will become a loop.
10443   if (IsDivergentIdx)
10444     return true;
10445 
10446   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10447   unsigned NumInsts = NumElem /* Number of compares */ +
10448                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10449   return NumInsts <= 16;
10450 }
10451 
10452 static bool shouldExpandVectorDynExt(SDNode *N) {
10453   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10454   if (isa<ConstantSDNode>(Idx))
10455     return false;
10456 
10457   SDValue Vec = N->getOperand(0);
10458   EVT VecVT = Vec.getValueType();
10459   EVT EltVT = VecVT.getVectorElementType();
10460   unsigned EltSize = EltVT.getSizeInBits();
10461   unsigned NumElem = VecVT.getVectorNumElements();
10462 
10463   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
10464                                                     Idx->isDivergent());
10465 }
10466 
10467 SDValue SITargetLowering::performExtractVectorEltCombine(
10468   SDNode *N, DAGCombinerInfo &DCI) const {
10469   SDValue Vec = N->getOperand(0);
10470   SelectionDAG &DAG = DCI.DAG;
10471 
10472   EVT VecVT = Vec.getValueType();
10473   EVT EltVT = VecVT.getVectorElementType();
10474 
10475   if ((Vec.getOpcode() == ISD::FNEG ||
10476        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10477     SDLoc SL(N);
10478     EVT EltVT = N->getValueType(0);
10479     SDValue Idx = N->getOperand(1);
10480     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10481                               Vec.getOperand(0), Idx);
10482     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10483   }
10484 
10485   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10486   //    =>
10487   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10488   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10489   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10490   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10491     SDLoc SL(N);
10492     EVT EltVT = N->getValueType(0);
10493     SDValue Idx = N->getOperand(1);
10494     unsigned Opc = Vec.getOpcode();
10495 
10496     switch(Opc) {
10497     default:
10498       break;
10499       // TODO: Support other binary operations.
10500     case ISD::FADD:
10501     case ISD::FSUB:
10502     case ISD::FMUL:
10503     case ISD::ADD:
10504     case ISD::UMIN:
10505     case ISD::UMAX:
10506     case ISD::SMIN:
10507     case ISD::SMAX:
10508     case ISD::FMAXNUM:
10509     case ISD::FMINNUM:
10510     case ISD::FMAXNUM_IEEE:
10511     case ISD::FMINNUM_IEEE: {
10512       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10513                                  Vec.getOperand(0), Idx);
10514       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10515                                  Vec.getOperand(1), Idx);
10516 
10517       DCI.AddToWorklist(Elt0.getNode());
10518       DCI.AddToWorklist(Elt1.getNode());
10519       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10520     }
10521     }
10522   }
10523 
10524   unsigned VecSize = VecVT.getSizeInBits();
10525   unsigned EltSize = EltVT.getSizeInBits();
10526 
10527   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10528   if (::shouldExpandVectorDynExt(N)) {
10529     SDLoc SL(N);
10530     SDValue Idx = N->getOperand(1);
10531     SDValue V;
10532     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10533       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10534       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10535       if (I == 0)
10536         V = Elt;
10537       else
10538         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10539     }
10540     return V;
10541   }
10542 
10543   if (!DCI.isBeforeLegalize())
10544     return SDValue();
10545 
10546   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10547   // elements. This exposes more load reduction opportunities by replacing
10548   // multiple small extract_vector_elements with a single 32-bit extract.
10549   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10550   if (isa<MemSDNode>(Vec) &&
10551       EltSize <= 16 &&
10552       EltVT.isByteSized() &&
10553       VecSize > 32 &&
10554       VecSize % 32 == 0 &&
10555       Idx) {
10556     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10557 
10558     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10559     unsigned EltIdx = BitIndex / 32;
10560     unsigned LeftoverBitIdx = BitIndex % 32;
10561     SDLoc SL(N);
10562 
10563     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10564     DCI.AddToWorklist(Cast.getNode());
10565 
10566     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10567                               DAG.getConstant(EltIdx, SL, MVT::i32));
10568     DCI.AddToWorklist(Elt.getNode());
10569     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10570                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10571     DCI.AddToWorklist(Srl.getNode());
10572 
10573     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10574     DCI.AddToWorklist(Trunc.getNode());
10575     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10576   }
10577 
10578   return SDValue();
10579 }
10580 
10581 SDValue
10582 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10583                                                 DAGCombinerInfo &DCI) const {
10584   SDValue Vec = N->getOperand(0);
10585   SDValue Idx = N->getOperand(2);
10586   EVT VecVT = Vec.getValueType();
10587   EVT EltVT = VecVT.getVectorElementType();
10588 
10589   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10590   // => BUILD_VECTOR n x select (e, const-idx)
10591   if (!::shouldExpandVectorDynExt(N))
10592     return SDValue();
10593 
10594   SelectionDAG &DAG = DCI.DAG;
10595   SDLoc SL(N);
10596   SDValue Ins = N->getOperand(1);
10597   EVT IdxVT = Idx.getValueType();
10598 
10599   SmallVector<SDValue, 16> Ops;
10600   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10601     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10602     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10603     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10604     Ops.push_back(V);
10605   }
10606 
10607   return DAG.getBuildVector(VecVT, SL, Ops);
10608 }
10609 
10610 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10611                                           const SDNode *N0,
10612                                           const SDNode *N1) const {
10613   EVT VT = N0->getValueType(0);
10614 
10615   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10616   // support denormals ever.
10617   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10618        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10619         getSubtarget()->hasMadF16())) &&
10620        isOperationLegal(ISD::FMAD, VT))
10621     return ISD::FMAD;
10622 
10623   const TargetOptions &Options = DAG.getTarget().Options;
10624   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10625        (N0->getFlags().hasAllowContract() &&
10626         N1->getFlags().hasAllowContract())) &&
10627       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10628     return ISD::FMA;
10629   }
10630 
10631   return 0;
10632 }
10633 
10634 // For a reassociatable opcode perform:
10635 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10636 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10637                                                SelectionDAG &DAG) const {
10638   EVT VT = N->getValueType(0);
10639   if (VT != MVT::i32 && VT != MVT::i64)
10640     return SDValue();
10641 
10642   if (DAG.isBaseWithConstantOffset(SDValue(N, 0)))
10643     return SDValue();
10644 
10645   unsigned Opc = N->getOpcode();
10646   SDValue Op0 = N->getOperand(0);
10647   SDValue Op1 = N->getOperand(1);
10648 
10649   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10650     return SDValue();
10651 
10652   if (Op0->isDivergent())
10653     std::swap(Op0, Op1);
10654 
10655   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10656     return SDValue();
10657 
10658   SDValue Op2 = Op1.getOperand(1);
10659   Op1 = Op1.getOperand(0);
10660   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10661     return SDValue();
10662 
10663   if (Op1->isDivergent())
10664     std::swap(Op1, Op2);
10665 
10666   SDLoc SL(N);
10667   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10668   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10669 }
10670 
10671 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10672                            EVT VT,
10673                            SDValue N0, SDValue N1, SDValue N2,
10674                            bool Signed) {
10675   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10676   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10677   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10678   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10679 }
10680 
10681 // Fold (add (mul x, y), z) --> (mad_[iu]64_[iu]32 x, y, z) plus high
10682 // multiplies, if any.
10683 //
10684 // Full 64-bit multiplies that feed into an addition are lowered here instead
10685 // of using the generic expansion. The generic expansion ends up with
10686 // a tree of ADD nodes that prevents us from using the "add" part of the
10687 // MAD instruction. The expansion produced here results in a chain of ADDs
10688 // instead of a tree.
10689 SDValue SITargetLowering::tryFoldToMad64_32(SDNode *N,
10690                                             DAGCombinerInfo &DCI) const {
10691   assert(N->getOpcode() == ISD::ADD);
10692 
10693   SelectionDAG &DAG = DCI.DAG;
10694   EVT VT = N->getValueType(0);
10695   SDLoc SL(N);
10696   SDValue LHS = N->getOperand(0);
10697   SDValue RHS = N->getOperand(1);
10698 
10699   if (VT.isVector())
10700     return SDValue();
10701 
10702   // S_MUL_HI_[IU]32 was added in gfx9, which allows us to keep the overall
10703   // result in scalar registers for uniform values.
10704   if (!N->isDivergent() && Subtarget->hasSMulHi())
10705     return SDValue();
10706 
10707   unsigned NumBits = VT.getScalarSizeInBits();
10708   if (NumBits <= 32 || NumBits > 64)
10709     return SDValue();
10710 
10711   if (LHS.getOpcode() != ISD::MUL) {
10712     assert(RHS.getOpcode() == ISD::MUL);
10713     std::swap(LHS, RHS);
10714   }
10715 
10716   // Avoid the fold if it would unduly increase the number of multiplies due to
10717   // multiple uses, except on hardware with full-rate multiply-add (which is
10718   // part of full-rate 64-bit ops).
10719   if (!Subtarget->hasFullRate64Ops()) {
10720     unsigned NumUsers = 0;
10721     for (SDNode *Use : LHS->uses()) {
10722       // There is a use that does not feed into addition, so the multiply can't
10723       // be removed. We prefer MUL + ADD + ADDC over MAD + MUL.
10724       if (Use->getOpcode() != ISD::ADD)
10725         return SDValue();
10726 
10727       // We prefer 2xMAD over MUL + 2xADD + 2xADDC (code density), and prefer
10728       // MUL + 3xADD + 3xADDC over 3xMAD.
10729       ++NumUsers;
10730       if (NumUsers >= 3)
10731         return SDValue();
10732     }
10733   }
10734 
10735   SDValue MulLHS = LHS.getOperand(0);
10736   SDValue MulRHS = LHS.getOperand(1);
10737   SDValue AddRHS = RHS;
10738 
10739   // Always check whether operands are small unsigned values, since that
10740   // knowledge is useful in more cases. Check for small signed values only if
10741   // doing so can unlock a shorter code sequence.
10742   bool MulLHSUnsigned32 = numBitsUnsigned(MulLHS, DAG) <= 32;
10743   bool MulRHSUnsigned32 = numBitsUnsigned(MulRHS, DAG) <= 32;
10744 
10745   bool MulSignedLo = false;
10746   if (!MulLHSUnsigned32 || !MulRHSUnsigned32) {
10747     MulSignedLo = numBitsSigned(MulLHS, DAG) <= 32 &&
10748                   numBitsSigned(MulRHS, DAG) <= 32;
10749   }
10750 
10751   // The operands and final result all have the same number of bits. If
10752   // operands need to be extended, they can be extended with garbage. The
10753   // resulting garbage in the high bits of the mad_[iu]64_[iu]32 result is
10754   // truncated away in the end.
10755   if (VT != MVT::i64) {
10756     MulLHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulLHS);
10757     MulRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, MulRHS);
10758     AddRHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i64, AddRHS);
10759   }
10760 
10761   // The basic code generated is conceptually straightforward. Pseudo code:
10762   //
10763   //   accum = mad_64_32 lhs.lo, rhs.lo, accum
10764   //   accum.hi = add (mul lhs.hi, rhs.lo), accum.hi
10765   //   accum.hi = add (mul lhs.lo, rhs.hi), accum.hi
10766   //
10767   // The second and third lines are optional, depending on whether the factors
10768   // are {sign,zero}-extended or not.
10769   //
10770   // The actual DAG is noisier than the pseudo code, but only due to
10771   // instructions that disassemble values into low and high parts, and
10772   // assemble the final result.
10773   SDValue Zero = DAG.getConstant(0, SL, MVT::i32);
10774   SDValue One = DAG.getConstant(1, SL, MVT::i32);
10775 
10776   auto MulLHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulLHS);
10777   auto MulRHSLo = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, MulRHS);
10778   SDValue Accum =
10779       getMad64_32(DAG, SL, MVT::i64, MulLHSLo, MulRHSLo, AddRHS, MulSignedLo);
10780 
10781   if (!MulSignedLo && (!MulLHSUnsigned32 || !MulRHSUnsigned32)) {
10782     auto AccumLo = DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, Accum, Zero);
10783     auto AccumHi = DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, Accum, One);
10784 
10785     if (!MulLHSUnsigned32) {
10786       auto MulLHSHi =
10787           DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulLHS, One);
10788       SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSHi, MulRHSLo);
10789       AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi);
10790     }
10791 
10792     if (!MulRHSUnsigned32) {
10793       auto MulRHSHi =
10794           DAG.getNode(ISD::EXTRACT_ELEMENT, SL, MVT::i32, MulRHS, One);
10795       SDValue MulHi = DAG.getNode(ISD::MUL, SL, MVT::i32, MulLHSLo, MulRHSHi);
10796       AccumHi = DAG.getNode(ISD::ADD, SL, MVT::i32, MulHi, AccumHi);
10797     }
10798 
10799     Accum = DAG.getBuildVector(MVT::v2i32, SL, {AccumLo, AccumHi});
10800     Accum = DAG.getBitcast(MVT::i64, Accum);
10801   }
10802 
10803   if (VT != MVT::i64)
10804     Accum = DAG.getNode(ISD::TRUNCATE, SL, VT, Accum);
10805   return Accum;
10806 }
10807 
10808 SDValue SITargetLowering::performAddCombine(SDNode *N,
10809                                             DAGCombinerInfo &DCI) const {
10810   SelectionDAG &DAG = DCI.DAG;
10811   EVT VT = N->getValueType(0);
10812   SDLoc SL(N);
10813   SDValue LHS = N->getOperand(0);
10814   SDValue RHS = N->getOperand(1);
10815 
10816   if (LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) {
10817     if (Subtarget->hasMad64_32()) {
10818       if (SDValue Folded = tryFoldToMad64_32(N, DCI))
10819         return Folded;
10820     }
10821 
10822     return SDValue();
10823   }
10824 
10825   if (SDValue V = reassociateScalarOps(N, DAG)) {
10826     return V;
10827   }
10828 
10829   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10830     return SDValue();
10831 
10832   // add x, zext (setcc) => addcarry x, 0, setcc
10833   // add x, sext (setcc) => subcarry x, 0, setcc
10834   unsigned Opc = LHS.getOpcode();
10835   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10836       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10837     std::swap(RHS, LHS);
10838 
10839   Opc = RHS.getOpcode();
10840   switch (Opc) {
10841   default: break;
10842   case ISD::ZERO_EXTEND:
10843   case ISD::SIGN_EXTEND:
10844   case ISD::ANY_EXTEND: {
10845     auto Cond = RHS.getOperand(0);
10846     // If this won't be a real VOPC output, we would still need to insert an
10847     // extra instruction anyway.
10848     if (!isBoolSGPR(Cond))
10849       break;
10850     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10851     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10852     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10853     return DAG.getNode(Opc, SL, VTList, Args);
10854   }
10855   case ISD::ADDCARRY: {
10856     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10857     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10858     if (!C || C->getZExtValue() != 0) break;
10859     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10860     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10861   }
10862   }
10863   return SDValue();
10864 }
10865 
10866 SDValue SITargetLowering::performSubCombine(SDNode *N,
10867                                             DAGCombinerInfo &DCI) const {
10868   SelectionDAG &DAG = DCI.DAG;
10869   EVT VT = N->getValueType(0);
10870 
10871   if (VT != MVT::i32)
10872     return SDValue();
10873 
10874   SDLoc SL(N);
10875   SDValue LHS = N->getOperand(0);
10876   SDValue RHS = N->getOperand(1);
10877 
10878   // sub x, zext (setcc) => subcarry x, 0, setcc
10879   // sub x, sext (setcc) => addcarry x, 0, setcc
10880   unsigned Opc = RHS.getOpcode();
10881   switch (Opc) {
10882   default: break;
10883   case ISD::ZERO_EXTEND:
10884   case ISD::SIGN_EXTEND:
10885   case ISD::ANY_EXTEND: {
10886     auto Cond = RHS.getOperand(0);
10887     // If this won't be a real VOPC output, we would still need to insert an
10888     // extra instruction anyway.
10889     if (!isBoolSGPR(Cond))
10890       break;
10891     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10892     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10893     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10894     return DAG.getNode(Opc, SL, VTList, Args);
10895   }
10896   }
10897 
10898   if (LHS.getOpcode() == ISD::SUBCARRY) {
10899     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10900     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10901     if (!C || !C->isZero())
10902       return SDValue();
10903     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10904     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10905   }
10906   return SDValue();
10907 }
10908 
10909 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10910   DAGCombinerInfo &DCI) const {
10911 
10912   if (N->getValueType(0) != MVT::i32)
10913     return SDValue();
10914 
10915   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10916   if (!C || C->getZExtValue() != 0)
10917     return SDValue();
10918 
10919   SelectionDAG &DAG = DCI.DAG;
10920   SDValue LHS = N->getOperand(0);
10921 
10922   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10923   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10924   unsigned LHSOpc = LHS.getOpcode();
10925   unsigned Opc = N->getOpcode();
10926   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10927       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10928     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10929     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10930   }
10931   return SDValue();
10932 }
10933 
10934 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10935                                              DAGCombinerInfo &DCI) const {
10936   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10937     return SDValue();
10938 
10939   SelectionDAG &DAG = DCI.DAG;
10940   EVT VT = N->getValueType(0);
10941 
10942   SDLoc SL(N);
10943   SDValue LHS = N->getOperand(0);
10944   SDValue RHS = N->getOperand(1);
10945 
10946   // These should really be instruction patterns, but writing patterns with
10947   // source modifiers is a pain.
10948 
10949   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10950   if (LHS.getOpcode() == ISD::FADD) {
10951     SDValue A = LHS.getOperand(0);
10952     if (A == LHS.getOperand(1)) {
10953       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10954       if (FusedOp != 0) {
10955         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10956         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10957       }
10958     }
10959   }
10960 
10961   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10962   if (RHS.getOpcode() == ISD::FADD) {
10963     SDValue A = RHS.getOperand(0);
10964     if (A == RHS.getOperand(1)) {
10965       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10966       if (FusedOp != 0) {
10967         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10968         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10969       }
10970     }
10971   }
10972 
10973   return SDValue();
10974 }
10975 
10976 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10977                                              DAGCombinerInfo &DCI) const {
10978   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10979     return SDValue();
10980 
10981   SelectionDAG &DAG = DCI.DAG;
10982   SDLoc SL(N);
10983   EVT VT = N->getValueType(0);
10984   assert(!VT.isVector());
10985 
10986   // Try to get the fneg to fold into the source modifier. This undoes generic
10987   // DAG combines and folds them into the mad.
10988   //
10989   // Only do this if we are not trying to support denormals. v_mad_f32 does
10990   // not support denormals ever.
10991   SDValue LHS = N->getOperand(0);
10992   SDValue RHS = N->getOperand(1);
10993   if (LHS.getOpcode() == ISD::FADD) {
10994     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10995     SDValue A = LHS.getOperand(0);
10996     if (A == LHS.getOperand(1)) {
10997       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10998       if (FusedOp != 0){
10999         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
11000         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
11001 
11002         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
11003       }
11004     }
11005   }
11006 
11007   if (RHS.getOpcode() == ISD::FADD) {
11008     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
11009 
11010     SDValue A = RHS.getOperand(0);
11011     if (A == RHS.getOperand(1)) {
11012       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
11013       if (FusedOp != 0){
11014         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
11015         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
11016       }
11017     }
11018   }
11019 
11020   return SDValue();
11021 }
11022 
11023 SDValue SITargetLowering::performFMACombine(SDNode *N,
11024                                             DAGCombinerInfo &DCI) const {
11025   SelectionDAG &DAG = DCI.DAG;
11026   EVT VT = N->getValueType(0);
11027   SDLoc SL(N);
11028 
11029   if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
11030     return SDValue();
11031 
11032   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
11033   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
11034   SDValue Op1 = N->getOperand(0);
11035   SDValue Op2 = N->getOperand(1);
11036   SDValue FMA = N->getOperand(2);
11037 
11038   if (FMA.getOpcode() != ISD::FMA ||
11039       Op1.getOpcode() != ISD::FP_EXTEND ||
11040       Op2.getOpcode() != ISD::FP_EXTEND)
11041     return SDValue();
11042 
11043   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
11044   // regardless of the denorm mode setting. Therefore,
11045   // unsafe-fp-math/fp-contract is sufficient to allow generating fdot2.
11046   const TargetOptions &Options = DAG.getTarget().Options;
11047   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
11048       (N->getFlags().hasAllowContract() &&
11049        FMA->getFlags().hasAllowContract())) {
11050     Op1 = Op1.getOperand(0);
11051     Op2 = Op2.getOperand(0);
11052     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11053         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11054       return SDValue();
11055 
11056     SDValue Vec1 = Op1.getOperand(0);
11057     SDValue Idx1 = Op1.getOperand(1);
11058     SDValue Vec2 = Op2.getOperand(0);
11059 
11060     SDValue FMAOp1 = FMA.getOperand(0);
11061     SDValue FMAOp2 = FMA.getOperand(1);
11062     SDValue FMAAcc = FMA.getOperand(2);
11063 
11064     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
11065         FMAOp2.getOpcode() != ISD::FP_EXTEND)
11066       return SDValue();
11067 
11068     FMAOp1 = FMAOp1.getOperand(0);
11069     FMAOp2 = FMAOp2.getOperand(0);
11070     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11071         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11072       return SDValue();
11073 
11074     SDValue Vec3 = FMAOp1.getOperand(0);
11075     SDValue Vec4 = FMAOp2.getOperand(0);
11076     SDValue Idx2 = FMAOp1.getOperand(1);
11077 
11078     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
11079         // Idx1 and Idx2 cannot be the same.
11080         Idx1 == Idx2)
11081       return SDValue();
11082 
11083     if (Vec1 == Vec2 || Vec3 == Vec4)
11084       return SDValue();
11085 
11086     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
11087       return SDValue();
11088 
11089     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
11090         (Vec1 == Vec4 && Vec2 == Vec3)) {
11091       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
11092                          DAG.getTargetConstant(0, SL, MVT::i1));
11093     }
11094   }
11095   return SDValue();
11096 }
11097 
11098 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
11099                                               DAGCombinerInfo &DCI) const {
11100   SelectionDAG &DAG = DCI.DAG;
11101   SDLoc SL(N);
11102 
11103   SDValue LHS = N->getOperand(0);
11104   SDValue RHS = N->getOperand(1);
11105   EVT VT = LHS.getValueType();
11106   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
11107 
11108   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
11109   if (!CRHS) {
11110     CRHS = dyn_cast<ConstantSDNode>(LHS);
11111     if (CRHS) {
11112       std::swap(LHS, RHS);
11113       CC = getSetCCSwappedOperands(CC);
11114     }
11115   }
11116 
11117   if (CRHS) {
11118     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
11119         isBoolSGPR(LHS.getOperand(0))) {
11120       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
11121       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
11122       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
11123       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
11124       if ((CRHS->isAllOnes() &&
11125            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
11126           (CRHS->isZero() &&
11127            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
11128         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
11129                            DAG.getConstant(-1, SL, MVT::i1));
11130       if ((CRHS->isAllOnes() &&
11131            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
11132           (CRHS->isZero() &&
11133            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
11134         return LHS.getOperand(0);
11135     }
11136 
11137     const APInt &CRHSVal = CRHS->getAPIntValue();
11138     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
11139         LHS.getOpcode() == ISD::SELECT &&
11140         isa<ConstantSDNode>(LHS.getOperand(1)) &&
11141         isa<ConstantSDNode>(LHS.getOperand(2)) &&
11142         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
11143         isBoolSGPR(LHS.getOperand(0))) {
11144       // Given CT != FT:
11145       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
11146       // setcc (select cc, CT, CF), CF, ne => cc
11147       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
11148       // setcc (select cc, CT, CF), CT, eq => cc
11149       const APInt &CT = LHS.getConstantOperandAPInt(1);
11150       const APInt &CF = LHS.getConstantOperandAPInt(2);
11151 
11152       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
11153           (CT == CRHSVal && CC == ISD::SETNE))
11154         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
11155                            DAG.getConstant(-1, SL, MVT::i1));
11156       if ((CF == CRHSVal && CC == ISD::SETNE) ||
11157           (CT == CRHSVal && CC == ISD::SETEQ))
11158         return LHS.getOperand(0);
11159     }
11160   }
11161 
11162   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
11163                                            VT != MVT::f16))
11164     return SDValue();
11165 
11166   // Match isinf/isfinite pattern
11167   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
11168   // (fcmp one (fabs x), inf) -> (fp_class x,
11169   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
11170   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
11171     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
11172     if (!CRHS)
11173       return SDValue();
11174 
11175     const APFloat &APF = CRHS->getValueAPF();
11176     if (APF.isInfinity() && !APF.isNegative()) {
11177       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
11178                                  SIInstrFlags::N_INFINITY;
11179       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
11180                                     SIInstrFlags::P_ZERO |
11181                                     SIInstrFlags::N_NORMAL |
11182                                     SIInstrFlags::P_NORMAL |
11183                                     SIInstrFlags::N_SUBNORMAL |
11184                                     SIInstrFlags::P_SUBNORMAL;
11185       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
11186       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
11187                          DAG.getConstant(Mask, SL, MVT::i32));
11188     }
11189   }
11190 
11191   return SDValue();
11192 }
11193 
11194 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
11195                                                      DAGCombinerInfo &DCI) const {
11196   SelectionDAG &DAG = DCI.DAG;
11197   SDLoc SL(N);
11198   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
11199 
11200   SDValue Src = N->getOperand(0);
11201   SDValue Shift = N->getOperand(0);
11202 
11203   // TODO: Extend type shouldn't matter (assuming legal types).
11204   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
11205     Shift = Shift.getOperand(0);
11206 
11207   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
11208     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
11209     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
11210     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
11211     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
11212     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
11213     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
11214       SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0),
11215                                  SDLoc(Shift.getOperand(0)), MVT::i32);
11216 
11217       unsigned ShiftOffset = 8 * Offset;
11218       if (Shift.getOpcode() == ISD::SHL)
11219         ShiftOffset -= C->getZExtValue();
11220       else
11221         ShiftOffset += C->getZExtValue();
11222 
11223       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
11224         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
11225                            MVT::f32, Shifted);
11226       }
11227     }
11228   }
11229 
11230   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11231   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
11232   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
11233     // We simplified Src. If this node is not dead, visit it again so it is
11234     // folded properly.
11235     if (N->getOpcode() != ISD::DELETED_NODE)
11236       DCI.AddToWorklist(N);
11237     return SDValue(N, 0);
11238   }
11239 
11240   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
11241   if (SDValue DemandedSrc =
11242           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
11243     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
11244 
11245   return SDValue();
11246 }
11247 
11248 SDValue SITargetLowering::performClampCombine(SDNode *N,
11249                                               DAGCombinerInfo &DCI) const {
11250   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
11251   if (!CSrc)
11252     return SDValue();
11253 
11254   const MachineFunction &MF = DCI.DAG.getMachineFunction();
11255   const APFloat &F = CSrc->getValueAPF();
11256   APFloat Zero = APFloat::getZero(F.getSemantics());
11257   if (F < Zero ||
11258       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
11259     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
11260   }
11261 
11262   APFloat One(F.getSemantics(), "1.0");
11263   if (F > One)
11264     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
11265 
11266   return SDValue(CSrc, 0);
11267 }
11268 
11269 
11270 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
11271                                             DAGCombinerInfo &DCI) const {
11272   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
11273     return SDValue();
11274   switch (N->getOpcode()) {
11275   case ISD::ADD:
11276     return performAddCombine(N, DCI);
11277   case ISD::SUB:
11278     return performSubCombine(N, DCI);
11279   case ISD::ADDCARRY:
11280   case ISD::SUBCARRY:
11281     return performAddCarrySubCarryCombine(N, DCI);
11282   case ISD::FADD:
11283     return performFAddCombine(N, DCI);
11284   case ISD::FSUB:
11285     return performFSubCombine(N, DCI);
11286   case ISD::SETCC:
11287     return performSetCCCombine(N, DCI);
11288   case ISD::FMAXNUM:
11289   case ISD::FMINNUM:
11290   case ISD::FMAXNUM_IEEE:
11291   case ISD::FMINNUM_IEEE:
11292   case ISD::SMAX:
11293   case ISD::SMIN:
11294   case ISD::UMAX:
11295   case ISD::UMIN:
11296   case AMDGPUISD::FMIN_LEGACY:
11297   case AMDGPUISD::FMAX_LEGACY:
11298     return performMinMaxCombine(N, DCI);
11299   case ISD::FMA:
11300     return performFMACombine(N, DCI);
11301   case ISD::AND:
11302     return performAndCombine(N, DCI);
11303   case ISD::OR:
11304     return performOrCombine(N, DCI);
11305   case ISD::XOR:
11306     return performXorCombine(N, DCI);
11307   case ISD::ZERO_EXTEND:
11308     return performZeroExtendCombine(N, DCI);
11309   case ISD::SIGN_EXTEND_INREG:
11310     return performSignExtendInRegCombine(N , DCI);
11311   case AMDGPUISD::FP_CLASS:
11312     return performClassCombine(N, DCI);
11313   case ISD::FCANONICALIZE:
11314     return performFCanonicalizeCombine(N, DCI);
11315   case AMDGPUISD::RCP:
11316     return performRcpCombine(N, DCI);
11317   case AMDGPUISD::FRACT:
11318   case AMDGPUISD::RSQ:
11319   case AMDGPUISD::RCP_LEGACY:
11320   case AMDGPUISD::RCP_IFLAG:
11321   case AMDGPUISD::RSQ_CLAMP:
11322   case AMDGPUISD::LDEXP: {
11323     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
11324     SDValue Src = N->getOperand(0);
11325     if (Src.isUndef())
11326       return Src;
11327     break;
11328   }
11329   case ISD::SINT_TO_FP:
11330   case ISD::UINT_TO_FP:
11331     return performUCharToFloatCombine(N, DCI);
11332   case AMDGPUISD::CVT_F32_UBYTE0:
11333   case AMDGPUISD::CVT_F32_UBYTE1:
11334   case AMDGPUISD::CVT_F32_UBYTE2:
11335   case AMDGPUISD::CVT_F32_UBYTE3:
11336     return performCvtF32UByteNCombine(N, DCI);
11337   case AMDGPUISD::FMED3:
11338     return performFMed3Combine(N, DCI);
11339   case AMDGPUISD::CVT_PKRTZ_F16_F32:
11340     return performCvtPkRTZCombine(N, DCI);
11341   case AMDGPUISD::CLAMP:
11342     return performClampCombine(N, DCI);
11343   case ISD::SCALAR_TO_VECTOR: {
11344     SelectionDAG &DAG = DCI.DAG;
11345     EVT VT = N->getValueType(0);
11346 
11347     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
11348     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
11349       SDLoc SL(N);
11350       SDValue Src = N->getOperand(0);
11351       EVT EltVT = Src.getValueType();
11352       if (EltVT == MVT::f16)
11353         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
11354 
11355       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
11356       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
11357     }
11358 
11359     break;
11360   }
11361   case ISD::EXTRACT_VECTOR_ELT:
11362     return performExtractVectorEltCombine(N, DCI);
11363   case ISD::INSERT_VECTOR_ELT:
11364     return performInsertVectorEltCombine(N, DCI);
11365   case ISD::LOAD: {
11366     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
11367       return Widended;
11368     LLVM_FALLTHROUGH;
11369   }
11370   default: {
11371     if (!DCI.isBeforeLegalize()) {
11372       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
11373         return performMemSDNodeCombine(MemNode, DCI);
11374     }
11375 
11376     break;
11377   }
11378   }
11379 
11380   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
11381 }
11382 
11383 /// Helper function for adjustWritemask
11384 static unsigned SubIdx2Lane(unsigned Idx) {
11385   switch (Idx) {
11386   default: return ~0u;
11387   case AMDGPU::sub0: return 0;
11388   case AMDGPU::sub1: return 1;
11389   case AMDGPU::sub2: return 2;
11390   case AMDGPU::sub3: return 3;
11391   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
11392   }
11393 }
11394 
11395 /// Adjust the writemask of MIMG instructions
11396 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
11397                                           SelectionDAG &DAG) const {
11398   unsigned Opcode = Node->getMachineOpcode();
11399 
11400   // Subtract 1 because the vdata output is not a MachineSDNode operand.
11401   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
11402   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
11403     return Node; // not implemented for D16
11404 
11405   SDNode *Users[5] = { nullptr };
11406   unsigned Lane = 0;
11407   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
11408   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
11409   unsigned NewDmask = 0;
11410   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
11411   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
11412   bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
11413                   Node->getConstantOperandVal(LWEIdx))
11414                      ? true
11415                      : false;
11416   unsigned TFCLane = 0;
11417   bool HasChain = Node->getNumValues() > 1;
11418 
11419   if (OldDmask == 0) {
11420     // These are folded out, but on the chance it happens don't assert.
11421     return Node;
11422   }
11423 
11424   unsigned OldBitsSet = countPopulation(OldDmask);
11425   // Work out which is the TFE/LWE lane if that is enabled.
11426   if (UsesTFC) {
11427     TFCLane = OldBitsSet;
11428   }
11429 
11430   // Try to figure out the used register components
11431   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
11432        I != E; ++I) {
11433 
11434     // Don't look at users of the chain.
11435     if (I.getUse().getResNo() != 0)
11436       continue;
11437 
11438     // Abort if we can't understand the usage
11439     if (!I->isMachineOpcode() ||
11440         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
11441       return Node;
11442 
11443     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
11444     // Note that subregs are packed, i.e. Lane==0 is the first bit set
11445     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
11446     // set, etc.
11447     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
11448     if (Lane == ~0u)
11449       return Node;
11450 
11451     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
11452     if (UsesTFC && Lane == TFCLane) {
11453       Users[Lane] = *I;
11454     } else {
11455       // Set which texture component corresponds to the lane.
11456       unsigned Comp;
11457       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
11458         Comp = countTrailingZeros(Dmask);
11459         Dmask &= ~(1 << Comp);
11460       }
11461 
11462       // Abort if we have more than one user per component.
11463       if (Users[Lane])
11464         return Node;
11465 
11466       Users[Lane] = *I;
11467       NewDmask |= 1 << Comp;
11468     }
11469   }
11470 
11471   // Don't allow 0 dmask, as hardware assumes one channel enabled.
11472   bool NoChannels = !NewDmask;
11473   if (NoChannels) {
11474     if (!UsesTFC) {
11475       // No uses of the result and not using TFC. Then do nothing.
11476       return Node;
11477     }
11478     // If the original dmask has one channel - then nothing to do
11479     if (OldBitsSet == 1)
11480       return Node;
11481     // Use an arbitrary dmask - required for the instruction to work
11482     NewDmask = 1;
11483   }
11484   // Abort if there's no change
11485   if (NewDmask == OldDmask)
11486     return Node;
11487 
11488   unsigned BitsSet = countPopulation(NewDmask);
11489 
11490   // Check for TFE or LWE - increase the number of channels by one to account
11491   // for the extra return value
11492   // This will need adjustment for D16 if this is also included in
11493   // adjustWriteMask (this function) but at present D16 are excluded.
11494   unsigned NewChannels = BitsSet + UsesTFC;
11495 
11496   int NewOpcode =
11497       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
11498   assert(NewOpcode != -1 &&
11499          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
11500          "failed to find equivalent MIMG op");
11501 
11502   // Adjust the writemask in the node
11503   SmallVector<SDValue, 12> Ops;
11504   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
11505   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
11506   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11507 
11508   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11509 
11510   MVT ResultVT = NewChannels == 1 ?
11511     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11512                            NewChannels == 5 ? 8 : NewChannels);
11513   SDVTList NewVTList = HasChain ?
11514     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11515 
11516 
11517   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11518                                               NewVTList, Ops);
11519 
11520   if (HasChain) {
11521     // Update chain.
11522     DAG.setNodeMemRefs(NewNode, Node->memoperands());
11523     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11524   }
11525 
11526   if (NewChannels == 1) {
11527     assert(Node->hasNUsesOfValue(1, 0));
11528     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11529                                       SDLoc(Node), Users[Lane]->getValueType(0),
11530                                       SDValue(NewNode, 0));
11531     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11532     return nullptr;
11533   }
11534 
11535   // Update the users of the node with the new indices
11536   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11537     SDNode *User = Users[i];
11538     if (!User) {
11539       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11540       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11541       if (i || !NoChannels)
11542         continue;
11543     } else {
11544       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11545       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11546     }
11547 
11548     switch (Idx) {
11549     default: break;
11550     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11551     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11552     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11553     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11554     }
11555   }
11556 
11557   DAG.RemoveDeadNode(Node);
11558   return nullptr;
11559 }
11560 
11561 static bool isFrameIndexOp(SDValue Op) {
11562   if (Op.getOpcode() == ISD::AssertZext)
11563     Op = Op.getOperand(0);
11564 
11565   return isa<FrameIndexSDNode>(Op);
11566 }
11567 
11568 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11569 /// with frame index operands.
11570 /// LLVM assumes that inputs are to these instructions are registers.
11571 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11572                                                         SelectionDAG &DAG) const {
11573   if (Node->getOpcode() == ISD::CopyToReg) {
11574     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11575     SDValue SrcVal = Node->getOperand(2);
11576 
11577     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11578     // to try understanding copies to physical registers.
11579     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11580       SDLoc SL(Node);
11581       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11582       SDValue VReg = DAG.getRegister(
11583         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11584 
11585       SDNode *Glued = Node->getGluedNode();
11586       SDValue ToVReg
11587         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11588                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11589       SDValue ToResultReg
11590         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11591                            VReg, ToVReg.getValue(1));
11592       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11593       DAG.RemoveDeadNode(Node);
11594       return ToResultReg.getNode();
11595     }
11596   }
11597 
11598   SmallVector<SDValue, 8> Ops;
11599   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11600     if (!isFrameIndexOp(Node->getOperand(i))) {
11601       Ops.push_back(Node->getOperand(i));
11602       continue;
11603     }
11604 
11605     SDLoc DL(Node);
11606     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11607                                      Node->getOperand(i).getValueType(),
11608                                      Node->getOperand(i)), 0));
11609   }
11610 
11611   return DAG.UpdateNodeOperands(Node, Ops);
11612 }
11613 
11614 /// Fold the instructions after selecting them.
11615 /// Returns null if users were already updated.
11616 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11617                                           SelectionDAG &DAG) const {
11618   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11619   unsigned Opcode = Node->getMachineOpcode();
11620 
11621   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11622       !TII->isGather4(Opcode) &&
11623       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11624     return adjustWritemask(Node, DAG);
11625   }
11626 
11627   if (Opcode == AMDGPU::INSERT_SUBREG ||
11628       Opcode == AMDGPU::REG_SEQUENCE) {
11629     legalizeTargetIndependentNode(Node, DAG);
11630     return Node;
11631   }
11632 
11633   switch (Opcode) {
11634   case AMDGPU::V_DIV_SCALE_F32_e64:
11635   case AMDGPU::V_DIV_SCALE_F64_e64: {
11636     // Satisfy the operand register constraint when one of the inputs is
11637     // undefined. Ordinarily each undef value will have its own implicit_def of
11638     // a vreg, so force these to use a single register.
11639     SDValue Src0 = Node->getOperand(1);
11640     SDValue Src1 = Node->getOperand(3);
11641     SDValue Src2 = Node->getOperand(5);
11642 
11643     if ((Src0.isMachineOpcode() &&
11644          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11645         (Src0 == Src1 || Src0 == Src2))
11646       break;
11647 
11648     MVT VT = Src0.getValueType().getSimpleVT();
11649     const TargetRegisterClass *RC =
11650         getRegClassFor(VT, Src0.getNode()->isDivergent());
11651 
11652     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11653     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11654 
11655     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11656                                       UndefReg, Src0, SDValue());
11657 
11658     // src0 must be the same register as src1 or src2, even if the value is
11659     // undefined, so make sure we don't violate this constraint.
11660     if (Src0.isMachineOpcode() &&
11661         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11662       if (Src1.isMachineOpcode() &&
11663           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11664         Src0 = Src1;
11665       else if (Src2.isMachineOpcode() &&
11666                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11667         Src0 = Src2;
11668       else {
11669         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11670         Src0 = UndefReg;
11671         Src1 = UndefReg;
11672       }
11673     } else
11674       break;
11675 
11676     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11677     Ops[1] = Src0;
11678     Ops[3] = Src1;
11679     Ops[5] = Src2;
11680     Ops.push_back(ImpDef.getValue(1));
11681     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11682   }
11683   default:
11684     break;
11685   }
11686 
11687   return Node;
11688 }
11689 
11690 // Any MIMG instructions that use tfe or lwe require an initialization of the
11691 // result register that will be written in the case of a memory access failure.
11692 // The required code is also added to tie this init code to the result of the
11693 // img instruction.
11694 void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
11695   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11696   const SIRegisterInfo &TRI = TII->getRegisterInfo();
11697   MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11698   MachineBasicBlock &MBB = *MI.getParent();
11699 
11700   MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
11701   MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
11702   MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
11703 
11704   if (!TFE && !LWE) // intersect_ray
11705     return;
11706 
11707   unsigned TFEVal = TFE ? TFE->getImm() : 0;
11708   unsigned LWEVal = LWE->getImm();
11709   unsigned D16Val = D16 ? D16->getImm() : 0;
11710 
11711   if (!TFEVal && !LWEVal)
11712     return;
11713 
11714   // At least one of TFE or LWE are non-zero
11715   // We have to insert a suitable initialization of the result value and
11716   // tie this to the dest of the image instruction.
11717 
11718   const DebugLoc &DL = MI.getDebugLoc();
11719 
11720   int DstIdx =
11721       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
11722 
11723   // Calculate which dword we have to initialize to 0.
11724   MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
11725 
11726   // check that dmask operand is found.
11727   assert(MO_Dmask && "Expected dmask operand in instruction");
11728 
11729   unsigned dmask = MO_Dmask->getImm();
11730   // Determine the number of active lanes taking into account the
11731   // Gather4 special case
11732   unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask);
11733 
11734   bool Packed = !Subtarget->hasUnpackedD16VMem();
11735 
11736   unsigned InitIdx =
11737       D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
11738 
11739   // Abandon attempt if the dst size isn't large enough
11740   // - this is in fact an error but this is picked up elsewhere and
11741   // reported correctly.
11742   uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
11743   if (DstSize < InitIdx)
11744     return;
11745 
11746   // Create a register for the initialization value.
11747   Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11748   unsigned NewDst = 0; // Final initialized value will be in here
11749 
11750   // If PRTStrictNull feature is enabled (the default) then initialize
11751   // all the result registers to 0, otherwise just the error indication
11752   // register (VGPRn+1)
11753   unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
11754   unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
11755 
11756   BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
11757   for (; SizeLeft; SizeLeft--, CurrIdx++) {
11758     NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11759     // Initialize dword
11760     Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
11761     BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
11762       .addImm(0);
11763     // Insert into the super-reg
11764     BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
11765       .addReg(PrevDst)
11766       .addReg(SubReg)
11767       .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
11768 
11769     PrevDst = NewDst;
11770   }
11771 
11772   // Add as an implicit operand
11773   MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
11774 
11775   // Tie the just added implicit operand to the dst
11776   MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
11777 }
11778 
11779 /// Assign the register class depending on the number of
11780 /// bits set in the writemask
11781 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11782                                                      SDNode *Node) const {
11783   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11784 
11785   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11786 
11787   if (TII->isVOP3(MI.getOpcode())) {
11788     // Make sure constant bus requirements are respected.
11789     TII->legalizeOperandsVOP3(MRI, MI);
11790 
11791     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11792     // This saves a chain-copy of registers and better balance register
11793     // use between vgpr and agpr as agpr tuples tend to be big.
11794     if (MI.getDesc().OpInfo) {
11795       unsigned Opc = MI.getOpcode();
11796       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11797       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11798                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11799         if (I == -1)
11800           break;
11801         MachineOperand &Op = MI.getOperand(I);
11802         if (!Op.isReg() || !Op.getReg().isVirtual())
11803           continue;
11804         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11805         if (!TRI->hasAGPRs(RC))
11806           continue;
11807         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11808         if (!Src || !Src->isCopy() ||
11809             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11810           continue;
11811         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11812         // All uses of agpr64 and agpr32 can also accept vgpr except for
11813         // v_accvgpr_read, but we do not produce agpr reads during selection,
11814         // so no use checks are needed.
11815         MRI.setRegClass(Op.getReg(), NewRC);
11816       }
11817 
11818       // Resolve the rest of AV operands to AGPRs.
11819       if (auto *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2)) {
11820         if (Src2->isReg() && Src2->getReg().isVirtual()) {
11821           auto *RC = TRI->getRegClassForReg(MRI, Src2->getReg());
11822           if (TRI->isVectorSuperClass(RC)) {
11823             auto *NewRC = TRI->getEquivalentAGPRClass(RC);
11824             MRI.setRegClass(Src2->getReg(), NewRC);
11825             if (Src2->isTied())
11826               MRI.setRegClass(MI.getOperand(0).getReg(), NewRC);
11827           }
11828         }
11829       }
11830     }
11831 
11832     return;
11833   }
11834 
11835   if (TII->isMIMG(MI) && !MI.mayStore())
11836     AddIMGInit(MI);
11837 }
11838 
11839 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11840                               uint64_t Val) {
11841   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11842   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11843 }
11844 
11845 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11846                                                 const SDLoc &DL,
11847                                                 SDValue Ptr) const {
11848   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11849 
11850   // Build the half of the subregister with the constants before building the
11851   // full 128-bit register. If we are building multiple resource descriptors,
11852   // this will allow CSEing of the 2-component register.
11853   const SDValue Ops0[] = {
11854     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11855     buildSMovImm32(DAG, DL, 0),
11856     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11857     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11858     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11859   };
11860 
11861   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11862                                                 MVT::v2i32, Ops0), 0);
11863 
11864   // Combine the constants and the pointer.
11865   const SDValue Ops1[] = {
11866     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11867     Ptr,
11868     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11869     SubRegHi,
11870     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11871   };
11872 
11873   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11874 }
11875 
11876 /// Return a resource descriptor with the 'Add TID' bit enabled
11877 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11878 ///        of the resource descriptor) to create an offset, which is added to
11879 ///        the resource pointer.
11880 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11881                                            SDValue Ptr, uint32_t RsrcDword1,
11882                                            uint64_t RsrcDword2And3) const {
11883   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11884   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11885   if (RsrcDword1) {
11886     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11887                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11888                     0);
11889   }
11890 
11891   SDValue DataLo = buildSMovImm32(DAG, DL,
11892                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11893   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11894 
11895   const SDValue Ops[] = {
11896     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11897     PtrLo,
11898     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11899     PtrHi,
11900     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11901     DataLo,
11902     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11903     DataHi,
11904     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11905   };
11906 
11907   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11908 }
11909 
11910 //===----------------------------------------------------------------------===//
11911 //                         SI Inline Assembly Support
11912 //===----------------------------------------------------------------------===//
11913 
11914 std::pair<unsigned, const TargetRegisterClass *>
11915 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
11916                                                StringRef Constraint,
11917                                                MVT VT) const {
11918   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
11919 
11920   const TargetRegisterClass *RC = nullptr;
11921   if (Constraint.size() == 1) {
11922     const unsigned BitWidth = VT.getSizeInBits();
11923     switch (Constraint[0]) {
11924     default:
11925       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11926     case 's':
11927     case 'r':
11928       switch (BitWidth) {
11929       case 16:
11930         RC = &AMDGPU::SReg_32RegClass;
11931         break;
11932       case 64:
11933         RC = &AMDGPU::SGPR_64RegClass;
11934         break;
11935       default:
11936         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11937         if (!RC)
11938           return std::make_pair(0U, nullptr);
11939         break;
11940       }
11941       break;
11942     case 'v':
11943       switch (BitWidth) {
11944       case 16:
11945         RC = &AMDGPU::VGPR_32RegClass;
11946         break;
11947       default:
11948         RC = TRI->getVGPRClassForBitWidth(BitWidth);
11949         if (!RC)
11950           return std::make_pair(0U, nullptr);
11951         break;
11952       }
11953       break;
11954     case 'a':
11955       if (!Subtarget->hasMAIInsts())
11956         break;
11957       switch (BitWidth) {
11958       case 16:
11959         RC = &AMDGPU::AGPR_32RegClass;
11960         break;
11961       default:
11962         RC = TRI->getAGPRClassForBitWidth(BitWidth);
11963         if (!RC)
11964           return std::make_pair(0U, nullptr);
11965         break;
11966       }
11967       break;
11968     }
11969     // We actually support i128, i16 and f16 as inline parameters
11970     // even if they are not reported as legal
11971     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11972                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11973       return std::make_pair(0U, RC);
11974   }
11975 
11976   if (Constraint.startswith("{") && Constraint.endswith("}")) {
11977     StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
11978     if (RegName.consume_front("v")) {
11979       RC = &AMDGPU::VGPR_32RegClass;
11980     } else if (RegName.consume_front("s")) {
11981       RC = &AMDGPU::SGPR_32RegClass;
11982     } else if (RegName.consume_front("a")) {
11983       RC = &AMDGPU::AGPR_32RegClass;
11984     }
11985 
11986     if (RC) {
11987       uint32_t Idx;
11988       if (RegName.consume_front("[")) {
11989         uint32_t End;
11990         bool Failed = RegName.consumeInteger(10, Idx);
11991         Failed |= !RegName.consume_front(":");
11992         Failed |= RegName.consumeInteger(10, End);
11993         Failed |= !RegName.consume_back("]");
11994         if (!Failed) {
11995           uint32_t Width = (End - Idx + 1) * 32;
11996           MCRegister Reg = RC->getRegister(Idx);
11997           if (SIRegisterInfo::isVGPRClass(RC))
11998             RC = TRI->getVGPRClassForBitWidth(Width);
11999           else if (SIRegisterInfo::isSGPRClass(RC))
12000             RC = TRI->getSGPRClassForBitWidth(Width);
12001           else if (SIRegisterInfo::isAGPRClass(RC))
12002             RC = TRI->getAGPRClassForBitWidth(Width);
12003           if (RC) {
12004             Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC);
12005             return std::make_pair(Reg, RC);
12006           }
12007         }
12008       } else {
12009         bool Failed = RegName.getAsInteger(10, Idx);
12010         if (!Failed && Idx < RC->getNumRegs())
12011           return std::make_pair(RC->getRegister(Idx), RC);
12012       }
12013     }
12014   }
12015 
12016   auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
12017   if (Ret.first)
12018     Ret.second = TRI->getPhysRegClass(Ret.first);
12019 
12020   return Ret;
12021 }
12022 
12023 static bool isImmConstraint(StringRef Constraint) {
12024   if (Constraint.size() == 1) {
12025     switch (Constraint[0]) {
12026     default: break;
12027     case 'I':
12028     case 'J':
12029     case 'A':
12030     case 'B':
12031     case 'C':
12032       return true;
12033     }
12034   } else if (Constraint == "DA" ||
12035              Constraint == "DB") {
12036     return true;
12037   }
12038   return false;
12039 }
12040 
12041 SITargetLowering::ConstraintType
12042 SITargetLowering::getConstraintType(StringRef Constraint) const {
12043   if (Constraint.size() == 1) {
12044     switch (Constraint[0]) {
12045     default: break;
12046     case 's':
12047     case 'v':
12048     case 'a':
12049       return C_RegisterClass;
12050     }
12051   }
12052   if (isImmConstraint(Constraint)) {
12053     return C_Other;
12054   }
12055   return TargetLowering::getConstraintType(Constraint);
12056 }
12057 
12058 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
12059   if (!AMDGPU::isInlinableIntLiteral(Val)) {
12060     Val = Val & maskTrailingOnes<uint64_t>(Size);
12061   }
12062   return Val;
12063 }
12064 
12065 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12066                                                     std::string &Constraint,
12067                                                     std::vector<SDValue> &Ops,
12068                                                     SelectionDAG &DAG) const {
12069   if (isImmConstraint(Constraint)) {
12070     uint64_t Val;
12071     if (getAsmOperandConstVal(Op, Val) &&
12072         checkAsmConstraintVal(Op, Constraint, Val)) {
12073       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
12074       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
12075     }
12076   } else {
12077     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12078   }
12079 }
12080 
12081 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
12082   unsigned Size = Op.getScalarValueSizeInBits();
12083   if (Size > 64)
12084     return false;
12085 
12086   if (Size == 16 && !Subtarget->has16BitInsts())
12087     return false;
12088 
12089   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12090     Val = C->getSExtValue();
12091     return true;
12092   }
12093   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
12094     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
12095     return true;
12096   }
12097   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
12098     if (Size != 16 || Op.getNumOperands() != 2)
12099       return false;
12100     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
12101       return false;
12102     if (ConstantSDNode *C = V->getConstantSplatNode()) {
12103       Val = C->getSExtValue();
12104       return true;
12105     }
12106     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
12107       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
12108       return true;
12109     }
12110   }
12111 
12112   return false;
12113 }
12114 
12115 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
12116                                              const std::string &Constraint,
12117                                              uint64_t Val) const {
12118   if (Constraint.size() == 1) {
12119     switch (Constraint[0]) {
12120     case 'I':
12121       return AMDGPU::isInlinableIntLiteral(Val);
12122     case 'J':
12123       return isInt<16>(Val);
12124     case 'A':
12125       return checkAsmConstraintValA(Op, Val);
12126     case 'B':
12127       return isInt<32>(Val);
12128     case 'C':
12129       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
12130              AMDGPU::isInlinableIntLiteral(Val);
12131     default:
12132       break;
12133     }
12134   } else if (Constraint.size() == 2) {
12135     if (Constraint == "DA") {
12136       int64_t HiBits = static_cast<int32_t>(Val >> 32);
12137       int64_t LoBits = static_cast<int32_t>(Val);
12138       return checkAsmConstraintValA(Op, HiBits, 32) &&
12139              checkAsmConstraintValA(Op, LoBits, 32);
12140     }
12141     if (Constraint == "DB") {
12142       return true;
12143     }
12144   }
12145   llvm_unreachable("Invalid asm constraint");
12146 }
12147 
12148 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
12149                                               uint64_t Val,
12150                                               unsigned MaxSize) const {
12151   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
12152   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
12153   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
12154       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
12155       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
12156     return true;
12157   }
12158   return false;
12159 }
12160 
12161 static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
12162   switch (UnalignedClassID) {
12163   case AMDGPU::VReg_64RegClassID:
12164     return AMDGPU::VReg_64_Align2RegClassID;
12165   case AMDGPU::VReg_96RegClassID:
12166     return AMDGPU::VReg_96_Align2RegClassID;
12167   case AMDGPU::VReg_128RegClassID:
12168     return AMDGPU::VReg_128_Align2RegClassID;
12169   case AMDGPU::VReg_160RegClassID:
12170     return AMDGPU::VReg_160_Align2RegClassID;
12171   case AMDGPU::VReg_192RegClassID:
12172     return AMDGPU::VReg_192_Align2RegClassID;
12173   case AMDGPU::VReg_224RegClassID:
12174     return AMDGPU::VReg_224_Align2RegClassID;
12175   case AMDGPU::VReg_256RegClassID:
12176     return AMDGPU::VReg_256_Align2RegClassID;
12177   case AMDGPU::VReg_512RegClassID:
12178     return AMDGPU::VReg_512_Align2RegClassID;
12179   case AMDGPU::VReg_1024RegClassID:
12180     return AMDGPU::VReg_1024_Align2RegClassID;
12181   case AMDGPU::AReg_64RegClassID:
12182     return AMDGPU::AReg_64_Align2RegClassID;
12183   case AMDGPU::AReg_96RegClassID:
12184     return AMDGPU::AReg_96_Align2RegClassID;
12185   case AMDGPU::AReg_128RegClassID:
12186     return AMDGPU::AReg_128_Align2RegClassID;
12187   case AMDGPU::AReg_160RegClassID:
12188     return AMDGPU::AReg_160_Align2RegClassID;
12189   case AMDGPU::AReg_192RegClassID:
12190     return AMDGPU::AReg_192_Align2RegClassID;
12191   case AMDGPU::AReg_256RegClassID:
12192     return AMDGPU::AReg_256_Align2RegClassID;
12193   case AMDGPU::AReg_512RegClassID:
12194     return AMDGPU::AReg_512_Align2RegClassID;
12195   case AMDGPU::AReg_1024RegClassID:
12196     return AMDGPU::AReg_1024_Align2RegClassID;
12197   default:
12198     return -1;
12199   }
12200 }
12201 
12202 // Figure out which registers should be reserved for stack access. Only after
12203 // the function is legalized do we know all of the non-spill stack objects or if
12204 // calls are present.
12205 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
12206   MachineRegisterInfo &MRI = MF.getRegInfo();
12207   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12208   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
12209   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12210   const SIInstrInfo *TII = ST.getInstrInfo();
12211 
12212   if (Info->isEntryFunction()) {
12213     // Callable functions have fixed registers used for stack access.
12214     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
12215   }
12216 
12217   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
12218                              Info->getStackPtrOffsetReg()));
12219   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
12220     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
12221 
12222   // We need to worry about replacing the default register with itself in case
12223   // of MIR testcases missing the MFI.
12224   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
12225     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
12226 
12227   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
12228     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
12229 
12230   Info->limitOccupancy(MF);
12231 
12232   if (ST.isWave32() && !MF.empty()) {
12233     for (auto &MBB : MF) {
12234       for (auto &MI : MBB) {
12235         TII->fixImplicitOperands(MI);
12236       }
12237     }
12238   }
12239 
12240   // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
12241   // classes if required. Ideally the register class constraints would differ
12242   // per-subtarget, but there's no easy way to achieve that right now. This is
12243   // not a problem for VGPRs because the correctly aligned VGPR class is implied
12244   // from using them as the register class for legal types.
12245   if (ST.needsAlignedVGPRs()) {
12246     for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
12247       const Register Reg = Register::index2VirtReg(I);
12248       const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
12249       if (!RC)
12250         continue;
12251       int NewClassID = getAlignedAGPRClassID(RC->getID());
12252       if (NewClassID != -1)
12253         MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
12254     }
12255   }
12256 
12257   TargetLoweringBase::finalizeLowering(MF);
12258 }
12259 
12260 void SITargetLowering::computeKnownBitsForFrameIndex(
12261   const int FI, KnownBits &Known, const MachineFunction &MF) const {
12262   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
12263 
12264   // Set the high bits to zero based on the maximum allowed scratch size per
12265   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
12266   // calculation won't overflow, so assume the sign bit is never set.
12267   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
12268 }
12269 
12270 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
12271                                    KnownBits &Known, unsigned Dim) {
12272   unsigned MaxValue =
12273       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
12274   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
12275 }
12276 
12277 void SITargetLowering::computeKnownBitsForTargetInstr(
12278     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
12279     const MachineRegisterInfo &MRI, unsigned Depth) const {
12280   const MachineInstr *MI = MRI.getVRegDef(R);
12281   switch (MI->getOpcode()) {
12282   case AMDGPU::G_INTRINSIC: {
12283     switch (MI->getIntrinsicID()) {
12284     case Intrinsic::amdgcn_workitem_id_x:
12285       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
12286       break;
12287     case Intrinsic::amdgcn_workitem_id_y:
12288       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
12289       break;
12290     case Intrinsic::amdgcn_workitem_id_z:
12291       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
12292       break;
12293     case Intrinsic::amdgcn_mbcnt_lo:
12294     case Intrinsic::amdgcn_mbcnt_hi: {
12295       // These return at most the wavefront size - 1.
12296       unsigned Size = MRI.getType(R).getSizeInBits();
12297       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
12298       break;
12299     }
12300     case Intrinsic::amdgcn_groupstaticsize: {
12301       // We can report everything over the maximum size as 0. We can't report
12302       // based on the actual size because we don't know if it's accurate or not
12303       // at any given point.
12304       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
12305       break;
12306     }
12307     }
12308     break;
12309   }
12310   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
12311     Known.Zero.setHighBits(24);
12312     break;
12313   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
12314     Known.Zero.setHighBits(16);
12315     break;
12316   }
12317 }
12318 
12319 Align SITargetLowering::computeKnownAlignForTargetInstr(
12320   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
12321   unsigned Depth) const {
12322   const MachineInstr *MI = MRI.getVRegDef(R);
12323   switch (MI->getOpcode()) {
12324   case AMDGPU::G_INTRINSIC:
12325   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
12326     // FIXME: Can this move to generic code? What about the case where the call
12327     // site specifies a lower alignment?
12328     Intrinsic::ID IID = MI->getIntrinsicID();
12329     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
12330     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
12331     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
12332       return *RetAlign;
12333     return Align(1);
12334   }
12335   default:
12336     return Align(1);
12337   }
12338 }
12339 
12340 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12341   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
12342   const Align CacheLineAlign = Align(64);
12343 
12344   // Pre-GFX10 target did not benefit from loop alignment
12345   if (!ML || DisableLoopAlignment ||
12346       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
12347       getSubtarget()->hasInstFwdPrefetchBug())
12348     return PrefAlign;
12349 
12350   // On GFX10 I$ is 4 x 64 bytes cache lines.
12351   // By default prefetcher keeps one cache line behind and reads two ahead.
12352   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
12353   // behind and one ahead.
12354   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
12355   // If loop fits 64 bytes it always spans no more than two cache lines and
12356   // does not need an alignment.
12357   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
12358   // Else if loop is less or equal 192 bytes we need two lines behind.
12359 
12360   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12361   const MachineBasicBlock *Header = ML->getHeader();
12362   if (Header->getAlignment() != PrefAlign)
12363     return Header->getAlignment(); // Already processed.
12364 
12365   unsigned LoopSize = 0;
12366   for (const MachineBasicBlock *MBB : ML->blocks()) {
12367     // If inner loop block is aligned assume in average half of the alignment
12368     // size to be added as nops.
12369     if (MBB != Header)
12370       LoopSize += MBB->getAlignment().value() / 2;
12371 
12372     for (const MachineInstr &MI : *MBB) {
12373       LoopSize += TII->getInstSizeInBytes(MI);
12374       if (LoopSize > 192)
12375         return PrefAlign;
12376     }
12377   }
12378 
12379   if (LoopSize <= 64)
12380     return PrefAlign;
12381 
12382   if (LoopSize <= 128)
12383     return CacheLineAlign;
12384 
12385   // If any of parent loops is surrounded by prefetch instructions do not
12386   // insert new for inner loop, which would reset parent's settings.
12387   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
12388     if (MachineBasicBlock *Exit = P->getExitBlock()) {
12389       auto I = Exit->getFirstNonDebugInstr();
12390       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
12391         return CacheLineAlign;
12392     }
12393   }
12394 
12395   MachineBasicBlock *Pre = ML->getLoopPreheader();
12396   MachineBasicBlock *Exit = ML->getExitBlock();
12397 
12398   if (Pre && Exit) {
12399     auto PreTerm = Pre->getFirstTerminator();
12400     if (PreTerm == Pre->begin() ||
12401         std::prev(PreTerm)->getOpcode() != AMDGPU::S_INST_PREFETCH)
12402       BuildMI(*Pre, PreTerm, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH))
12403           .addImm(1); // prefetch 2 lines behind PC
12404 
12405     auto ExitHead = Exit->getFirstNonDebugInstr();
12406     if (ExitHead == Exit->end() ||
12407         ExitHead->getOpcode() != AMDGPU::S_INST_PREFETCH)
12408       BuildMI(*Exit, ExitHead, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH))
12409           .addImm(2); // prefetch 1 line behind PC
12410   }
12411 
12412   return CacheLineAlign;
12413 }
12414 
12415 LLVM_ATTRIBUTE_UNUSED
12416 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
12417   assert(N->getOpcode() == ISD::CopyFromReg);
12418   do {
12419     // Follow the chain until we find an INLINEASM node.
12420     N = N->getOperand(0).getNode();
12421     if (N->getOpcode() == ISD::INLINEASM ||
12422         N->getOpcode() == ISD::INLINEASM_BR)
12423       return true;
12424   } while (N->getOpcode() == ISD::CopyFromReg);
12425   return false;
12426 }
12427 
12428 bool SITargetLowering::isSDNodeSourceOfDivergence(
12429     const SDNode *N, FunctionLoweringInfo *FLI,
12430     LegacyDivergenceAnalysis *KDA) const {
12431   switch (N->getOpcode()) {
12432   case ISD::CopyFromReg: {
12433     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
12434     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
12435     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12436     Register Reg = R->getReg();
12437 
12438     // FIXME: Why does this need to consider isLiveIn?
12439     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
12440       return !TRI->isSGPRReg(MRI, Reg);
12441 
12442     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
12443       return KDA->isDivergent(V);
12444 
12445     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
12446     return !TRI->isSGPRReg(MRI, Reg);
12447   }
12448   case ISD::LOAD: {
12449     const LoadSDNode *L = cast<LoadSDNode>(N);
12450     unsigned AS = L->getAddressSpace();
12451     // A flat load may access private memory.
12452     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
12453   }
12454   case ISD::CALLSEQ_END:
12455     return true;
12456   case ISD::INTRINSIC_WO_CHAIN:
12457     return AMDGPU::isIntrinsicSourceOfDivergence(
12458         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
12459   case ISD::INTRINSIC_W_CHAIN:
12460     return AMDGPU::isIntrinsicSourceOfDivergence(
12461         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
12462   case AMDGPUISD::ATOMIC_CMP_SWAP:
12463   case AMDGPUISD::ATOMIC_INC:
12464   case AMDGPUISD::ATOMIC_DEC:
12465   case AMDGPUISD::ATOMIC_LOAD_FMIN:
12466   case AMDGPUISD::ATOMIC_LOAD_FMAX:
12467   case AMDGPUISD::BUFFER_ATOMIC_SWAP:
12468   case AMDGPUISD::BUFFER_ATOMIC_ADD:
12469   case AMDGPUISD::BUFFER_ATOMIC_SUB:
12470   case AMDGPUISD::BUFFER_ATOMIC_SMIN:
12471   case AMDGPUISD::BUFFER_ATOMIC_UMIN:
12472   case AMDGPUISD::BUFFER_ATOMIC_SMAX:
12473   case AMDGPUISD::BUFFER_ATOMIC_UMAX:
12474   case AMDGPUISD::BUFFER_ATOMIC_AND:
12475   case AMDGPUISD::BUFFER_ATOMIC_OR:
12476   case AMDGPUISD::BUFFER_ATOMIC_XOR:
12477   case AMDGPUISD::BUFFER_ATOMIC_INC:
12478   case AMDGPUISD::BUFFER_ATOMIC_DEC:
12479   case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
12480   case AMDGPUISD::BUFFER_ATOMIC_CSUB:
12481   case AMDGPUISD::BUFFER_ATOMIC_FADD:
12482   case AMDGPUISD::BUFFER_ATOMIC_FMIN:
12483   case AMDGPUISD::BUFFER_ATOMIC_FMAX:
12484     // Target-specific read-modify-write atomics are sources of divergence.
12485     return true;
12486   default:
12487     if (auto *A = dyn_cast<AtomicSDNode>(N)) {
12488       // Generic read-modify-write atomics are sources of divergence.
12489       return A->readMem() && A->writeMem();
12490     }
12491     return false;
12492   }
12493 }
12494 
12495 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
12496                                                EVT VT) const {
12497   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
12498   case MVT::f32:
12499     return hasFP32Denormals(DAG.getMachineFunction());
12500   case MVT::f64:
12501   case MVT::f16:
12502     return hasFP64FP16Denormals(DAG.getMachineFunction());
12503   default:
12504     return false;
12505   }
12506 }
12507 
12508 bool SITargetLowering::denormalsEnabledForType(LLT Ty,
12509                                                MachineFunction &MF) const {
12510   switch (Ty.getScalarSizeInBits()) {
12511   case 32:
12512     return hasFP32Denormals(MF);
12513   case 64:
12514   case 16:
12515     return hasFP64FP16Denormals(MF);
12516   default:
12517     return false;
12518   }
12519 }
12520 
12521 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
12522                                                     const SelectionDAG &DAG,
12523                                                     bool SNaN,
12524                                                     unsigned Depth) const {
12525   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
12526     const MachineFunction &MF = DAG.getMachineFunction();
12527     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12528 
12529     if (Info->getMode().DX10Clamp)
12530       return true; // Clamped to 0.
12531     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
12532   }
12533 
12534   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
12535                                                             SNaN, Depth);
12536 }
12537 
12538 // Global FP atomic instructions have a hardcoded FP mode and do not support
12539 // FP32 denormals, and only support v2f16 denormals.
12540 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
12541   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
12542   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
12543   if (&Flt == &APFloat::IEEEsingle())
12544     return DenormMode == DenormalMode::getPreserveSign();
12545   return DenormMode == DenormalMode::getIEEE();
12546 }
12547 
12548 TargetLowering::AtomicExpansionKind
12549 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
12550   unsigned AS = RMW->getPointerAddressSpace();
12551   if (AS == AMDGPUAS::PRIVATE_ADDRESS)
12552     return AtomicExpansionKind::NotAtomic;
12553 
12554   auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) {
12555     OptimizationRemarkEmitter ORE(RMW->getFunction());
12556     LLVMContext &Ctx = RMW->getFunction()->getContext();
12557     SmallVector<StringRef> SSNs;
12558     Ctx.getSyncScopeNames(SSNs);
12559     auto MemScope = SSNs[RMW->getSyncScopeID()].empty()
12560                         ? "system"
12561                         : SSNs[RMW->getSyncScopeID()];
12562     ORE.emit([&]() {
12563       return OptimizationRemark(DEBUG_TYPE, "Passed", RMW)
12564              << "Hardware instruction generated for atomic "
12565              << RMW->getOperationName(RMW->getOperation())
12566              << " operation at memory scope " << MemScope
12567              << " due to an unsafe request.";
12568     });
12569     return Kind;
12570   };
12571 
12572   switch (RMW->getOperation()) {
12573   case AtomicRMWInst::FAdd: {
12574     Type *Ty = RMW->getType();
12575 
12576     // We don't have a way to support 16-bit atomics now, so just leave them
12577     // as-is.
12578     if (Ty->isHalfTy())
12579       return AtomicExpansionKind::None;
12580 
12581     if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
12582       return AtomicExpansionKind::CmpXChg;
12583 
12584     if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) &&
12585          Subtarget->hasAtomicFaddInsts()) {
12586       if (Subtarget->hasGFX940Insts())
12587         return AtomicExpansionKind::None;
12588 
12589       // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
12590       // floating point atomic instructions. May generate more efficient code,
12591       // but may not respect rounding and denormal modes, and may give incorrect
12592       // results for certain memory destinations.
12593       if (RMW->getFunction()
12594               ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12595               .getValueAsString() != "true")
12596         return AtomicExpansionKind::CmpXChg;
12597 
12598       if (Subtarget->hasGFX90AInsts()) {
12599         if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS)
12600           return AtomicExpansionKind::CmpXChg;
12601 
12602         auto SSID = RMW->getSyncScopeID();
12603         if (SSID == SyncScope::System ||
12604             SSID == RMW->getContext().getOrInsertSyncScopeID("one-as"))
12605           return AtomicExpansionKind::CmpXChg;
12606 
12607         return ReportUnsafeHWInst(AtomicExpansionKind::None);
12608       }
12609 
12610       if (AS == AMDGPUAS::FLAT_ADDRESS)
12611         return AtomicExpansionKind::CmpXChg;
12612 
12613       return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12614                               : AtomicExpansionKind::CmpXChg;
12615     }
12616 
12617     // DS FP atomics do respect the denormal mode, but the rounding mode is
12618     // fixed to round-to-nearest-even.
12619     // The only exception is DS_ADD_F64 which never flushes regardless of mode.
12620     if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) {
12621       if (!Ty->isDoubleTy())
12622         return AtomicExpansionKind::None;
12623 
12624       if (fpModeMatchesGlobalFPAtomicMode(RMW))
12625         return AtomicExpansionKind::None;
12626 
12627       return RMW->getFunction()
12628                          ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12629                          .getValueAsString() == "true"
12630                  ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12631                  : AtomicExpansionKind::CmpXChg;
12632     }
12633 
12634     return AtomicExpansionKind::CmpXChg;
12635   }
12636   default:
12637     break;
12638   }
12639 
12640   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
12641 }
12642 
12643 TargetLowering::AtomicExpansionKind
12644 SITargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
12645   return LI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12646              ? AtomicExpansionKind::NotAtomic
12647              : AtomicExpansionKind::None;
12648 }
12649 
12650 TargetLowering::AtomicExpansionKind
12651 SITargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
12652   return SI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12653              ? AtomicExpansionKind::NotAtomic
12654              : AtomicExpansionKind::None;
12655 }
12656 
12657 TargetLowering::AtomicExpansionKind
12658 SITargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *CmpX) const {
12659   return CmpX->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12660              ? AtomicExpansionKind::NotAtomic
12661              : AtomicExpansionKind::None;
12662 }
12663 
12664 const TargetRegisterClass *
12665 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
12666   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
12667   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12668   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
12669     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
12670                                                : &AMDGPU::SReg_32RegClass;
12671   if (!TRI->isSGPRClass(RC) && !isDivergent)
12672     return TRI->getEquivalentSGPRClass(RC);
12673   else if (TRI->isSGPRClass(RC) && isDivergent)
12674     return TRI->getEquivalentVGPRClass(RC);
12675 
12676   return RC;
12677 }
12678 
12679 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
12680 // uniform values (as produced by the mask results of control flow intrinsics)
12681 // used outside of divergent blocks. The phi users need to also be treated as
12682 // always uniform.
12683 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
12684                       unsigned WaveSize) {
12685   // FIXME: We assume we never cast the mask results of a control flow
12686   // intrinsic.
12687   // Early exit if the type won't be consistent as a compile time hack.
12688   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
12689   if (!IT || IT->getBitWidth() != WaveSize)
12690     return false;
12691 
12692   if (!isa<Instruction>(V))
12693     return false;
12694   if (!Visited.insert(V).second)
12695     return false;
12696   bool Result = false;
12697   for (auto U : V->users()) {
12698     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
12699       if (V == U->getOperand(1)) {
12700         switch (Intrinsic->getIntrinsicID()) {
12701         default:
12702           Result = false;
12703           break;
12704         case Intrinsic::amdgcn_if_break:
12705         case Intrinsic::amdgcn_if:
12706         case Intrinsic::amdgcn_else:
12707           Result = true;
12708           break;
12709         }
12710       }
12711       if (V == U->getOperand(0)) {
12712         switch (Intrinsic->getIntrinsicID()) {
12713         default:
12714           Result = false;
12715           break;
12716         case Intrinsic::amdgcn_end_cf:
12717         case Intrinsic::amdgcn_loop:
12718           Result = true;
12719           break;
12720         }
12721       }
12722     } else {
12723       Result = hasCFUser(U, Visited, WaveSize);
12724     }
12725     if (Result)
12726       break;
12727   }
12728   return Result;
12729 }
12730 
12731 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
12732                                                const Value *V) const {
12733   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
12734     if (CI->isInlineAsm()) {
12735       // FIXME: This cannot give a correct answer. This should only trigger in
12736       // the case where inline asm returns mixed SGPR and VGPR results, used
12737       // outside the defining block. We don't have a specific result to
12738       // consider, so this assumes if any value is SGPR, the overall register
12739       // also needs to be SGPR.
12740       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
12741       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
12742           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
12743       for (auto &TC : TargetConstraints) {
12744         if (TC.Type == InlineAsm::isOutput) {
12745           ComputeConstraintToUse(TC, SDValue());
12746           const TargetRegisterClass *RC = getRegForInlineAsmConstraint(
12747               SIRI, TC.ConstraintCode, TC.ConstraintVT).second;
12748           if (RC && SIRI->isSGPRClass(RC))
12749             return true;
12750         }
12751       }
12752     }
12753   }
12754   SmallPtrSet<const Value *, 16> Visited;
12755   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
12756 }
12757 
12758 std::pair<InstructionCost, MVT>
12759 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
12760                                           Type *Ty) const {
12761   std::pair<InstructionCost, MVT> Cost =
12762       TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
12763   auto Size = DL.getTypeSizeInBits(Ty);
12764   // Maximum load or store can handle 8 dwords for scalar and 4 for
12765   // vector ALU. Let's assume anything above 8 dwords is expensive
12766   // even if legal.
12767   if (Size <= 256)
12768     return Cost;
12769 
12770   Cost.first += (Size + 255) / 256;
12771   return Cost;
12772 }
12773 
12774 bool SITargetLowering::hasMemSDNodeUser(SDNode *N) const {
12775   SDNode::use_iterator I = N->use_begin(), E = N->use_end();
12776   for (; I != E; ++I) {
12777     if (MemSDNode *M = dyn_cast<MemSDNode>(*I)) {
12778       if (getBasePtrIndex(M) == I.getOperandNo())
12779         return true;
12780     }
12781   }
12782   return false;
12783 }
12784 
12785 bool SITargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0,
12786                                            SDValue N1) const {
12787   if (!N0.hasOneUse())
12788     return false;
12789   // Take care of the opportunity to keep N0 uniform
12790   if (N0->isDivergent() || !N1->isDivergent())
12791     return true;
12792   // Check if we have a good chance to form the memory access pattern with the
12793   // base and offset
12794   return (DAG.isBaseWithConstantOffset(N0) &&
12795           hasMemSDNodeUser(*N0->use_begin()));
12796 }
12797 
12798 MachineMemOperand::Flags
12799 SITargetLowering::getTargetMMOFlags(const Instruction &I) const {
12800   // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load.
12801   if (I.getMetadata("amdgpu.noclobber"))
12802     return MONoClobber;
12803   return MachineMemOperand::MONone;
12804 }
12805