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/Statistic.h"
21 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
22 #include "llvm/BinaryFormat/ELF.h"
23 #include "llvm/CodeGen/Analysis.h"
24 #include "llvm/CodeGen/FunctionLoweringInfo.h"
25 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
26 #include "llvm/CodeGen/MachineLoopInfo.h"
27 #include "llvm/IR/DiagnosticInfo.h"
28 #include "llvm/IR/IntrinsicsAMDGPU.h"
29 #include "llvm/IR/IntrinsicsR600.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/KnownBits.h"
32 
33 using namespace llvm;
34 
35 #define DEBUG_TYPE "si-lower"
36 
37 STATISTIC(NumTailCalls, "Number of tail calls");
38 
39 static cl::opt<bool> DisableLoopAlignment(
40   "amdgpu-disable-loop-alignment",
41   cl::desc("Do not align and prefetch loops"),
42   cl::init(false));
43 
44 static cl::opt<bool> VGPRReserveforSGPRSpill(
45     "amdgpu-reserve-vgpr-for-sgpr-spill",
46     cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true));
47 
48 static cl::opt<bool> UseDivergentRegisterIndexing(
49   "amdgpu-use-divergent-register-indexing",
50   cl::Hidden,
51   cl::desc("Use indirect register addressing for divergent indexes"),
52   cl::init(false));
53 
54 static bool hasFP32Denormals(const MachineFunction &MF) {
55   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
56   return Info->getMode().allFP32Denormals();
57 }
58 
59 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
60   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
61   return Info->getMode().allFP64FP16Denormals();
62 }
63 
64 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
65   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
66   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
67     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
68       return AMDGPU::SGPR0 + Reg;
69     }
70   }
71   llvm_unreachable("Cannot allocate sgpr");
72 }
73 
74 SITargetLowering::SITargetLowering(const TargetMachine &TM,
75                                    const GCNSubtarget &STI)
76     : AMDGPUTargetLowering(TM, STI),
77       Subtarget(&STI) {
78   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
79   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
80 
81   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
82   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
83 
84   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
85 
86   const SIRegisterInfo *TRI = STI.getRegisterInfo();
87   const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class();
88 
89   addRegisterClass(MVT::f64, V64RegClass);
90   addRegisterClass(MVT::v2f32, V64RegClass);
91 
92   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
93   addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96));
94 
95   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
96   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
97 
98   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
99   addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128));
100 
101   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
102   addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160));
103 
104   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
105   addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256));
106 
107   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
108   addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256));
109 
110   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
111   addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512));
112 
113   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
114   addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512));
115 
116   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
117   addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024));
118 
119   if (Subtarget->has16BitInsts()) {
120     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
121     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
122 
123     // Unless there are also VOP3P operations, not operations are really legal.
124     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
125     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
126     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
127     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
128   }
129 
130   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
131   addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024));
132 
133   computeRegisterProperties(Subtarget->getRegisterInfo());
134 
135   // The boolean content concept here is too inflexible. Compares only ever
136   // really produce a 1-bit result. Any copy/extend from these will turn into a
137   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
138   // it's what most targets use.
139   setBooleanContents(ZeroOrOneBooleanContent);
140   setBooleanVectorContents(ZeroOrOneBooleanContent);
141 
142   // We need to custom lower vector stores from local memory
143   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
144   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
145   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
146   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
147   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
148   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
149   setOperationAction(ISD::LOAD, MVT::i1, Custom);
150   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
151 
152   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
153   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
154   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
155   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
156   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
157   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
158   setOperationAction(ISD::STORE, MVT::i1, Custom);
159   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
160 
161   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
162   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
163   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
164   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
165   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
166   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
167   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
168   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
169   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
170   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
171   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
172   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
173   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
174   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
175   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
176   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
177 
178   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
179   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
180   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
181   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
182   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
183 
184   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
185   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
186 
187   setOperationAction(ISD::SELECT, MVT::i1, Promote);
188   setOperationAction(ISD::SELECT, MVT::i64, Custom);
189   setOperationAction(ISD::SELECT, MVT::f64, Promote);
190   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
191 
192   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
193   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
194   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
195   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
196   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
197 
198   setOperationAction(ISD::SETCC, MVT::i1, Promote);
199   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
200   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
201   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
202 
203   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
204   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
205   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
206   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
207   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
208   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
209   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
210   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
211 
212   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
213   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
214   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
215   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
216   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
217   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
218   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
219   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
220 
221   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
222   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
223   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
224   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
225   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
226   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
227 
228   setOperationAction(ISD::UADDO, MVT::i32, Legal);
229   setOperationAction(ISD::USUBO, MVT::i32, Legal);
230 
231   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
232   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
233 
234   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
235   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
236   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
237 
238 #if 0
239   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
240   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
241 #endif
242 
243   // We only support LOAD/STORE and vector manipulation ops for vectors
244   // with > 4 elements.
245   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
246                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
247                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
248                   MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) {
249     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
250       switch (Op) {
251       case ISD::LOAD:
252       case ISD::STORE:
253       case ISD::BUILD_VECTOR:
254       case ISD::BITCAST:
255       case ISD::EXTRACT_VECTOR_ELT:
256       case ISD::INSERT_VECTOR_ELT:
257       case ISD::INSERT_SUBVECTOR:
258       case ISD::EXTRACT_SUBVECTOR:
259       case ISD::SCALAR_TO_VECTOR:
260         break;
261       case ISD::CONCAT_VECTORS:
262         setOperationAction(Op, VT, Custom);
263         break;
264       default:
265         setOperationAction(Op, VT, Expand);
266         break;
267       }
268     }
269   }
270 
271   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
272 
273   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
274   // is expanded to avoid having two separate loops in case the index is a VGPR.
275 
276   // Most operations are naturally 32-bit vector operations. We only support
277   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
278   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
279     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
280     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
281 
282     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
283     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
284 
285     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
286     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
287 
288     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
289     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
290   }
291 
292   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
293     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
294     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
295 
296     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
297     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
298 
299     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
300     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
301 
302     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
303     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
304   }
305 
306   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
307     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
308     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
309 
310     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
311     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
312 
313     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
314     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
315 
316     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
317     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
318   }
319 
320   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
321     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
322     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
323 
324     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
325     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
326 
327     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
328     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
329 
330     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
331     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
332   }
333 
334   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
335   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
336   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
337   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
338 
339   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
340   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
341 
342   // Avoid stack access for these.
343   // TODO: Generalize to more vector types.
344   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
345   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
346   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
347   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
348 
349   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
350   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
351   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
352   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
353   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
354 
355   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
356   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
357   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
358 
359   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
360   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
361   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
362   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
363 
364   // Deal with vec3 vector operations when widened to vec4.
365   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
366   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
367   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
368   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
369 
370   // Deal with vec5 vector operations when widened to vec8.
371   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
372   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
373   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
374   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
375 
376   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
377   // and output demarshalling
378   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
379   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
380 
381   // We can't return success/failure, only the old value,
382   // let LLVM add the comparison
383   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
384   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
385 
386   if (Subtarget->hasFlatAddressSpace()) {
387     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
388     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
389   }
390 
391   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
392   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
393 
394   // FIXME: This should be narrowed to i32, but that only happens if i64 is
395   // illegal.
396   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
397   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
398   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
399 
400   // On SI this is s_memtime and s_memrealtime on VI.
401   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
402   setOperationAction(ISD::TRAP, MVT::Other, Custom);
403   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
404 
405   if (Subtarget->has16BitInsts()) {
406     setOperationAction(ISD::FPOW, MVT::f16, Promote);
407     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
408     setOperationAction(ISD::FLOG, MVT::f16, Custom);
409     setOperationAction(ISD::FEXP, MVT::f16, Custom);
410     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
411   }
412 
413   if (Subtarget->hasMadMacF32Insts())
414     setOperationAction(ISD::FMAD, MVT::f32, Legal);
415 
416   if (!Subtarget->hasBFI()) {
417     // fcopysign can be done in a single instruction with BFI.
418     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
419     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
420   }
421 
422   if (!Subtarget->hasBCNT(32))
423     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
424 
425   if (!Subtarget->hasBCNT(64))
426     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
427 
428   if (Subtarget->hasFFBH())
429     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
430 
431   if (Subtarget->hasFFBL())
432     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
433 
434   // We only really have 32-bit BFE instructions (and 16-bit on VI).
435   //
436   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
437   // effort to match them now. We want this to be false for i64 cases when the
438   // extraction isn't restricted to the upper or lower half. Ideally we would
439   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
440   // span the midpoint are probably relatively rare, so don't worry about them
441   // for now.
442   if (Subtarget->hasBFE())
443     setHasExtractBitsInsn(true);
444 
445   // Clamp modifier on add/sub
446   if (Subtarget->hasIntClamp()) {
447     setOperationAction(ISD::UADDSAT, MVT::i32, Legal);
448     setOperationAction(ISD::USUBSAT, MVT::i32, Legal);
449   }
450 
451   if (Subtarget->hasAddNoCarry()) {
452     setOperationAction(ISD::SADDSAT, MVT::i16, Legal);
453     setOperationAction(ISD::SSUBSAT, MVT::i16, Legal);
454     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
455     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
456   }
457 
458   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
459   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
460   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
461   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
462 
463 
464   // These are really only legal for ieee_mode functions. We should be avoiding
465   // them for functions that don't have ieee_mode enabled, so just say they are
466   // legal.
467   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
468   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
469   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
470   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
471 
472 
473   if (Subtarget->haveRoundOpsF64()) {
474     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
475     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
476     setOperationAction(ISD::FRINT, MVT::f64, Legal);
477   } else {
478     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
479     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
480     setOperationAction(ISD::FRINT, MVT::f64, Custom);
481     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
482   }
483 
484   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
485 
486   setOperationAction(ISD::FSIN, MVT::f32, Custom);
487   setOperationAction(ISD::FCOS, MVT::f32, Custom);
488   setOperationAction(ISD::FDIV, MVT::f32, Custom);
489   setOperationAction(ISD::FDIV, MVT::f64, Custom);
490 
491   if (Subtarget->has16BitInsts()) {
492     setOperationAction(ISD::Constant, MVT::i16, Legal);
493 
494     setOperationAction(ISD::SMIN, MVT::i16, Legal);
495     setOperationAction(ISD::SMAX, MVT::i16, Legal);
496 
497     setOperationAction(ISD::UMIN, MVT::i16, Legal);
498     setOperationAction(ISD::UMAX, MVT::i16, Legal);
499 
500     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
501     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
502 
503     setOperationAction(ISD::ROTR, MVT::i16, Expand);
504     setOperationAction(ISD::ROTL, MVT::i16, Expand);
505 
506     setOperationAction(ISD::SDIV, MVT::i16, Promote);
507     setOperationAction(ISD::UDIV, MVT::i16, Promote);
508     setOperationAction(ISD::SREM, MVT::i16, Promote);
509     setOperationAction(ISD::UREM, MVT::i16, Promote);
510     setOperationAction(ISD::UADDSAT, MVT::i16, Legal);
511     setOperationAction(ISD::USUBSAT, MVT::i16, Legal);
512 
513     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
514 
515     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
516     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
517     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
518     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
519     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
520 
521     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
522 
523     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
524 
525     setOperationAction(ISD::LOAD, MVT::i16, Custom);
526 
527     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
528 
529     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
530     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
531     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
532     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
533 
534     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Custom);
535     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Custom);
536 
537     // F16 - Constant Actions.
538     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
539 
540     // F16 - Load/Store Actions.
541     setOperationAction(ISD::LOAD, MVT::f16, Promote);
542     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
543     setOperationAction(ISD::STORE, MVT::f16, Promote);
544     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
545 
546     // F16 - VOP1 Actions.
547     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
548     setOperationAction(ISD::FCOS, MVT::f16, Custom);
549     setOperationAction(ISD::FSIN, MVT::f16, Custom);
550 
551     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
552     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
553 
554     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
555     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
556     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
557     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
558     setOperationAction(ISD::FROUND, MVT::f16, Custom);
559 
560     // F16 - VOP2 Actions.
561     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
562     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
563 
564     setOperationAction(ISD::FDIV, MVT::f16, Custom);
565 
566     // F16 - VOP3 Actions.
567     setOperationAction(ISD::FMA, MVT::f16, Legal);
568     if (STI.hasMadF16())
569       setOperationAction(ISD::FMAD, MVT::f16, Legal);
570 
571     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
572       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
573         switch (Op) {
574         case ISD::LOAD:
575         case ISD::STORE:
576         case ISD::BUILD_VECTOR:
577         case ISD::BITCAST:
578         case ISD::EXTRACT_VECTOR_ELT:
579         case ISD::INSERT_VECTOR_ELT:
580         case ISD::INSERT_SUBVECTOR:
581         case ISD::EXTRACT_SUBVECTOR:
582         case ISD::SCALAR_TO_VECTOR:
583           break;
584         case ISD::CONCAT_VECTORS:
585           setOperationAction(Op, VT, Custom);
586           break;
587         default:
588           setOperationAction(Op, VT, Expand);
589           break;
590         }
591       }
592     }
593 
594     // v_perm_b32 can handle either of these.
595     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
596     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
597     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
598 
599     // XXX - Do these do anything? Vector constants turn into build_vector.
600     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
601     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
602 
603     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
604     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
605 
606     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
607     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
608     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
609     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
610 
611     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
612     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
613     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
614     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
615 
616     setOperationAction(ISD::AND, MVT::v2i16, Promote);
617     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
618     setOperationAction(ISD::OR, MVT::v2i16, Promote);
619     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
620     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
621     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
622 
623     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
624     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
625     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
626     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
627 
628     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
629     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
630     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
631     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
632 
633     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
634     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
635     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
636     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
637 
638     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
639     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
640     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
641 
642     if (!Subtarget->hasVOP3PInsts()) {
643       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
644       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
645     }
646 
647     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
648     // This isn't really legal, but this avoids the legalizer unrolling it (and
649     // allows matching fneg (fabs x) patterns)
650     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
651 
652     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
653     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
654     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
655     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
656 
657     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
658     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
659 
660     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
661     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
662   }
663 
664   if (Subtarget->hasVOP3PInsts()) {
665     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
666     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
667     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
668     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
669     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
670     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
671     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
672     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
673     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
674     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
675 
676     setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal);
677     setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal);
678     setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal);
679     setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal);
680 
681     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
682     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
683     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
684 
685     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
686     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
687 
688     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
689 
690     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
691     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
692 
693     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
694     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
695 
696     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
697     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
698     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
699     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
700     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
701     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
702 
703     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
704     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
705     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
706     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
707 
708     setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom);
709     setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom);
710     setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom);
711     setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom);
712 
713     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
714     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
715     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
716 
717     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
718     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
719 
720     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
721     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
722     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
723 
724     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
725     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
726     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
727 
728     if (Subtarget->hasPackedFP32Ops()) {
729       setOperationAction(ISD::FADD, MVT::v2f32, Legal);
730       setOperationAction(ISD::FMUL, MVT::v2f32, Legal);
731       setOperationAction(ISD::FMA,  MVT::v2f32, Legal);
732       setOperationAction(ISD::FNEG, MVT::v2f32, Legal);
733 
734       for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) {
735         setOperationAction(ISD::FADD, VT, Custom);
736         setOperationAction(ISD::FMUL, VT, Custom);
737         setOperationAction(ISD::FMA, VT, Custom);
738       }
739     }
740   }
741 
742   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
743   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
744 
745   if (Subtarget->has16BitInsts()) {
746     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
747     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
748     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
749     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
750   } else {
751     // Legalization hack.
752     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
753     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
754 
755     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
756     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
757   }
758 
759   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
760     setOperationAction(ISD::SELECT, VT, Custom);
761   }
762 
763   setOperationAction(ISD::SMULO, MVT::i64, Custom);
764   setOperationAction(ISD::UMULO, MVT::i64, Custom);
765 
766   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
767   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
768   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
769   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
770   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
771   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
772   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
773 
774   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
775   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
776   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom);
777   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom);
778   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
779   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
780   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
781   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
782   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
783   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
784   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
785 
786   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
787   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
788   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
789   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom);
790   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom);
791   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
792   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
793   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
794   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
795   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
796 
797   setTargetDAGCombine(ISD::ADD);
798   setTargetDAGCombine(ISD::ADDCARRY);
799   setTargetDAGCombine(ISD::SUB);
800   setTargetDAGCombine(ISD::SUBCARRY);
801   setTargetDAGCombine(ISD::FADD);
802   setTargetDAGCombine(ISD::FSUB);
803   setTargetDAGCombine(ISD::FMINNUM);
804   setTargetDAGCombine(ISD::FMAXNUM);
805   setTargetDAGCombine(ISD::FMINNUM_IEEE);
806   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
807   setTargetDAGCombine(ISD::FMA);
808   setTargetDAGCombine(ISD::SMIN);
809   setTargetDAGCombine(ISD::SMAX);
810   setTargetDAGCombine(ISD::UMIN);
811   setTargetDAGCombine(ISD::UMAX);
812   setTargetDAGCombine(ISD::SETCC);
813   setTargetDAGCombine(ISD::AND);
814   setTargetDAGCombine(ISD::OR);
815   setTargetDAGCombine(ISD::XOR);
816   setTargetDAGCombine(ISD::SINT_TO_FP);
817   setTargetDAGCombine(ISD::UINT_TO_FP);
818   setTargetDAGCombine(ISD::FCANONICALIZE);
819   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
820   setTargetDAGCombine(ISD::ZERO_EXTEND);
821   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
822   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
823   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
824 
825   // All memory operations. Some folding on the pointer operand is done to help
826   // matching the constant offsets in the addressing modes.
827   setTargetDAGCombine(ISD::LOAD);
828   setTargetDAGCombine(ISD::STORE);
829   setTargetDAGCombine(ISD::ATOMIC_LOAD);
830   setTargetDAGCombine(ISD::ATOMIC_STORE);
831   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
832   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
833   setTargetDAGCombine(ISD::ATOMIC_SWAP);
834   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
835   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
836   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
837   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
838   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
839   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
840   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
841   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
842   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
843   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
844   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
845   setTargetDAGCombine(ISD::INTRINSIC_VOID);
846   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
847 
848   // FIXME: In other contexts we pretend this is a per-function property.
849   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
850 
851   setSchedulingPreference(Sched::RegPressure);
852 }
853 
854 const GCNSubtarget *SITargetLowering::getSubtarget() const {
855   return Subtarget;
856 }
857 
858 //===----------------------------------------------------------------------===//
859 // TargetLowering queries
860 //===----------------------------------------------------------------------===//
861 
862 // v_mad_mix* support a conversion from f16 to f32.
863 //
864 // There is only one special case when denormals are enabled we don't currently,
865 // where this is OK to use.
866 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
867                                        EVT DestVT, EVT SrcVT) const {
868   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
869           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
870     DestVT.getScalarType() == MVT::f32 &&
871     SrcVT.getScalarType() == MVT::f16 &&
872     // TODO: This probably only requires no input flushing?
873     !hasFP32Denormals(DAG.getMachineFunction());
874 }
875 
876 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
877   // SI has some legal vector types, but no legal vector operations. Say no
878   // shuffles are legal in order to prefer scalarizing some vector operations.
879   return false;
880 }
881 
882 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
883                                                     CallingConv::ID CC,
884                                                     EVT VT) const {
885   if (CC == CallingConv::AMDGPU_KERNEL)
886     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
887 
888   if (VT.isVector()) {
889     EVT ScalarVT = VT.getScalarType();
890     unsigned Size = ScalarVT.getSizeInBits();
891     if (Size == 16) {
892       if (Subtarget->has16BitInsts())
893         return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
894       return VT.isInteger() ? MVT::i32 : MVT::f32;
895     }
896 
897     if (Size < 16)
898       return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
899     return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
900   }
901 
902   if (VT.getSizeInBits() > 32)
903     return MVT::i32;
904 
905   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
906 }
907 
908 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
909                                                          CallingConv::ID CC,
910                                                          EVT VT) const {
911   if (CC == CallingConv::AMDGPU_KERNEL)
912     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
913 
914   if (VT.isVector()) {
915     unsigned NumElts = VT.getVectorNumElements();
916     EVT ScalarVT = VT.getScalarType();
917     unsigned Size = ScalarVT.getSizeInBits();
918 
919     // FIXME: Should probably promote 8-bit vectors to i16.
920     if (Size == 16 && Subtarget->has16BitInsts())
921       return (NumElts + 1) / 2;
922 
923     if (Size <= 32)
924       return NumElts;
925 
926     if (Size > 32)
927       return NumElts * ((Size + 31) / 32);
928   } else if (VT.getSizeInBits() > 32)
929     return (VT.getSizeInBits() + 31) / 32;
930 
931   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
932 }
933 
934 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
935   LLVMContext &Context, CallingConv::ID CC,
936   EVT VT, EVT &IntermediateVT,
937   unsigned &NumIntermediates, MVT &RegisterVT) const {
938   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
939     unsigned NumElts = VT.getVectorNumElements();
940     EVT ScalarVT = VT.getScalarType();
941     unsigned Size = ScalarVT.getSizeInBits();
942     // FIXME: We should fix the ABI to be the same on targets without 16-bit
943     // support, but unless we can properly handle 3-vectors, it will be still be
944     // inconsistent.
945     if (Size == 16 && Subtarget->has16BitInsts()) {
946       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
947       IntermediateVT = RegisterVT;
948       NumIntermediates = (NumElts + 1) / 2;
949       return NumIntermediates;
950     }
951 
952     if (Size == 32) {
953       RegisterVT = ScalarVT.getSimpleVT();
954       IntermediateVT = RegisterVT;
955       NumIntermediates = NumElts;
956       return NumIntermediates;
957     }
958 
959     if (Size < 16 && Subtarget->has16BitInsts()) {
960       // FIXME: Should probably form v2i16 pieces
961       RegisterVT = MVT::i16;
962       IntermediateVT = ScalarVT;
963       NumIntermediates = NumElts;
964       return NumIntermediates;
965     }
966 
967 
968     if (Size != 16 && Size <= 32) {
969       RegisterVT = MVT::i32;
970       IntermediateVT = ScalarVT;
971       NumIntermediates = NumElts;
972       return NumIntermediates;
973     }
974 
975     if (Size > 32) {
976       RegisterVT = MVT::i32;
977       IntermediateVT = RegisterVT;
978       NumIntermediates = NumElts * ((Size + 31) / 32);
979       return NumIntermediates;
980     }
981   }
982 
983   return TargetLowering::getVectorTypeBreakdownForCallingConv(
984     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
985 }
986 
987 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
988   assert(DMaskLanes != 0);
989 
990   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
991     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
992     return EVT::getVectorVT(Ty->getContext(),
993                             EVT::getEVT(VT->getElementType()),
994                             NumElts);
995   }
996 
997   return EVT::getEVT(Ty);
998 }
999 
1000 // Peek through TFE struct returns to only use the data size.
1001 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
1002   auto *ST = dyn_cast<StructType>(Ty);
1003   if (!ST)
1004     return memVTFromImageData(Ty, DMaskLanes);
1005 
1006   // Some intrinsics return an aggregate type - special case to work out the
1007   // correct memVT.
1008   //
1009   // Only limited forms of aggregate type currently expected.
1010   if (ST->getNumContainedTypes() != 2 ||
1011       !ST->getContainedType(1)->isIntegerTy(32))
1012     return EVT();
1013   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
1014 }
1015 
1016 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1017                                           const CallInst &CI,
1018                                           MachineFunction &MF,
1019                                           unsigned IntrID) const {
1020   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1021           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1022     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1023                                                   (Intrinsic::ID)IntrID);
1024     if (Attr.hasFnAttribute(Attribute::ReadNone))
1025       return false;
1026 
1027     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1028 
1029     if (RsrcIntr->IsImage) {
1030       Info.ptrVal =
1031           MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1032       Info.align.reset();
1033     } else {
1034       Info.ptrVal =
1035           MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1036     }
1037 
1038     Info.flags = MachineMemOperand::MODereferenceable;
1039     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
1040       unsigned DMaskLanes = 4;
1041 
1042       if (RsrcIntr->IsImage) {
1043         const AMDGPU::ImageDimIntrinsicInfo *Intr
1044           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1045         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1046           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1047 
1048         if (!BaseOpcode->Gather4) {
1049           // If this isn't a gather, we may have excess loaded elements in the
1050           // IR type. Check the dmask for the real number of elements loaded.
1051           unsigned DMask
1052             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1053           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1054         }
1055 
1056         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1057       } else
1058         Info.memVT = EVT::getEVT(CI.getType());
1059 
1060       // FIXME: What does alignment mean for an image?
1061       Info.opc = ISD::INTRINSIC_W_CHAIN;
1062       Info.flags |= MachineMemOperand::MOLoad;
1063     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
1064       Info.opc = ISD::INTRINSIC_VOID;
1065 
1066       Type *DataTy = CI.getArgOperand(0)->getType();
1067       if (RsrcIntr->IsImage) {
1068         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1069         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1070         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1071       } else
1072         Info.memVT = EVT::getEVT(DataTy);
1073 
1074       Info.flags |= MachineMemOperand::MOStore;
1075     } else {
1076       // Atomic
1077       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1078                                             ISD::INTRINSIC_W_CHAIN;
1079       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1080       Info.flags = MachineMemOperand::MOLoad |
1081                    MachineMemOperand::MOStore |
1082                    MachineMemOperand::MODereferenceable;
1083 
1084       // XXX - Should this be volatile without known ordering?
1085       Info.flags |= MachineMemOperand::MOVolatile;
1086     }
1087     return true;
1088   }
1089 
1090   switch (IntrID) {
1091   case Intrinsic::amdgcn_atomic_inc:
1092   case Intrinsic::amdgcn_atomic_dec:
1093   case Intrinsic::amdgcn_ds_ordered_add:
1094   case Intrinsic::amdgcn_ds_ordered_swap:
1095   case Intrinsic::amdgcn_ds_fadd:
1096   case Intrinsic::amdgcn_ds_fmin:
1097   case Intrinsic::amdgcn_ds_fmax: {
1098     Info.opc = ISD::INTRINSIC_W_CHAIN;
1099     Info.memVT = MVT::getVT(CI.getType());
1100     Info.ptrVal = CI.getOperand(0);
1101     Info.align.reset();
1102     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1103 
1104     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1105     if (!Vol->isZero())
1106       Info.flags |= MachineMemOperand::MOVolatile;
1107 
1108     return true;
1109   }
1110   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1111     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1112 
1113     Info.opc = ISD::INTRINSIC_W_CHAIN;
1114     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1115     Info.ptrVal =
1116         MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1117     Info.align.reset();
1118     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1119 
1120     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1121     if (!Vol || !Vol->isZero())
1122       Info.flags |= MachineMemOperand::MOVolatile;
1123 
1124     return true;
1125   }
1126   case Intrinsic::amdgcn_ds_append:
1127   case Intrinsic::amdgcn_ds_consume: {
1128     Info.opc = ISD::INTRINSIC_W_CHAIN;
1129     Info.memVT = MVT::getVT(CI.getType());
1130     Info.ptrVal = CI.getOperand(0);
1131     Info.align.reset();
1132     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1133 
1134     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1135     if (!Vol->isZero())
1136       Info.flags |= MachineMemOperand::MOVolatile;
1137 
1138     return true;
1139   }
1140   case Intrinsic::amdgcn_global_atomic_csub: {
1141     Info.opc = ISD::INTRINSIC_W_CHAIN;
1142     Info.memVT = MVT::getVT(CI.getType());
1143     Info.ptrVal = CI.getOperand(0);
1144     Info.align.reset();
1145     Info.flags = MachineMemOperand::MOLoad |
1146                  MachineMemOperand::MOStore |
1147                  MachineMemOperand::MOVolatile;
1148     return true;
1149   }
1150   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1151     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1152     Info.opc = ISD::INTRINSIC_W_CHAIN;
1153     Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1154     Info.ptrVal =
1155         MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1156     Info.align.reset();
1157     Info.flags = MachineMemOperand::MOLoad |
1158                  MachineMemOperand::MODereferenceable;
1159     return true;
1160   }
1161   case Intrinsic::amdgcn_global_atomic_fadd:
1162   case Intrinsic::amdgcn_global_atomic_fmin:
1163   case Intrinsic::amdgcn_global_atomic_fmax:
1164   case Intrinsic::amdgcn_flat_atomic_fadd:
1165   case Intrinsic::amdgcn_flat_atomic_fmin:
1166   case Intrinsic::amdgcn_flat_atomic_fmax: {
1167     Info.opc = ISD::INTRINSIC_W_CHAIN;
1168     Info.memVT = MVT::getVT(CI.getType());
1169     Info.ptrVal = CI.getOperand(0);
1170     Info.align.reset();
1171     Info.flags = MachineMemOperand::MOLoad |
1172                  MachineMemOperand::MOStore |
1173                  MachineMemOperand::MODereferenceable |
1174                  MachineMemOperand::MOVolatile;
1175     return true;
1176   }
1177   case Intrinsic::amdgcn_ds_gws_init:
1178   case Intrinsic::amdgcn_ds_gws_barrier:
1179   case Intrinsic::amdgcn_ds_gws_sema_v:
1180   case Intrinsic::amdgcn_ds_gws_sema_br:
1181   case Intrinsic::amdgcn_ds_gws_sema_p:
1182   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1183     Info.opc = ISD::INTRINSIC_VOID;
1184 
1185     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1186     Info.ptrVal =
1187         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1188 
1189     // This is an abstract access, but we need to specify a type and size.
1190     Info.memVT = MVT::i32;
1191     Info.size = 4;
1192     Info.align = Align(4);
1193 
1194     Info.flags = MachineMemOperand::MOStore;
1195     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1196       Info.flags = MachineMemOperand::MOLoad;
1197     return true;
1198   }
1199   default:
1200     return false;
1201   }
1202 }
1203 
1204 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1205                                             SmallVectorImpl<Value*> &Ops,
1206                                             Type *&AccessTy) const {
1207   switch (II->getIntrinsicID()) {
1208   case Intrinsic::amdgcn_atomic_inc:
1209   case Intrinsic::amdgcn_atomic_dec:
1210   case Intrinsic::amdgcn_ds_ordered_add:
1211   case Intrinsic::amdgcn_ds_ordered_swap:
1212   case Intrinsic::amdgcn_ds_append:
1213   case Intrinsic::amdgcn_ds_consume:
1214   case Intrinsic::amdgcn_ds_fadd:
1215   case Intrinsic::amdgcn_ds_fmin:
1216   case Intrinsic::amdgcn_ds_fmax:
1217   case Intrinsic::amdgcn_global_atomic_fadd:
1218   case Intrinsic::amdgcn_flat_atomic_fadd:
1219   case Intrinsic::amdgcn_flat_atomic_fmin:
1220   case Intrinsic::amdgcn_flat_atomic_fmax:
1221   case Intrinsic::amdgcn_global_atomic_csub: {
1222     Value *Ptr = II->getArgOperand(0);
1223     AccessTy = II->getType();
1224     Ops.push_back(Ptr);
1225     return true;
1226   }
1227   default:
1228     return false;
1229   }
1230 }
1231 
1232 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1233   if (!Subtarget->hasFlatInstOffsets()) {
1234     // Flat instructions do not have offsets, and only have the register
1235     // address.
1236     return AM.BaseOffs == 0 && AM.Scale == 0;
1237   }
1238 
1239   return AM.Scale == 0 &&
1240          (AM.BaseOffs == 0 ||
1241           Subtarget->getInstrInfo()->isLegalFLATOffset(
1242               AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT));
1243 }
1244 
1245 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1246   if (Subtarget->hasFlatGlobalInsts())
1247     return AM.Scale == 0 &&
1248            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1249                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1250                                     SIInstrFlags::FlatGlobal));
1251 
1252   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1253       // Assume the we will use FLAT for all global memory accesses
1254       // on VI.
1255       // FIXME: This assumption is currently wrong.  On VI we still use
1256       // MUBUF instructions for the r + i addressing mode.  As currently
1257       // implemented, the MUBUF instructions only work on buffer < 4GB.
1258       // It may be possible to support > 4GB buffers with MUBUF instructions,
1259       // by setting the stride value in the resource descriptor which would
1260       // increase the size limit to (stride * 4GB).  However, this is risky,
1261       // because it has never been validated.
1262     return isLegalFlatAddressingMode(AM);
1263   }
1264 
1265   return isLegalMUBUFAddressingMode(AM);
1266 }
1267 
1268 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1269   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1270   // additionally can do r + r + i with addr64. 32-bit has more addressing
1271   // mode options. Depending on the resource constant, it can also do
1272   // (i64 r0) + (i32 r1) * (i14 i).
1273   //
1274   // Private arrays end up using a scratch buffer most of the time, so also
1275   // assume those use MUBUF instructions. Scratch loads / stores are currently
1276   // implemented as mubuf instructions with offen bit set, so slightly
1277   // different than the normal addr64.
1278   if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1279     return false;
1280 
1281   // FIXME: Since we can split immediate into soffset and immediate offset,
1282   // would it make sense to allow any immediate?
1283 
1284   switch (AM.Scale) {
1285   case 0: // r + i or just i, depending on HasBaseReg.
1286     return true;
1287   case 1:
1288     return true; // We have r + r or r + i.
1289   case 2:
1290     if (AM.HasBaseReg) {
1291       // Reject 2 * r + r.
1292       return false;
1293     }
1294 
1295     // Allow 2 * r as r + r
1296     // Or  2 * r + i is allowed as r + r + i.
1297     return true;
1298   default: // Don't allow n * r
1299     return false;
1300   }
1301 }
1302 
1303 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1304                                              const AddrMode &AM, Type *Ty,
1305                                              unsigned AS, Instruction *I) const {
1306   // No global is ever allowed as a base.
1307   if (AM.BaseGV)
1308     return false;
1309 
1310   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1311     return isLegalGlobalAddressingMode(AM);
1312 
1313   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1314       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1315       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1316     // If the offset isn't a multiple of 4, it probably isn't going to be
1317     // correctly aligned.
1318     // FIXME: Can we get the real alignment here?
1319     if (AM.BaseOffs % 4 != 0)
1320       return isLegalMUBUFAddressingMode(AM);
1321 
1322     // There are no SMRD extloads, so if we have to do a small type access we
1323     // will use a MUBUF load.
1324     // FIXME?: We also need to do this if unaligned, but we don't know the
1325     // alignment here.
1326     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1327       return isLegalGlobalAddressingMode(AM);
1328 
1329     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1330       // SMRD instructions have an 8-bit, dword offset on SI.
1331       if (!isUInt<8>(AM.BaseOffs / 4))
1332         return false;
1333     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1334       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1335       // in 8-bits, it can use a smaller encoding.
1336       if (!isUInt<32>(AM.BaseOffs / 4))
1337         return false;
1338     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1339       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1340       if (!isUInt<20>(AM.BaseOffs))
1341         return false;
1342     } else
1343       llvm_unreachable("unhandled generation");
1344 
1345     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1346       return true;
1347 
1348     if (AM.Scale == 1 && AM.HasBaseReg)
1349       return true;
1350 
1351     return false;
1352 
1353   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1354     return isLegalMUBUFAddressingMode(AM);
1355   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1356              AS == AMDGPUAS::REGION_ADDRESS) {
1357     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1358     // field.
1359     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1360     // an 8-bit dword offset but we don't know the alignment here.
1361     if (!isUInt<16>(AM.BaseOffs))
1362       return false;
1363 
1364     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1365       return true;
1366 
1367     if (AM.Scale == 1 && AM.HasBaseReg)
1368       return true;
1369 
1370     return false;
1371   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1372              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1373     // For an unknown address space, this usually means that this is for some
1374     // reason being used for pure arithmetic, and not based on some addressing
1375     // computation. We don't have instructions that compute pointers with any
1376     // addressing modes, so treat them as having no offset like flat
1377     // instructions.
1378     return isLegalFlatAddressingMode(AM);
1379   }
1380 
1381   // Assume a user alias of global for unknown address spaces.
1382   return isLegalGlobalAddressingMode(AM);
1383 }
1384 
1385 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1386                                         const SelectionDAG &DAG) const {
1387   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1388     return (MemVT.getSizeInBits() <= 4 * 32);
1389   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1390     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1391     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1392   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1393     return (MemVT.getSizeInBits() <= 2 * 32);
1394   }
1395   return true;
1396 }
1397 
1398 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1399     unsigned Size, unsigned AddrSpace, Align Alignment,
1400     MachineMemOperand::Flags Flags, bool *IsFast) const {
1401   if (IsFast)
1402     *IsFast = false;
1403 
1404   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1405       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1406     // Check if alignment requirements for ds_read/write instructions are
1407     // disabled.
1408     if (Subtarget->hasUnalignedDSAccessEnabled() &&
1409         !Subtarget->hasLDSMisalignedBug()) {
1410       if (IsFast)
1411         *IsFast = Alignment != Align(2);
1412       return true;
1413     }
1414 
1415     // Either, the alignment requirements are "enabled", or there is an
1416     // unaligned LDS access related hardware bug though alignment requirements
1417     // are "disabled". In either case, we need to check for proper alignment
1418     // requirements.
1419     //
1420     if (Size == 64) {
1421       // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
1422       // can do a 4 byte aligned, 8 byte access in a single operation using
1423       // ds_read2/write2_b32 with adjacent offsets.
1424       bool AlignedBy4 = Alignment >= Align(4);
1425       if (IsFast)
1426         *IsFast = AlignedBy4;
1427 
1428       return AlignedBy4;
1429     }
1430     if (Size == 96) {
1431       // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
1432       // gfx8 and older.
1433       bool AlignedBy16 = Alignment >= Align(16);
1434       if (IsFast)
1435         *IsFast = AlignedBy16;
1436 
1437       return AlignedBy16;
1438     }
1439     if (Size == 128) {
1440       // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
1441       // gfx8 and older, but  we can do a 8 byte aligned, 16 byte access in a
1442       // single operation using ds_read2/write2_b64.
1443       bool AlignedBy8 = Alignment >= Align(8);
1444       if (IsFast)
1445         *IsFast = AlignedBy8;
1446 
1447       return AlignedBy8;
1448     }
1449   }
1450 
1451   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1452     bool AlignedBy4 = Alignment >= Align(4);
1453     if (IsFast)
1454       *IsFast = AlignedBy4;
1455 
1456     return AlignedBy4 ||
1457            Subtarget->enableFlatScratch() ||
1458            Subtarget->hasUnalignedScratchAccess();
1459   }
1460 
1461   // FIXME: We have to be conservative here and assume that flat operations
1462   // will access scratch.  If we had access to the IR function, then we
1463   // could determine if any private memory was used in the function.
1464   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1465       !Subtarget->hasUnalignedScratchAccess()) {
1466     bool AlignedBy4 = Alignment >= Align(4);
1467     if (IsFast)
1468       *IsFast = AlignedBy4;
1469 
1470     return AlignedBy4;
1471   }
1472 
1473   if (Subtarget->hasUnalignedBufferAccessEnabled() &&
1474       !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1475         AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1476     // If we have an uniform constant load, it still requires using a slow
1477     // buffer instruction if unaligned.
1478     if (IsFast) {
1479       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1480       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1481       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1482                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1483         Alignment >= Align(4) : Alignment != Align(2);
1484     }
1485 
1486     return true;
1487   }
1488 
1489   // Smaller than dword value must be aligned.
1490   if (Size < 32)
1491     return false;
1492 
1493   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1494   // byte-address are ignored, thus forcing Dword alignment.
1495   // This applies to private, global, and constant memory.
1496   if (IsFast)
1497     *IsFast = true;
1498 
1499   return Size >= 32 && Alignment >= Align(4);
1500 }
1501 
1502 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1503     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1504     bool *IsFast) const {
1505   if (IsFast)
1506     *IsFast = false;
1507 
1508   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1509   // which isn't a simple VT.
1510   // Until MVT is extended to handle this, simply check for the size and
1511   // rely on the condition below: allow accesses if the size is a multiple of 4.
1512   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1513                            VT.getStoreSize() > 16)) {
1514     return false;
1515   }
1516 
1517   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1518                                             Alignment, Flags, IsFast);
1519 }
1520 
1521 EVT SITargetLowering::getOptimalMemOpType(
1522     const MemOp &Op, const AttributeList &FuncAttributes) const {
1523   // FIXME: Should account for address space here.
1524 
1525   // The default fallback uses the private pointer size as a guess for a type to
1526   // use. Make sure we switch these to 64-bit accesses.
1527 
1528   if (Op.size() >= 16 &&
1529       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1530     return MVT::v4i32;
1531 
1532   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1533     return MVT::v2i32;
1534 
1535   // Use the default.
1536   return MVT::Other;
1537 }
1538 
1539 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1540   const MemSDNode *MemNode = cast<MemSDNode>(N);
1541   const Value *Ptr = MemNode->getMemOperand()->getValue();
1542   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1543   return I && I->getMetadata("amdgpu.noclobber");
1544 }
1545 
1546 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1547   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1548          AS == AMDGPUAS::PRIVATE_ADDRESS;
1549 }
1550 
1551 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1552                                            unsigned DestAS) const {
1553   // Flat -> private/local is a simple truncate.
1554   // Flat -> global is no-op
1555   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1556     return true;
1557 
1558   const GCNTargetMachine &TM =
1559       static_cast<const GCNTargetMachine &>(getTargetMachine());
1560   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1561 }
1562 
1563 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1564   const MemSDNode *MemNode = cast<MemSDNode>(N);
1565 
1566   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1567 }
1568 
1569 TargetLoweringBase::LegalizeTypeAction
1570 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1571   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1572       VT.getScalarType().bitsLE(MVT::i16))
1573     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1574   return TargetLoweringBase::getPreferredVectorAction(VT);
1575 }
1576 
1577 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1578                                                          Type *Ty) const {
1579   // FIXME: Could be smarter if called for vector constants.
1580   return true;
1581 }
1582 
1583 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1584   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1585     switch (Op) {
1586     case ISD::LOAD:
1587     case ISD::STORE:
1588 
1589     // These operations are done with 32-bit instructions anyway.
1590     case ISD::AND:
1591     case ISD::OR:
1592     case ISD::XOR:
1593     case ISD::SELECT:
1594       // TODO: Extensions?
1595       return true;
1596     default:
1597       return false;
1598     }
1599   }
1600 
1601   // SimplifySetCC uses this function to determine whether or not it should
1602   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1603   if (VT == MVT::i1 && Op == ISD::SETCC)
1604     return false;
1605 
1606   return TargetLowering::isTypeDesirableForOp(Op, VT);
1607 }
1608 
1609 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1610                                                    const SDLoc &SL,
1611                                                    SDValue Chain,
1612                                                    uint64_t Offset) const {
1613   const DataLayout &DL = DAG.getDataLayout();
1614   MachineFunction &MF = DAG.getMachineFunction();
1615   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1616 
1617   const ArgDescriptor *InputPtrReg;
1618   const TargetRegisterClass *RC;
1619   LLT ArgTy;
1620 
1621   std::tie(InputPtrReg, RC, ArgTy) =
1622       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1623 
1624   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1625   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1626   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1627     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1628 
1629   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1630 }
1631 
1632 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1633                                             const SDLoc &SL) const {
1634   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1635                                                FIRST_IMPLICIT);
1636   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1637 }
1638 
1639 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1640                                          const SDLoc &SL, SDValue Val,
1641                                          bool Signed,
1642                                          const ISD::InputArg *Arg) const {
1643   // First, if it is a widened vector, narrow it.
1644   if (VT.isVector() &&
1645       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1646     EVT NarrowedVT =
1647         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1648                          VT.getVectorNumElements());
1649     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1650                       DAG.getConstant(0, SL, MVT::i32));
1651   }
1652 
1653   // Then convert the vector elements or scalar value.
1654   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1655       VT.bitsLT(MemVT)) {
1656     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1657     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1658   }
1659 
1660   if (MemVT.isFloatingPoint())
1661     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1662   else if (Signed)
1663     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1664   else
1665     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1666 
1667   return Val;
1668 }
1669 
1670 SDValue SITargetLowering::lowerKernargMemParameter(
1671     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1672     uint64_t Offset, Align Alignment, bool Signed,
1673     const ISD::InputArg *Arg) const {
1674   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1675 
1676   // Try to avoid using an extload by loading earlier than the argument address,
1677   // and extracting the relevant bits. The load should hopefully be merged with
1678   // the previous argument.
1679   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1680     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1681     int64_t AlignDownOffset = alignDown(Offset, 4);
1682     int64_t OffsetDiff = Offset - AlignDownOffset;
1683 
1684     EVT IntVT = MemVT.changeTypeToInteger();
1685 
1686     // TODO: If we passed in the base kernel offset we could have a better
1687     // alignment than 4, but we don't really need it.
1688     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1689     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1690                                MachineMemOperand::MODereferenceable |
1691                                    MachineMemOperand::MOInvariant);
1692 
1693     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1694     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1695 
1696     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1697     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1698     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1699 
1700 
1701     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1702   }
1703 
1704   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1705   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1706                              MachineMemOperand::MODereferenceable |
1707                                  MachineMemOperand::MOInvariant);
1708 
1709   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1710   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1711 }
1712 
1713 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1714                                               const SDLoc &SL, SDValue Chain,
1715                                               const ISD::InputArg &Arg) const {
1716   MachineFunction &MF = DAG.getMachineFunction();
1717   MachineFrameInfo &MFI = MF.getFrameInfo();
1718 
1719   if (Arg.Flags.isByVal()) {
1720     unsigned Size = Arg.Flags.getByValSize();
1721     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1722     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1723   }
1724 
1725   unsigned ArgOffset = VA.getLocMemOffset();
1726   unsigned ArgSize = VA.getValVT().getStoreSize();
1727 
1728   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1729 
1730   // Create load nodes to retrieve arguments from the stack.
1731   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1732   SDValue ArgValue;
1733 
1734   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1735   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1736   MVT MemVT = VA.getValVT();
1737 
1738   switch (VA.getLocInfo()) {
1739   default:
1740     break;
1741   case CCValAssign::BCvt:
1742     MemVT = VA.getLocVT();
1743     break;
1744   case CCValAssign::SExt:
1745     ExtType = ISD::SEXTLOAD;
1746     break;
1747   case CCValAssign::ZExt:
1748     ExtType = ISD::ZEXTLOAD;
1749     break;
1750   case CCValAssign::AExt:
1751     ExtType = ISD::EXTLOAD;
1752     break;
1753   }
1754 
1755   ArgValue = DAG.getExtLoad(
1756     ExtType, SL, VA.getLocVT(), Chain, FIN,
1757     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1758     MemVT);
1759   return ArgValue;
1760 }
1761 
1762 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1763   const SIMachineFunctionInfo &MFI,
1764   EVT VT,
1765   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1766   const ArgDescriptor *Reg;
1767   const TargetRegisterClass *RC;
1768   LLT Ty;
1769 
1770   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1771   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1772 }
1773 
1774 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1775                                CallingConv::ID CallConv,
1776                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1777                                FunctionType *FType,
1778                                SIMachineFunctionInfo *Info) {
1779   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1780     const ISD::InputArg *Arg = &Ins[I];
1781 
1782     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1783            "vector type argument should have been split");
1784 
1785     // First check if it's a PS input addr.
1786     if (CallConv == CallingConv::AMDGPU_PS &&
1787         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1788       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1789 
1790       // Inconveniently only the first part of the split is marked as isSplit,
1791       // so skip to the end. We only want to increment PSInputNum once for the
1792       // entire split argument.
1793       if (Arg->Flags.isSplit()) {
1794         while (!Arg->Flags.isSplitEnd()) {
1795           assert((!Arg->VT.isVector() ||
1796                   Arg->VT.getScalarSizeInBits() == 16) &&
1797                  "unexpected vector split in ps argument type");
1798           if (!SkipArg)
1799             Splits.push_back(*Arg);
1800           Arg = &Ins[++I];
1801         }
1802       }
1803 
1804       if (SkipArg) {
1805         // We can safely skip PS inputs.
1806         Skipped.set(Arg->getOrigArgIndex());
1807         ++PSInputNum;
1808         continue;
1809       }
1810 
1811       Info->markPSInputAllocated(PSInputNum);
1812       if (Arg->Used)
1813         Info->markPSInputEnabled(PSInputNum);
1814 
1815       ++PSInputNum;
1816     }
1817 
1818     Splits.push_back(*Arg);
1819   }
1820 }
1821 
1822 // Allocate special inputs passed in VGPRs.
1823 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1824                                                       MachineFunction &MF,
1825                                                       const SIRegisterInfo &TRI,
1826                                                       SIMachineFunctionInfo &Info) const {
1827   const LLT S32 = LLT::scalar(32);
1828   MachineRegisterInfo &MRI = MF.getRegInfo();
1829 
1830   if (Info.hasWorkItemIDX()) {
1831     Register Reg = AMDGPU::VGPR0;
1832     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1833 
1834     CCInfo.AllocateReg(Reg);
1835     unsigned Mask = (Subtarget->hasPackedTID() &&
1836                      Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
1837     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1838   }
1839 
1840   if (Info.hasWorkItemIDY()) {
1841     assert(Info.hasWorkItemIDX());
1842     if (Subtarget->hasPackedTID()) {
1843       Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1844                                                         0x3ff << 10));
1845     } else {
1846       unsigned Reg = AMDGPU::VGPR1;
1847       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1848 
1849       CCInfo.AllocateReg(Reg);
1850       Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1851     }
1852   }
1853 
1854   if (Info.hasWorkItemIDZ()) {
1855     assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
1856     if (Subtarget->hasPackedTID()) {
1857       Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1858                                                         0x3ff << 20));
1859     } else {
1860       unsigned Reg = AMDGPU::VGPR2;
1861       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1862 
1863       CCInfo.AllocateReg(Reg);
1864       Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1865     }
1866   }
1867 }
1868 
1869 // Try to allocate a VGPR at the end of the argument list, or if no argument
1870 // VGPRs are left allocating a stack slot.
1871 // If \p Mask is is given it indicates bitfield position in the register.
1872 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1873 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1874                                          ArgDescriptor Arg = ArgDescriptor()) {
1875   if (Arg.isSet())
1876     return ArgDescriptor::createArg(Arg, Mask);
1877 
1878   ArrayRef<MCPhysReg> ArgVGPRs
1879     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1880   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1881   if (RegIdx == ArgVGPRs.size()) {
1882     // Spill to stack required.
1883     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1884 
1885     return ArgDescriptor::createStack(Offset, Mask);
1886   }
1887 
1888   unsigned Reg = ArgVGPRs[RegIdx];
1889   Reg = CCInfo.AllocateReg(Reg);
1890   assert(Reg != AMDGPU::NoRegister);
1891 
1892   MachineFunction &MF = CCInfo.getMachineFunction();
1893   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1894   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1895   return ArgDescriptor::createRegister(Reg, Mask);
1896 }
1897 
1898 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1899                                              const TargetRegisterClass *RC,
1900                                              unsigned NumArgRegs) {
1901   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1902   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1903   if (RegIdx == ArgSGPRs.size())
1904     report_fatal_error("ran out of SGPRs for arguments");
1905 
1906   unsigned Reg = ArgSGPRs[RegIdx];
1907   Reg = CCInfo.AllocateReg(Reg);
1908   assert(Reg != AMDGPU::NoRegister);
1909 
1910   MachineFunction &MF = CCInfo.getMachineFunction();
1911   MF.addLiveIn(Reg, RC);
1912   return ArgDescriptor::createRegister(Reg);
1913 }
1914 
1915 // If this has a fixed position, we still should allocate the register in the
1916 // CCInfo state. Technically we could get away with this for values passed
1917 // outside of the normal argument range.
1918 static void allocateFixedSGPRInputImpl(CCState &CCInfo,
1919                                        const TargetRegisterClass *RC,
1920                                        MCRegister Reg) {
1921   Reg = CCInfo.AllocateReg(Reg);
1922   assert(Reg != AMDGPU::NoRegister);
1923   MachineFunction &MF = CCInfo.getMachineFunction();
1924   MF.addLiveIn(Reg, RC);
1925 }
1926 
1927 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
1928   if (Arg) {
1929     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
1930                                Arg.getRegister());
1931   } else
1932     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1933 }
1934 
1935 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
1936   if (Arg) {
1937     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
1938                                Arg.getRegister());
1939   } else
1940     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1941 }
1942 
1943 /// Allocate implicit function VGPR arguments at the end of allocated user
1944 /// arguments.
1945 void SITargetLowering::allocateSpecialInputVGPRs(
1946   CCState &CCInfo, MachineFunction &MF,
1947   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1948   const unsigned Mask = 0x3ff;
1949   ArgDescriptor Arg;
1950 
1951   if (Info.hasWorkItemIDX()) {
1952     Arg = allocateVGPR32Input(CCInfo, Mask);
1953     Info.setWorkItemIDX(Arg);
1954   }
1955 
1956   if (Info.hasWorkItemIDY()) {
1957     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1958     Info.setWorkItemIDY(Arg);
1959   }
1960 
1961   if (Info.hasWorkItemIDZ())
1962     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1963 }
1964 
1965 /// Allocate implicit function VGPR arguments in fixed registers.
1966 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1967   CCState &CCInfo, MachineFunction &MF,
1968   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1969   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1970   if (!Reg)
1971     report_fatal_error("failed to allocated VGPR for implicit arguments");
1972 
1973   const unsigned Mask = 0x3ff;
1974   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1975   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1976   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1977 }
1978 
1979 void SITargetLowering::allocateSpecialInputSGPRs(
1980   CCState &CCInfo,
1981   MachineFunction &MF,
1982   const SIRegisterInfo &TRI,
1983   SIMachineFunctionInfo &Info) const {
1984   auto &ArgInfo = Info.getArgInfo();
1985 
1986   // TODO: Unify handling with private memory pointers.
1987 
1988   if (Info.hasDispatchPtr())
1989     allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
1990 
1991   if (Info.hasQueuePtr())
1992     allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
1993 
1994   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
1995   // constant offset from the kernarg segment.
1996   if (Info.hasImplicitArgPtr())
1997     allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
1998 
1999   if (Info.hasDispatchID())
2000     allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2001 
2002   // flat_scratch_init is not applicable for non-kernel functions.
2003 
2004   if (Info.hasWorkGroupIDX())
2005     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2006 
2007   if (Info.hasWorkGroupIDY())
2008     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2009 
2010   if (Info.hasWorkGroupIDZ())
2011     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2012 }
2013 
2014 // Allocate special inputs passed in user SGPRs.
2015 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2016                                             MachineFunction &MF,
2017                                             const SIRegisterInfo &TRI,
2018                                             SIMachineFunctionInfo &Info) const {
2019   if (Info.hasImplicitBufferPtr()) {
2020     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2021     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2022     CCInfo.AllocateReg(ImplicitBufferPtrReg);
2023   }
2024 
2025   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2026   if (Info.hasPrivateSegmentBuffer()) {
2027     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2028     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2029     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2030   }
2031 
2032   if (Info.hasDispatchPtr()) {
2033     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2034     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2035     CCInfo.AllocateReg(DispatchPtrReg);
2036   }
2037 
2038   if (Info.hasQueuePtr()) {
2039     Register QueuePtrReg = Info.addQueuePtr(TRI);
2040     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2041     CCInfo.AllocateReg(QueuePtrReg);
2042   }
2043 
2044   if (Info.hasKernargSegmentPtr()) {
2045     MachineRegisterInfo &MRI = MF.getRegInfo();
2046     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2047     CCInfo.AllocateReg(InputPtrReg);
2048 
2049     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2050     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2051   }
2052 
2053   if (Info.hasDispatchID()) {
2054     Register DispatchIDReg = Info.addDispatchID(TRI);
2055     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2056     CCInfo.AllocateReg(DispatchIDReg);
2057   }
2058 
2059   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2060     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2061     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2062     CCInfo.AllocateReg(FlatScratchInitReg);
2063   }
2064 
2065   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2066   // these from the dispatch pointer.
2067 }
2068 
2069 // Allocate special input registers that are initialized per-wave.
2070 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2071                                            MachineFunction &MF,
2072                                            SIMachineFunctionInfo &Info,
2073                                            CallingConv::ID CallConv,
2074                                            bool IsShader) const {
2075   if (Info.hasWorkGroupIDX()) {
2076     Register Reg = Info.addWorkGroupIDX();
2077     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2078     CCInfo.AllocateReg(Reg);
2079   }
2080 
2081   if (Info.hasWorkGroupIDY()) {
2082     Register Reg = Info.addWorkGroupIDY();
2083     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2084     CCInfo.AllocateReg(Reg);
2085   }
2086 
2087   if (Info.hasWorkGroupIDZ()) {
2088     Register Reg = Info.addWorkGroupIDZ();
2089     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2090     CCInfo.AllocateReg(Reg);
2091   }
2092 
2093   if (Info.hasWorkGroupInfo()) {
2094     Register Reg = Info.addWorkGroupInfo();
2095     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2096     CCInfo.AllocateReg(Reg);
2097   }
2098 
2099   if (Info.hasPrivateSegmentWaveByteOffset()) {
2100     // Scratch wave offset passed in system SGPR.
2101     unsigned PrivateSegmentWaveByteOffsetReg;
2102 
2103     if (IsShader) {
2104       PrivateSegmentWaveByteOffsetReg =
2105         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2106 
2107       // This is true if the scratch wave byte offset doesn't have a fixed
2108       // location.
2109       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2110         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2111         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2112       }
2113     } else
2114       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2115 
2116     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2117     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2118   }
2119 }
2120 
2121 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2122                                      MachineFunction &MF,
2123                                      const SIRegisterInfo &TRI,
2124                                      SIMachineFunctionInfo &Info) {
2125   // Now that we've figured out where the scratch register inputs are, see if
2126   // should reserve the arguments and use them directly.
2127   MachineFrameInfo &MFI = MF.getFrameInfo();
2128   bool HasStackObjects = MFI.hasStackObjects();
2129   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2130 
2131   // Record that we know we have non-spill stack objects so we don't need to
2132   // check all stack objects later.
2133   if (HasStackObjects)
2134     Info.setHasNonSpillStackObjects(true);
2135 
2136   // Everything live out of a block is spilled with fast regalloc, so it's
2137   // almost certain that spilling will be required.
2138   if (TM.getOptLevel() == CodeGenOpt::None)
2139     HasStackObjects = true;
2140 
2141   // For now assume stack access is needed in any callee functions, so we need
2142   // the scratch registers to pass in.
2143   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2144 
2145   if (!ST.enableFlatScratch()) {
2146     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2147       // If we have stack objects, we unquestionably need the private buffer
2148       // resource. For the Code Object V2 ABI, this will be the first 4 user
2149       // SGPR inputs. We can reserve those and use them directly.
2150 
2151       Register PrivateSegmentBufferReg =
2152           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2153       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2154     } else {
2155       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2156       // We tentatively reserve the last registers (skipping the last registers
2157       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2158       // we'll replace these with the ones immediately after those which were
2159       // really allocated. In the prologue copies will be inserted from the
2160       // argument to these reserved registers.
2161 
2162       // Without HSA, relocations are used for the scratch pointer and the
2163       // buffer resource setup is always inserted in the prologue. Scratch wave
2164       // offset is still in an input SGPR.
2165       Info.setScratchRSrcReg(ReservedBufferReg);
2166     }
2167   }
2168 
2169   MachineRegisterInfo &MRI = MF.getRegInfo();
2170 
2171   // For entry functions we have to set up the stack pointer if we use it,
2172   // whereas non-entry functions get this "for free". This means there is no
2173   // intrinsic advantage to using S32 over S34 in cases where we do not have
2174   // calls but do need a frame pointer (i.e. if we are requested to have one
2175   // because frame pointer elimination is disabled). To keep things simple we
2176   // only ever use S32 as the call ABI stack pointer, and so using it does not
2177   // imply we need a separate frame pointer.
2178   //
2179   // Try to use s32 as the SP, but move it if it would interfere with input
2180   // arguments. This won't work with calls though.
2181   //
2182   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2183   // registers.
2184   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2185     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2186   } else {
2187     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2188 
2189     if (MFI.hasCalls())
2190       report_fatal_error("call in graphics shader with too many input SGPRs");
2191 
2192     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2193       if (!MRI.isLiveIn(Reg)) {
2194         Info.setStackPtrOffsetReg(Reg);
2195         break;
2196       }
2197     }
2198 
2199     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2200       report_fatal_error("failed to find register for SP");
2201   }
2202 
2203   // hasFP should be accurate for entry functions even before the frame is
2204   // finalized, because it does not rely on the known stack size, only
2205   // properties like whether variable sized objects are present.
2206   if (ST.getFrameLowering()->hasFP(MF)) {
2207     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2208   }
2209 }
2210 
2211 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2212   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2213   return !Info->isEntryFunction();
2214 }
2215 
2216 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2217 
2218 }
2219 
2220 void SITargetLowering::insertCopiesSplitCSR(
2221   MachineBasicBlock *Entry,
2222   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2223   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2224 
2225   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2226   if (!IStart)
2227     return;
2228 
2229   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2230   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2231   MachineBasicBlock::iterator MBBI = Entry->begin();
2232   for (const MCPhysReg *I = IStart; *I; ++I) {
2233     const TargetRegisterClass *RC = nullptr;
2234     if (AMDGPU::SReg_64RegClass.contains(*I))
2235       RC = &AMDGPU::SGPR_64RegClass;
2236     else if (AMDGPU::SReg_32RegClass.contains(*I))
2237       RC = &AMDGPU::SGPR_32RegClass;
2238     else
2239       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2240 
2241     Register NewVR = MRI->createVirtualRegister(RC);
2242     // Create copy from CSR to a virtual register.
2243     Entry->addLiveIn(*I);
2244     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2245       .addReg(*I);
2246 
2247     // Insert the copy-back instructions right before the terminator.
2248     for (auto *Exit : Exits)
2249       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2250               TII->get(TargetOpcode::COPY), *I)
2251         .addReg(NewVR);
2252   }
2253 }
2254 
2255 SDValue SITargetLowering::LowerFormalArguments(
2256     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2257     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2258     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2259   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2260 
2261   MachineFunction &MF = DAG.getMachineFunction();
2262   const Function &Fn = MF.getFunction();
2263   FunctionType *FType = MF.getFunction().getFunctionType();
2264   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2265 
2266   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2267     DiagnosticInfoUnsupported NoGraphicsHSA(
2268         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2269     DAG.getContext()->diagnose(NoGraphicsHSA);
2270     return DAG.getEntryNode();
2271   }
2272 
2273   Info->allocateModuleLDSGlobal(Fn.getParent());
2274 
2275   SmallVector<ISD::InputArg, 16> Splits;
2276   SmallVector<CCValAssign, 16> ArgLocs;
2277   BitVector Skipped(Ins.size());
2278   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2279                  *DAG.getContext());
2280 
2281   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2282   bool IsKernel = AMDGPU::isKernel(CallConv);
2283   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2284 
2285   if (IsGraphics) {
2286     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2287            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2288            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2289            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2290            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2291            !Info->hasWorkItemIDZ());
2292   }
2293 
2294   if (CallConv == CallingConv::AMDGPU_PS) {
2295     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2296 
2297     // At least one interpolation mode must be enabled or else the GPU will
2298     // hang.
2299     //
2300     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2301     // set PSInputAddr, the user wants to enable some bits after the compilation
2302     // based on run-time states. Since we can't know what the final PSInputEna
2303     // will look like, so we shouldn't do anything here and the user should take
2304     // responsibility for the correct programming.
2305     //
2306     // Otherwise, the following restrictions apply:
2307     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2308     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2309     //   enabled too.
2310     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2311         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2312       CCInfo.AllocateReg(AMDGPU::VGPR0);
2313       CCInfo.AllocateReg(AMDGPU::VGPR1);
2314       Info->markPSInputAllocated(0);
2315       Info->markPSInputEnabled(0);
2316     }
2317     if (Subtarget->isAmdPalOS()) {
2318       // For isAmdPalOS, the user does not enable some bits after compilation
2319       // based on run-time states; the register values being generated here are
2320       // the final ones set in hardware. Therefore we need to apply the
2321       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2322       // a bit is set in PSInputAddr but not PSInputEnable is where the
2323       // frontend set up an input arg for a particular interpolation mode, but
2324       // nothing uses that input arg. Really we should have an earlier pass
2325       // that removes such an arg.)
2326       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2327       if ((PsInputBits & 0x7F) == 0 ||
2328           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2329         Info->markPSInputEnabled(
2330             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2331     }
2332   } else if (IsKernel) {
2333     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2334   } else {
2335     Splits.append(Ins.begin(), Ins.end());
2336   }
2337 
2338   if (IsEntryFunc) {
2339     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2340     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2341   } else {
2342     // For the fixed ABI, pass workitem IDs in the last argument register.
2343     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2344       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2345   }
2346 
2347   if (IsKernel) {
2348     analyzeFormalArgumentsCompute(CCInfo, Ins);
2349   } else {
2350     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2351     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2352   }
2353 
2354   SmallVector<SDValue, 16> Chains;
2355 
2356   // FIXME: This is the minimum kernel argument alignment. We should improve
2357   // this to the maximum alignment of the arguments.
2358   //
2359   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2360   // kern arg offset.
2361   const Align KernelArgBaseAlign = Align(16);
2362 
2363   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2364     const ISD::InputArg &Arg = Ins[i];
2365     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2366       InVals.push_back(DAG.getUNDEF(Arg.VT));
2367       continue;
2368     }
2369 
2370     CCValAssign &VA = ArgLocs[ArgIdx++];
2371     MVT VT = VA.getLocVT();
2372 
2373     if (IsEntryFunc && VA.isMemLoc()) {
2374       VT = Ins[i].VT;
2375       EVT MemVT = VA.getLocVT();
2376 
2377       const uint64_t Offset = VA.getLocMemOffset();
2378       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2379 
2380       if (Arg.Flags.isByRef()) {
2381         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2382 
2383         const GCNTargetMachine &TM =
2384             static_cast<const GCNTargetMachine &>(getTargetMachine());
2385         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2386                                     Arg.Flags.getPointerAddrSpace())) {
2387           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2388                                      Arg.Flags.getPointerAddrSpace());
2389         }
2390 
2391         InVals.push_back(Ptr);
2392         continue;
2393       }
2394 
2395       SDValue Arg = lowerKernargMemParameter(
2396         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2397       Chains.push_back(Arg.getValue(1));
2398 
2399       auto *ParamTy =
2400         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2401       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2402           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2403                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2404         // On SI local pointers are just offsets into LDS, so they are always
2405         // less than 16-bits.  On CI and newer they could potentially be
2406         // real pointers, so we can't guarantee their size.
2407         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2408                           DAG.getValueType(MVT::i16));
2409       }
2410 
2411       InVals.push_back(Arg);
2412       continue;
2413     } else if (!IsEntryFunc && VA.isMemLoc()) {
2414       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2415       InVals.push_back(Val);
2416       if (!Arg.Flags.isByVal())
2417         Chains.push_back(Val.getValue(1));
2418       continue;
2419     }
2420 
2421     assert(VA.isRegLoc() && "Parameter must be in a register!");
2422 
2423     Register Reg = VA.getLocReg();
2424     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2425     EVT ValVT = VA.getValVT();
2426 
2427     Reg = MF.addLiveIn(Reg, RC);
2428     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2429 
2430     if (Arg.Flags.isSRet()) {
2431       // The return object should be reasonably addressable.
2432 
2433       // FIXME: This helps when the return is a real sret. If it is a
2434       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2435       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2436       unsigned NumBits
2437         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2438       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2439         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2440     }
2441 
2442     // If this is an 8 or 16-bit value, it is really passed promoted
2443     // to 32 bits. Insert an assert[sz]ext to capture this, then
2444     // truncate to the right size.
2445     switch (VA.getLocInfo()) {
2446     case CCValAssign::Full:
2447       break;
2448     case CCValAssign::BCvt:
2449       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2450       break;
2451     case CCValAssign::SExt:
2452       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2453                         DAG.getValueType(ValVT));
2454       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2455       break;
2456     case CCValAssign::ZExt:
2457       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2458                         DAG.getValueType(ValVT));
2459       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2460       break;
2461     case CCValAssign::AExt:
2462       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2463       break;
2464     default:
2465       llvm_unreachable("Unknown loc info!");
2466     }
2467 
2468     InVals.push_back(Val);
2469   }
2470 
2471   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2472     // Special inputs come after user arguments.
2473     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2474   }
2475 
2476   // Start adding system SGPRs.
2477   if (IsEntryFunc) {
2478     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2479   } else {
2480     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2481     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2482   }
2483 
2484   auto &ArgUsageInfo =
2485     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2486   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2487 
2488   unsigned StackArgSize = CCInfo.getNextStackOffset();
2489   Info->setBytesInStackArgArea(StackArgSize);
2490 
2491   return Chains.empty() ? Chain :
2492     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2493 }
2494 
2495 // TODO: If return values can't fit in registers, we should return as many as
2496 // possible in registers before passing on stack.
2497 bool SITargetLowering::CanLowerReturn(
2498   CallingConv::ID CallConv,
2499   MachineFunction &MF, bool IsVarArg,
2500   const SmallVectorImpl<ISD::OutputArg> &Outs,
2501   LLVMContext &Context) const {
2502   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2503   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2504   // for shaders. Vector types should be explicitly handled by CC.
2505   if (AMDGPU::isEntryFunctionCC(CallConv))
2506     return true;
2507 
2508   SmallVector<CCValAssign, 16> RVLocs;
2509   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2510   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2511 }
2512 
2513 SDValue
2514 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2515                               bool isVarArg,
2516                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2517                               const SmallVectorImpl<SDValue> &OutVals,
2518                               const SDLoc &DL, SelectionDAG &DAG) const {
2519   MachineFunction &MF = DAG.getMachineFunction();
2520   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2521 
2522   if (AMDGPU::isKernel(CallConv)) {
2523     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2524                                              OutVals, DL, DAG);
2525   }
2526 
2527   bool IsShader = AMDGPU::isShader(CallConv);
2528 
2529   Info->setIfReturnsVoid(Outs.empty());
2530   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2531 
2532   // CCValAssign - represent the assignment of the return value to a location.
2533   SmallVector<CCValAssign, 48> RVLocs;
2534   SmallVector<ISD::OutputArg, 48> Splits;
2535 
2536   // CCState - Info about the registers and stack slots.
2537   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2538                  *DAG.getContext());
2539 
2540   // Analyze outgoing return values.
2541   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2542 
2543   SDValue Flag;
2544   SmallVector<SDValue, 48> RetOps;
2545   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2546 
2547   // Add return address for callable functions.
2548   if (!Info->isEntryFunction()) {
2549     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2550     SDValue ReturnAddrReg = CreateLiveInRegister(
2551       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2552 
2553     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2554         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2555         MVT::i64);
2556     Chain =
2557         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2558     Flag = Chain.getValue(1);
2559     RetOps.push_back(ReturnAddrVirtualReg);
2560   }
2561 
2562   // Copy the result values into the output registers.
2563   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2564        ++I, ++RealRVLocIdx) {
2565     CCValAssign &VA = RVLocs[I];
2566     assert(VA.isRegLoc() && "Can only return in registers!");
2567     // TODO: Partially return in registers if return values don't fit.
2568     SDValue Arg = OutVals[RealRVLocIdx];
2569 
2570     // Copied from other backends.
2571     switch (VA.getLocInfo()) {
2572     case CCValAssign::Full:
2573       break;
2574     case CCValAssign::BCvt:
2575       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2576       break;
2577     case CCValAssign::SExt:
2578       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2579       break;
2580     case CCValAssign::ZExt:
2581       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2582       break;
2583     case CCValAssign::AExt:
2584       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2585       break;
2586     default:
2587       llvm_unreachable("Unknown loc info!");
2588     }
2589 
2590     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2591     Flag = Chain.getValue(1);
2592     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2593   }
2594 
2595   // FIXME: Does sret work properly?
2596   if (!Info->isEntryFunction()) {
2597     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2598     const MCPhysReg *I =
2599       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2600     if (I) {
2601       for (; *I; ++I) {
2602         if (AMDGPU::SReg_64RegClass.contains(*I))
2603           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2604         else if (AMDGPU::SReg_32RegClass.contains(*I))
2605           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2606         else
2607           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2608       }
2609     }
2610   }
2611 
2612   // Update chain and glue.
2613   RetOps[0] = Chain;
2614   if (Flag.getNode())
2615     RetOps.push_back(Flag);
2616 
2617   unsigned Opc = AMDGPUISD::ENDPGM;
2618   if (!IsWaveEnd)
2619     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2620   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2621 }
2622 
2623 SDValue SITargetLowering::LowerCallResult(
2624     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2625     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2626     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2627     SDValue ThisVal) const {
2628   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2629 
2630   // Assign locations to each value returned by this call.
2631   SmallVector<CCValAssign, 16> RVLocs;
2632   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2633                  *DAG.getContext());
2634   CCInfo.AnalyzeCallResult(Ins, RetCC);
2635 
2636   // Copy all of the result registers out of their specified physreg.
2637   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2638     CCValAssign VA = RVLocs[i];
2639     SDValue Val;
2640 
2641     if (VA.isRegLoc()) {
2642       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2643       Chain = Val.getValue(1);
2644       InFlag = Val.getValue(2);
2645     } else if (VA.isMemLoc()) {
2646       report_fatal_error("TODO: return values in memory");
2647     } else
2648       llvm_unreachable("unknown argument location type");
2649 
2650     switch (VA.getLocInfo()) {
2651     case CCValAssign::Full:
2652       break;
2653     case CCValAssign::BCvt:
2654       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2655       break;
2656     case CCValAssign::ZExt:
2657       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2658                         DAG.getValueType(VA.getValVT()));
2659       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2660       break;
2661     case CCValAssign::SExt:
2662       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2663                         DAG.getValueType(VA.getValVT()));
2664       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2665       break;
2666     case CCValAssign::AExt:
2667       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2668       break;
2669     default:
2670       llvm_unreachable("Unknown loc info!");
2671     }
2672 
2673     InVals.push_back(Val);
2674   }
2675 
2676   return Chain;
2677 }
2678 
2679 // Add code to pass special inputs required depending on used features separate
2680 // from the explicit user arguments present in the IR.
2681 void SITargetLowering::passSpecialInputs(
2682     CallLoweringInfo &CLI,
2683     CCState &CCInfo,
2684     const SIMachineFunctionInfo &Info,
2685     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2686     SmallVectorImpl<SDValue> &MemOpChains,
2687     SDValue Chain) const {
2688   // If we don't have a call site, this was a call inserted by
2689   // legalization. These can never use special inputs.
2690   if (!CLI.CB)
2691     return;
2692 
2693   SelectionDAG &DAG = CLI.DAG;
2694   const SDLoc &DL = CLI.DL;
2695 
2696   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2697   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2698 
2699   const AMDGPUFunctionArgInfo *CalleeArgInfo
2700     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2701   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2702     auto &ArgUsageInfo =
2703       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2704     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2705   }
2706 
2707   // TODO: Unify with private memory register handling. This is complicated by
2708   // the fact that at least in kernels, the input argument is not necessarily
2709   // in the same location as the input.
2710   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2711     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2712     AMDGPUFunctionArgInfo::QUEUE_PTR,
2713     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
2714     AMDGPUFunctionArgInfo::DISPATCH_ID,
2715     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2716     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2717     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
2718   };
2719 
2720   for (auto InputID : InputRegs) {
2721     const ArgDescriptor *OutgoingArg;
2722     const TargetRegisterClass *ArgRC;
2723     LLT ArgTy;
2724 
2725     std::tie(OutgoingArg, ArgRC, ArgTy) =
2726         CalleeArgInfo->getPreloadedValue(InputID);
2727     if (!OutgoingArg)
2728       continue;
2729 
2730     const ArgDescriptor *IncomingArg;
2731     const TargetRegisterClass *IncomingArgRC;
2732     LLT Ty;
2733     std::tie(IncomingArg, IncomingArgRC, Ty) =
2734         CallerArgInfo.getPreloadedValue(InputID);
2735     assert(IncomingArgRC == ArgRC);
2736 
2737     // All special arguments are ints for now.
2738     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2739     SDValue InputReg;
2740 
2741     if (IncomingArg) {
2742       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2743     } else {
2744       // The implicit arg ptr is special because it doesn't have a corresponding
2745       // input for kernels, and is computed from the kernarg segment pointer.
2746       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2747       InputReg = getImplicitArgPtr(DAG, DL);
2748     }
2749 
2750     if (OutgoingArg->isRegister()) {
2751       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2752       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2753         report_fatal_error("failed to allocate implicit input argument");
2754     } else {
2755       unsigned SpecialArgOffset =
2756           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2757       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2758                                               SpecialArgOffset);
2759       MemOpChains.push_back(ArgStore);
2760     }
2761   }
2762 
2763   // Pack workitem IDs into a single register or pass it as is if already
2764   // packed.
2765   const ArgDescriptor *OutgoingArg;
2766   const TargetRegisterClass *ArgRC;
2767   LLT Ty;
2768 
2769   std::tie(OutgoingArg, ArgRC, Ty) =
2770       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2771   if (!OutgoingArg)
2772     std::tie(OutgoingArg, ArgRC, Ty) =
2773         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2774   if (!OutgoingArg)
2775     std::tie(OutgoingArg, ArgRC, Ty) =
2776         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2777   if (!OutgoingArg)
2778     return;
2779 
2780   const ArgDescriptor *IncomingArgX = std::get<0>(
2781       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2782   const ArgDescriptor *IncomingArgY = std::get<0>(
2783       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2784   const ArgDescriptor *IncomingArgZ = std::get<0>(
2785       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2786 
2787   SDValue InputReg;
2788   SDLoc SL;
2789 
2790   // If incoming ids are not packed we need to pack them.
2791   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX)
2792     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2793 
2794   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
2795     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2796     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2797                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2798     InputReg = InputReg.getNode() ?
2799                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2800   }
2801 
2802   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
2803     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2804     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2805                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2806     InputReg = InputReg.getNode() ?
2807                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2808   }
2809 
2810   if (!InputReg.getNode()) {
2811     // Workitem ids are already packed, any of present incoming arguments
2812     // will carry all required fields.
2813     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2814       IncomingArgX ? *IncomingArgX :
2815       IncomingArgY ? *IncomingArgY :
2816                      *IncomingArgZ, ~0u);
2817     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2818   }
2819 
2820   if (OutgoingArg->isRegister()) {
2821     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2822     CCInfo.AllocateReg(OutgoingArg->getRegister());
2823   } else {
2824     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2825     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2826                                             SpecialArgOffset);
2827     MemOpChains.push_back(ArgStore);
2828   }
2829 }
2830 
2831 static bool canGuaranteeTCO(CallingConv::ID CC) {
2832   return CC == CallingConv::Fast;
2833 }
2834 
2835 /// Return true if we might ever do TCO for calls with this calling convention.
2836 static bool mayTailCallThisCC(CallingConv::ID CC) {
2837   switch (CC) {
2838   case CallingConv::C:
2839   case CallingConv::AMDGPU_Gfx:
2840     return true;
2841   default:
2842     return canGuaranteeTCO(CC);
2843   }
2844 }
2845 
2846 bool SITargetLowering::isEligibleForTailCallOptimization(
2847     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2848     const SmallVectorImpl<ISD::OutputArg> &Outs,
2849     const SmallVectorImpl<SDValue> &OutVals,
2850     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2851   if (!mayTailCallThisCC(CalleeCC))
2852     return false;
2853 
2854   // For a divergent call target, we need to do a waterfall loop over the
2855   // possible callees which precludes us from using a simple jump.
2856   if (Callee->isDivergent())
2857     return false;
2858 
2859   MachineFunction &MF = DAG.getMachineFunction();
2860   const Function &CallerF = MF.getFunction();
2861   CallingConv::ID CallerCC = CallerF.getCallingConv();
2862   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2863   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2864 
2865   // Kernels aren't callable, and don't have a live in return address so it
2866   // doesn't make sense to do a tail call with entry functions.
2867   if (!CallerPreserved)
2868     return false;
2869 
2870   bool CCMatch = CallerCC == CalleeCC;
2871 
2872   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2873     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2874       return true;
2875     return false;
2876   }
2877 
2878   // TODO: Can we handle var args?
2879   if (IsVarArg)
2880     return false;
2881 
2882   for (const Argument &Arg : CallerF.args()) {
2883     if (Arg.hasByValAttr())
2884       return false;
2885   }
2886 
2887   LLVMContext &Ctx = *DAG.getContext();
2888 
2889   // Check that the call results are passed in the same way.
2890   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2891                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2892                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2893     return false;
2894 
2895   // The callee has to preserve all registers the caller needs to preserve.
2896   if (!CCMatch) {
2897     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2898     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2899       return false;
2900   }
2901 
2902   // Nothing more to check if the callee is taking no arguments.
2903   if (Outs.empty())
2904     return true;
2905 
2906   SmallVector<CCValAssign, 16> ArgLocs;
2907   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2908 
2909   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2910 
2911   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2912   // If the stack arguments for this call do not fit into our own save area then
2913   // the call cannot be made tail.
2914   // TODO: Is this really necessary?
2915   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2916     return false;
2917 
2918   const MachineRegisterInfo &MRI = MF.getRegInfo();
2919   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2920 }
2921 
2922 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2923   if (!CI->isTailCall())
2924     return false;
2925 
2926   const Function *ParentFn = CI->getParent()->getParent();
2927   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2928     return false;
2929   return true;
2930 }
2931 
2932 // The wave scratch offset register is used as the global base pointer.
2933 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2934                                     SmallVectorImpl<SDValue> &InVals) const {
2935   SelectionDAG &DAG = CLI.DAG;
2936   const SDLoc &DL = CLI.DL;
2937   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2938   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2939   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2940   SDValue Chain = CLI.Chain;
2941   SDValue Callee = CLI.Callee;
2942   bool &IsTailCall = CLI.IsTailCall;
2943   CallingConv::ID CallConv = CLI.CallConv;
2944   bool IsVarArg = CLI.IsVarArg;
2945   bool IsSibCall = false;
2946   bool IsThisReturn = false;
2947   MachineFunction &MF = DAG.getMachineFunction();
2948 
2949   if (Callee.isUndef() || isNullConstant(Callee)) {
2950     if (!CLI.IsTailCall) {
2951       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2952         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2953     }
2954 
2955     return Chain;
2956   }
2957 
2958   if (IsVarArg) {
2959     return lowerUnhandledCall(CLI, InVals,
2960                               "unsupported call to variadic function ");
2961   }
2962 
2963   if (!CLI.CB)
2964     report_fatal_error("unsupported libcall legalization");
2965 
2966   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2967     return lowerUnhandledCall(CLI, InVals,
2968                               "unsupported required tail call to function ");
2969   }
2970 
2971   if (AMDGPU::isShader(CallConv)) {
2972     // Note the issue is with the CC of the called function, not of the call
2973     // itself.
2974     return lowerUnhandledCall(CLI, InVals,
2975                               "unsupported call to a shader function ");
2976   }
2977 
2978   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
2979       CallConv != CallingConv::AMDGPU_Gfx) {
2980     // Only allow calls with specific calling conventions.
2981     return lowerUnhandledCall(CLI, InVals,
2982                               "unsupported calling convention for call from "
2983                               "graphics shader of function ");
2984   }
2985 
2986   if (IsTailCall) {
2987     IsTailCall = isEligibleForTailCallOptimization(
2988       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2989     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
2990       report_fatal_error("failed to perform tail call elimination on a call "
2991                          "site marked musttail");
2992     }
2993 
2994     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2995 
2996     // A sibling call is one where we're under the usual C ABI and not planning
2997     // to change that but can still do a tail call:
2998     if (!TailCallOpt && IsTailCall)
2999       IsSibCall = true;
3000 
3001     if (IsTailCall)
3002       ++NumTailCalls;
3003   }
3004 
3005   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3006   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3007   SmallVector<SDValue, 8> MemOpChains;
3008 
3009   // Analyze operands of the call, assigning locations to each operand.
3010   SmallVector<CCValAssign, 16> ArgLocs;
3011   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3012   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3013 
3014   if (AMDGPUTargetMachine::EnableFixedFunctionABI &&
3015       CallConv != CallingConv::AMDGPU_Gfx) {
3016     // With a fixed ABI, allocate fixed registers before user arguments.
3017     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3018   }
3019 
3020   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3021 
3022   // Get a count of how many bytes are to be pushed on the stack.
3023   unsigned NumBytes = CCInfo.getNextStackOffset();
3024 
3025   if (IsSibCall) {
3026     // Since we're not changing the ABI to make this a tail call, the memory
3027     // operands are already available in the caller's incoming argument space.
3028     NumBytes = 0;
3029   }
3030 
3031   // FPDiff is the byte offset of the call's argument area from the callee's.
3032   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3033   // by this amount for a tail call. In a sibling call it must be 0 because the
3034   // caller will deallocate the entire stack and the callee still expects its
3035   // arguments to begin at SP+0. Completely unused for non-tail calls.
3036   int32_t FPDiff = 0;
3037   MachineFrameInfo &MFI = MF.getFrameInfo();
3038 
3039   // Adjust the stack pointer for the new arguments...
3040   // These operations are automatically eliminated by the prolog/epilog pass
3041   if (!IsSibCall) {
3042     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3043 
3044     if (!Subtarget->enableFlatScratch()) {
3045       SmallVector<SDValue, 4> CopyFromChains;
3046 
3047       // In the HSA case, this should be an identity copy.
3048       SDValue ScratchRSrcReg
3049         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3050       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3051       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3052       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3053     }
3054   }
3055 
3056   MVT PtrVT = MVT::i32;
3057 
3058   // Walk the register/memloc assignments, inserting copies/loads.
3059   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3060     CCValAssign &VA = ArgLocs[i];
3061     SDValue Arg = OutVals[i];
3062 
3063     // Promote the value if needed.
3064     switch (VA.getLocInfo()) {
3065     case CCValAssign::Full:
3066       break;
3067     case CCValAssign::BCvt:
3068       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3069       break;
3070     case CCValAssign::ZExt:
3071       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3072       break;
3073     case CCValAssign::SExt:
3074       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3075       break;
3076     case CCValAssign::AExt:
3077       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3078       break;
3079     case CCValAssign::FPExt:
3080       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3081       break;
3082     default:
3083       llvm_unreachable("Unknown loc info!");
3084     }
3085 
3086     if (VA.isRegLoc()) {
3087       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3088     } else {
3089       assert(VA.isMemLoc());
3090 
3091       SDValue DstAddr;
3092       MachinePointerInfo DstInfo;
3093 
3094       unsigned LocMemOffset = VA.getLocMemOffset();
3095       int32_t Offset = LocMemOffset;
3096 
3097       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3098       MaybeAlign Alignment;
3099 
3100       if (IsTailCall) {
3101         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3102         unsigned OpSize = Flags.isByVal() ?
3103           Flags.getByValSize() : VA.getValVT().getStoreSize();
3104 
3105         // FIXME: We can have better than the minimum byval required alignment.
3106         Alignment =
3107             Flags.isByVal()
3108                 ? Flags.getNonZeroByValAlign()
3109                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3110 
3111         Offset = Offset + FPDiff;
3112         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3113 
3114         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3115         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3116 
3117         // Make sure any stack arguments overlapping with where we're storing
3118         // are loaded before this eventual operation. Otherwise they'll be
3119         // clobbered.
3120 
3121         // FIXME: Why is this really necessary? This seems to just result in a
3122         // lot of code to copy the stack and write them back to the same
3123         // locations, which are supposed to be immutable?
3124         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3125       } else {
3126         // Stores to the argument stack area are relative to the stack pointer.
3127         SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3128                                         MVT::i32);
3129         DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3130         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3131         Alignment =
3132             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3133       }
3134 
3135       if (Outs[i].Flags.isByVal()) {
3136         SDValue SizeNode =
3137             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3138         SDValue Cpy =
3139             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3140                           Outs[i].Flags.getNonZeroByValAlign(),
3141                           /*isVol = */ false, /*AlwaysInline = */ true,
3142                           /*isTailCall = */ false, DstInfo,
3143                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3144 
3145         MemOpChains.push_back(Cpy);
3146       } else {
3147         SDValue Store =
3148             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3149         MemOpChains.push_back(Store);
3150       }
3151     }
3152   }
3153 
3154   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
3155       CallConv != CallingConv::AMDGPU_Gfx) {
3156     // Copy special input registers after user input arguments.
3157     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3158   }
3159 
3160   if (!MemOpChains.empty())
3161     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3162 
3163   // Build a sequence of copy-to-reg nodes chained together with token chain
3164   // and flag operands which copy the outgoing args into the appropriate regs.
3165   SDValue InFlag;
3166   for (auto &RegToPass : RegsToPass) {
3167     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3168                              RegToPass.second, InFlag);
3169     InFlag = Chain.getValue(1);
3170   }
3171 
3172 
3173   SDValue PhysReturnAddrReg;
3174   if (IsTailCall) {
3175     // Since the return is being combined with the call, we need to pass on the
3176     // return address.
3177 
3178     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3179     SDValue ReturnAddrReg = CreateLiveInRegister(
3180       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3181 
3182     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3183                                         MVT::i64);
3184     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3185     InFlag = Chain.getValue(1);
3186   }
3187 
3188   // We don't usually want to end the call-sequence here because we would tidy
3189   // the frame up *after* the call, however in the ABI-changing tail-call case
3190   // we've carefully laid out the parameters so that when sp is reset they'll be
3191   // in the correct location.
3192   if (IsTailCall && !IsSibCall) {
3193     Chain = DAG.getCALLSEQ_END(Chain,
3194                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3195                                DAG.getTargetConstant(0, DL, MVT::i32),
3196                                InFlag, DL);
3197     InFlag = Chain.getValue(1);
3198   }
3199 
3200   std::vector<SDValue> Ops;
3201   Ops.push_back(Chain);
3202   Ops.push_back(Callee);
3203   // Add a redundant copy of the callee global which will not be legalized, as
3204   // we need direct access to the callee later.
3205   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3206     const GlobalValue *GV = GSD->getGlobal();
3207     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3208   } else {
3209     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3210   }
3211 
3212   if (IsTailCall) {
3213     // Each tail call may have to adjust the stack by a different amount, so
3214     // this information must travel along with the operation for eventual
3215     // consumption by emitEpilogue.
3216     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3217 
3218     Ops.push_back(PhysReturnAddrReg);
3219   }
3220 
3221   // Add argument registers to the end of the list so that they are known live
3222   // into the call.
3223   for (auto &RegToPass : RegsToPass) {
3224     Ops.push_back(DAG.getRegister(RegToPass.first,
3225                                   RegToPass.second.getValueType()));
3226   }
3227 
3228   // Add a register mask operand representing the call-preserved registers.
3229 
3230   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3231   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3232   assert(Mask && "Missing call preserved mask for calling convention");
3233   Ops.push_back(DAG.getRegisterMask(Mask));
3234 
3235   if (InFlag.getNode())
3236     Ops.push_back(InFlag);
3237 
3238   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3239 
3240   // If we're doing a tall call, use a TC_RETURN here rather than an
3241   // actual call instruction.
3242   if (IsTailCall) {
3243     MFI.setHasTailCall();
3244     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3245   }
3246 
3247   // Returns a chain and a flag for retval copy to use.
3248   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3249   Chain = Call.getValue(0);
3250   InFlag = Call.getValue(1);
3251 
3252   uint64_t CalleePopBytes = NumBytes;
3253   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3254                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3255                              InFlag, DL);
3256   if (!Ins.empty())
3257     InFlag = Chain.getValue(1);
3258 
3259   // Handle result values, copying them out of physregs into vregs that we
3260   // return.
3261   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3262                          InVals, IsThisReturn,
3263                          IsThisReturn ? OutVals[0] : SDValue());
3264 }
3265 
3266 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3267 // except for applying the wave size scale to the increment amount.
3268 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3269     SDValue Op, SelectionDAG &DAG) const {
3270   const MachineFunction &MF = DAG.getMachineFunction();
3271   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3272 
3273   SDLoc dl(Op);
3274   EVT VT = Op.getValueType();
3275   SDValue Tmp1 = Op;
3276   SDValue Tmp2 = Op.getValue(1);
3277   SDValue Tmp3 = Op.getOperand(2);
3278   SDValue Chain = Tmp1.getOperand(0);
3279 
3280   Register SPReg = Info->getStackPtrOffsetReg();
3281 
3282   // Chain the dynamic stack allocation so that it doesn't modify the stack
3283   // pointer when other instructions are using the stack.
3284   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3285 
3286   SDValue Size  = Tmp2.getOperand(1);
3287   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3288   Chain = SP.getValue(1);
3289   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3290   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3291   const TargetFrameLowering *TFL = ST.getFrameLowering();
3292   unsigned Opc =
3293     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3294     ISD::ADD : ISD::SUB;
3295 
3296   SDValue ScaledSize = DAG.getNode(
3297       ISD::SHL, dl, VT, Size,
3298       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3299 
3300   Align StackAlign = TFL->getStackAlign();
3301   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3302   if (Alignment && *Alignment > StackAlign) {
3303     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3304                        DAG.getConstant(-(uint64_t)Alignment->value()
3305                                            << ST.getWavefrontSizeLog2(),
3306                                        dl, VT));
3307   }
3308 
3309   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3310   Tmp2 = DAG.getCALLSEQ_END(
3311       Chain, DAG.getIntPtrConstant(0, dl, true),
3312       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3313 
3314   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3315 }
3316 
3317 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3318                                                   SelectionDAG &DAG) const {
3319   // We only handle constant sizes here to allow non-entry block, static sized
3320   // allocas. A truly dynamic value is more difficult to support because we
3321   // don't know if the size value is uniform or not. If the size isn't uniform,
3322   // we would need to do a wave reduction to get the maximum size to know how
3323   // much to increment the uniform stack pointer.
3324   SDValue Size = Op.getOperand(1);
3325   if (isa<ConstantSDNode>(Size))
3326       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3327 
3328   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3329 }
3330 
3331 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3332                                              const MachineFunction &MF) const {
3333   Register Reg = StringSwitch<Register>(RegName)
3334     .Case("m0", AMDGPU::M0)
3335     .Case("exec", AMDGPU::EXEC)
3336     .Case("exec_lo", AMDGPU::EXEC_LO)
3337     .Case("exec_hi", AMDGPU::EXEC_HI)
3338     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3339     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3340     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3341     .Default(Register());
3342 
3343   if (Reg == AMDGPU::NoRegister) {
3344     report_fatal_error(Twine("invalid register name \""
3345                              + StringRef(RegName)  + "\"."));
3346 
3347   }
3348 
3349   if (!Subtarget->hasFlatScrRegister() &&
3350        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3351     report_fatal_error(Twine("invalid register \""
3352                              + StringRef(RegName)  + "\" for subtarget."));
3353   }
3354 
3355   switch (Reg) {
3356   case AMDGPU::M0:
3357   case AMDGPU::EXEC_LO:
3358   case AMDGPU::EXEC_HI:
3359   case AMDGPU::FLAT_SCR_LO:
3360   case AMDGPU::FLAT_SCR_HI:
3361     if (VT.getSizeInBits() == 32)
3362       return Reg;
3363     break;
3364   case AMDGPU::EXEC:
3365   case AMDGPU::FLAT_SCR:
3366     if (VT.getSizeInBits() == 64)
3367       return Reg;
3368     break;
3369   default:
3370     llvm_unreachable("missing register type checking");
3371   }
3372 
3373   report_fatal_error(Twine("invalid type for register \""
3374                            + StringRef(RegName) + "\"."));
3375 }
3376 
3377 // If kill is not the last instruction, split the block so kill is always a
3378 // proper terminator.
3379 MachineBasicBlock *
3380 SITargetLowering::splitKillBlock(MachineInstr &MI,
3381                                  MachineBasicBlock *BB) const {
3382   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3383   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3384   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3385   return SplitBB;
3386 }
3387 
3388 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3389 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3390 // be the first instruction in the remainder block.
3391 //
3392 /// \returns { LoopBody, Remainder }
3393 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3394 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3395   MachineFunction *MF = MBB.getParent();
3396   MachineBasicBlock::iterator I(&MI);
3397 
3398   // To insert the loop we need to split the block. Move everything after this
3399   // point to a new block, and insert a new empty block between the two.
3400   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3401   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3402   MachineFunction::iterator MBBI(MBB);
3403   ++MBBI;
3404 
3405   MF->insert(MBBI, LoopBB);
3406   MF->insert(MBBI, RemainderBB);
3407 
3408   LoopBB->addSuccessor(LoopBB);
3409   LoopBB->addSuccessor(RemainderBB);
3410 
3411   // Move the rest of the block into a new block.
3412   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3413 
3414   if (InstInLoop) {
3415     auto Next = std::next(I);
3416 
3417     // Move instruction to loop body.
3418     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3419 
3420     // Move the rest of the block.
3421     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3422   } else {
3423     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3424   }
3425 
3426   MBB.addSuccessor(LoopBB);
3427 
3428   return std::make_pair(LoopBB, RemainderBB);
3429 }
3430 
3431 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3432 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3433   MachineBasicBlock *MBB = MI.getParent();
3434   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3435   auto I = MI.getIterator();
3436   auto E = std::next(I);
3437 
3438   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3439     .addImm(0);
3440 
3441   MIBundleBuilder Bundler(*MBB, I, E);
3442   finalizeBundle(*MBB, Bundler.begin());
3443 }
3444 
3445 MachineBasicBlock *
3446 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3447                                          MachineBasicBlock *BB) const {
3448   const DebugLoc &DL = MI.getDebugLoc();
3449 
3450   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3451 
3452   MachineBasicBlock *LoopBB;
3453   MachineBasicBlock *RemainderBB;
3454   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3455 
3456   // Apparently kill flags are only valid if the def is in the same block?
3457   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3458     Src->setIsKill(false);
3459 
3460   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3461 
3462   MachineBasicBlock::iterator I = LoopBB->end();
3463 
3464   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3465     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3466 
3467   // Clear TRAP_STS.MEM_VIOL
3468   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3469     .addImm(0)
3470     .addImm(EncodedReg);
3471 
3472   bundleInstWithWaitcnt(MI);
3473 
3474   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3475 
3476   // Load and check TRAP_STS.MEM_VIOL
3477   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3478     .addImm(EncodedReg);
3479 
3480   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3481   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3482     .addReg(Reg, RegState::Kill)
3483     .addImm(0);
3484   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3485     .addMBB(LoopBB);
3486 
3487   return RemainderBB;
3488 }
3489 
3490 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3491 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3492 // will only do one iteration. In the worst case, this will loop 64 times.
3493 //
3494 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3495 static MachineBasicBlock::iterator
3496 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3497                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3498                        const DebugLoc &DL, const MachineOperand &Idx,
3499                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3500                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3501                        Register &SGPRIdxReg) {
3502 
3503   MachineFunction *MF = OrigBB.getParent();
3504   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3505   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3506   MachineBasicBlock::iterator I = LoopBB.begin();
3507 
3508   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3509   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3510   Register NewExec = MRI.createVirtualRegister(BoolRC);
3511   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3512   Register CondReg = MRI.createVirtualRegister(BoolRC);
3513 
3514   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3515     .addReg(InitReg)
3516     .addMBB(&OrigBB)
3517     .addReg(ResultReg)
3518     .addMBB(&LoopBB);
3519 
3520   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3521     .addReg(InitSaveExecReg)
3522     .addMBB(&OrigBB)
3523     .addReg(NewExec)
3524     .addMBB(&LoopBB);
3525 
3526   // Read the next variant <- also loop target.
3527   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3528       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3529 
3530   // Compare the just read M0 value to all possible Idx values.
3531   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3532       .addReg(CurrentIdxReg)
3533       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3534 
3535   // Update EXEC, save the original EXEC value to VCC.
3536   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3537                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3538           NewExec)
3539     .addReg(CondReg, RegState::Kill);
3540 
3541   MRI.setSimpleHint(NewExec, CondReg);
3542 
3543   if (UseGPRIdxMode) {
3544     if (Offset == 0) {
3545       SGPRIdxReg = CurrentIdxReg;
3546     } else {
3547       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3548       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3549           .addReg(CurrentIdxReg, RegState::Kill)
3550           .addImm(Offset);
3551     }
3552   } else {
3553     // Move index from VCC into M0
3554     if (Offset == 0) {
3555       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3556         .addReg(CurrentIdxReg, RegState::Kill);
3557     } else {
3558       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3559         .addReg(CurrentIdxReg, RegState::Kill)
3560         .addImm(Offset);
3561     }
3562   }
3563 
3564   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3565   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3566   MachineInstr *InsertPt =
3567     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3568                                                   : AMDGPU::S_XOR_B64_term), Exec)
3569       .addReg(Exec)
3570       .addReg(NewExec);
3571 
3572   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3573   // s_cbranch_scc0?
3574 
3575   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3576   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3577     .addMBB(&LoopBB);
3578 
3579   return InsertPt->getIterator();
3580 }
3581 
3582 // This has slightly sub-optimal regalloc when the source vector is killed by
3583 // the read. The register allocator does not understand that the kill is
3584 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3585 // subregister from it, using 1 more VGPR than necessary. This was saved when
3586 // this was expanded after register allocation.
3587 static MachineBasicBlock::iterator
3588 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3589                unsigned InitResultReg, unsigned PhiReg, int Offset,
3590                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3591   MachineFunction *MF = MBB.getParent();
3592   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3593   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3594   MachineRegisterInfo &MRI = MF->getRegInfo();
3595   const DebugLoc &DL = MI.getDebugLoc();
3596   MachineBasicBlock::iterator I(&MI);
3597 
3598   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3599   Register DstReg = MI.getOperand(0).getReg();
3600   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3601   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3602   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3603   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3604 
3605   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3606 
3607   // Save the EXEC mask
3608   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3609     .addReg(Exec);
3610 
3611   MachineBasicBlock *LoopBB;
3612   MachineBasicBlock *RemainderBB;
3613   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3614 
3615   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3616 
3617   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3618                                       InitResultReg, DstReg, PhiReg, TmpExec,
3619                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3620 
3621   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3622   MachineFunction::iterator MBBI(LoopBB);
3623   ++MBBI;
3624   MF->insert(MBBI, LandingPad);
3625   LoopBB->removeSuccessor(RemainderBB);
3626   LandingPad->addSuccessor(RemainderBB);
3627   LoopBB->addSuccessor(LandingPad);
3628   MachineBasicBlock::iterator First = LandingPad->begin();
3629   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3630     .addReg(SaveExec);
3631 
3632   return InsPt;
3633 }
3634 
3635 // Returns subreg index, offset
3636 static std::pair<unsigned, int>
3637 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3638                             const TargetRegisterClass *SuperRC,
3639                             unsigned VecReg,
3640                             int Offset) {
3641   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3642 
3643   // Skip out of bounds offsets, or else we would end up using an undefined
3644   // register.
3645   if (Offset >= NumElts || Offset < 0)
3646     return std::make_pair(AMDGPU::sub0, Offset);
3647 
3648   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3649 }
3650 
3651 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3652                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3653                                  int Offset) {
3654   MachineBasicBlock *MBB = MI.getParent();
3655   const DebugLoc &DL = MI.getDebugLoc();
3656   MachineBasicBlock::iterator I(&MI);
3657 
3658   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3659 
3660   assert(Idx->getReg() != AMDGPU::NoRegister);
3661 
3662   if (Offset == 0) {
3663     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3664   } else {
3665     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3666         .add(*Idx)
3667         .addImm(Offset);
3668   }
3669 }
3670 
3671 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3672                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3673                                    int Offset) {
3674   MachineBasicBlock *MBB = MI.getParent();
3675   const DebugLoc &DL = MI.getDebugLoc();
3676   MachineBasicBlock::iterator I(&MI);
3677 
3678   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3679 
3680   if (Offset == 0)
3681     return Idx->getReg();
3682 
3683   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3684   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3685       .add(*Idx)
3686       .addImm(Offset);
3687   return Tmp;
3688 }
3689 
3690 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3691                                           MachineBasicBlock &MBB,
3692                                           const GCNSubtarget &ST) {
3693   const SIInstrInfo *TII = ST.getInstrInfo();
3694   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3695   MachineFunction *MF = MBB.getParent();
3696   MachineRegisterInfo &MRI = MF->getRegInfo();
3697 
3698   Register Dst = MI.getOperand(0).getReg();
3699   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3700   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3701   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3702 
3703   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3704   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3705 
3706   unsigned SubReg;
3707   std::tie(SubReg, Offset)
3708     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3709 
3710   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3711 
3712   // Check for a SGPR index.
3713   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3714     MachineBasicBlock::iterator I(&MI);
3715     const DebugLoc &DL = MI.getDebugLoc();
3716 
3717     if (UseGPRIdxMode) {
3718       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3719       // to avoid interfering with other uses, so probably requires a new
3720       // optimization pass.
3721       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3722 
3723       const MCInstrDesc &GPRIDXDesc =
3724           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3725       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3726           .addReg(SrcReg)
3727           .addReg(Idx)
3728           .addImm(SubReg);
3729     } else {
3730       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3731 
3732       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3733         .addReg(SrcReg, 0, SubReg)
3734         .addReg(SrcReg, RegState::Implicit);
3735     }
3736 
3737     MI.eraseFromParent();
3738 
3739     return &MBB;
3740   }
3741 
3742   // Control flow needs to be inserted if indexing with a VGPR.
3743   const DebugLoc &DL = MI.getDebugLoc();
3744   MachineBasicBlock::iterator I(&MI);
3745 
3746   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3747   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3748 
3749   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3750 
3751   Register SGPRIdxReg;
3752   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3753                               UseGPRIdxMode, SGPRIdxReg);
3754 
3755   MachineBasicBlock *LoopBB = InsPt->getParent();
3756 
3757   if (UseGPRIdxMode) {
3758     const MCInstrDesc &GPRIDXDesc =
3759         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3760 
3761     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3762         .addReg(SrcReg)
3763         .addReg(SGPRIdxReg)
3764         .addImm(SubReg);
3765   } else {
3766     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3767       .addReg(SrcReg, 0, SubReg)
3768       .addReg(SrcReg, RegState::Implicit);
3769   }
3770 
3771   MI.eraseFromParent();
3772 
3773   return LoopBB;
3774 }
3775 
3776 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3777                                           MachineBasicBlock &MBB,
3778                                           const GCNSubtarget &ST) {
3779   const SIInstrInfo *TII = ST.getInstrInfo();
3780   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3781   MachineFunction *MF = MBB.getParent();
3782   MachineRegisterInfo &MRI = MF->getRegInfo();
3783 
3784   Register Dst = MI.getOperand(0).getReg();
3785   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3786   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3787   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3788   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3789   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3790   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3791 
3792   // This can be an immediate, but will be folded later.
3793   assert(Val->getReg());
3794 
3795   unsigned SubReg;
3796   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3797                                                          SrcVec->getReg(),
3798                                                          Offset);
3799   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3800 
3801   if (Idx->getReg() == AMDGPU::NoRegister) {
3802     MachineBasicBlock::iterator I(&MI);
3803     const DebugLoc &DL = MI.getDebugLoc();
3804 
3805     assert(Offset == 0);
3806 
3807     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3808         .add(*SrcVec)
3809         .add(*Val)
3810         .addImm(SubReg);
3811 
3812     MI.eraseFromParent();
3813     return &MBB;
3814   }
3815 
3816   // Check for a SGPR index.
3817   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3818     MachineBasicBlock::iterator I(&MI);
3819     const DebugLoc &DL = MI.getDebugLoc();
3820 
3821     if (UseGPRIdxMode) {
3822       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3823 
3824       const MCInstrDesc &GPRIDXDesc =
3825           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3826       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3827           .addReg(SrcVec->getReg())
3828           .add(*Val)
3829           .addReg(Idx)
3830           .addImm(SubReg);
3831     } else {
3832       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3833 
3834       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3835           TRI.getRegSizeInBits(*VecRC), 32, false);
3836       BuildMI(MBB, I, DL, MovRelDesc, Dst)
3837           .addReg(SrcVec->getReg())
3838           .add(*Val)
3839           .addImm(SubReg);
3840     }
3841     MI.eraseFromParent();
3842     return &MBB;
3843   }
3844 
3845   // Control flow needs to be inserted if indexing with a VGPR.
3846   if (Val->isReg())
3847     MRI.clearKillFlags(Val->getReg());
3848 
3849   const DebugLoc &DL = MI.getDebugLoc();
3850 
3851   Register PhiReg = MRI.createVirtualRegister(VecRC);
3852 
3853   Register SGPRIdxReg;
3854   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
3855                               UseGPRIdxMode, SGPRIdxReg);
3856   MachineBasicBlock *LoopBB = InsPt->getParent();
3857 
3858   if (UseGPRIdxMode) {
3859     const MCInstrDesc &GPRIDXDesc =
3860         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3861 
3862     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3863         .addReg(PhiReg)
3864         .add(*Val)
3865         .addReg(SGPRIdxReg)
3866         .addImm(AMDGPU::sub0);
3867   } else {
3868     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3869         TRI.getRegSizeInBits(*VecRC), 32, false);
3870     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3871         .addReg(PhiReg)
3872         .add(*Val)
3873         .addImm(AMDGPU::sub0);
3874   }
3875 
3876   MI.eraseFromParent();
3877   return LoopBB;
3878 }
3879 
3880 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3881   MachineInstr &MI, MachineBasicBlock *BB) const {
3882 
3883   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3884   MachineFunction *MF = BB->getParent();
3885   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3886 
3887   switch (MI.getOpcode()) {
3888   case AMDGPU::S_UADDO_PSEUDO:
3889   case AMDGPU::S_USUBO_PSEUDO: {
3890     const DebugLoc &DL = MI.getDebugLoc();
3891     MachineOperand &Dest0 = MI.getOperand(0);
3892     MachineOperand &Dest1 = MI.getOperand(1);
3893     MachineOperand &Src0 = MI.getOperand(2);
3894     MachineOperand &Src1 = MI.getOperand(3);
3895 
3896     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3897                        ? AMDGPU::S_ADD_I32
3898                        : AMDGPU::S_SUB_I32;
3899     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3900 
3901     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3902         .addImm(1)
3903         .addImm(0);
3904 
3905     MI.eraseFromParent();
3906     return BB;
3907   }
3908   case AMDGPU::S_ADD_U64_PSEUDO:
3909   case AMDGPU::S_SUB_U64_PSEUDO: {
3910     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3911     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3912     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3913     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3914     const DebugLoc &DL = MI.getDebugLoc();
3915 
3916     MachineOperand &Dest = MI.getOperand(0);
3917     MachineOperand &Src0 = MI.getOperand(1);
3918     MachineOperand &Src1 = MI.getOperand(2);
3919 
3920     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3921     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3922 
3923     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3924         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3925     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3926         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3927 
3928     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3929         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3930     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3931         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3932 
3933     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3934 
3935     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3936     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3937     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3938     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3939     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3940         .addReg(DestSub0)
3941         .addImm(AMDGPU::sub0)
3942         .addReg(DestSub1)
3943         .addImm(AMDGPU::sub1);
3944     MI.eraseFromParent();
3945     return BB;
3946   }
3947   case AMDGPU::V_ADD_U64_PSEUDO:
3948   case AMDGPU::V_SUB_U64_PSEUDO: {
3949     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3950     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3951     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3952     const DebugLoc &DL = MI.getDebugLoc();
3953 
3954     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
3955 
3956     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3957 
3958     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3959     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3960 
3961     Register CarryReg = MRI.createVirtualRegister(CarryRC);
3962     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
3963 
3964     MachineOperand &Dest = MI.getOperand(0);
3965     MachineOperand &Src0 = MI.getOperand(1);
3966     MachineOperand &Src1 = MI.getOperand(2);
3967 
3968     const TargetRegisterClass *Src0RC = Src0.isReg()
3969                                             ? MRI.getRegClass(Src0.getReg())
3970                                             : &AMDGPU::VReg_64RegClass;
3971     const TargetRegisterClass *Src1RC = Src1.isReg()
3972                                             ? MRI.getRegClass(Src1.getReg())
3973                                             : &AMDGPU::VReg_64RegClass;
3974 
3975     const TargetRegisterClass *Src0SubRC =
3976         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
3977     const TargetRegisterClass *Src1SubRC =
3978         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
3979 
3980     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
3981         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
3982     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
3983         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
3984 
3985     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
3986         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
3987     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
3988         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
3989 
3990     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
3991     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3992                                .addReg(CarryReg, RegState::Define)
3993                                .add(SrcReg0Sub0)
3994                                .add(SrcReg1Sub0)
3995                                .addImm(0); // clamp bit
3996 
3997     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
3998     MachineInstr *HiHalf =
3999         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4000             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4001             .add(SrcReg0Sub1)
4002             .add(SrcReg1Sub1)
4003             .addReg(CarryReg, RegState::Kill)
4004             .addImm(0); // clamp bit
4005 
4006     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4007         .addReg(DestSub0)
4008         .addImm(AMDGPU::sub0)
4009         .addReg(DestSub1)
4010         .addImm(AMDGPU::sub1);
4011     TII->legalizeOperands(*LoHalf);
4012     TII->legalizeOperands(*HiHalf);
4013     MI.eraseFromParent();
4014     return BB;
4015   }
4016   case AMDGPU::S_ADD_CO_PSEUDO:
4017   case AMDGPU::S_SUB_CO_PSEUDO: {
4018     // This pseudo has a chance to be selected
4019     // only from uniform add/subcarry node. All the VGPR operands
4020     // therefore assumed to be splat vectors.
4021     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4022     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4023     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4024     MachineBasicBlock::iterator MII = MI;
4025     const DebugLoc &DL = MI.getDebugLoc();
4026     MachineOperand &Dest = MI.getOperand(0);
4027     MachineOperand &CarryDest = MI.getOperand(1);
4028     MachineOperand &Src0 = MI.getOperand(2);
4029     MachineOperand &Src1 = MI.getOperand(3);
4030     MachineOperand &Src2 = MI.getOperand(4);
4031     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4032                        ? AMDGPU::S_ADDC_U32
4033                        : AMDGPU::S_SUBB_U32;
4034     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4035       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4036       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4037           .addReg(Src0.getReg());
4038       Src0.setReg(RegOp0);
4039     }
4040     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4041       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4042       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4043           .addReg(Src1.getReg());
4044       Src1.setReg(RegOp1);
4045     }
4046     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4047     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4048       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4049           .addReg(Src2.getReg());
4050       Src2.setReg(RegOp2);
4051     }
4052 
4053     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4054     if (TRI->getRegSizeInBits(*Src2RC) == 64) {
4055       if (ST.hasScalarCompareEq64()) {
4056         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4057             .addReg(Src2.getReg())
4058             .addImm(0);
4059       } else {
4060         const TargetRegisterClass *SubRC =
4061             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4062         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4063             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4064         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4065             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4066         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4067 
4068         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4069             .add(Src2Sub0)
4070             .add(Src2Sub1);
4071 
4072         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4073             .addReg(Src2_32, RegState::Kill)
4074             .addImm(0);
4075       }
4076     } else {
4077       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4078           .addReg(Src2.getReg())
4079           .addImm(0);
4080     }
4081 
4082     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4083 
4084     BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg())
4085       .addReg(AMDGPU::SCC);
4086     MI.eraseFromParent();
4087     return BB;
4088   }
4089   case AMDGPU::SI_INIT_M0: {
4090     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4091             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4092         .add(MI.getOperand(0));
4093     MI.eraseFromParent();
4094     return BB;
4095   }
4096   case AMDGPU::GET_GROUPSTATICSIZE: {
4097     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4098            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4099     DebugLoc DL = MI.getDebugLoc();
4100     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4101         .add(MI.getOperand(0))
4102         .addImm(MFI->getLDSSize());
4103     MI.eraseFromParent();
4104     return BB;
4105   }
4106   case AMDGPU::SI_INDIRECT_SRC_V1:
4107   case AMDGPU::SI_INDIRECT_SRC_V2:
4108   case AMDGPU::SI_INDIRECT_SRC_V4:
4109   case AMDGPU::SI_INDIRECT_SRC_V8:
4110   case AMDGPU::SI_INDIRECT_SRC_V16:
4111   case AMDGPU::SI_INDIRECT_SRC_V32:
4112     return emitIndirectSrc(MI, *BB, *getSubtarget());
4113   case AMDGPU::SI_INDIRECT_DST_V1:
4114   case AMDGPU::SI_INDIRECT_DST_V2:
4115   case AMDGPU::SI_INDIRECT_DST_V4:
4116   case AMDGPU::SI_INDIRECT_DST_V8:
4117   case AMDGPU::SI_INDIRECT_DST_V16:
4118   case AMDGPU::SI_INDIRECT_DST_V32:
4119     return emitIndirectDst(MI, *BB, *getSubtarget());
4120   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4121   case AMDGPU::SI_KILL_I1_PSEUDO:
4122     return splitKillBlock(MI, BB);
4123   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4124     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4125     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4126     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4127 
4128     Register Dst = MI.getOperand(0).getReg();
4129     Register Src0 = MI.getOperand(1).getReg();
4130     Register Src1 = MI.getOperand(2).getReg();
4131     const DebugLoc &DL = MI.getDebugLoc();
4132     Register SrcCond = MI.getOperand(3).getReg();
4133 
4134     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4135     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4136     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4137     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4138 
4139     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4140       .addReg(SrcCond);
4141     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4142       .addImm(0)
4143       .addReg(Src0, 0, AMDGPU::sub0)
4144       .addImm(0)
4145       .addReg(Src1, 0, AMDGPU::sub0)
4146       .addReg(SrcCondCopy);
4147     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4148       .addImm(0)
4149       .addReg(Src0, 0, AMDGPU::sub1)
4150       .addImm(0)
4151       .addReg(Src1, 0, AMDGPU::sub1)
4152       .addReg(SrcCondCopy);
4153 
4154     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4155       .addReg(DstLo)
4156       .addImm(AMDGPU::sub0)
4157       .addReg(DstHi)
4158       .addImm(AMDGPU::sub1);
4159     MI.eraseFromParent();
4160     return BB;
4161   }
4162   case AMDGPU::SI_BR_UNDEF: {
4163     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4164     const DebugLoc &DL = MI.getDebugLoc();
4165     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4166                            .add(MI.getOperand(0));
4167     Br->getOperand(1).setIsUndef(true); // read undef SCC
4168     MI.eraseFromParent();
4169     return BB;
4170   }
4171   case AMDGPU::ADJCALLSTACKUP:
4172   case AMDGPU::ADJCALLSTACKDOWN: {
4173     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4174     MachineInstrBuilder MIB(*MF, &MI);
4175     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4176        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4177     return BB;
4178   }
4179   case AMDGPU::SI_CALL_ISEL: {
4180     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4181     const DebugLoc &DL = MI.getDebugLoc();
4182 
4183     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4184 
4185     MachineInstrBuilder MIB;
4186     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4187 
4188     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
4189       MIB.add(MI.getOperand(I));
4190 
4191     MIB.cloneMemRefs(MI);
4192     MI.eraseFromParent();
4193     return BB;
4194   }
4195   case AMDGPU::V_ADD_CO_U32_e32:
4196   case AMDGPU::V_SUB_CO_U32_e32:
4197   case AMDGPU::V_SUBREV_CO_U32_e32: {
4198     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4199     const DebugLoc &DL = MI.getDebugLoc();
4200     unsigned Opc = MI.getOpcode();
4201 
4202     bool NeedClampOperand = false;
4203     if (TII->pseudoToMCOpcode(Opc) == -1) {
4204       Opc = AMDGPU::getVOPe64(Opc);
4205       NeedClampOperand = true;
4206     }
4207 
4208     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4209     if (TII->isVOP3(*I)) {
4210       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4211       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4212       I.addReg(TRI->getVCC(), RegState::Define);
4213     }
4214     I.add(MI.getOperand(1))
4215      .add(MI.getOperand(2));
4216     if (NeedClampOperand)
4217       I.addImm(0); // clamp bit for e64 encoding
4218 
4219     TII->legalizeOperands(*I);
4220 
4221     MI.eraseFromParent();
4222     return BB;
4223   }
4224   case AMDGPU::DS_GWS_INIT:
4225   case AMDGPU::DS_GWS_SEMA_V:
4226   case AMDGPU::DS_GWS_SEMA_BR:
4227   case AMDGPU::DS_GWS_SEMA_P:
4228   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4229   case AMDGPU::DS_GWS_BARRIER:
4230     // A s_waitcnt 0 is required to be the instruction immediately following.
4231     if (getSubtarget()->hasGWSAutoReplay()) {
4232       bundleInstWithWaitcnt(MI);
4233       return BB;
4234     }
4235 
4236     return emitGWSMemViolTestLoop(MI, BB);
4237   case AMDGPU::S_SETREG_B32: {
4238     // Try to optimize cases that only set the denormal mode or rounding mode.
4239     //
4240     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4241     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4242     // instead.
4243     //
4244     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4245     // allow you to have a no side effect instruction in the output of a
4246     // sideeffecting pattern.
4247     unsigned ID, Offset, Width;
4248     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4249     if (ID != AMDGPU::Hwreg::ID_MODE)
4250       return BB;
4251 
4252     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4253     const unsigned SetMask = WidthMask << Offset;
4254 
4255     if (getSubtarget()->hasDenormModeInst()) {
4256       unsigned SetDenormOp = 0;
4257       unsigned SetRoundOp = 0;
4258 
4259       // The dedicated instructions can only set the whole denorm or round mode
4260       // at once, not a subset of bits in either.
4261       if (SetMask ==
4262           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4263         // If this fully sets both the round and denorm mode, emit the two
4264         // dedicated instructions for these.
4265         SetRoundOp = AMDGPU::S_ROUND_MODE;
4266         SetDenormOp = AMDGPU::S_DENORM_MODE;
4267       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4268         SetRoundOp = AMDGPU::S_ROUND_MODE;
4269       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4270         SetDenormOp = AMDGPU::S_DENORM_MODE;
4271       }
4272 
4273       if (SetRoundOp || SetDenormOp) {
4274         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4275         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4276         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4277           unsigned ImmVal = Def->getOperand(1).getImm();
4278           if (SetRoundOp) {
4279             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4280                 .addImm(ImmVal & 0xf);
4281 
4282             // If we also have the denorm mode, get just the denorm mode bits.
4283             ImmVal >>= 4;
4284           }
4285 
4286           if (SetDenormOp) {
4287             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4288                 .addImm(ImmVal & 0xf);
4289           }
4290 
4291           MI.eraseFromParent();
4292           return BB;
4293         }
4294       }
4295     }
4296 
4297     // If only FP bits are touched, used the no side effects pseudo.
4298     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4299                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4300       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4301 
4302     return BB;
4303   }
4304   default:
4305     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4306   }
4307 }
4308 
4309 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4310   return isTypeLegal(VT.getScalarType());
4311 }
4312 
4313 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4314   // This currently forces unfolding various combinations of fsub into fma with
4315   // free fneg'd operands. As long as we have fast FMA (controlled by
4316   // isFMAFasterThanFMulAndFAdd), we should perform these.
4317 
4318   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4319   // most of these combines appear to be cycle neutral but save on instruction
4320   // count / code size.
4321   return true;
4322 }
4323 
4324 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4325                                          EVT VT) const {
4326   if (!VT.isVector()) {
4327     return MVT::i1;
4328   }
4329   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4330 }
4331 
4332 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4333   // TODO: Should i16 be used always if legal? For now it would force VALU
4334   // shifts.
4335   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4336 }
4337 
4338 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4339   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4340              ? Ty.changeElementSize(16)
4341              : Ty.changeElementSize(32);
4342 }
4343 
4344 // Answering this is somewhat tricky and depends on the specific device which
4345 // have different rates for fma or all f64 operations.
4346 //
4347 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4348 // regardless of which device (although the number of cycles differs between
4349 // devices), so it is always profitable for f64.
4350 //
4351 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4352 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4353 // which we can always do even without fused FP ops since it returns the same
4354 // result as the separate operations and since it is always full
4355 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4356 // however does not support denormals, so we do report fma as faster if we have
4357 // a fast fma device and require denormals.
4358 //
4359 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4360                                                   EVT VT) const {
4361   VT = VT.getScalarType();
4362 
4363   switch (VT.getSimpleVT().SimpleTy) {
4364   case MVT::f32: {
4365     // If mad is not available this depends only on if f32 fma is full rate.
4366     if (!Subtarget->hasMadMacF32Insts())
4367       return Subtarget->hasFastFMAF32();
4368 
4369     // Otherwise f32 mad is always full rate and returns the same result as
4370     // the separate operations so should be preferred over fma.
4371     // However does not support denomals.
4372     if (hasFP32Denormals(MF))
4373       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4374 
4375     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4376     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4377   }
4378   case MVT::f64:
4379     return true;
4380   case MVT::f16:
4381     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4382   default:
4383     break;
4384   }
4385 
4386   return false;
4387 }
4388 
4389 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4390                                    const SDNode *N) const {
4391   // TODO: Check future ftz flag
4392   // v_mad_f32/v_mac_f32 do not support denormals.
4393   EVT VT = N->getValueType(0);
4394   if (VT == MVT::f32)
4395     return Subtarget->hasMadMacF32Insts() &&
4396            !hasFP32Denormals(DAG.getMachineFunction());
4397   if (VT == MVT::f16) {
4398     return Subtarget->hasMadF16() &&
4399            !hasFP64FP16Denormals(DAG.getMachineFunction());
4400   }
4401 
4402   return false;
4403 }
4404 
4405 //===----------------------------------------------------------------------===//
4406 // Custom DAG Lowering Operations
4407 //===----------------------------------------------------------------------===//
4408 
4409 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4410 // wider vector type is legal.
4411 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4412                                              SelectionDAG &DAG) const {
4413   unsigned Opc = Op.getOpcode();
4414   EVT VT = Op.getValueType();
4415   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4416 
4417   SDValue Lo, Hi;
4418   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4419 
4420   SDLoc SL(Op);
4421   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4422                              Op->getFlags());
4423   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4424                              Op->getFlags());
4425 
4426   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4427 }
4428 
4429 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4430 // wider vector type is legal.
4431 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4432                                               SelectionDAG &DAG) const {
4433   unsigned Opc = Op.getOpcode();
4434   EVT VT = Op.getValueType();
4435   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4436          VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32);
4437 
4438   SDValue Lo0, Hi0;
4439   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4440   SDValue Lo1, Hi1;
4441   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4442 
4443   SDLoc SL(Op);
4444 
4445   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4446                              Op->getFlags());
4447   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4448                              Op->getFlags());
4449 
4450   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4451 }
4452 
4453 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4454                                               SelectionDAG &DAG) const {
4455   unsigned Opc = Op.getOpcode();
4456   EVT VT = Op.getValueType();
4457   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4458          VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32);
4459 
4460   SDValue Lo0, Hi0;
4461   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4462   SDValue Lo1, Hi1;
4463   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4464   SDValue Lo2, Hi2;
4465   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4466 
4467   SDLoc SL(Op);
4468 
4469   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4470                              Op->getFlags());
4471   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4472                              Op->getFlags());
4473 
4474   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4475 }
4476 
4477 
4478 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4479   switch (Op.getOpcode()) {
4480   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4481   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4482   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4483   case ISD::LOAD: {
4484     SDValue Result = LowerLOAD(Op, DAG);
4485     assert((!Result.getNode() ||
4486             Result.getNode()->getNumValues() == 2) &&
4487            "Load should return a value and a chain");
4488     return Result;
4489   }
4490 
4491   case ISD::FSIN:
4492   case ISD::FCOS:
4493     return LowerTrig(Op, DAG);
4494   case ISD::SELECT: return LowerSELECT(Op, DAG);
4495   case ISD::FDIV: return LowerFDIV(Op, DAG);
4496   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4497   case ISD::STORE: return LowerSTORE(Op, DAG);
4498   case ISD::GlobalAddress: {
4499     MachineFunction &MF = DAG.getMachineFunction();
4500     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4501     return LowerGlobalAddress(MFI, Op, DAG);
4502   }
4503   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4504   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4505   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4506   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4507   case ISD::INSERT_SUBVECTOR:
4508     return lowerINSERT_SUBVECTOR(Op, DAG);
4509   case ISD::INSERT_VECTOR_ELT:
4510     return lowerINSERT_VECTOR_ELT(Op, DAG);
4511   case ISD::EXTRACT_VECTOR_ELT:
4512     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4513   case ISD::VECTOR_SHUFFLE:
4514     return lowerVECTOR_SHUFFLE(Op, DAG);
4515   case ISD::BUILD_VECTOR:
4516     return lowerBUILD_VECTOR(Op, DAG);
4517   case ISD::FP_ROUND:
4518     return lowerFP_ROUND(Op, DAG);
4519   case ISD::TRAP:
4520     return lowerTRAP(Op, DAG);
4521   case ISD::DEBUGTRAP:
4522     return lowerDEBUGTRAP(Op, DAG);
4523   case ISD::FABS:
4524   case ISD::FNEG:
4525   case ISD::FCANONICALIZE:
4526   case ISD::BSWAP:
4527     return splitUnaryVectorOp(Op, DAG);
4528   case ISD::FMINNUM:
4529   case ISD::FMAXNUM:
4530     return lowerFMINNUM_FMAXNUM(Op, DAG);
4531   case ISD::FMA:
4532     return splitTernaryVectorOp(Op, DAG);
4533   case ISD::FP_TO_SINT:
4534   case ISD::FP_TO_UINT:
4535     return LowerFP_TO_INT(Op, DAG);
4536   case ISD::SHL:
4537   case ISD::SRA:
4538   case ISD::SRL:
4539   case ISD::ADD:
4540   case ISD::SUB:
4541   case ISD::MUL:
4542   case ISD::SMIN:
4543   case ISD::SMAX:
4544   case ISD::UMIN:
4545   case ISD::UMAX:
4546   case ISD::FADD:
4547   case ISD::FMUL:
4548   case ISD::FMINNUM_IEEE:
4549   case ISD::FMAXNUM_IEEE:
4550   case ISD::UADDSAT:
4551   case ISD::USUBSAT:
4552   case ISD::SADDSAT:
4553   case ISD::SSUBSAT:
4554     return splitBinaryVectorOp(Op, DAG);
4555   case ISD::SMULO:
4556   case ISD::UMULO:
4557     return lowerXMULO(Op, DAG);
4558   case ISD::DYNAMIC_STACKALLOC:
4559     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4560   }
4561   return SDValue();
4562 }
4563 
4564 // Used for D16: Casts the result of an instruction into the right vector,
4565 // packs values if loads return unpacked values.
4566 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4567                                        const SDLoc &DL,
4568                                        SelectionDAG &DAG, bool Unpacked) {
4569   if (!LoadVT.isVector())
4570     return Result;
4571 
4572   // Cast back to the original packed type or to a larger type that is a
4573   // multiple of 32 bit for D16. Widening the return type is a required for
4574   // legalization.
4575   EVT FittingLoadVT = LoadVT;
4576   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4577     FittingLoadVT =
4578         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4579                          LoadVT.getVectorNumElements() + 1);
4580   }
4581 
4582   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4583     // Truncate to v2i16/v4i16.
4584     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4585 
4586     // Workaround legalizer not scalarizing truncate after vector op
4587     // legalization but not creating intermediate vector trunc.
4588     SmallVector<SDValue, 4> Elts;
4589     DAG.ExtractVectorElements(Result, Elts);
4590     for (SDValue &Elt : Elts)
4591       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4592 
4593     // Pad illegal v1i16/v3fi6 to v4i16
4594     if ((LoadVT.getVectorNumElements() % 2) == 1)
4595       Elts.push_back(DAG.getUNDEF(MVT::i16));
4596 
4597     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4598 
4599     // Bitcast to original type (v2f16/v4f16).
4600     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4601   }
4602 
4603   // Cast back to the original packed type.
4604   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4605 }
4606 
4607 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4608                                               MemSDNode *M,
4609                                               SelectionDAG &DAG,
4610                                               ArrayRef<SDValue> Ops,
4611                                               bool IsIntrinsic) const {
4612   SDLoc DL(M);
4613 
4614   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4615   EVT LoadVT = M->getValueType(0);
4616 
4617   EVT EquivLoadVT = LoadVT;
4618   if (LoadVT.isVector()) {
4619     if (Unpacked) {
4620       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4621                                      LoadVT.getVectorNumElements());
4622     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4623       // Widen v3f16 to legal type
4624       EquivLoadVT =
4625           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4626                            LoadVT.getVectorNumElements() + 1);
4627     }
4628   }
4629 
4630   // Change from v4f16/v2f16 to EquivLoadVT.
4631   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4632 
4633   SDValue Load
4634     = DAG.getMemIntrinsicNode(
4635       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4636       VTList, Ops, M->getMemoryVT(),
4637       M->getMemOperand());
4638 
4639   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4640 
4641   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4642 }
4643 
4644 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4645                                              SelectionDAG &DAG,
4646                                              ArrayRef<SDValue> Ops) const {
4647   SDLoc DL(M);
4648   EVT LoadVT = M->getValueType(0);
4649   EVT EltType = LoadVT.getScalarType();
4650   EVT IntVT = LoadVT.changeTypeToInteger();
4651 
4652   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4653 
4654   unsigned Opc =
4655       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4656 
4657   if (IsD16) {
4658     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4659   }
4660 
4661   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4662   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4663     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4664 
4665   if (isTypeLegal(LoadVT)) {
4666     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4667                                M->getMemOperand(), DAG);
4668   }
4669 
4670   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4671   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4672   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4673                                         M->getMemOperand(), DAG);
4674   return DAG.getMergeValues(
4675       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4676       DL);
4677 }
4678 
4679 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4680                                   SDNode *N, SelectionDAG &DAG) {
4681   EVT VT = N->getValueType(0);
4682   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4683   unsigned CondCode = CD->getZExtValue();
4684   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4685     return DAG.getUNDEF(VT);
4686 
4687   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4688 
4689   SDValue LHS = N->getOperand(1);
4690   SDValue RHS = N->getOperand(2);
4691 
4692   SDLoc DL(N);
4693 
4694   EVT CmpVT = LHS.getValueType();
4695   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4696     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4697       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4698     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4699     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4700   }
4701 
4702   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4703 
4704   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4705   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4706 
4707   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4708                               DAG.getCondCode(CCOpcode));
4709   if (VT.bitsEq(CCVT))
4710     return SetCC;
4711   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4712 }
4713 
4714 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4715                                   SDNode *N, SelectionDAG &DAG) {
4716   EVT VT = N->getValueType(0);
4717   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4718 
4719   unsigned CondCode = CD->getZExtValue();
4720   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4721     return DAG.getUNDEF(VT);
4722 
4723   SDValue Src0 = N->getOperand(1);
4724   SDValue Src1 = N->getOperand(2);
4725   EVT CmpVT = Src0.getValueType();
4726   SDLoc SL(N);
4727 
4728   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4729     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4730     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4731   }
4732 
4733   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4734   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4735   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4736   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4737   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4738                               Src1, DAG.getCondCode(CCOpcode));
4739   if (VT.bitsEq(CCVT))
4740     return SetCC;
4741   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4742 }
4743 
4744 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4745                                     SelectionDAG &DAG) {
4746   EVT VT = N->getValueType(0);
4747   SDValue Src = N->getOperand(1);
4748   SDLoc SL(N);
4749 
4750   if (Src.getOpcode() == ISD::SETCC) {
4751     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4752     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4753                        Src.getOperand(1), Src.getOperand(2));
4754   }
4755   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4756     // (ballot 0) -> 0
4757     if (Arg->isNullValue())
4758       return DAG.getConstant(0, SL, VT);
4759 
4760     // (ballot 1) -> EXEC/EXEC_LO
4761     if (Arg->isOne()) {
4762       Register Exec;
4763       if (VT.getScalarSizeInBits() == 32)
4764         Exec = AMDGPU::EXEC_LO;
4765       else if (VT.getScalarSizeInBits() == 64)
4766         Exec = AMDGPU::EXEC;
4767       else
4768         return SDValue();
4769 
4770       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4771     }
4772   }
4773 
4774   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4775   // ISD::SETNE)
4776   return DAG.getNode(
4777       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4778       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4779 }
4780 
4781 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4782                                           SmallVectorImpl<SDValue> &Results,
4783                                           SelectionDAG &DAG) const {
4784   switch (N->getOpcode()) {
4785   case ISD::INSERT_VECTOR_ELT: {
4786     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4787       Results.push_back(Res);
4788     return;
4789   }
4790   case ISD::EXTRACT_VECTOR_ELT: {
4791     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4792       Results.push_back(Res);
4793     return;
4794   }
4795   case ISD::INTRINSIC_WO_CHAIN: {
4796     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4797     switch (IID) {
4798     case Intrinsic::amdgcn_cvt_pkrtz: {
4799       SDValue Src0 = N->getOperand(1);
4800       SDValue Src1 = N->getOperand(2);
4801       SDLoc SL(N);
4802       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4803                                 Src0, Src1);
4804       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4805       return;
4806     }
4807     case Intrinsic::amdgcn_cvt_pknorm_i16:
4808     case Intrinsic::amdgcn_cvt_pknorm_u16:
4809     case Intrinsic::amdgcn_cvt_pk_i16:
4810     case Intrinsic::amdgcn_cvt_pk_u16: {
4811       SDValue Src0 = N->getOperand(1);
4812       SDValue Src1 = N->getOperand(2);
4813       SDLoc SL(N);
4814       unsigned Opcode;
4815 
4816       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4817         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4818       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4819         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4820       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4821         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4822       else
4823         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4824 
4825       EVT VT = N->getValueType(0);
4826       if (isTypeLegal(VT))
4827         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4828       else {
4829         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4830         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4831       }
4832       return;
4833     }
4834     }
4835     break;
4836   }
4837   case ISD::INTRINSIC_W_CHAIN: {
4838     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4839       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4840         // FIXME: Hacky
4841         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
4842           Results.push_back(Res.getOperand(I));
4843         }
4844       } else {
4845         Results.push_back(Res);
4846         Results.push_back(Res.getValue(1));
4847       }
4848       return;
4849     }
4850 
4851     break;
4852   }
4853   case ISD::SELECT: {
4854     SDLoc SL(N);
4855     EVT VT = N->getValueType(0);
4856     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4857     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4858     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4859 
4860     EVT SelectVT = NewVT;
4861     if (NewVT.bitsLT(MVT::i32)) {
4862       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4863       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4864       SelectVT = MVT::i32;
4865     }
4866 
4867     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4868                                     N->getOperand(0), LHS, RHS);
4869 
4870     if (NewVT != SelectVT)
4871       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4872     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4873     return;
4874   }
4875   case ISD::FNEG: {
4876     if (N->getValueType(0) != MVT::v2f16)
4877       break;
4878 
4879     SDLoc SL(N);
4880     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4881 
4882     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4883                              BC,
4884                              DAG.getConstant(0x80008000, SL, MVT::i32));
4885     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4886     return;
4887   }
4888   case ISD::FABS: {
4889     if (N->getValueType(0) != MVT::v2f16)
4890       break;
4891 
4892     SDLoc SL(N);
4893     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4894 
4895     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4896                              BC,
4897                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4898     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4899     return;
4900   }
4901   default:
4902     break;
4903   }
4904 }
4905 
4906 /// Helper function for LowerBRCOND
4907 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4908 
4909   SDNode *Parent = Value.getNode();
4910   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4911        I != E; ++I) {
4912 
4913     if (I.getUse().get() != Value)
4914       continue;
4915 
4916     if (I->getOpcode() == Opcode)
4917       return *I;
4918   }
4919   return nullptr;
4920 }
4921 
4922 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4923   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4924     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4925     case Intrinsic::amdgcn_if:
4926       return AMDGPUISD::IF;
4927     case Intrinsic::amdgcn_else:
4928       return AMDGPUISD::ELSE;
4929     case Intrinsic::amdgcn_loop:
4930       return AMDGPUISD::LOOP;
4931     case Intrinsic::amdgcn_end_cf:
4932       llvm_unreachable("should not occur");
4933     default:
4934       return 0;
4935     }
4936   }
4937 
4938   // break, if_break, else_break are all only used as inputs to loop, not
4939   // directly as branch conditions.
4940   return 0;
4941 }
4942 
4943 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4944   const Triple &TT = getTargetMachine().getTargetTriple();
4945   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4946           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4947          AMDGPU::shouldEmitConstantsToTextSection(TT);
4948 }
4949 
4950 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4951   // FIXME: Either avoid relying on address space here or change the default
4952   // address space for functions to avoid the explicit check.
4953   return (GV->getValueType()->isFunctionTy() ||
4954           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
4955          !shouldEmitFixup(GV) &&
4956          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4957 }
4958 
4959 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4960   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4961 }
4962 
4963 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
4964   if (!GV->hasExternalLinkage())
4965     return true;
4966 
4967   const auto OS = getTargetMachine().getTargetTriple().getOS();
4968   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
4969 }
4970 
4971 /// This transforms the control flow intrinsics to get the branch destination as
4972 /// last parameter, also switches branch target with BR if the need arise
4973 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4974                                       SelectionDAG &DAG) const {
4975   SDLoc DL(BRCOND);
4976 
4977   SDNode *Intr = BRCOND.getOperand(1).getNode();
4978   SDValue Target = BRCOND.getOperand(2);
4979   SDNode *BR = nullptr;
4980   SDNode *SetCC = nullptr;
4981 
4982   if (Intr->getOpcode() == ISD::SETCC) {
4983     // As long as we negate the condition everything is fine
4984     SetCC = Intr;
4985     Intr = SetCC->getOperand(0).getNode();
4986 
4987   } else {
4988     // Get the target from BR if we don't negate the condition
4989     BR = findUser(BRCOND, ISD::BR);
4990     assert(BR && "brcond missing unconditional branch user");
4991     Target = BR->getOperand(1);
4992   }
4993 
4994   unsigned CFNode = isCFIntrinsic(Intr);
4995   if (CFNode == 0) {
4996     // This is a uniform branch so we don't need to legalize.
4997     return BRCOND;
4998   }
4999 
5000   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5001                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5002 
5003   assert(!SetCC ||
5004         (SetCC->getConstantOperandVal(1) == 1 &&
5005          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5006                                                              ISD::SETNE));
5007 
5008   // operands of the new intrinsic call
5009   SmallVector<SDValue, 4> Ops;
5010   if (HaveChain)
5011     Ops.push_back(BRCOND.getOperand(0));
5012 
5013   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5014   Ops.push_back(Target);
5015 
5016   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5017 
5018   // build the new intrinsic call
5019   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5020 
5021   if (!HaveChain) {
5022     SDValue Ops[] =  {
5023       SDValue(Result, 0),
5024       BRCOND.getOperand(0)
5025     };
5026 
5027     Result = DAG.getMergeValues(Ops, DL).getNode();
5028   }
5029 
5030   if (BR) {
5031     // Give the branch instruction our target
5032     SDValue Ops[] = {
5033       BR->getOperand(0),
5034       BRCOND.getOperand(2)
5035     };
5036     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5037     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5038   }
5039 
5040   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5041 
5042   // Copy the intrinsic results to registers
5043   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5044     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5045     if (!CopyToReg)
5046       continue;
5047 
5048     Chain = DAG.getCopyToReg(
5049       Chain, DL,
5050       CopyToReg->getOperand(1),
5051       SDValue(Result, i - 1),
5052       SDValue());
5053 
5054     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5055   }
5056 
5057   // Remove the old intrinsic from the chain
5058   DAG.ReplaceAllUsesOfValueWith(
5059     SDValue(Intr, Intr->getNumValues() - 1),
5060     Intr->getOperand(0));
5061 
5062   return Chain;
5063 }
5064 
5065 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5066                                           SelectionDAG &DAG) const {
5067   MVT VT = Op.getSimpleValueType();
5068   SDLoc DL(Op);
5069   // Checking the depth
5070   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5071     return DAG.getConstant(0, DL, VT);
5072 
5073   MachineFunction &MF = DAG.getMachineFunction();
5074   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5075   // Check for kernel and shader functions
5076   if (Info->isEntryFunction())
5077     return DAG.getConstant(0, DL, VT);
5078 
5079   MachineFrameInfo &MFI = MF.getFrameInfo();
5080   // There is a call to @llvm.returnaddress in this function
5081   MFI.setReturnAddressIsTaken(true);
5082 
5083   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5084   // Get the return address reg and mark it as an implicit live-in
5085   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5086 
5087   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5088 }
5089 
5090 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5091                                             SDValue Op,
5092                                             const SDLoc &DL,
5093                                             EVT VT) const {
5094   return Op.getValueType().bitsLE(VT) ?
5095       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5096     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5097                 DAG.getTargetConstant(0, DL, MVT::i32));
5098 }
5099 
5100 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5101   assert(Op.getValueType() == MVT::f16 &&
5102          "Do not know how to custom lower FP_ROUND for non-f16 type");
5103 
5104   SDValue Src = Op.getOperand(0);
5105   EVT SrcVT = Src.getValueType();
5106   if (SrcVT != MVT::f64)
5107     return Op;
5108 
5109   SDLoc DL(Op);
5110 
5111   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5112   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5113   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5114 }
5115 
5116 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5117                                                SelectionDAG &DAG) const {
5118   EVT VT = Op.getValueType();
5119   const MachineFunction &MF = DAG.getMachineFunction();
5120   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5121   bool IsIEEEMode = Info->getMode().IEEE;
5122 
5123   // FIXME: Assert during selection that this is only selected for
5124   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5125   // mode functions, but this happens to be OK since it's only done in cases
5126   // where there is known no sNaN.
5127   if (IsIEEEMode)
5128     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5129 
5130   if (VT == MVT::v4f16)
5131     return splitBinaryVectorOp(Op, DAG);
5132   return Op;
5133 }
5134 
5135 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5136   EVT VT = Op.getValueType();
5137   SDLoc SL(Op);
5138   SDValue LHS = Op.getOperand(0);
5139   SDValue RHS = Op.getOperand(1);
5140   bool isSigned = Op.getOpcode() == ISD::SMULO;
5141 
5142   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5143     const APInt &C = RHSC->getAPIntValue();
5144     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5145     if (C.isPowerOf2()) {
5146       // smulo(x, signed_min) is same as umulo(x, signed_min).
5147       bool UseArithShift = isSigned && !C.isMinSignedValue();
5148       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5149       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5150       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5151           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5152                       SL, VT, Result, ShiftAmt),
5153           LHS, ISD::SETNE);
5154       return DAG.getMergeValues({ Result, Overflow }, SL);
5155     }
5156   }
5157 
5158   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5159   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5160                             SL, VT, LHS, RHS);
5161 
5162   SDValue Sign = isSigned
5163     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5164                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5165     : DAG.getConstant(0, SL, VT);
5166   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5167 
5168   return DAG.getMergeValues({ Result, Overflow }, SL);
5169 }
5170 
5171 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5172   if (!Subtarget->isTrapHandlerEnabled() ||
5173       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5174     return lowerTrapEndpgm(Op, DAG);
5175 
5176   if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) {
5177     switch (*HsaAbiVer) {
5178     case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
5179     case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
5180       return lowerTrapHsaQueuePtr(Op, DAG);
5181     case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
5182       return Subtarget->supportsGetDoorbellID() ?
5183           lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG);
5184     }
5185   }
5186 
5187   llvm_unreachable("Unknown trap handler");
5188 }
5189 
5190 SDValue SITargetLowering::lowerTrapEndpgm(
5191     SDValue Op, SelectionDAG &DAG) const {
5192   SDLoc SL(Op);
5193   SDValue Chain = Op.getOperand(0);
5194   return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5195 }
5196 
5197 SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5198     SDValue Op, SelectionDAG &DAG) const {
5199   SDLoc SL(Op);
5200   SDValue Chain = Op.getOperand(0);
5201 
5202   MachineFunction &MF = DAG.getMachineFunction();
5203   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5204   Register UserSGPR = Info->getQueuePtrUserSGPR();
5205   assert(UserSGPR != AMDGPU::NoRegister);
5206   SDValue QueuePtr = CreateLiveInRegister(
5207     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5208   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5209   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5210                                    QueuePtr, SDValue());
5211 
5212   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5213   SDValue Ops[] = {
5214     ToReg,
5215     DAG.getTargetConstant(TrapID, SL, MVT::i16),
5216     SGPR01,
5217     ToReg.getValue(1)
5218   };
5219   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5220 }
5221 
5222 SDValue SITargetLowering::lowerTrapHsa(
5223     SDValue Op, SelectionDAG &DAG) const {
5224   SDLoc SL(Op);
5225   SDValue Chain = Op.getOperand(0);
5226 
5227   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5228   SDValue Ops[] = {
5229     Chain,
5230     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5231   };
5232   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5233 }
5234 
5235 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5236   SDLoc SL(Op);
5237   SDValue Chain = Op.getOperand(0);
5238   MachineFunction &MF = DAG.getMachineFunction();
5239 
5240   if (!Subtarget->isTrapHandlerEnabled() ||
5241       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5242     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5243                                      "debugtrap handler not supported",
5244                                      Op.getDebugLoc(),
5245                                      DS_Warning);
5246     LLVMContext &Ctx = MF.getFunction().getContext();
5247     Ctx.diagnose(NoTrap);
5248     return Chain;
5249   }
5250 
5251   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5252   SDValue Ops[] = {
5253     Chain,
5254     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5255   };
5256   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5257 }
5258 
5259 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5260                                              SelectionDAG &DAG) const {
5261   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5262   if (Subtarget->hasApertureRegs()) {
5263     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5264         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5265         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5266     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5267         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5268         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5269     unsigned Encoding =
5270         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5271         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5272         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5273 
5274     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5275     SDValue ApertureReg = SDValue(
5276         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5277     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5278     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5279   }
5280 
5281   MachineFunction &MF = DAG.getMachineFunction();
5282   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5283   Register UserSGPR = Info->getQueuePtrUserSGPR();
5284   assert(UserSGPR != AMDGPU::NoRegister);
5285 
5286   SDValue QueuePtr = CreateLiveInRegister(
5287     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5288 
5289   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5290   // private_segment_aperture_base_hi.
5291   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5292 
5293   SDValue Ptr =
5294       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5295 
5296   // TODO: Use custom target PseudoSourceValue.
5297   // TODO: We should use the value from the IR intrinsic call, but it might not
5298   // be available and how do we get it?
5299   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5300   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5301                      commonAlignment(Align(64), StructOffset),
5302                      MachineMemOperand::MODereferenceable |
5303                          MachineMemOperand::MOInvariant);
5304 }
5305 
5306 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5307                                              SelectionDAG &DAG) const {
5308   SDLoc SL(Op);
5309   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5310 
5311   SDValue Src = ASC->getOperand(0);
5312   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5313 
5314   const AMDGPUTargetMachine &TM =
5315     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5316 
5317   // flat -> local/private
5318   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5319     unsigned DestAS = ASC->getDestAddressSpace();
5320 
5321     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5322         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5323       unsigned NullVal = TM.getNullPointerValue(DestAS);
5324       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5325       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5326       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5327 
5328       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
5329                          NonNull, Ptr, SegmentNullPtr);
5330     }
5331   }
5332 
5333   // local/private -> flat
5334   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5335     unsigned SrcAS = ASC->getSrcAddressSpace();
5336 
5337     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5338         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5339       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5340       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5341 
5342       SDValue NonNull
5343         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5344 
5345       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5346       SDValue CvtPtr
5347         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5348 
5349       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5350                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5351                          FlatNullPtr);
5352     }
5353   }
5354 
5355   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5356       Src.getValueType() == MVT::i64)
5357     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5358 
5359   // global <-> flat are no-ops and never emitted.
5360 
5361   const MachineFunction &MF = DAG.getMachineFunction();
5362   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5363     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5364   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5365 
5366   return DAG.getUNDEF(ASC->getValueType(0));
5367 }
5368 
5369 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5370 // the small vector and inserting them into the big vector. That is better than
5371 // the default expansion of doing it via a stack slot. Even though the use of
5372 // the stack slot would be optimized away afterwards, the stack slot itself
5373 // remains.
5374 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5375                                                 SelectionDAG &DAG) const {
5376   SDValue Vec = Op.getOperand(0);
5377   SDValue Ins = Op.getOperand(1);
5378   SDValue Idx = Op.getOperand(2);
5379   EVT VecVT = Vec.getValueType();
5380   EVT InsVT = Ins.getValueType();
5381   EVT EltVT = VecVT.getVectorElementType();
5382   unsigned InsNumElts = InsVT.getVectorNumElements();
5383   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5384   SDLoc SL(Op);
5385 
5386   for (unsigned I = 0; I != InsNumElts; ++I) {
5387     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5388                               DAG.getConstant(I, SL, MVT::i32));
5389     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5390                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5391   }
5392   return Vec;
5393 }
5394 
5395 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5396                                                  SelectionDAG &DAG) const {
5397   SDValue Vec = Op.getOperand(0);
5398   SDValue InsVal = Op.getOperand(1);
5399   SDValue Idx = Op.getOperand(2);
5400   EVT VecVT = Vec.getValueType();
5401   EVT EltVT = VecVT.getVectorElementType();
5402   unsigned VecSize = VecVT.getSizeInBits();
5403   unsigned EltSize = EltVT.getSizeInBits();
5404 
5405 
5406   assert(VecSize <= 64);
5407 
5408   unsigned NumElts = VecVT.getVectorNumElements();
5409   SDLoc SL(Op);
5410   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5411 
5412   if (NumElts == 4 && EltSize == 16 && KIdx) {
5413     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5414 
5415     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5416                                  DAG.getConstant(0, SL, MVT::i32));
5417     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5418                                  DAG.getConstant(1, SL, MVT::i32));
5419 
5420     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5421     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5422 
5423     unsigned Idx = KIdx->getZExtValue();
5424     bool InsertLo = Idx < 2;
5425     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5426       InsertLo ? LoVec : HiVec,
5427       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5428       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5429 
5430     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5431 
5432     SDValue Concat = InsertLo ?
5433       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5434       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5435 
5436     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5437   }
5438 
5439   if (isa<ConstantSDNode>(Idx))
5440     return SDValue();
5441 
5442   MVT IntVT = MVT::getIntegerVT(VecSize);
5443 
5444   // Avoid stack access for dynamic indexing.
5445   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5446 
5447   // Create a congruent vector with the target value in each element so that
5448   // the required element can be masked and ORed into the target vector.
5449   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5450                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5451 
5452   assert(isPowerOf2_32(EltSize));
5453   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5454 
5455   // Convert vector index to bit-index.
5456   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5457 
5458   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5459   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5460                             DAG.getConstant(0xffff, SL, IntVT),
5461                             ScaledIdx);
5462 
5463   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5464   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5465                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5466 
5467   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5468   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5469 }
5470 
5471 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5472                                                   SelectionDAG &DAG) const {
5473   SDLoc SL(Op);
5474 
5475   EVT ResultVT = Op.getValueType();
5476   SDValue Vec = Op.getOperand(0);
5477   SDValue Idx = Op.getOperand(1);
5478   EVT VecVT = Vec.getValueType();
5479   unsigned VecSize = VecVT.getSizeInBits();
5480   EVT EltVT = VecVT.getVectorElementType();
5481   assert(VecSize <= 64);
5482 
5483   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5484 
5485   // Make sure we do any optimizations that will make it easier to fold
5486   // source modifiers before obscuring it with bit operations.
5487 
5488   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5489   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5490     return Combined;
5491 
5492   unsigned EltSize = EltVT.getSizeInBits();
5493   assert(isPowerOf2_32(EltSize));
5494 
5495   MVT IntVT = MVT::getIntegerVT(VecSize);
5496   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5497 
5498   // Convert vector index to bit-index (* EltSize)
5499   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5500 
5501   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5502   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5503 
5504   if (ResultVT == MVT::f16) {
5505     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5506     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5507   }
5508 
5509   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5510 }
5511 
5512 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5513   assert(Elt % 2 == 0);
5514   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5515 }
5516 
5517 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5518                                               SelectionDAG &DAG) const {
5519   SDLoc SL(Op);
5520   EVT ResultVT = Op.getValueType();
5521   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5522 
5523   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5524   EVT EltVT = PackVT.getVectorElementType();
5525   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5526 
5527   // vector_shuffle <0,1,6,7> lhs, rhs
5528   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5529   //
5530   // vector_shuffle <6,7,2,3> lhs, rhs
5531   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5532   //
5533   // vector_shuffle <6,7,0,1> lhs, rhs
5534   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5535 
5536   // Avoid scalarizing when both halves are reading from consecutive elements.
5537   SmallVector<SDValue, 4> Pieces;
5538   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5539     if (elementPairIsContiguous(SVN->getMask(), I)) {
5540       const int Idx = SVN->getMaskElt(I);
5541       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5542       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5543       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5544                                     PackVT, SVN->getOperand(VecIdx),
5545                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5546       Pieces.push_back(SubVec);
5547     } else {
5548       const int Idx0 = SVN->getMaskElt(I);
5549       const int Idx1 = SVN->getMaskElt(I + 1);
5550       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5551       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5552       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5553       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5554 
5555       SDValue Vec0 = SVN->getOperand(VecIdx0);
5556       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5557                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5558 
5559       SDValue Vec1 = SVN->getOperand(VecIdx1);
5560       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5561                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5562       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5563     }
5564   }
5565 
5566   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5567 }
5568 
5569 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5570                                             SelectionDAG &DAG) const {
5571   SDLoc SL(Op);
5572   EVT VT = Op.getValueType();
5573 
5574   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5575     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5576 
5577     // Turn into pair of packed build_vectors.
5578     // TODO: Special case for constants that can be materialized with s_mov_b64.
5579     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5580                                     { Op.getOperand(0), Op.getOperand(1) });
5581     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5582                                     { Op.getOperand(2), Op.getOperand(3) });
5583 
5584     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5585     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5586 
5587     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5588     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5589   }
5590 
5591   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5592   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5593 
5594   SDValue Lo = Op.getOperand(0);
5595   SDValue Hi = Op.getOperand(1);
5596 
5597   // Avoid adding defined bits with the zero_extend.
5598   if (Hi.isUndef()) {
5599     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5600     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5601     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5602   }
5603 
5604   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5605   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5606 
5607   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5608                               DAG.getConstant(16, SL, MVT::i32));
5609   if (Lo.isUndef())
5610     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5611 
5612   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5613   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5614 
5615   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5616   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5617 }
5618 
5619 bool
5620 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5621   // We can fold offsets for anything that doesn't require a GOT relocation.
5622   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5623           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5624           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5625          !shouldEmitGOTReloc(GA->getGlobal());
5626 }
5627 
5628 static SDValue
5629 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5630                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5631                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5632   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5633   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5634   // lowered to the following code sequence:
5635   //
5636   // For constant address space:
5637   //   s_getpc_b64 s[0:1]
5638   //   s_add_u32 s0, s0, $symbol
5639   //   s_addc_u32 s1, s1, 0
5640   //
5641   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5642   //   a fixup or relocation is emitted to replace $symbol with a literal
5643   //   constant, which is a pc-relative offset from the encoding of the $symbol
5644   //   operand to the global variable.
5645   //
5646   // For global address space:
5647   //   s_getpc_b64 s[0:1]
5648   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5649   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5650   //
5651   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5652   //   fixups or relocations are emitted to replace $symbol@*@lo and
5653   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5654   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5655   //   operand to the global variable.
5656   //
5657   // What we want here is an offset from the value returned by s_getpc
5658   // (which is the address of the s_add_u32 instruction) to the global
5659   // variable, but since the encoding of $symbol starts 4 bytes after the start
5660   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5661   // small. This requires us to add 4 to the global variable offset in order to
5662   // compute the correct address. Similarly for the s_addc_u32 instruction, the
5663   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
5664   // instruction.
5665   SDValue PtrLo =
5666       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5667   SDValue PtrHi;
5668   if (GAFlags == SIInstrInfo::MO_NONE) {
5669     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5670   } else {
5671     PtrHi =
5672         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
5673   }
5674   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5675 }
5676 
5677 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5678                                              SDValue Op,
5679                                              SelectionDAG &DAG) const {
5680   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5681   SDLoc DL(GSD);
5682   EVT PtrVT = Op.getValueType();
5683 
5684   const GlobalValue *GV = GSD->getGlobal();
5685   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5686        shouldUseLDSConstAddress(GV)) ||
5687       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5688       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
5689     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5690         GV->hasExternalLinkage()) {
5691       Type *Ty = GV->getValueType();
5692       // HIP uses an unsized array `extern __shared__ T s[]` or similar
5693       // zero-sized type in other languages to declare the dynamic shared
5694       // memory which size is not known at the compile time. They will be
5695       // allocated by the runtime and placed directly after the static
5696       // allocated ones. They all share the same offset.
5697       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
5698         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
5699         // Adjust alignment for that dynamic shared memory array.
5700         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
5701         return SDValue(
5702             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
5703       }
5704     }
5705     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5706   }
5707 
5708   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5709     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5710                                             SIInstrInfo::MO_ABS32_LO);
5711     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5712   }
5713 
5714   if (shouldEmitFixup(GV))
5715     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5716   else if (shouldEmitPCReloc(GV))
5717     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5718                                    SIInstrInfo::MO_REL32);
5719 
5720   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5721                                             SIInstrInfo::MO_GOTPCREL32);
5722 
5723   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5724   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5725   const DataLayout &DataLayout = DAG.getDataLayout();
5726   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
5727   MachinePointerInfo PtrInfo
5728     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5729 
5730   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
5731                      MachineMemOperand::MODereferenceable |
5732                          MachineMemOperand::MOInvariant);
5733 }
5734 
5735 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5736                                    const SDLoc &DL, SDValue V) const {
5737   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5738   // the destination register.
5739   //
5740   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5741   // so we will end up with redundant moves to m0.
5742   //
5743   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5744 
5745   // A Null SDValue creates a glue result.
5746   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5747                                   V, Chain);
5748   return SDValue(M0, 0);
5749 }
5750 
5751 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5752                                                  SDValue Op,
5753                                                  MVT VT,
5754                                                  unsigned Offset) const {
5755   SDLoc SL(Op);
5756   SDValue Param = lowerKernargMemParameter(
5757       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
5758   // The local size values will have the hi 16-bits as zero.
5759   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5760                      DAG.getValueType(VT));
5761 }
5762 
5763 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5764                                         EVT VT) {
5765   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5766                                       "non-hsa intrinsic with hsa target",
5767                                       DL.getDebugLoc());
5768   DAG.getContext()->diagnose(BadIntrin);
5769   return DAG.getUNDEF(VT);
5770 }
5771 
5772 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5773                                          EVT VT) {
5774   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5775                                       "intrinsic not supported on subtarget",
5776                                       DL.getDebugLoc());
5777   DAG.getContext()->diagnose(BadIntrin);
5778   return DAG.getUNDEF(VT);
5779 }
5780 
5781 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5782                                     ArrayRef<SDValue> Elts) {
5783   assert(!Elts.empty());
5784   MVT Type;
5785   unsigned NumElts;
5786 
5787   if (Elts.size() == 1) {
5788     Type = MVT::f32;
5789     NumElts = 1;
5790   } else if (Elts.size() == 2) {
5791     Type = MVT::v2f32;
5792     NumElts = 2;
5793   } else if (Elts.size() == 3) {
5794     Type = MVT::v3f32;
5795     NumElts = 3;
5796   } else if (Elts.size() <= 4) {
5797     Type = MVT::v4f32;
5798     NumElts = 4;
5799   } else if (Elts.size() <= 8) {
5800     Type = MVT::v8f32;
5801     NumElts = 8;
5802   } else {
5803     assert(Elts.size() <= 16);
5804     Type = MVT::v16f32;
5805     NumElts = 16;
5806   }
5807 
5808   SmallVector<SDValue, 16> VecElts(NumElts);
5809   for (unsigned i = 0; i < Elts.size(); ++i) {
5810     SDValue Elt = Elts[i];
5811     if (Elt.getValueType() != MVT::f32)
5812       Elt = DAG.getBitcast(MVT::f32, Elt);
5813     VecElts[i] = Elt;
5814   }
5815   for (unsigned i = Elts.size(); i < NumElts; ++i)
5816     VecElts[i] = DAG.getUNDEF(MVT::f32);
5817 
5818   if (NumElts == 1)
5819     return VecElts[0];
5820   return DAG.getBuildVector(Type, DL, VecElts);
5821 }
5822 
5823 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5824                               SDValue Src, int ExtraElts) {
5825   EVT SrcVT = Src.getValueType();
5826 
5827   SmallVector<SDValue, 8> Elts;
5828 
5829   if (SrcVT.isVector())
5830     DAG.ExtractVectorElements(Src, Elts);
5831   else
5832     Elts.push_back(Src);
5833 
5834   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5835   while (ExtraElts--)
5836     Elts.push_back(Undef);
5837 
5838   return DAG.getBuildVector(CastVT, DL, Elts);
5839 }
5840 
5841 // Re-construct the required return value for a image load intrinsic.
5842 // This is more complicated due to the optional use TexFailCtrl which means the required
5843 // return type is an aggregate
5844 static SDValue constructRetValue(SelectionDAG &DAG,
5845                                  MachineSDNode *Result,
5846                                  ArrayRef<EVT> ResultTypes,
5847                                  bool IsTexFail, bool Unpacked, bool IsD16,
5848                                  int DMaskPop, int NumVDataDwords,
5849                                  const SDLoc &DL) {
5850   // Determine the required return type. This is the same regardless of IsTexFail flag
5851   EVT ReqRetVT = ResultTypes[0];
5852   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5853   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5854     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5855 
5856   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5857     DMaskPop : (DMaskPop + 1) / 2;
5858 
5859   MVT DataDwordVT = NumDataDwords == 1 ?
5860     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5861 
5862   MVT MaskPopVT = MaskPopDwords == 1 ?
5863     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5864 
5865   SDValue Data(Result, 0);
5866   SDValue TexFail;
5867 
5868   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
5869     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5870     if (MaskPopVT.isVector()) {
5871       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5872                          SDValue(Result, 0), ZeroIdx);
5873     } else {
5874       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5875                          SDValue(Result, 0), ZeroIdx);
5876     }
5877   }
5878 
5879   if (DataDwordVT.isVector())
5880     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5881                           NumDataDwords - MaskPopDwords);
5882 
5883   if (IsD16)
5884     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5885 
5886   EVT LegalReqRetVT = ReqRetVT;
5887   if (!ReqRetVT.isVector()) {
5888     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5889   } else {
5890     // We need to widen the return vector to a legal type
5891     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
5892         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
5893       LegalReqRetVT =
5894           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
5895                            ReqRetVT.getVectorNumElements() + 1);
5896     }
5897   }
5898   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
5899 
5900   if (IsTexFail) {
5901     TexFail =
5902         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
5903                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5904 
5905     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5906   }
5907 
5908   if (Result->getNumValues() == 1)
5909     return Data;
5910 
5911   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5912 }
5913 
5914 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5915                          SDValue *LWE, bool &IsTexFail) {
5916   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5917 
5918   uint64_t Value = TexFailCtrlConst->getZExtValue();
5919   if (Value) {
5920     IsTexFail = true;
5921   }
5922 
5923   SDLoc DL(TexFailCtrlConst);
5924   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5925   Value &= ~(uint64_t)0x1;
5926   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5927   Value &= ~(uint64_t)0x2;
5928 
5929   return Value == 0;
5930 }
5931 
5932 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
5933                                       MVT PackVectorVT,
5934                                       SmallVectorImpl<SDValue> &PackedAddrs,
5935                                       unsigned DimIdx, unsigned EndIdx,
5936                                       unsigned NumGradients) {
5937   SDLoc DL(Op);
5938   for (unsigned I = DimIdx; I < EndIdx; I++) {
5939     SDValue Addr = Op.getOperand(I);
5940 
5941     // Gradients are packed with undef for each coordinate.
5942     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
5943     // 1D: undef,dx/dh; undef,dx/dv
5944     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
5945     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
5946     if (((I + 1) >= EndIdx) ||
5947         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
5948                                          I == DimIdx + NumGradients - 1))) {
5949       if (Addr.getValueType() != MVT::i16)
5950         Addr = DAG.getBitcast(MVT::i16, Addr);
5951       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
5952     } else {
5953       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
5954       I++;
5955     }
5956     Addr = DAG.getBitcast(MVT::f32, Addr);
5957     PackedAddrs.push_back(Addr);
5958   }
5959 }
5960 
5961 SDValue SITargetLowering::lowerImage(SDValue Op,
5962                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5963                                      SelectionDAG &DAG, bool WithChain) const {
5964   SDLoc DL(Op);
5965   MachineFunction &MF = DAG.getMachineFunction();
5966   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5967   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5968       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5969   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5970   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5971       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5972   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5973       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5974   unsigned IntrOpcode = Intr->BaseOpcode;
5975   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
5976 
5977   SmallVector<EVT, 3> ResultTypes(Op->values());
5978   SmallVector<EVT, 3> OrigResultTypes(Op->values());
5979   bool IsD16 = false;
5980   bool IsG16 = false;
5981   bool IsA16 = false;
5982   SDValue VData;
5983   int NumVDataDwords;
5984   bool AdjustRetType = false;
5985 
5986   // Offset of intrinsic arguments
5987   const unsigned ArgOffset = WithChain ? 2 : 1;
5988 
5989   unsigned DMask;
5990   unsigned DMaskLanes = 0;
5991 
5992   if (BaseOpcode->Atomic) {
5993     VData = Op.getOperand(2);
5994 
5995     bool Is64Bit = VData.getValueType() == MVT::i64;
5996     if (BaseOpcode->AtomicX2) {
5997       SDValue VData2 = Op.getOperand(3);
5998       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5999                                  {VData, VData2});
6000       if (Is64Bit)
6001         VData = DAG.getBitcast(MVT::v4i32, VData);
6002 
6003       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6004       DMask = Is64Bit ? 0xf : 0x3;
6005       NumVDataDwords = Is64Bit ? 4 : 2;
6006     } else {
6007       DMask = Is64Bit ? 0x3 : 0x1;
6008       NumVDataDwords = Is64Bit ? 2 : 1;
6009     }
6010   } else {
6011     auto *DMaskConst =
6012         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6013     DMask = DMaskConst->getZExtValue();
6014     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6015 
6016     if (BaseOpcode->Store) {
6017       VData = Op.getOperand(2);
6018 
6019       MVT StoreVT = VData.getSimpleValueType();
6020       if (StoreVT.getScalarType() == MVT::f16) {
6021         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6022           return Op; // D16 is unsupported for this instruction
6023 
6024         IsD16 = true;
6025         VData = handleD16VData(VData, DAG, true);
6026       }
6027 
6028       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6029     } else {
6030       // Work out the num dwords based on the dmask popcount and underlying type
6031       // and whether packing is supported.
6032       MVT LoadVT = ResultTypes[0].getSimpleVT();
6033       if (LoadVT.getScalarType() == MVT::f16) {
6034         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6035           return Op; // D16 is unsupported for this instruction
6036 
6037         IsD16 = true;
6038       }
6039 
6040       // Confirm that the return type is large enough for the dmask specified
6041       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6042           (!LoadVT.isVector() && DMaskLanes > 1))
6043           return Op;
6044 
6045       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6046       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6047       // instructions.
6048       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6049           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6050         NumVDataDwords = (DMaskLanes + 1) / 2;
6051       else
6052         NumVDataDwords = DMaskLanes;
6053 
6054       AdjustRetType = true;
6055     }
6056   }
6057 
6058   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6059   SmallVector<SDValue, 4> VAddrs;
6060 
6061   // Optimize _L to _LZ when _L is zero
6062   if (LZMappingInfo) {
6063     if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>(
6064             Op.getOperand(ArgOffset + Intr->LodIndex))) {
6065       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
6066         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
6067         VAddrEnd--;                      // remove 'lod'
6068       }
6069     }
6070   }
6071 
6072   // Optimize _mip away, when 'lod' is zero
6073   if (MIPMappingInfo) {
6074     if (auto *ConstantLod = dyn_cast<ConstantSDNode>(
6075             Op.getOperand(ArgOffset + Intr->MipIndex))) {
6076       if (ConstantLod->isNullValue()) {
6077         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
6078         VAddrEnd--;                           // remove 'mip'
6079       }
6080     }
6081   }
6082 
6083   // Push back extra arguments.
6084   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++)
6085     VAddrs.push_back(Op.getOperand(ArgOffset + I));
6086 
6087   // Check for 16 bit addresses or derivatives and pack if true.
6088   MVT VAddrVT =
6089       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6090   MVT VAddrScalarVT = VAddrVT.getScalarType();
6091   MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6092   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6093 
6094   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6095   VAddrScalarVT = VAddrVT.getScalarType();
6096   MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6097   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6098 
6099   if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
6100     // 16 bit gradients are supported, but are tied to the A16 control
6101     // so both gradients and addresses must be 16 bit
6102     LLVM_DEBUG(
6103         dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6104                   "require 16 bit args for both gradients and addresses");
6105     return Op;
6106   }
6107 
6108   if (IsA16) {
6109     if (!ST->hasA16()) {
6110       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6111                            "support 16 bit addresses\n");
6112       return Op;
6113     }
6114   }
6115 
6116   // We've dealt with incorrect input so we know that if IsA16, IsG16
6117   // are set then we have to compress/pack operands (either address,
6118   // gradient or both)
6119   // In the case where a16 and gradients are tied (no G16 support) then we
6120   // have already verified that both IsA16 and IsG16 are true
6121   if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
6122     // Activate g16
6123     const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6124         AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6125     IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6126   }
6127 
6128   // Add gradients (packed or unpacked)
6129   if (IsG16) {
6130     // Pack the gradients
6131     // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6132     packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
6133                               ArgOffset + Intr->GradientStart,
6134                               ArgOffset + Intr->CoordStart, Intr->NumGradients);
6135   } else {
6136     for (unsigned I = ArgOffset + Intr->GradientStart;
6137          I < ArgOffset + Intr->CoordStart; I++)
6138       VAddrs.push_back(Op.getOperand(I));
6139   }
6140 
6141   // Add addresses (packed or unpacked)
6142   if (IsA16) {
6143     packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
6144                               ArgOffset + Intr->CoordStart, VAddrEnd,
6145                               0 /* No gradients */);
6146   } else {
6147     // Add uncompressed address
6148     for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6149       VAddrs.push_back(Op.getOperand(I));
6150   }
6151 
6152   // If the register allocator cannot place the address registers contiguously
6153   // without introducing moves, then using the non-sequential address encoding
6154   // is always preferable, since it saves VALU instructions and is usually a
6155   // wash in terms of code size or even better.
6156   //
6157   // However, we currently have no way of hinting to the register allocator that
6158   // MIMG addresses should be placed contiguously when it is possible to do so,
6159   // so force non-NSA for the common 2-address case as a heuristic.
6160   //
6161   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6162   // allocation when possible.
6163   bool UseNSA =
6164       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
6165   SDValue VAddr;
6166   if (!UseNSA)
6167     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6168 
6169   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6170   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6171   SDValue Unorm;
6172   if (!BaseOpcode->Sampler) {
6173     Unorm = True;
6174   } else {
6175     auto UnormConst =
6176         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6177 
6178     Unorm = UnormConst->getZExtValue() ? True : False;
6179   }
6180 
6181   SDValue TFE;
6182   SDValue LWE;
6183   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6184   bool IsTexFail = false;
6185   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6186     return Op;
6187 
6188   if (IsTexFail) {
6189     if (!DMaskLanes) {
6190       // Expecting to get an error flag since TFC is on - and dmask is 0
6191       // Force dmask to be at least 1 otherwise the instruction will fail
6192       DMask = 0x1;
6193       DMaskLanes = 1;
6194       NumVDataDwords = 1;
6195     }
6196     NumVDataDwords += 1;
6197     AdjustRetType = true;
6198   }
6199 
6200   // Has something earlier tagged that the return type needs adjusting
6201   // This happens if the instruction is a load or has set TexFailCtrl flags
6202   if (AdjustRetType) {
6203     // NumVDataDwords reflects the true number of dwords required in the return type
6204     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6205       // This is a no-op load. This can be eliminated
6206       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6207       if (isa<MemSDNode>(Op))
6208         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6209       return Undef;
6210     }
6211 
6212     EVT NewVT = NumVDataDwords > 1 ?
6213                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6214                 : MVT::i32;
6215 
6216     ResultTypes[0] = NewVT;
6217     if (ResultTypes.size() == 3) {
6218       // Original result was aggregate type used for TexFailCtrl results
6219       // The actual instruction returns as a vector type which has now been
6220       // created. Remove the aggregate result.
6221       ResultTypes.erase(&ResultTypes[1]);
6222     }
6223   }
6224 
6225   unsigned CPol = cast<ConstantSDNode>(
6226       Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6227   if (BaseOpcode->Atomic)
6228     CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6229   if (CPol & ~AMDGPU::CPol::ALL)
6230     return Op;
6231 
6232   SmallVector<SDValue, 26> Ops;
6233   if (BaseOpcode->Store || BaseOpcode->Atomic)
6234     Ops.push_back(VData); // vdata
6235   if (UseNSA)
6236     append_range(Ops, VAddrs);
6237   else
6238     Ops.push_back(VAddr);
6239   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6240   if (BaseOpcode->Sampler)
6241     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6242   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6243   if (IsGFX10Plus)
6244     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6245   Ops.push_back(Unorm);
6246   Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6247   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6248                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6249   if (IsGFX10Plus)
6250     Ops.push_back(IsA16 ? True : False);
6251   if (!Subtarget->hasGFX90AInsts()) {
6252     Ops.push_back(TFE); //tfe
6253   } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6254     report_fatal_error("TFE is not supported on this GPU");
6255   }
6256   Ops.push_back(LWE); // lwe
6257   if (!IsGFX10Plus)
6258     Ops.push_back(DimInfo->DA ? True : False);
6259   if (BaseOpcode->HasD16)
6260     Ops.push_back(IsD16 ? True : False);
6261   if (isa<MemSDNode>(Op))
6262     Ops.push_back(Op.getOperand(0)); // chain
6263 
6264   int NumVAddrDwords =
6265       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6266   int Opcode = -1;
6267 
6268   if (IsGFX10Plus) {
6269     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6270                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6271                                           : AMDGPU::MIMGEncGfx10Default,
6272                                    NumVDataDwords, NumVAddrDwords);
6273   } else {
6274     if (Subtarget->hasGFX90AInsts()) {
6275       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6276                                      NumVDataDwords, NumVAddrDwords);
6277       if (Opcode == -1)
6278         report_fatal_error(
6279             "requested image instruction is not supported on this GPU");
6280     }
6281     if (Opcode == -1 &&
6282         Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6283       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6284                                      NumVDataDwords, NumVAddrDwords);
6285     if (Opcode == -1)
6286       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6287                                      NumVDataDwords, NumVAddrDwords);
6288   }
6289   assert(Opcode != -1);
6290 
6291   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6292   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6293     MachineMemOperand *MemRef = MemOp->getMemOperand();
6294     DAG.setNodeMemRefs(NewNode, {MemRef});
6295   }
6296 
6297   if (BaseOpcode->AtomicX2) {
6298     SmallVector<SDValue, 1> Elt;
6299     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6300     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6301   }
6302   if (BaseOpcode->Store)
6303     return SDValue(NewNode, 0);
6304   return constructRetValue(DAG, NewNode,
6305                            OrigResultTypes, IsTexFail,
6306                            Subtarget->hasUnpackedD16VMem(), IsD16,
6307                            DMaskLanes, NumVDataDwords, DL);
6308 }
6309 
6310 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6311                                        SDValue Offset, SDValue CachePolicy,
6312                                        SelectionDAG &DAG) const {
6313   MachineFunction &MF = DAG.getMachineFunction();
6314 
6315   const DataLayout &DataLayout = DAG.getDataLayout();
6316   Align Alignment =
6317       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6318 
6319   MachineMemOperand *MMO = MF.getMachineMemOperand(
6320       MachinePointerInfo(),
6321       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6322           MachineMemOperand::MOInvariant,
6323       VT.getStoreSize(), Alignment);
6324 
6325   if (!Offset->isDivergent()) {
6326     SDValue Ops[] = {
6327         Rsrc,
6328         Offset, // Offset
6329         CachePolicy
6330     };
6331 
6332     // Widen vec3 load to vec4.
6333     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6334       EVT WidenedVT =
6335           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6336       auto WidenedOp = DAG.getMemIntrinsicNode(
6337           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6338           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6339       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6340                                    DAG.getVectorIdxConstant(0, DL));
6341       return Subvector;
6342     }
6343 
6344     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6345                                    DAG.getVTList(VT), Ops, VT, MMO);
6346   }
6347 
6348   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6349   // assume that the buffer is unswizzled.
6350   SmallVector<SDValue, 4> Loads;
6351   unsigned NumLoads = 1;
6352   MVT LoadVT = VT.getSimpleVT();
6353   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6354   assert((LoadVT.getScalarType() == MVT::i32 ||
6355           LoadVT.getScalarType() == MVT::f32));
6356 
6357   if (NumElts == 8 || NumElts == 16) {
6358     NumLoads = NumElts / 4;
6359     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6360   }
6361 
6362   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6363   SDValue Ops[] = {
6364       DAG.getEntryNode(),                               // Chain
6365       Rsrc,                                             // rsrc
6366       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6367       {},                                               // voffset
6368       {},                                               // soffset
6369       {},                                               // offset
6370       CachePolicy,                                      // cachepolicy
6371       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6372   };
6373 
6374   // Use the alignment to ensure that the required offsets will fit into the
6375   // immediate offsets.
6376   setBufferOffsets(Offset, DAG, &Ops[3],
6377                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6378 
6379   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6380   for (unsigned i = 0; i < NumLoads; ++i) {
6381     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6382     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6383                                         LoadVT, MMO, DAG));
6384   }
6385 
6386   if (NumElts == 8 || NumElts == 16)
6387     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6388 
6389   return Loads[0];
6390 }
6391 
6392 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6393                                                   SelectionDAG &DAG) const {
6394   MachineFunction &MF = DAG.getMachineFunction();
6395   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6396 
6397   EVT VT = Op.getValueType();
6398   SDLoc DL(Op);
6399   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6400 
6401   // TODO: Should this propagate fast-math-flags?
6402 
6403   switch (IntrinsicID) {
6404   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6405     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6406       return emitNonHSAIntrinsicError(DAG, DL, VT);
6407     return getPreloadedValue(DAG, *MFI, VT,
6408                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6409   }
6410   case Intrinsic::amdgcn_dispatch_ptr:
6411   case Intrinsic::amdgcn_queue_ptr: {
6412     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6413       DiagnosticInfoUnsupported BadIntrin(
6414           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6415           DL.getDebugLoc());
6416       DAG.getContext()->diagnose(BadIntrin);
6417       return DAG.getUNDEF(VT);
6418     }
6419 
6420     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6421       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6422     return getPreloadedValue(DAG, *MFI, VT, RegID);
6423   }
6424   case Intrinsic::amdgcn_implicitarg_ptr: {
6425     if (MFI->isEntryFunction())
6426       return getImplicitArgPtr(DAG, DL);
6427     return getPreloadedValue(DAG, *MFI, VT,
6428                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6429   }
6430   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6431     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6432       // This only makes sense to call in a kernel, so just lower to null.
6433       return DAG.getConstant(0, DL, VT);
6434     }
6435 
6436     return getPreloadedValue(DAG, *MFI, VT,
6437                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6438   }
6439   case Intrinsic::amdgcn_dispatch_id: {
6440     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6441   }
6442   case Intrinsic::amdgcn_rcp:
6443     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6444   case Intrinsic::amdgcn_rsq:
6445     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6446   case Intrinsic::amdgcn_rsq_legacy:
6447     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6448       return emitRemovedIntrinsicError(DAG, DL, VT);
6449     return SDValue();
6450   case Intrinsic::amdgcn_rcp_legacy:
6451     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6452       return emitRemovedIntrinsicError(DAG, DL, VT);
6453     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6454   case Intrinsic::amdgcn_rsq_clamp: {
6455     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6456       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6457 
6458     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6459     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6460     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6461 
6462     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6463     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6464                               DAG.getConstantFP(Max, DL, VT));
6465     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6466                        DAG.getConstantFP(Min, DL, VT));
6467   }
6468   case Intrinsic::r600_read_ngroups_x:
6469     if (Subtarget->isAmdHsaOS())
6470       return emitNonHSAIntrinsicError(DAG, DL, VT);
6471 
6472     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6473                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6474                                     false);
6475   case Intrinsic::r600_read_ngroups_y:
6476     if (Subtarget->isAmdHsaOS())
6477       return emitNonHSAIntrinsicError(DAG, DL, VT);
6478 
6479     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6480                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6481                                     false);
6482   case Intrinsic::r600_read_ngroups_z:
6483     if (Subtarget->isAmdHsaOS())
6484       return emitNonHSAIntrinsicError(DAG, DL, VT);
6485 
6486     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6487                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6488                                     false);
6489   case Intrinsic::r600_read_global_size_x:
6490     if (Subtarget->isAmdHsaOS())
6491       return emitNonHSAIntrinsicError(DAG, DL, VT);
6492 
6493     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6494                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6495                                     Align(4), false);
6496   case Intrinsic::r600_read_global_size_y:
6497     if (Subtarget->isAmdHsaOS())
6498       return emitNonHSAIntrinsicError(DAG, DL, VT);
6499 
6500     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6501                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6502                                     Align(4), false);
6503   case Intrinsic::r600_read_global_size_z:
6504     if (Subtarget->isAmdHsaOS())
6505       return emitNonHSAIntrinsicError(DAG, DL, VT);
6506 
6507     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6508                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6509                                     Align(4), false);
6510   case Intrinsic::r600_read_local_size_x:
6511     if (Subtarget->isAmdHsaOS())
6512       return emitNonHSAIntrinsicError(DAG, DL, VT);
6513 
6514     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6515                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6516   case Intrinsic::r600_read_local_size_y:
6517     if (Subtarget->isAmdHsaOS())
6518       return emitNonHSAIntrinsicError(DAG, DL, VT);
6519 
6520     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6521                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6522   case Intrinsic::r600_read_local_size_z:
6523     if (Subtarget->isAmdHsaOS())
6524       return emitNonHSAIntrinsicError(DAG, DL, VT);
6525 
6526     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6527                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6528   case Intrinsic::amdgcn_workgroup_id_x:
6529     return getPreloadedValue(DAG, *MFI, VT,
6530                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6531   case Intrinsic::amdgcn_workgroup_id_y:
6532     return getPreloadedValue(DAG, *MFI, VT,
6533                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6534   case Intrinsic::amdgcn_workgroup_id_z:
6535     return getPreloadedValue(DAG, *MFI, VT,
6536                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6537   case Intrinsic::amdgcn_workitem_id_x:
6538     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6539                           SDLoc(DAG.getEntryNode()),
6540                           MFI->getArgInfo().WorkItemIDX);
6541   case Intrinsic::amdgcn_workitem_id_y:
6542     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6543                           SDLoc(DAG.getEntryNode()),
6544                           MFI->getArgInfo().WorkItemIDY);
6545   case Intrinsic::amdgcn_workitem_id_z:
6546     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6547                           SDLoc(DAG.getEntryNode()),
6548                           MFI->getArgInfo().WorkItemIDZ);
6549   case Intrinsic::amdgcn_wavefrontsize:
6550     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6551                            SDLoc(Op), MVT::i32);
6552   case Intrinsic::amdgcn_s_buffer_load: {
6553     unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6554     if (CPol & ~AMDGPU::CPol::ALL)
6555       return Op;
6556     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6557                         DAG);
6558   }
6559   case Intrinsic::amdgcn_fdiv_fast:
6560     return lowerFDIV_FAST(Op, DAG);
6561   case Intrinsic::amdgcn_sin:
6562     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6563 
6564   case Intrinsic::amdgcn_cos:
6565     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6566 
6567   case Intrinsic::amdgcn_mul_u24:
6568     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6569   case Intrinsic::amdgcn_mul_i24:
6570     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6571 
6572   case Intrinsic::amdgcn_log_clamp: {
6573     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6574       return SDValue();
6575 
6576     return emitRemovedIntrinsicError(DAG, DL, VT);
6577   }
6578   case Intrinsic::amdgcn_ldexp:
6579     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6580                        Op.getOperand(1), Op.getOperand(2));
6581 
6582   case Intrinsic::amdgcn_fract:
6583     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6584 
6585   case Intrinsic::amdgcn_class:
6586     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6587                        Op.getOperand(1), Op.getOperand(2));
6588   case Intrinsic::amdgcn_div_fmas:
6589     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6590                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6591                        Op.getOperand(4));
6592 
6593   case Intrinsic::amdgcn_div_fixup:
6594     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6595                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6596 
6597   case Intrinsic::amdgcn_div_scale: {
6598     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6599 
6600     // Translate to the operands expected by the machine instruction. The
6601     // first parameter must be the same as the first instruction.
6602     SDValue Numerator = Op.getOperand(1);
6603     SDValue Denominator = Op.getOperand(2);
6604 
6605     // Note this order is opposite of the machine instruction's operations,
6606     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6607     // intrinsic has the numerator as the first operand to match a normal
6608     // division operation.
6609 
6610     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6611 
6612     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6613                        Denominator, Numerator);
6614   }
6615   case Intrinsic::amdgcn_icmp: {
6616     // There is a Pat that handles this variant, so return it as-is.
6617     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6618         Op.getConstantOperandVal(2) == 0 &&
6619         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6620       return Op;
6621     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6622   }
6623   case Intrinsic::amdgcn_fcmp: {
6624     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6625   }
6626   case Intrinsic::amdgcn_ballot:
6627     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6628   case Intrinsic::amdgcn_fmed3:
6629     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6630                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6631   case Intrinsic::amdgcn_fdot2:
6632     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6633                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6634                        Op.getOperand(4));
6635   case Intrinsic::amdgcn_fmul_legacy:
6636     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6637                        Op.getOperand(1), Op.getOperand(2));
6638   case Intrinsic::amdgcn_sffbh:
6639     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6640   case Intrinsic::amdgcn_sbfe:
6641     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6642                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6643   case Intrinsic::amdgcn_ubfe:
6644     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6645                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6646   case Intrinsic::amdgcn_cvt_pkrtz:
6647   case Intrinsic::amdgcn_cvt_pknorm_i16:
6648   case Intrinsic::amdgcn_cvt_pknorm_u16:
6649   case Intrinsic::amdgcn_cvt_pk_i16:
6650   case Intrinsic::amdgcn_cvt_pk_u16: {
6651     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6652     EVT VT = Op.getValueType();
6653     unsigned Opcode;
6654 
6655     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6656       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6657     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6658       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6659     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6660       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6661     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6662       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6663     else
6664       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6665 
6666     if (isTypeLegal(VT))
6667       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6668 
6669     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6670                                Op.getOperand(1), Op.getOperand(2));
6671     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6672   }
6673   case Intrinsic::amdgcn_fmad_ftz:
6674     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6675                        Op.getOperand(2), Op.getOperand(3));
6676 
6677   case Intrinsic::amdgcn_if_break:
6678     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6679                                       Op->getOperand(1), Op->getOperand(2)), 0);
6680 
6681   case Intrinsic::amdgcn_groupstaticsize: {
6682     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6683     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6684       return Op;
6685 
6686     const Module *M = MF.getFunction().getParent();
6687     const GlobalValue *GV =
6688         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6689     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6690                                             SIInstrInfo::MO_ABS32_LO);
6691     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6692   }
6693   case Intrinsic::amdgcn_is_shared:
6694   case Intrinsic::amdgcn_is_private: {
6695     SDLoc SL(Op);
6696     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6697       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6698     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6699     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6700                                  Op.getOperand(1));
6701 
6702     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6703                                 DAG.getConstant(1, SL, MVT::i32));
6704     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6705   }
6706   case Intrinsic::amdgcn_alignbit:
6707     return DAG.getNode(ISD::FSHR, DL, VT,
6708                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6709   case Intrinsic::amdgcn_perm:
6710     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
6711                        Op.getOperand(2), Op.getOperand(3));
6712   case Intrinsic::amdgcn_reloc_constant: {
6713     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6714     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6715     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6716     auto RelocSymbol = cast<GlobalVariable>(
6717         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6718     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6719                                             SIInstrInfo::MO_ABS32_LO);
6720     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6721   }
6722   default:
6723     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6724             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6725       return lowerImage(Op, ImageDimIntr, DAG, false);
6726 
6727     return Op;
6728   }
6729 }
6730 
6731 // This function computes an appropriate offset to pass to
6732 // MachineMemOperand::setOffset() based on the offset inputs to
6733 // an intrinsic.  If any of the offsets are non-contstant or
6734 // if VIndex is non-zero then this function returns 0.  Otherwise,
6735 // it returns the sum of VOffset, SOffset, and Offset.
6736 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6737                                       SDValue SOffset,
6738                                       SDValue Offset,
6739                                       SDValue VIndex = SDValue()) {
6740 
6741   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6742       !isa<ConstantSDNode>(Offset))
6743     return 0;
6744 
6745   if (VIndex) {
6746     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6747       return 0;
6748   }
6749 
6750   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6751          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6752          cast<ConstantSDNode>(Offset)->getSExtValue();
6753 }
6754 
6755 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
6756                                                      SelectionDAG &DAG,
6757                                                      unsigned NewOpcode) const {
6758   SDLoc DL(Op);
6759 
6760   SDValue VData = Op.getOperand(2);
6761   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6762   SDValue Ops[] = {
6763     Op.getOperand(0), // Chain
6764     VData,            // vdata
6765     Op.getOperand(3), // rsrc
6766     DAG.getConstant(0, DL, MVT::i32), // vindex
6767     Offsets.first,    // voffset
6768     Op.getOperand(5), // soffset
6769     Offsets.second,   // offset
6770     Op.getOperand(6), // cachepolicy
6771     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6772   };
6773 
6774   auto *M = cast<MemSDNode>(Op);
6775   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6776 
6777   EVT MemVT = VData.getValueType();
6778   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6779                                  M->getMemOperand());
6780 }
6781 
6782 SDValue
6783 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
6784                                                 unsigned NewOpcode) const {
6785   SDLoc DL(Op);
6786 
6787   SDValue VData = Op.getOperand(2);
6788   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6789   SDValue Ops[] = {
6790     Op.getOperand(0), // Chain
6791     VData,            // vdata
6792     Op.getOperand(3), // rsrc
6793     Op.getOperand(4), // vindex
6794     Offsets.first,    // voffset
6795     Op.getOperand(6), // soffset
6796     Offsets.second,   // offset
6797     Op.getOperand(7), // cachepolicy
6798     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6799   };
6800 
6801   auto *M = cast<MemSDNode>(Op);
6802   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6803                                                       Ops[3]));
6804 
6805   EVT MemVT = VData.getValueType();
6806   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6807                                  M->getMemOperand());
6808 }
6809 
6810 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6811                                                  SelectionDAG &DAG) const {
6812   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6813   SDLoc DL(Op);
6814 
6815   switch (IntrID) {
6816   case Intrinsic::amdgcn_ds_ordered_add:
6817   case Intrinsic::amdgcn_ds_ordered_swap: {
6818     MemSDNode *M = cast<MemSDNode>(Op);
6819     SDValue Chain = M->getOperand(0);
6820     SDValue M0 = M->getOperand(2);
6821     SDValue Value = M->getOperand(3);
6822     unsigned IndexOperand = M->getConstantOperandVal(7);
6823     unsigned WaveRelease = M->getConstantOperandVal(8);
6824     unsigned WaveDone = M->getConstantOperandVal(9);
6825 
6826     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6827     IndexOperand &= ~0x3f;
6828     unsigned CountDw = 0;
6829 
6830     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6831       CountDw = (IndexOperand >> 24) & 0xf;
6832       IndexOperand &= ~(0xf << 24);
6833 
6834       if (CountDw < 1 || CountDw > 4) {
6835         report_fatal_error(
6836             "ds_ordered_count: dword count must be between 1 and 4");
6837       }
6838     }
6839 
6840     if (IndexOperand)
6841       report_fatal_error("ds_ordered_count: bad index operand");
6842 
6843     if (WaveDone && !WaveRelease)
6844       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6845 
6846     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6847     unsigned ShaderType =
6848         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
6849     unsigned Offset0 = OrderedCountIndex << 2;
6850     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6851                        (Instruction << 4);
6852 
6853     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6854       Offset1 |= (CountDw - 1) << 6;
6855 
6856     unsigned Offset = Offset0 | (Offset1 << 8);
6857 
6858     SDValue Ops[] = {
6859       Chain,
6860       Value,
6861       DAG.getTargetConstant(Offset, DL, MVT::i16),
6862       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6863     };
6864     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6865                                    M->getVTList(), Ops, M->getMemoryVT(),
6866                                    M->getMemOperand());
6867   }
6868   case Intrinsic::amdgcn_ds_fadd: {
6869     MemSDNode *M = cast<MemSDNode>(Op);
6870     unsigned Opc;
6871     switch (IntrID) {
6872     case Intrinsic::amdgcn_ds_fadd:
6873       Opc = ISD::ATOMIC_LOAD_FADD;
6874       break;
6875     }
6876 
6877     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6878                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6879                          M->getMemOperand());
6880   }
6881   case Intrinsic::amdgcn_atomic_inc:
6882   case Intrinsic::amdgcn_atomic_dec:
6883   case Intrinsic::amdgcn_ds_fmin:
6884   case Intrinsic::amdgcn_ds_fmax: {
6885     MemSDNode *M = cast<MemSDNode>(Op);
6886     unsigned Opc;
6887     switch (IntrID) {
6888     case Intrinsic::amdgcn_atomic_inc:
6889       Opc = AMDGPUISD::ATOMIC_INC;
6890       break;
6891     case Intrinsic::amdgcn_atomic_dec:
6892       Opc = AMDGPUISD::ATOMIC_DEC;
6893       break;
6894     case Intrinsic::amdgcn_ds_fmin:
6895       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6896       break;
6897     case Intrinsic::amdgcn_ds_fmax:
6898       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6899       break;
6900     default:
6901       llvm_unreachable("Unknown intrinsic!");
6902     }
6903     SDValue Ops[] = {
6904       M->getOperand(0), // Chain
6905       M->getOperand(2), // Ptr
6906       M->getOperand(3)  // Value
6907     };
6908 
6909     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6910                                    M->getMemoryVT(), M->getMemOperand());
6911   }
6912   case Intrinsic::amdgcn_buffer_load:
6913   case Intrinsic::amdgcn_buffer_load_format: {
6914     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6915     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6916     unsigned IdxEn = 1;
6917     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6918       IdxEn = Idx->getZExtValue() != 0;
6919     SDValue Ops[] = {
6920       Op.getOperand(0), // Chain
6921       Op.getOperand(2), // rsrc
6922       Op.getOperand(3), // vindex
6923       SDValue(),        // voffset -- will be set by setBufferOffsets
6924       SDValue(),        // soffset -- will be set by setBufferOffsets
6925       SDValue(),        // offset -- will be set by setBufferOffsets
6926       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6927       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6928     };
6929 
6930     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6931     // We don't know the offset if vindex is non-zero, so clear it.
6932     if (IdxEn)
6933       Offset = 0;
6934 
6935     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6936         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6937 
6938     EVT VT = Op.getValueType();
6939     EVT IntVT = VT.changeTypeToInteger();
6940     auto *M = cast<MemSDNode>(Op);
6941     M->getMemOperand()->setOffset(Offset);
6942     EVT LoadVT = Op.getValueType();
6943 
6944     if (LoadVT.getScalarType() == MVT::f16)
6945       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6946                                  M, DAG, Ops);
6947 
6948     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6949     if (LoadVT.getScalarType() == MVT::i8 ||
6950         LoadVT.getScalarType() == MVT::i16)
6951       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6952 
6953     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6954                                M->getMemOperand(), DAG);
6955   }
6956   case Intrinsic::amdgcn_raw_buffer_load:
6957   case Intrinsic::amdgcn_raw_buffer_load_format: {
6958     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6959 
6960     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6961     SDValue Ops[] = {
6962       Op.getOperand(0), // Chain
6963       Op.getOperand(2), // rsrc
6964       DAG.getConstant(0, DL, MVT::i32), // vindex
6965       Offsets.first,    // voffset
6966       Op.getOperand(4), // soffset
6967       Offsets.second,   // offset
6968       Op.getOperand(5), // cachepolicy, swizzled buffer
6969       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6970     };
6971 
6972     auto *M = cast<MemSDNode>(Op);
6973     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6974     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6975   }
6976   case Intrinsic::amdgcn_struct_buffer_load:
6977   case Intrinsic::amdgcn_struct_buffer_load_format: {
6978     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6979 
6980     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6981     SDValue Ops[] = {
6982       Op.getOperand(0), // Chain
6983       Op.getOperand(2), // rsrc
6984       Op.getOperand(3), // vindex
6985       Offsets.first,    // voffset
6986       Op.getOperand(5), // soffset
6987       Offsets.second,   // offset
6988       Op.getOperand(6), // cachepolicy, swizzled buffer
6989       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6990     };
6991 
6992     auto *M = cast<MemSDNode>(Op);
6993     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
6994                                                         Ops[2]));
6995     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6996   }
6997   case Intrinsic::amdgcn_tbuffer_load: {
6998     MemSDNode *M = cast<MemSDNode>(Op);
6999     EVT LoadVT = Op.getValueType();
7000 
7001     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7002     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7003     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7004     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7005     unsigned IdxEn = 1;
7006     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
7007       IdxEn = Idx->getZExtValue() != 0;
7008     SDValue Ops[] = {
7009       Op.getOperand(0),  // Chain
7010       Op.getOperand(2),  // rsrc
7011       Op.getOperand(3),  // vindex
7012       Op.getOperand(4),  // voffset
7013       Op.getOperand(5),  // soffset
7014       Op.getOperand(6),  // offset
7015       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7016       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7017       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7018     };
7019 
7020     if (LoadVT.getScalarType() == MVT::f16)
7021       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7022                                  M, DAG, Ops);
7023     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7024                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7025                                DAG);
7026   }
7027   case Intrinsic::amdgcn_raw_tbuffer_load: {
7028     MemSDNode *M = cast<MemSDNode>(Op);
7029     EVT LoadVT = Op.getValueType();
7030     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7031 
7032     SDValue Ops[] = {
7033       Op.getOperand(0),  // Chain
7034       Op.getOperand(2),  // rsrc
7035       DAG.getConstant(0, DL, MVT::i32), // vindex
7036       Offsets.first,     // voffset
7037       Op.getOperand(4),  // soffset
7038       Offsets.second,    // offset
7039       Op.getOperand(5),  // format
7040       Op.getOperand(6),  // cachepolicy, swizzled buffer
7041       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7042     };
7043 
7044     if (LoadVT.getScalarType() == MVT::f16)
7045       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7046                                  M, DAG, Ops);
7047     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7048                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7049                                DAG);
7050   }
7051   case Intrinsic::amdgcn_struct_tbuffer_load: {
7052     MemSDNode *M = cast<MemSDNode>(Op);
7053     EVT LoadVT = Op.getValueType();
7054     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7055 
7056     SDValue Ops[] = {
7057       Op.getOperand(0),  // Chain
7058       Op.getOperand(2),  // rsrc
7059       Op.getOperand(3),  // vindex
7060       Offsets.first,     // voffset
7061       Op.getOperand(5),  // soffset
7062       Offsets.second,    // offset
7063       Op.getOperand(6),  // format
7064       Op.getOperand(7),  // cachepolicy, swizzled buffer
7065       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7066     };
7067 
7068     if (LoadVT.getScalarType() == MVT::f16)
7069       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7070                                  M, DAG, Ops);
7071     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7072                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7073                                DAG);
7074   }
7075   case Intrinsic::amdgcn_buffer_atomic_swap:
7076   case Intrinsic::amdgcn_buffer_atomic_add:
7077   case Intrinsic::amdgcn_buffer_atomic_sub:
7078   case Intrinsic::amdgcn_buffer_atomic_csub:
7079   case Intrinsic::amdgcn_buffer_atomic_smin:
7080   case Intrinsic::amdgcn_buffer_atomic_umin:
7081   case Intrinsic::amdgcn_buffer_atomic_smax:
7082   case Intrinsic::amdgcn_buffer_atomic_umax:
7083   case Intrinsic::amdgcn_buffer_atomic_and:
7084   case Intrinsic::amdgcn_buffer_atomic_or:
7085   case Intrinsic::amdgcn_buffer_atomic_xor:
7086   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7087     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7088     unsigned IdxEn = 1;
7089     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7090       IdxEn = Idx->getZExtValue() != 0;
7091     SDValue Ops[] = {
7092       Op.getOperand(0), // Chain
7093       Op.getOperand(2), // vdata
7094       Op.getOperand(3), // rsrc
7095       Op.getOperand(4), // vindex
7096       SDValue(),        // voffset -- will be set by setBufferOffsets
7097       SDValue(),        // soffset -- will be set by setBufferOffsets
7098       SDValue(),        // offset -- will be set by setBufferOffsets
7099       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7100       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7101     };
7102     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7103     // We don't know the offset if vindex is non-zero, so clear it.
7104     if (IdxEn)
7105       Offset = 0;
7106     EVT VT = Op.getValueType();
7107 
7108     auto *M = cast<MemSDNode>(Op);
7109     M->getMemOperand()->setOffset(Offset);
7110     unsigned Opcode = 0;
7111 
7112     switch (IntrID) {
7113     case Intrinsic::amdgcn_buffer_atomic_swap:
7114       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7115       break;
7116     case Intrinsic::amdgcn_buffer_atomic_add:
7117       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7118       break;
7119     case Intrinsic::amdgcn_buffer_atomic_sub:
7120       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7121       break;
7122     case Intrinsic::amdgcn_buffer_atomic_csub:
7123       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7124       break;
7125     case Intrinsic::amdgcn_buffer_atomic_smin:
7126       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7127       break;
7128     case Intrinsic::amdgcn_buffer_atomic_umin:
7129       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7130       break;
7131     case Intrinsic::amdgcn_buffer_atomic_smax:
7132       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7133       break;
7134     case Intrinsic::amdgcn_buffer_atomic_umax:
7135       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7136       break;
7137     case Intrinsic::amdgcn_buffer_atomic_and:
7138       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7139       break;
7140     case Intrinsic::amdgcn_buffer_atomic_or:
7141       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7142       break;
7143     case Intrinsic::amdgcn_buffer_atomic_xor:
7144       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7145       break;
7146     case Intrinsic::amdgcn_buffer_atomic_fadd:
7147       if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7148         DiagnosticInfoUnsupported
7149           NoFpRet(DAG.getMachineFunction().getFunction(),
7150                   "return versions of fp atomics not supported",
7151                   DL.getDebugLoc(), DS_Error);
7152         DAG.getContext()->diagnose(NoFpRet);
7153         return SDValue();
7154       }
7155       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7156       break;
7157     default:
7158       llvm_unreachable("unhandled atomic opcode");
7159     }
7160 
7161     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7162                                    M->getMemOperand());
7163   }
7164   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7165     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7166   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7167     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7168   case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7169     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7170   case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7171     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7172   case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7173     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7174   case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7175     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7176   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7177     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7178   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7179     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7180   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7181     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7182   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7183     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7184   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7185     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7186   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7187     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7188   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7189     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7190   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7191     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7192   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7193     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7194   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7195     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7196   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7197     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7198   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7199     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7200   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7201     return lowerStructBufferAtomicIntrin(Op, DAG,
7202                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7203   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7204     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7205   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7206     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7207   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7208     return lowerStructBufferAtomicIntrin(Op, DAG,
7209                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7210   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7211     return lowerStructBufferAtomicIntrin(Op, DAG,
7212                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7213   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7214     return lowerStructBufferAtomicIntrin(Op, DAG,
7215                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7216   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7217     return lowerStructBufferAtomicIntrin(Op, DAG,
7218                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7219   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7220     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7221   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7222     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7223   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7224     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7225   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7226     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7227   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7228     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7229 
7230   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7231     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7232     unsigned IdxEn = 1;
7233     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
7234       IdxEn = Idx->getZExtValue() != 0;
7235     SDValue Ops[] = {
7236       Op.getOperand(0), // Chain
7237       Op.getOperand(2), // src
7238       Op.getOperand(3), // cmp
7239       Op.getOperand(4), // rsrc
7240       Op.getOperand(5), // vindex
7241       SDValue(),        // voffset -- will be set by setBufferOffsets
7242       SDValue(),        // soffset -- will be set by setBufferOffsets
7243       SDValue(),        // offset -- will be set by setBufferOffsets
7244       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7245       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7246     };
7247     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7248     // We don't know the offset if vindex is non-zero, so clear it.
7249     if (IdxEn)
7250       Offset = 0;
7251     EVT VT = Op.getValueType();
7252     auto *M = cast<MemSDNode>(Op);
7253     M->getMemOperand()->setOffset(Offset);
7254 
7255     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7256                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7257   }
7258   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7259     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7260     SDValue Ops[] = {
7261       Op.getOperand(0), // Chain
7262       Op.getOperand(2), // src
7263       Op.getOperand(3), // cmp
7264       Op.getOperand(4), // rsrc
7265       DAG.getConstant(0, DL, MVT::i32), // vindex
7266       Offsets.first,    // voffset
7267       Op.getOperand(6), // soffset
7268       Offsets.second,   // offset
7269       Op.getOperand(7), // cachepolicy
7270       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7271     };
7272     EVT VT = Op.getValueType();
7273     auto *M = cast<MemSDNode>(Op);
7274     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
7275 
7276     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7277                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7278   }
7279   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7280     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7281     SDValue Ops[] = {
7282       Op.getOperand(0), // Chain
7283       Op.getOperand(2), // src
7284       Op.getOperand(3), // cmp
7285       Op.getOperand(4), // rsrc
7286       Op.getOperand(5), // vindex
7287       Offsets.first,    // voffset
7288       Op.getOperand(7), // soffset
7289       Offsets.second,   // offset
7290       Op.getOperand(8), // cachepolicy
7291       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7292     };
7293     EVT VT = Op.getValueType();
7294     auto *M = cast<MemSDNode>(Op);
7295     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
7296                                                         Ops[4]));
7297 
7298     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7299                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7300   }
7301   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7302     SDLoc DL(Op);
7303     MemSDNode *M = cast<MemSDNode>(Op);
7304     SDValue NodePtr = M->getOperand(2);
7305     SDValue RayExtent = M->getOperand(3);
7306     SDValue RayOrigin = M->getOperand(4);
7307     SDValue RayDir = M->getOperand(5);
7308     SDValue RayInvDir = M->getOperand(6);
7309     SDValue TDescr = M->getOperand(7);
7310 
7311     assert(NodePtr.getValueType() == MVT::i32 ||
7312            NodePtr.getValueType() == MVT::i64);
7313     assert(RayDir.getValueType() == MVT::v4f16 ||
7314            RayDir.getValueType() == MVT::v4f32);
7315 
7316     bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7317     bool Is64 = NodePtr.getValueType() == MVT::i64;
7318     unsigned Opcode = IsA16 ? Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16_nsa
7319                                    : AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16_nsa
7320                             : Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_nsa
7321                                    : AMDGPU::IMAGE_BVH_INTERSECT_RAY_nsa;
7322 
7323     SmallVector<SDValue, 16> Ops;
7324 
7325     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7326       SmallVector<SDValue, 3> Lanes;
7327       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7328       if (Lanes[0].getValueSizeInBits() == 32) {
7329         for (unsigned I = 0; I < 3; ++I)
7330           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7331       } else {
7332         if (IsAligned) {
7333           Ops.push_back(
7334             DAG.getBitcast(MVT::i32,
7335                            DAG.getBuildVector(MVT::v2f16, DL,
7336                                               { Lanes[0], Lanes[1] })));
7337           Ops.push_back(Lanes[2]);
7338         } else {
7339           SDValue Elt0 = Ops.pop_back_val();
7340           Ops.push_back(
7341             DAG.getBitcast(MVT::i32,
7342                            DAG.getBuildVector(MVT::v2f16, DL,
7343                                               { Elt0, Lanes[0] })));
7344           Ops.push_back(
7345             DAG.getBitcast(MVT::i32,
7346                            DAG.getBuildVector(MVT::v2f16, DL,
7347                                               { Lanes[1], Lanes[2] })));
7348         }
7349       }
7350     };
7351 
7352     if (Is64)
7353       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7354     else
7355       Ops.push_back(NodePtr);
7356 
7357     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7358     packLanes(RayOrigin, true);
7359     packLanes(RayDir, true);
7360     packLanes(RayInvDir, false);
7361     Ops.push_back(TDescr);
7362     if (IsA16)
7363       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7364     Ops.push_back(M->getChain());
7365 
7366     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7367     MachineMemOperand *MemRef = M->getMemOperand();
7368     DAG.setNodeMemRefs(NewNode, {MemRef});
7369     return SDValue(NewNode, 0);
7370   }
7371   case Intrinsic::amdgcn_global_atomic_fadd:
7372     if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7373       DiagnosticInfoUnsupported
7374         NoFpRet(DAG.getMachineFunction().getFunction(),
7375                 "return versions of fp atomics not supported",
7376                 DL.getDebugLoc(), DS_Error);
7377       DAG.getContext()->diagnose(NoFpRet);
7378       return SDValue();
7379     }
7380     LLVM_FALLTHROUGH;
7381   case Intrinsic::amdgcn_global_atomic_fmin:
7382   case Intrinsic::amdgcn_global_atomic_fmax:
7383   case Intrinsic::amdgcn_flat_atomic_fadd:
7384   case Intrinsic::amdgcn_flat_atomic_fmin:
7385   case Intrinsic::amdgcn_flat_atomic_fmax: {
7386     MemSDNode *M = cast<MemSDNode>(Op);
7387     SDValue Ops[] = {
7388       M->getOperand(0), // Chain
7389       M->getOperand(2), // Ptr
7390       M->getOperand(3)  // Value
7391     };
7392     unsigned Opcode = 0;
7393     switch (IntrID) {
7394     case Intrinsic::amdgcn_global_atomic_fadd:
7395     case Intrinsic::amdgcn_flat_atomic_fadd: {
7396       EVT VT = Op.getOperand(3).getValueType();
7397       return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7398                            DAG.getVTList(VT, MVT::Other), Ops,
7399                            M->getMemOperand());
7400     }
7401     case Intrinsic::amdgcn_global_atomic_fmin:
7402     case Intrinsic::amdgcn_flat_atomic_fmin: {
7403       Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7404       break;
7405     }
7406     case Intrinsic::amdgcn_global_atomic_fmax:
7407     case Intrinsic::amdgcn_flat_atomic_fmax: {
7408       Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7409       break;
7410     }
7411     default:
7412       llvm_unreachable("unhandled atomic opcode");
7413     }
7414     return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7415                                    M->getVTList(), Ops, M->getMemoryVT(),
7416                                    M->getMemOperand());
7417   }
7418   default:
7419 
7420     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7421             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7422       return lowerImage(Op, ImageDimIntr, DAG, true);
7423 
7424     return SDValue();
7425   }
7426 }
7427 
7428 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7429 // dwordx4 if on SI.
7430 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7431                                               SDVTList VTList,
7432                                               ArrayRef<SDValue> Ops, EVT MemVT,
7433                                               MachineMemOperand *MMO,
7434                                               SelectionDAG &DAG) const {
7435   EVT VT = VTList.VTs[0];
7436   EVT WidenedVT = VT;
7437   EVT WidenedMemVT = MemVT;
7438   if (!Subtarget->hasDwordx3LoadStores() &&
7439       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7440     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7441                                  WidenedVT.getVectorElementType(), 4);
7442     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7443                                     WidenedMemVT.getVectorElementType(), 4);
7444     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7445   }
7446 
7447   assert(VTList.NumVTs == 2);
7448   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7449 
7450   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7451                                        WidenedMemVT, MMO);
7452   if (WidenedVT != VT) {
7453     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7454                                DAG.getVectorIdxConstant(0, DL));
7455     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7456   }
7457   return NewOp;
7458 }
7459 
7460 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7461                                          bool ImageStore) const {
7462   EVT StoreVT = VData.getValueType();
7463 
7464   // No change for f16 and legal vector D16 types.
7465   if (!StoreVT.isVector())
7466     return VData;
7467 
7468   SDLoc DL(VData);
7469   unsigned NumElements = StoreVT.getVectorNumElements();
7470 
7471   if (Subtarget->hasUnpackedD16VMem()) {
7472     // We need to unpack the packed data to store.
7473     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7474     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7475 
7476     EVT EquivStoreVT =
7477         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7478     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7479     return DAG.UnrollVectorOp(ZExt.getNode());
7480   }
7481 
7482   // The sq block of gfx8.1 does not estimate register use correctly for d16
7483   // image store instructions. The data operand is computed as if it were not a
7484   // d16 image instruction.
7485   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7486     // Bitcast to i16
7487     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7488     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7489 
7490     // Decompose into scalars
7491     SmallVector<SDValue, 4> Elts;
7492     DAG.ExtractVectorElements(IntVData, Elts);
7493 
7494     // Group pairs of i16 into v2i16 and bitcast to i32
7495     SmallVector<SDValue, 4> PackedElts;
7496     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7497       SDValue Pair =
7498           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7499       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7500       PackedElts.push_back(IntPair);
7501     }
7502     if ((NumElements % 2) == 1) {
7503       // Handle v3i16
7504       unsigned I = Elts.size() / 2;
7505       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7506                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7507       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7508       PackedElts.push_back(IntPair);
7509     }
7510 
7511     // Pad using UNDEF
7512     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7513 
7514     // Build final vector
7515     EVT VecVT =
7516         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7517     return DAG.getBuildVector(VecVT, DL, PackedElts);
7518   }
7519 
7520   if (NumElements == 3) {
7521     EVT IntStoreVT =
7522         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7523     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7524 
7525     EVT WidenedStoreVT = EVT::getVectorVT(
7526         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7527     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7528                                          WidenedStoreVT.getStoreSizeInBits());
7529     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7530     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7531   }
7532 
7533   assert(isTypeLegal(StoreVT));
7534   return VData;
7535 }
7536 
7537 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7538                                               SelectionDAG &DAG) const {
7539   SDLoc DL(Op);
7540   SDValue Chain = Op.getOperand(0);
7541   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7542   MachineFunction &MF = DAG.getMachineFunction();
7543 
7544   switch (IntrinsicID) {
7545   case Intrinsic::amdgcn_exp_compr: {
7546     SDValue Src0 = Op.getOperand(4);
7547     SDValue Src1 = Op.getOperand(5);
7548     // Hack around illegal type on SI by directly selecting it.
7549     if (isTypeLegal(Src0.getValueType()))
7550       return SDValue();
7551 
7552     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7553     SDValue Undef = DAG.getUNDEF(MVT::f32);
7554     const SDValue Ops[] = {
7555       Op.getOperand(2), // tgt
7556       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7557       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7558       Undef, // src2
7559       Undef, // src3
7560       Op.getOperand(7), // vm
7561       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7562       Op.getOperand(3), // en
7563       Op.getOperand(0) // Chain
7564     };
7565 
7566     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7567     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7568   }
7569   case Intrinsic::amdgcn_s_barrier: {
7570     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7571       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7572       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7573       if (WGSize <= ST.getWavefrontSize())
7574         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7575                                           Op.getOperand(0)), 0);
7576     }
7577     return SDValue();
7578   };
7579   case Intrinsic::amdgcn_tbuffer_store: {
7580     SDValue VData = Op.getOperand(2);
7581     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7582     if (IsD16)
7583       VData = handleD16VData(VData, DAG);
7584     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7585     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7586     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7587     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7588     unsigned IdxEn = 1;
7589     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7590       IdxEn = Idx->getZExtValue() != 0;
7591     SDValue Ops[] = {
7592       Chain,
7593       VData,             // vdata
7594       Op.getOperand(3),  // rsrc
7595       Op.getOperand(4),  // vindex
7596       Op.getOperand(5),  // voffset
7597       Op.getOperand(6),  // soffset
7598       Op.getOperand(7),  // offset
7599       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7600       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7601       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
7602     };
7603     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7604                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7605     MemSDNode *M = cast<MemSDNode>(Op);
7606     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7607                                    M->getMemoryVT(), M->getMemOperand());
7608   }
7609 
7610   case Intrinsic::amdgcn_struct_tbuffer_store: {
7611     SDValue VData = Op.getOperand(2);
7612     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7613     if (IsD16)
7614       VData = handleD16VData(VData, DAG);
7615     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7616     SDValue Ops[] = {
7617       Chain,
7618       VData,             // vdata
7619       Op.getOperand(3),  // rsrc
7620       Op.getOperand(4),  // vindex
7621       Offsets.first,     // voffset
7622       Op.getOperand(6),  // soffset
7623       Offsets.second,    // offset
7624       Op.getOperand(7),  // format
7625       Op.getOperand(8),  // cachepolicy, swizzled buffer
7626       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
7627     };
7628     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7629                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7630     MemSDNode *M = cast<MemSDNode>(Op);
7631     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7632                                    M->getMemoryVT(), M->getMemOperand());
7633   }
7634 
7635   case Intrinsic::amdgcn_raw_tbuffer_store: {
7636     SDValue VData = Op.getOperand(2);
7637     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7638     if (IsD16)
7639       VData = handleD16VData(VData, DAG);
7640     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7641     SDValue Ops[] = {
7642       Chain,
7643       VData,             // vdata
7644       Op.getOperand(3),  // rsrc
7645       DAG.getConstant(0, DL, MVT::i32), // vindex
7646       Offsets.first,     // voffset
7647       Op.getOperand(5),  // soffset
7648       Offsets.second,    // offset
7649       Op.getOperand(6),  // format
7650       Op.getOperand(7),  // cachepolicy, swizzled buffer
7651       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
7652     };
7653     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7654                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7655     MemSDNode *M = cast<MemSDNode>(Op);
7656     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7657                                    M->getMemoryVT(), M->getMemOperand());
7658   }
7659 
7660   case Intrinsic::amdgcn_buffer_store:
7661   case Intrinsic::amdgcn_buffer_store_format: {
7662     SDValue VData = Op.getOperand(2);
7663     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7664     if (IsD16)
7665       VData = handleD16VData(VData, DAG);
7666     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7667     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7668     unsigned IdxEn = 1;
7669     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7670       IdxEn = Idx->getZExtValue() != 0;
7671     SDValue Ops[] = {
7672       Chain,
7673       VData,
7674       Op.getOperand(3), // rsrc
7675       Op.getOperand(4), // vindex
7676       SDValue(), // voffset -- will be set by setBufferOffsets
7677       SDValue(), // soffset -- will be set by setBufferOffsets
7678       SDValue(), // offset -- will be set by setBufferOffsets
7679       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7680       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7681     };
7682     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7683     // We don't know the offset if vindex is non-zero, so clear it.
7684     if (IdxEn)
7685       Offset = 0;
7686     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7687                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7688     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7689     MemSDNode *M = cast<MemSDNode>(Op);
7690     M->getMemOperand()->setOffset(Offset);
7691 
7692     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7693     EVT VDataType = VData.getValueType().getScalarType();
7694     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7695       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7696 
7697     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7698                                    M->getMemoryVT(), M->getMemOperand());
7699   }
7700 
7701   case Intrinsic::amdgcn_raw_buffer_store:
7702   case Intrinsic::amdgcn_raw_buffer_store_format: {
7703     const bool IsFormat =
7704         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7705 
7706     SDValue VData = Op.getOperand(2);
7707     EVT VDataVT = VData.getValueType();
7708     EVT EltType = VDataVT.getScalarType();
7709     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7710     if (IsD16) {
7711       VData = handleD16VData(VData, DAG);
7712       VDataVT = VData.getValueType();
7713     }
7714 
7715     if (!isTypeLegal(VDataVT)) {
7716       VData =
7717           DAG.getNode(ISD::BITCAST, DL,
7718                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7719     }
7720 
7721     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7722     SDValue Ops[] = {
7723       Chain,
7724       VData,
7725       Op.getOperand(3), // rsrc
7726       DAG.getConstant(0, DL, MVT::i32), // vindex
7727       Offsets.first,    // voffset
7728       Op.getOperand(5), // soffset
7729       Offsets.second,   // offset
7730       Op.getOperand(6), // cachepolicy, swizzled buffer
7731       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7732     };
7733     unsigned Opc =
7734         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7735     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7736     MemSDNode *M = cast<MemSDNode>(Op);
7737     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
7738 
7739     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7740     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7741       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7742 
7743     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7744                                    M->getMemoryVT(), M->getMemOperand());
7745   }
7746 
7747   case Intrinsic::amdgcn_struct_buffer_store:
7748   case Intrinsic::amdgcn_struct_buffer_store_format: {
7749     const bool IsFormat =
7750         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7751 
7752     SDValue VData = Op.getOperand(2);
7753     EVT VDataVT = VData.getValueType();
7754     EVT EltType = VDataVT.getScalarType();
7755     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7756 
7757     if (IsD16) {
7758       VData = handleD16VData(VData, DAG);
7759       VDataVT = VData.getValueType();
7760     }
7761 
7762     if (!isTypeLegal(VDataVT)) {
7763       VData =
7764           DAG.getNode(ISD::BITCAST, DL,
7765                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7766     }
7767 
7768     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7769     SDValue Ops[] = {
7770       Chain,
7771       VData,
7772       Op.getOperand(3), // rsrc
7773       Op.getOperand(4), // vindex
7774       Offsets.first,    // voffset
7775       Op.getOperand(6), // soffset
7776       Offsets.second,   // offset
7777       Op.getOperand(7), // cachepolicy, swizzled buffer
7778       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7779     };
7780     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7781                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7782     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7783     MemSDNode *M = cast<MemSDNode>(Op);
7784     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7785                                                         Ops[3]));
7786 
7787     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7788     EVT VDataType = VData.getValueType().getScalarType();
7789     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7790       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7791 
7792     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7793                                    M->getMemoryVT(), M->getMemOperand());
7794   }
7795   case Intrinsic::amdgcn_end_cf:
7796     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7797                                       Op->getOperand(2), Chain), 0);
7798 
7799   default: {
7800     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7801             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7802       return lowerImage(Op, ImageDimIntr, DAG, true);
7803 
7804     return Op;
7805   }
7806   }
7807 }
7808 
7809 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7810 // offset (the offset that is included in bounds checking and swizzling, to be
7811 // split between the instruction's voffset and immoffset fields) and soffset
7812 // (the offset that is excluded from bounds checking and swizzling, to go in
7813 // the instruction's soffset field).  This function takes the first kind of
7814 // offset and figures out how to split it between voffset and immoffset.
7815 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7816     SDValue Offset, SelectionDAG &DAG) const {
7817   SDLoc DL(Offset);
7818   const unsigned MaxImm = 4095;
7819   SDValue N0 = Offset;
7820   ConstantSDNode *C1 = nullptr;
7821 
7822   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7823     N0 = SDValue();
7824   else if (DAG.isBaseWithConstantOffset(N0)) {
7825     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7826     N0 = N0.getOperand(0);
7827   }
7828 
7829   if (C1) {
7830     unsigned ImmOffset = C1->getZExtValue();
7831     // If the immediate value is too big for the immoffset field, put the value
7832     // and -4096 into the immoffset field so that the value that is copied/added
7833     // for the voffset field is a multiple of 4096, and it stands more chance
7834     // of being CSEd with the copy/add for another similar load/store.
7835     // However, do not do that rounding down to a multiple of 4096 if that is a
7836     // negative number, as it appears to be illegal to have a negative offset
7837     // in the vgpr, even if adding the immediate offset makes it positive.
7838     unsigned Overflow = ImmOffset & ~MaxImm;
7839     ImmOffset -= Overflow;
7840     if ((int32_t)Overflow < 0) {
7841       Overflow += ImmOffset;
7842       ImmOffset = 0;
7843     }
7844     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7845     if (Overflow) {
7846       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7847       if (!N0)
7848         N0 = OverflowVal;
7849       else {
7850         SDValue Ops[] = { N0, OverflowVal };
7851         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7852       }
7853     }
7854   }
7855   if (!N0)
7856     N0 = DAG.getConstant(0, DL, MVT::i32);
7857   if (!C1)
7858     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7859   return {N0, SDValue(C1, 0)};
7860 }
7861 
7862 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7863 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7864 // pointed to by Offsets.
7865 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7866                                             SelectionDAG &DAG, SDValue *Offsets,
7867                                             Align Alignment) const {
7868   SDLoc DL(CombinedOffset);
7869   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7870     uint32_t Imm = C->getZExtValue();
7871     uint32_t SOffset, ImmOffset;
7872     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
7873                                  Alignment)) {
7874       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7875       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7876       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7877       return SOffset + ImmOffset;
7878     }
7879   }
7880   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7881     SDValue N0 = CombinedOffset.getOperand(0);
7882     SDValue N1 = CombinedOffset.getOperand(1);
7883     uint32_t SOffset, ImmOffset;
7884     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7885     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7886                                                 Subtarget, Alignment)) {
7887       Offsets[0] = N0;
7888       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7889       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7890       return 0;
7891     }
7892   }
7893   Offsets[0] = CombinedOffset;
7894   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7895   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7896   return 0;
7897 }
7898 
7899 // Handle 8 bit and 16 bit buffer loads
7900 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7901                                                      EVT LoadVT, SDLoc DL,
7902                                                      ArrayRef<SDValue> Ops,
7903                                                      MemSDNode *M) const {
7904   EVT IntVT = LoadVT.changeTypeToInteger();
7905   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7906          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7907 
7908   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7909   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7910                                                Ops, IntVT,
7911                                                M->getMemOperand());
7912   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7913   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7914 
7915   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7916 }
7917 
7918 // Handle 8 bit and 16 bit buffer stores
7919 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7920                                                       EVT VDataType, SDLoc DL,
7921                                                       SDValue Ops[],
7922                                                       MemSDNode *M) const {
7923   if (VDataType == MVT::f16)
7924     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7925 
7926   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7927   Ops[1] = BufferStoreExt;
7928   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7929                                  AMDGPUISD::BUFFER_STORE_SHORT;
7930   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7931   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7932                                      M->getMemOperand());
7933 }
7934 
7935 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7936                                  ISD::LoadExtType ExtType, SDValue Op,
7937                                  const SDLoc &SL, EVT VT) {
7938   if (VT.bitsLT(Op.getValueType()))
7939     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7940 
7941   switch (ExtType) {
7942   case ISD::SEXTLOAD:
7943     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7944   case ISD::ZEXTLOAD:
7945     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7946   case ISD::EXTLOAD:
7947     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7948   case ISD::NON_EXTLOAD:
7949     return Op;
7950   }
7951 
7952   llvm_unreachable("invalid ext type");
7953 }
7954 
7955 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7956   SelectionDAG &DAG = DCI.DAG;
7957   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7958     return SDValue();
7959 
7960   // FIXME: Constant loads should all be marked invariant.
7961   unsigned AS = Ld->getAddressSpace();
7962   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7963       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7964       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7965     return SDValue();
7966 
7967   // Don't do this early, since it may interfere with adjacent load merging for
7968   // illegal types. We can avoid losing alignment information for exotic types
7969   // pre-legalize.
7970   EVT MemVT = Ld->getMemoryVT();
7971   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7972       MemVT.getSizeInBits() >= 32)
7973     return SDValue();
7974 
7975   SDLoc SL(Ld);
7976 
7977   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7978          "unexpected vector extload");
7979 
7980   // TODO: Drop only high part of range.
7981   SDValue Ptr = Ld->getBasePtr();
7982   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7983                                 MVT::i32, SL, Ld->getChain(), Ptr,
7984                                 Ld->getOffset(),
7985                                 Ld->getPointerInfo(), MVT::i32,
7986                                 Ld->getAlignment(),
7987                                 Ld->getMemOperand()->getFlags(),
7988                                 Ld->getAAInfo(),
7989                                 nullptr); // Drop ranges
7990 
7991   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7992   if (MemVT.isFloatingPoint()) {
7993     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7994            "unexpected fp extload");
7995     TruncVT = MemVT.changeTypeToInteger();
7996   }
7997 
7998   SDValue Cvt = NewLoad;
7999   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
8000     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
8001                       DAG.getValueType(TruncVT));
8002   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
8003              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
8004     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
8005   } else {
8006     assert(Ld->getExtensionType() == ISD::EXTLOAD);
8007   }
8008 
8009   EVT VT = Ld->getValueType(0);
8010   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8011 
8012   DCI.AddToWorklist(Cvt.getNode());
8013 
8014   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
8015   // the appropriate extension from the 32-bit load.
8016   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
8017   DCI.AddToWorklist(Cvt.getNode());
8018 
8019   // Handle conversion back to floating point if necessary.
8020   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8021 
8022   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8023 }
8024 
8025 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8026   SDLoc DL(Op);
8027   LoadSDNode *Load = cast<LoadSDNode>(Op);
8028   ISD::LoadExtType ExtType = Load->getExtensionType();
8029   EVT MemVT = Load->getMemoryVT();
8030 
8031   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8032     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8033       return SDValue();
8034 
8035     // FIXME: Copied from PPC
8036     // First, load into 32 bits, then truncate to 1 bit.
8037 
8038     SDValue Chain = Load->getChain();
8039     SDValue BasePtr = Load->getBasePtr();
8040     MachineMemOperand *MMO = Load->getMemOperand();
8041 
8042     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8043 
8044     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8045                                    BasePtr, RealMemVT, MMO);
8046 
8047     if (!MemVT.isVector()) {
8048       SDValue Ops[] = {
8049         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8050         NewLD.getValue(1)
8051       };
8052 
8053       return DAG.getMergeValues(Ops, DL);
8054     }
8055 
8056     SmallVector<SDValue, 3> Elts;
8057     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8058       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8059                                 DAG.getConstant(I, DL, MVT::i32));
8060 
8061       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8062     }
8063 
8064     SDValue Ops[] = {
8065       DAG.getBuildVector(MemVT, DL, Elts),
8066       NewLD.getValue(1)
8067     };
8068 
8069     return DAG.getMergeValues(Ops, DL);
8070   }
8071 
8072   if (!MemVT.isVector())
8073     return SDValue();
8074 
8075   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8076          "Custom lowering for non-i32 vectors hasn't been implemented.");
8077 
8078   unsigned Alignment = Load->getAlignment();
8079   unsigned AS = Load->getAddressSpace();
8080   if (Subtarget->hasLDSMisalignedBug() &&
8081       AS == AMDGPUAS::FLAT_ADDRESS &&
8082       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8083     return SplitVectorLoad(Op, DAG);
8084   }
8085 
8086   MachineFunction &MF = DAG.getMachineFunction();
8087   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8088   // If there is a possibilty that flat instruction access scratch memory
8089   // then we need to use the same legalization rules we use for private.
8090   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8091       !Subtarget->hasMultiDwordFlatScratchAddressing())
8092     AS = MFI->hasFlatScratchInit() ?
8093          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8094 
8095   unsigned NumElements = MemVT.getVectorNumElements();
8096 
8097   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8098       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8099     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8100       if (MemVT.isPow2VectorType())
8101         return SDValue();
8102       return WidenOrSplitVectorLoad(Op, DAG);
8103     }
8104     // Non-uniform loads will be selected to MUBUF instructions, so they
8105     // have the same legalization requirements as global and private
8106     // loads.
8107     //
8108   }
8109 
8110   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8111       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8112       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8113     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8114         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8115         Alignment >= 4 && NumElements < 32) {
8116       if (MemVT.isPow2VectorType())
8117         return SDValue();
8118       return WidenOrSplitVectorLoad(Op, DAG);
8119     }
8120     // Non-uniform loads will be selected to MUBUF instructions, so they
8121     // have the same legalization requirements as global and private
8122     // loads.
8123     //
8124   }
8125   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8126       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8127       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8128       AS == AMDGPUAS::FLAT_ADDRESS) {
8129     if (NumElements > 4)
8130       return SplitVectorLoad(Op, DAG);
8131     // v3 loads not supported on SI.
8132     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8133       return WidenOrSplitVectorLoad(Op, DAG);
8134 
8135     // v3 and v4 loads are supported for private and global memory.
8136     return SDValue();
8137   }
8138   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8139     // Depending on the setting of the private_element_size field in the
8140     // resource descriptor, we can only make private accesses up to a certain
8141     // size.
8142     switch (Subtarget->getMaxPrivateElementSize()) {
8143     case 4: {
8144       SDValue Ops[2];
8145       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8146       return DAG.getMergeValues(Ops, DL);
8147     }
8148     case 8:
8149       if (NumElements > 2)
8150         return SplitVectorLoad(Op, DAG);
8151       return SDValue();
8152     case 16:
8153       // Same as global/flat
8154       if (NumElements > 4)
8155         return SplitVectorLoad(Op, DAG);
8156       // v3 loads not supported on SI.
8157       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8158         return WidenOrSplitVectorLoad(Op, DAG);
8159 
8160       return SDValue();
8161     default:
8162       llvm_unreachable("unsupported private_element_size");
8163     }
8164   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8165     // Use ds_read_b128 or ds_read_b96 when possible.
8166     if (Subtarget->hasDS96AndDS128() &&
8167         ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) ||
8168          MemVT.getStoreSize() == 12) &&
8169         allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8170                                            Load->getAlign()))
8171       return SDValue();
8172 
8173     if (NumElements > 2)
8174       return SplitVectorLoad(Op, DAG);
8175 
8176     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8177     // address is negative, then the instruction is incorrectly treated as
8178     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8179     // loads here to avoid emitting ds_read2_b32. We may re-combine the
8180     // load later in the SILoadStoreOptimizer.
8181     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
8182         NumElements == 2 && MemVT.getStoreSize() == 8 &&
8183         Load->getAlignment() < 8) {
8184       return SplitVectorLoad(Op, DAG);
8185     }
8186   }
8187 
8188   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8189                                       MemVT, *Load->getMemOperand())) {
8190     SDValue Ops[2];
8191     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8192     return DAG.getMergeValues(Ops, DL);
8193   }
8194 
8195   return SDValue();
8196 }
8197 
8198 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8199   EVT VT = Op.getValueType();
8200   assert(VT.getSizeInBits() == 64);
8201 
8202   SDLoc DL(Op);
8203   SDValue Cond = Op.getOperand(0);
8204 
8205   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8206   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8207 
8208   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8209   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8210 
8211   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8212   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8213 
8214   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8215 
8216   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8217   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8218 
8219   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8220 
8221   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8222   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8223 }
8224 
8225 // Catch division cases where we can use shortcuts with rcp and rsq
8226 // instructions.
8227 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8228                                               SelectionDAG &DAG) const {
8229   SDLoc SL(Op);
8230   SDValue LHS = Op.getOperand(0);
8231   SDValue RHS = Op.getOperand(1);
8232   EVT VT = Op.getValueType();
8233   const SDNodeFlags Flags = Op->getFlags();
8234 
8235   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8236 
8237   // Without !fpmath accuracy information, we can't do more because we don't
8238   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8239   if (!AllowInaccurateRcp)
8240     return SDValue();
8241 
8242   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8243     if (CLHS->isExactlyValue(1.0)) {
8244       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8245       // the CI documentation has a worst case error of 1 ulp.
8246       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8247       // use it as long as we aren't trying to use denormals.
8248       //
8249       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8250 
8251       // 1.0 / sqrt(x) -> rsq(x)
8252 
8253       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8254       // error seems really high at 2^29 ULP.
8255       if (RHS.getOpcode() == ISD::FSQRT)
8256         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8257 
8258       // 1.0 / x -> rcp(x)
8259       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8260     }
8261 
8262     // Same as for 1.0, but expand the sign out of the constant.
8263     if (CLHS->isExactlyValue(-1.0)) {
8264       // -1.0 / x -> rcp (fneg x)
8265       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8266       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8267     }
8268   }
8269 
8270   // Turn into multiply by the reciprocal.
8271   // x / y -> x * (1.0 / y)
8272   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8273   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8274 }
8275 
8276 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8277                                                 SelectionDAG &DAG) const {
8278   SDLoc SL(Op);
8279   SDValue X = Op.getOperand(0);
8280   SDValue Y = Op.getOperand(1);
8281   EVT VT = Op.getValueType();
8282   const SDNodeFlags Flags = Op->getFlags();
8283 
8284   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8285                             DAG.getTarget().Options.UnsafeFPMath;
8286   if (!AllowInaccurateDiv)
8287     return SDValue();
8288 
8289   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8290   SDValue One = DAG.getConstantFP(1.0, SL, VT);
8291 
8292   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8293   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8294 
8295   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8296   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8297   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8298   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8299   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8300   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8301 }
8302 
8303 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8304                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8305                           SDNodeFlags Flags) {
8306   if (GlueChain->getNumValues() <= 1) {
8307     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8308   }
8309 
8310   assert(GlueChain->getNumValues() == 3);
8311 
8312   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8313   switch (Opcode) {
8314   default: llvm_unreachable("no chain equivalent for opcode");
8315   case ISD::FMUL:
8316     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8317     break;
8318   }
8319 
8320   return DAG.getNode(Opcode, SL, VTList,
8321                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8322                      Flags);
8323 }
8324 
8325 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8326                            EVT VT, SDValue A, SDValue B, SDValue C,
8327                            SDValue GlueChain, SDNodeFlags Flags) {
8328   if (GlueChain->getNumValues() <= 1) {
8329     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8330   }
8331 
8332   assert(GlueChain->getNumValues() == 3);
8333 
8334   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8335   switch (Opcode) {
8336   default: llvm_unreachable("no chain equivalent for opcode");
8337   case ISD::FMA:
8338     Opcode = AMDGPUISD::FMA_W_CHAIN;
8339     break;
8340   }
8341 
8342   return DAG.getNode(Opcode, SL, VTList,
8343                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8344                      Flags);
8345 }
8346 
8347 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8348   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8349     return FastLowered;
8350 
8351   SDLoc SL(Op);
8352   SDValue Src0 = Op.getOperand(0);
8353   SDValue Src1 = Op.getOperand(1);
8354 
8355   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8356   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8357 
8358   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8359   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8360 
8361   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8362   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8363 
8364   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8365 }
8366 
8367 // Faster 2.5 ULP division that does not support denormals.
8368 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8369   SDLoc SL(Op);
8370   SDValue LHS = Op.getOperand(1);
8371   SDValue RHS = Op.getOperand(2);
8372 
8373   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8374 
8375   const APFloat K0Val(BitsToFloat(0x6f800000));
8376   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8377 
8378   const APFloat K1Val(BitsToFloat(0x2f800000));
8379   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8380 
8381   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8382 
8383   EVT SetCCVT =
8384     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8385 
8386   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8387 
8388   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8389 
8390   // TODO: Should this propagate fast-math-flags?
8391   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8392 
8393   // rcp does not support denormals.
8394   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8395 
8396   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8397 
8398   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8399 }
8400 
8401 // Returns immediate value for setting the F32 denorm mode when using the
8402 // S_DENORM_MODE instruction.
8403 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8404                                     const SDLoc &SL, const GCNSubtarget *ST) {
8405   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8406   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8407                                 ? FP_DENORM_FLUSH_NONE
8408                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8409 
8410   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8411   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8412 }
8413 
8414 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8415   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8416     return FastLowered;
8417 
8418   // The selection matcher assumes anything with a chain selecting to a
8419   // mayRaiseFPException machine instruction. Since we're introducing a chain
8420   // here, we need to explicitly report nofpexcept for the regular fdiv
8421   // lowering.
8422   SDNodeFlags Flags = Op->getFlags();
8423   Flags.setNoFPExcept(true);
8424 
8425   SDLoc SL(Op);
8426   SDValue LHS = Op.getOperand(0);
8427   SDValue RHS = Op.getOperand(1);
8428 
8429   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8430 
8431   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8432 
8433   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8434                                           {RHS, RHS, LHS}, Flags);
8435   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8436                                         {LHS, RHS, LHS}, Flags);
8437 
8438   // Denominator is scaled to not be denormal, so using rcp is ok.
8439   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8440                                   DenominatorScaled, Flags);
8441   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8442                                      DenominatorScaled, Flags);
8443 
8444   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8445                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8446                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8447   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8448 
8449   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8450 
8451   if (!HasFP32Denormals) {
8452     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8453     // lowering. The chain dependence is insufficient, and we need glue. We do
8454     // not need the glue variants in a strictfp function.
8455 
8456     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8457 
8458     SDNode *EnableDenorm;
8459     if (Subtarget->hasDenormModeInst()) {
8460       const SDValue EnableDenormValue =
8461           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8462 
8463       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8464                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8465     } else {
8466       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8467                                                         SL, MVT::i32);
8468       EnableDenorm =
8469           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8470                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8471     }
8472 
8473     SDValue Ops[3] = {
8474       NegDivScale0,
8475       SDValue(EnableDenorm, 0),
8476       SDValue(EnableDenorm, 1)
8477     };
8478 
8479     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8480   }
8481 
8482   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8483                              ApproxRcp, One, NegDivScale0, Flags);
8484 
8485   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8486                              ApproxRcp, Fma0, Flags);
8487 
8488   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8489                            Fma1, Fma1, Flags);
8490 
8491   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8492                              NumeratorScaled, Mul, Flags);
8493 
8494   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8495                              Fma2, Fma1, Mul, Fma2, Flags);
8496 
8497   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8498                              NumeratorScaled, Fma3, Flags);
8499 
8500   if (!HasFP32Denormals) {
8501     SDNode *DisableDenorm;
8502     if (Subtarget->hasDenormModeInst()) {
8503       const SDValue DisableDenormValue =
8504           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8505 
8506       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8507                                   Fma4.getValue(1), DisableDenormValue,
8508                                   Fma4.getValue(2)).getNode();
8509     } else {
8510       const SDValue DisableDenormValue =
8511           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8512 
8513       DisableDenorm = DAG.getMachineNode(
8514           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8515           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8516     }
8517 
8518     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8519                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8520     DAG.setRoot(OutputChain);
8521   }
8522 
8523   SDValue Scale = NumeratorScaled.getValue(1);
8524   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8525                              {Fma4, Fma1, Fma3, Scale}, Flags);
8526 
8527   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8528 }
8529 
8530 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8531   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
8532     return FastLowered;
8533 
8534   SDLoc SL(Op);
8535   SDValue X = Op.getOperand(0);
8536   SDValue Y = Op.getOperand(1);
8537 
8538   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8539 
8540   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8541 
8542   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8543 
8544   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8545 
8546   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8547 
8548   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8549 
8550   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8551 
8552   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8553 
8554   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8555 
8556   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8557   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8558 
8559   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8560                              NegDivScale0, Mul, DivScale1);
8561 
8562   SDValue Scale;
8563 
8564   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8565     // Workaround a hardware bug on SI where the condition output from div_scale
8566     // is not usable.
8567 
8568     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8569 
8570     // Figure out if the scale to use for div_fmas.
8571     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8572     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8573     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8574     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8575 
8576     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8577     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8578 
8579     SDValue Scale0Hi
8580       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8581     SDValue Scale1Hi
8582       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8583 
8584     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8585     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8586     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8587   } else {
8588     Scale = DivScale1.getValue(1);
8589   }
8590 
8591   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8592                              Fma4, Fma3, Mul, Scale);
8593 
8594   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8595 }
8596 
8597 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8598   EVT VT = Op.getValueType();
8599 
8600   if (VT == MVT::f32)
8601     return LowerFDIV32(Op, DAG);
8602 
8603   if (VT == MVT::f64)
8604     return LowerFDIV64(Op, DAG);
8605 
8606   if (VT == MVT::f16)
8607     return LowerFDIV16(Op, DAG);
8608 
8609   llvm_unreachable("Unexpected type for fdiv");
8610 }
8611 
8612 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8613   SDLoc DL(Op);
8614   StoreSDNode *Store = cast<StoreSDNode>(Op);
8615   EVT VT = Store->getMemoryVT();
8616 
8617   if (VT == MVT::i1) {
8618     return DAG.getTruncStore(Store->getChain(), DL,
8619        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8620        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8621   }
8622 
8623   assert(VT.isVector() &&
8624          Store->getValue().getValueType().getScalarType() == MVT::i32);
8625 
8626   unsigned AS = Store->getAddressSpace();
8627   if (Subtarget->hasLDSMisalignedBug() &&
8628       AS == AMDGPUAS::FLAT_ADDRESS &&
8629       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8630     return SplitVectorStore(Op, DAG);
8631   }
8632 
8633   MachineFunction &MF = DAG.getMachineFunction();
8634   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8635   // If there is a possibilty that flat instruction access scratch memory
8636   // then we need to use the same legalization rules we use for private.
8637   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8638       !Subtarget->hasMultiDwordFlatScratchAddressing())
8639     AS = MFI->hasFlatScratchInit() ?
8640          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8641 
8642   unsigned NumElements = VT.getVectorNumElements();
8643   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8644       AS == AMDGPUAS::FLAT_ADDRESS) {
8645     if (NumElements > 4)
8646       return SplitVectorStore(Op, DAG);
8647     // v3 stores not supported on SI.
8648     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8649       return SplitVectorStore(Op, DAG);
8650 
8651     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8652                                         VT, *Store->getMemOperand()))
8653       return expandUnalignedStore(Store, DAG);
8654 
8655     return SDValue();
8656   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8657     switch (Subtarget->getMaxPrivateElementSize()) {
8658     case 4:
8659       return scalarizeVectorStore(Store, DAG);
8660     case 8:
8661       if (NumElements > 2)
8662         return SplitVectorStore(Op, DAG);
8663       return SDValue();
8664     case 16:
8665       if (NumElements > 4 ||
8666           (NumElements == 3 && !Subtarget->enableFlatScratch()))
8667         return SplitVectorStore(Op, DAG);
8668       return SDValue();
8669     default:
8670       llvm_unreachable("unsupported private_element_size");
8671     }
8672   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8673     // Use ds_write_b128 or ds_write_b96 when possible.
8674     if (Subtarget->hasDS96AndDS128() &&
8675         ((Subtarget->useDS128() && VT.getStoreSize() == 16) ||
8676          (VT.getStoreSize() == 12)) &&
8677         allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
8678                                            Store->getAlign()))
8679       return SDValue();
8680 
8681     if (NumElements > 2)
8682       return SplitVectorStore(Op, DAG);
8683 
8684     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8685     // address is negative, then the instruction is incorrectly treated as
8686     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8687     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8688     // store later in the SILoadStoreOptimizer.
8689     if (!Subtarget->hasUsableDSOffset() &&
8690         NumElements == 2 && VT.getStoreSize() == 8 &&
8691         Store->getAlignment() < 8) {
8692       return SplitVectorStore(Op, DAG);
8693     }
8694 
8695     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8696                                         VT, *Store->getMemOperand())) {
8697       if (VT.isVector())
8698         return SplitVectorStore(Op, DAG);
8699       return expandUnalignedStore(Store, DAG);
8700     }
8701 
8702     return SDValue();
8703   } else {
8704     llvm_unreachable("unhandled address space");
8705   }
8706 }
8707 
8708 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8709   SDLoc DL(Op);
8710   EVT VT = Op.getValueType();
8711   SDValue Arg = Op.getOperand(0);
8712   SDValue TrigVal;
8713 
8714   // Propagate fast-math flags so that the multiply we introduce can be folded
8715   // if Arg is already the result of a multiply by constant.
8716   auto Flags = Op->getFlags();
8717 
8718   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
8719 
8720   if (Subtarget->hasTrigReducedRange()) {
8721     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8722     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
8723   } else {
8724     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8725   }
8726 
8727   switch (Op.getOpcode()) {
8728   case ISD::FCOS:
8729     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
8730   case ISD::FSIN:
8731     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
8732   default:
8733     llvm_unreachable("Wrong trig opcode");
8734   }
8735 }
8736 
8737 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8738   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8739   assert(AtomicNode->isCompareAndSwap());
8740   unsigned AS = AtomicNode->getAddressSpace();
8741 
8742   // No custom lowering required for local address space
8743   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
8744     return Op;
8745 
8746   // Non-local address space requires custom lowering for atomic compare
8747   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8748   SDLoc DL(Op);
8749   SDValue ChainIn = Op.getOperand(0);
8750   SDValue Addr = Op.getOperand(1);
8751   SDValue Old = Op.getOperand(2);
8752   SDValue New = Op.getOperand(3);
8753   EVT VT = Op.getValueType();
8754   MVT SimpleVT = VT.getSimpleVT();
8755   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8756 
8757   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8758   SDValue Ops[] = { ChainIn, Addr, NewOld };
8759 
8760   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8761                                  Ops, VT, AtomicNode->getMemOperand());
8762 }
8763 
8764 //===----------------------------------------------------------------------===//
8765 // Custom DAG optimizations
8766 //===----------------------------------------------------------------------===//
8767 
8768 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8769                                                      DAGCombinerInfo &DCI) const {
8770   EVT VT = N->getValueType(0);
8771   EVT ScalarVT = VT.getScalarType();
8772   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8773     return SDValue();
8774 
8775   SelectionDAG &DAG = DCI.DAG;
8776   SDLoc DL(N);
8777 
8778   SDValue Src = N->getOperand(0);
8779   EVT SrcVT = Src.getValueType();
8780 
8781   // TODO: We could try to match extracting the higher bytes, which would be
8782   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8783   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8784   // about in practice.
8785   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8786     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8787       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8788       DCI.AddToWorklist(Cvt.getNode());
8789 
8790       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8791       if (ScalarVT != MVT::f32) {
8792         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8793                           DAG.getTargetConstant(0, DL, MVT::i32));
8794       }
8795       return Cvt;
8796     }
8797   }
8798 
8799   return SDValue();
8800 }
8801 
8802 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8803 
8804 // This is a variant of
8805 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8806 //
8807 // The normal DAG combiner will do this, but only if the add has one use since
8808 // that would increase the number of instructions.
8809 //
8810 // This prevents us from seeing a constant offset that can be folded into a
8811 // memory instruction's addressing mode. If we know the resulting add offset of
8812 // a pointer can be folded into an addressing offset, we can replace the pointer
8813 // operand with the add of new constant offset. This eliminates one of the uses,
8814 // and may allow the remaining use to also be simplified.
8815 //
8816 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8817                                                unsigned AddrSpace,
8818                                                EVT MemVT,
8819                                                DAGCombinerInfo &DCI) const {
8820   SDValue N0 = N->getOperand(0);
8821   SDValue N1 = N->getOperand(1);
8822 
8823   // We only do this to handle cases where it's profitable when there are
8824   // multiple uses of the add, so defer to the standard combine.
8825   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8826       N0->hasOneUse())
8827     return SDValue();
8828 
8829   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8830   if (!CN1)
8831     return SDValue();
8832 
8833   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8834   if (!CAdd)
8835     return SDValue();
8836 
8837   // If the resulting offset is too large, we can't fold it into the addressing
8838   // mode offset.
8839   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8840   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8841 
8842   AddrMode AM;
8843   AM.HasBaseReg = true;
8844   AM.BaseOffs = Offset.getSExtValue();
8845   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8846     return SDValue();
8847 
8848   SelectionDAG &DAG = DCI.DAG;
8849   SDLoc SL(N);
8850   EVT VT = N->getValueType(0);
8851 
8852   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8853   SDValue COffset = DAG.getConstant(Offset, SL, VT);
8854 
8855   SDNodeFlags Flags;
8856   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8857                           (N0.getOpcode() == ISD::OR ||
8858                            N0->getFlags().hasNoUnsignedWrap()));
8859 
8860   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8861 }
8862 
8863 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
8864 /// by the chain and intrinsic ID. Theoretically we would also need to check the
8865 /// specific intrinsic, but they all place the pointer operand first.
8866 static unsigned getBasePtrIndex(const MemSDNode *N) {
8867   switch (N->getOpcode()) {
8868   case ISD::STORE:
8869   case ISD::INTRINSIC_W_CHAIN:
8870   case ISD::INTRINSIC_VOID:
8871     return 2;
8872   default:
8873     return 1;
8874   }
8875 }
8876 
8877 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8878                                                   DAGCombinerInfo &DCI) const {
8879   SelectionDAG &DAG = DCI.DAG;
8880   SDLoc SL(N);
8881 
8882   unsigned PtrIdx = getBasePtrIndex(N);
8883   SDValue Ptr = N->getOperand(PtrIdx);
8884 
8885   // TODO: We could also do this for multiplies.
8886   if (Ptr.getOpcode() == ISD::SHL) {
8887     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8888                                           N->getMemoryVT(), DCI);
8889     if (NewPtr) {
8890       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8891 
8892       NewOps[PtrIdx] = NewPtr;
8893       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8894     }
8895   }
8896 
8897   return SDValue();
8898 }
8899 
8900 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8901   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8902          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8903          (Opc == ISD::XOR && Val == 0);
8904 }
8905 
8906 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8907 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8908 // integer combine opportunities since most 64-bit operations are decomposed
8909 // this way.  TODO: We won't want this for SALU especially if it is an inline
8910 // immediate.
8911 SDValue SITargetLowering::splitBinaryBitConstantOp(
8912   DAGCombinerInfo &DCI,
8913   const SDLoc &SL,
8914   unsigned Opc, SDValue LHS,
8915   const ConstantSDNode *CRHS) const {
8916   uint64_t Val = CRHS->getZExtValue();
8917   uint32_t ValLo = Lo_32(Val);
8918   uint32_t ValHi = Hi_32(Val);
8919   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8920 
8921     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8922          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8923         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8924     // If we need to materialize a 64-bit immediate, it will be split up later
8925     // anyway. Avoid creating the harder to understand 64-bit immediate
8926     // materialization.
8927     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8928   }
8929 
8930   return SDValue();
8931 }
8932 
8933 // Returns true if argument is a boolean value which is not serialized into
8934 // memory or argument and does not require v_cndmask_b32 to be deserialized.
8935 static bool isBoolSGPR(SDValue V) {
8936   if (V.getValueType() != MVT::i1)
8937     return false;
8938   switch (V.getOpcode()) {
8939   default:
8940     break;
8941   case ISD::SETCC:
8942   case AMDGPUISD::FP_CLASS:
8943     return true;
8944   case ISD::AND:
8945   case ISD::OR:
8946   case ISD::XOR:
8947     return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
8948   }
8949   return false;
8950 }
8951 
8952 // If a constant has all zeroes or all ones within each byte return it.
8953 // Otherwise return 0.
8954 static uint32_t getConstantPermuteMask(uint32_t C) {
8955   // 0xff for any zero byte in the mask
8956   uint32_t ZeroByteMask = 0;
8957   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8958   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8959   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8960   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8961   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8962   if ((NonZeroByteMask & C) != NonZeroByteMask)
8963     return 0; // Partial bytes selected.
8964   return C;
8965 }
8966 
8967 // Check if a node selects whole bytes from its operand 0 starting at a byte
8968 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8969 // or -1 if not succeeded.
8970 // Note byte select encoding:
8971 // value 0-3 selects corresponding source byte;
8972 // value 0xc selects zero;
8973 // value 0xff selects 0xff.
8974 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8975   assert(V.getValueSizeInBits() == 32);
8976 
8977   if (V.getNumOperands() != 2)
8978     return ~0;
8979 
8980   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8981   if (!N1)
8982     return ~0;
8983 
8984   uint32_t C = N1->getZExtValue();
8985 
8986   switch (V.getOpcode()) {
8987   default:
8988     break;
8989   case ISD::AND:
8990     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8991       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8992     }
8993     break;
8994 
8995   case ISD::OR:
8996     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8997       return (0x03020100 & ~ConstMask) | ConstMask;
8998     }
8999     break;
9000 
9001   case ISD::SHL:
9002     if (C % 8)
9003       return ~0;
9004 
9005     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
9006 
9007   case ISD::SRL:
9008     if (C % 8)
9009       return ~0;
9010 
9011     return uint32_t(0x0c0c0c0c03020100ull >> C);
9012   }
9013 
9014   return ~0;
9015 }
9016 
9017 SDValue SITargetLowering::performAndCombine(SDNode *N,
9018                                             DAGCombinerInfo &DCI) const {
9019   if (DCI.isBeforeLegalize())
9020     return SDValue();
9021 
9022   SelectionDAG &DAG = DCI.DAG;
9023   EVT VT = N->getValueType(0);
9024   SDValue LHS = N->getOperand(0);
9025   SDValue RHS = N->getOperand(1);
9026 
9027 
9028   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9029   if (VT == MVT::i64 && CRHS) {
9030     if (SDValue Split
9031         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9032       return Split;
9033   }
9034 
9035   if (CRHS && VT == MVT::i32) {
9036     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9037     // nb = number of trailing zeroes in mask
9038     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9039     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9040     uint64_t Mask = CRHS->getZExtValue();
9041     unsigned Bits = countPopulation(Mask);
9042     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9043         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9044       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9045         unsigned Shift = CShift->getZExtValue();
9046         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9047         unsigned Offset = NB + Shift;
9048         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9049           SDLoc SL(N);
9050           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9051                                     LHS->getOperand(0),
9052                                     DAG.getConstant(Offset, SL, MVT::i32),
9053                                     DAG.getConstant(Bits, SL, MVT::i32));
9054           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9055           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9056                                     DAG.getValueType(NarrowVT));
9057           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9058                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9059           return Shl;
9060         }
9061       }
9062     }
9063 
9064     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9065     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9066         isa<ConstantSDNode>(LHS.getOperand(2))) {
9067       uint32_t Sel = getConstantPermuteMask(Mask);
9068       if (!Sel)
9069         return SDValue();
9070 
9071       // Select 0xc for all zero bytes
9072       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9073       SDLoc DL(N);
9074       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9075                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9076     }
9077   }
9078 
9079   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9080   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9081   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9082     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9083     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9084 
9085     SDValue X = LHS.getOperand(0);
9086     SDValue Y = RHS.getOperand(0);
9087     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9088       return SDValue();
9089 
9090     if (LCC == ISD::SETO) {
9091       if (X != LHS.getOperand(1))
9092         return SDValue();
9093 
9094       if (RCC == ISD::SETUNE) {
9095         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9096         if (!C1 || !C1->isInfinity() || C1->isNegative())
9097           return SDValue();
9098 
9099         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9100                               SIInstrFlags::N_SUBNORMAL |
9101                               SIInstrFlags::N_ZERO |
9102                               SIInstrFlags::P_ZERO |
9103                               SIInstrFlags::P_SUBNORMAL |
9104                               SIInstrFlags::P_NORMAL;
9105 
9106         static_assert(((~(SIInstrFlags::S_NAN |
9107                           SIInstrFlags::Q_NAN |
9108                           SIInstrFlags::N_INFINITY |
9109                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9110                       "mask not equal");
9111 
9112         SDLoc DL(N);
9113         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9114                            X, DAG.getConstant(Mask, DL, MVT::i32));
9115       }
9116     }
9117   }
9118 
9119   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9120     std::swap(LHS, RHS);
9121 
9122   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9123       RHS.hasOneUse()) {
9124     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9125     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9126     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9127     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9128     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9129         (RHS.getOperand(0) == LHS.getOperand(0) &&
9130          LHS.getOperand(0) == LHS.getOperand(1))) {
9131       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9132       unsigned NewMask = LCC == ISD::SETO ?
9133         Mask->getZExtValue() & ~OrdMask :
9134         Mask->getZExtValue() & OrdMask;
9135 
9136       SDLoc DL(N);
9137       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9138                          DAG.getConstant(NewMask, DL, MVT::i32));
9139     }
9140   }
9141 
9142   if (VT == MVT::i32 &&
9143       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9144     // and x, (sext cc from i1) => select cc, x, 0
9145     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9146       std::swap(LHS, RHS);
9147     if (isBoolSGPR(RHS.getOperand(0)))
9148       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9149                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9150   }
9151 
9152   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9153   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9154   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9155       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9156     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9157     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9158     if (LHSMask != ~0u && RHSMask != ~0u) {
9159       // Canonicalize the expression in an attempt to have fewer unique masks
9160       // and therefore fewer registers used to hold the masks.
9161       if (LHSMask > RHSMask) {
9162         std::swap(LHSMask, RHSMask);
9163         std::swap(LHS, RHS);
9164       }
9165 
9166       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9167       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9168       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9169       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9170 
9171       // Check of we need to combine values from two sources within a byte.
9172       if (!(LHSUsedLanes & RHSUsedLanes) &&
9173           // If we select high and lower word keep it for SDWA.
9174           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9175           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9176         // Each byte in each mask is either selector mask 0-3, or has higher
9177         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9178         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9179         // mask which is not 0xff wins. By anding both masks we have a correct
9180         // result except that 0x0c shall be corrected to give 0x0c only.
9181         uint32_t Mask = LHSMask & RHSMask;
9182         for (unsigned I = 0; I < 32; I += 8) {
9183           uint32_t ByteSel = 0xff << I;
9184           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9185             Mask &= (0x0c << I) & 0xffffffff;
9186         }
9187 
9188         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9189         // or 0x0c.
9190         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9191         SDLoc DL(N);
9192 
9193         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9194                            LHS.getOperand(0), RHS.getOperand(0),
9195                            DAG.getConstant(Sel, DL, MVT::i32));
9196       }
9197     }
9198   }
9199 
9200   return SDValue();
9201 }
9202 
9203 SDValue SITargetLowering::performOrCombine(SDNode *N,
9204                                            DAGCombinerInfo &DCI) const {
9205   SelectionDAG &DAG = DCI.DAG;
9206   SDValue LHS = N->getOperand(0);
9207   SDValue RHS = N->getOperand(1);
9208 
9209   EVT VT = N->getValueType(0);
9210   if (VT == MVT::i1) {
9211     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9212     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9213         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9214       SDValue Src = LHS.getOperand(0);
9215       if (Src != RHS.getOperand(0))
9216         return SDValue();
9217 
9218       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9219       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9220       if (!CLHS || !CRHS)
9221         return SDValue();
9222 
9223       // Only 10 bits are used.
9224       static const uint32_t MaxMask = 0x3ff;
9225 
9226       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9227       SDLoc DL(N);
9228       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9229                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9230     }
9231 
9232     return SDValue();
9233   }
9234 
9235   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9236   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9237       LHS.getOpcode() == AMDGPUISD::PERM &&
9238       isa<ConstantSDNode>(LHS.getOperand(2))) {
9239     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9240     if (!Sel)
9241       return SDValue();
9242 
9243     Sel |= LHS.getConstantOperandVal(2);
9244     SDLoc DL(N);
9245     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9246                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9247   }
9248 
9249   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9250   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9251   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9252       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9253     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9254     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9255     if (LHSMask != ~0u && RHSMask != ~0u) {
9256       // Canonicalize the expression in an attempt to have fewer unique masks
9257       // and therefore fewer registers used to hold the masks.
9258       if (LHSMask > RHSMask) {
9259         std::swap(LHSMask, RHSMask);
9260         std::swap(LHS, RHS);
9261       }
9262 
9263       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9264       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9265       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9266       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9267 
9268       // Check of we need to combine values from two sources within a byte.
9269       if (!(LHSUsedLanes & RHSUsedLanes) &&
9270           // If we select high and lower word keep it for SDWA.
9271           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9272           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9273         // Kill zero bytes selected by other mask. Zero value is 0xc.
9274         LHSMask &= ~RHSUsedLanes;
9275         RHSMask &= ~LHSUsedLanes;
9276         // Add 4 to each active LHS lane
9277         LHSMask |= LHSUsedLanes & 0x04040404;
9278         // Combine masks
9279         uint32_t Sel = LHSMask | RHSMask;
9280         SDLoc DL(N);
9281 
9282         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9283                            LHS.getOperand(0), RHS.getOperand(0),
9284                            DAG.getConstant(Sel, DL, MVT::i32));
9285       }
9286     }
9287   }
9288 
9289   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9290     return SDValue();
9291 
9292   // TODO: This could be a generic combine with a predicate for extracting the
9293   // high half of an integer being free.
9294 
9295   // (or i64:x, (zero_extend i32:y)) ->
9296   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9297   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9298       RHS.getOpcode() != ISD::ZERO_EXTEND)
9299     std::swap(LHS, RHS);
9300 
9301   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9302     SDValue ExtSrc = RHS.getOperand(0);
9303     EVT SrcVT = ExtSrc.getValueType();
9304     if (SrcVT == MVT::i32) {
9305       SDLoc SL(N);
9306       SDValue LowLHS, HiBits;
9307       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9308       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9309 
9310       DCI.AddToWorklist(LowOr.getNode());
9311       DCI.AddToWorklist(HiBits.getNode());
9312 
9313       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9314                                 LowOr, HiBits);
9315       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9316     }
9317   }
9318 
9319   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9320   if (CRHS) {
9321     if (SDValue Split
9322           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
9323       return Split;
9324   }
9325 
9326   return SDValue();
9327 }
9328 
9329 SDValue SITargetLowering::performXorCombine(SDNode *N,
9330                                             DAGCombinerInfo &DCI) const {
9331   EVT VT = N->getValueType(0);
9332   if (VT != MVT::i64)
9333     return SDValue();
9334 
9335   SDValue LHS = N->getOperand(0);
9336   SDValue RHS = N->getOperand(1);
9337 
9338   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9339   if (CRHS) {
9340     if (SDValue Split
9341           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9342       return Split;
9343   }
9344 
9345   return SDValue();
9346 }
9347 
9348 // Instructions that will be lowered with a final instruction that zeros the
9349 // high result bits.
9350 // XXX - probably only need to list legal operations.
9351 static bool fp16SrcZerosHighBits(unsigned Opc) {
9352   switch (Opc) {
9353   case ISD::FADD:
9354   case ISD::FSUB:
9355   case ISD::FMUL:
9356   case ISD::FDIV:
9357   case ISD::FREM:
9358   case ISD::FMA:
9359   case ISD::FMAD:
9360   case ISD::FCANONICALIZE:
9361   case ISD::FP_ROUND:
9362   case ISD::UINT_TO_FP:
9363   case ISD::SINT_TO_FP:
9364   case ISD::FABS:
9365     // Fabs is lowered to a bit operation, but it's an and which will clear the
9366     // high bits anyway.
9367   case ISD::FSQRT:
9368   case ISD::FSIN:
9369   case ISD::FCOS:
9370   case ISD::FPOWI:
9371   case ISD::FPOW:
9372   case ISD::FLOG:
9373   case ISD::FLOG2:
9374   case ISD::FLOG10:
9375   case ISD::FEXP:
9376   case ISD::FEXP2:
9377   case ISD::FCEIL:
9378   case ISD::FTRUNC:
9379   case ISD::FRINT:
9380   case ISD::FNEARBYINT:
9381   case ISD::FROUND:
9382   case ISD::FFLOOR:
9383   case ISD::FMINNUM:
9384   case ISD::FMAXNUM:
9385   case AMDGPUISD::FRACT:
9386   case AMDGPUISD::CLAMP:
9387   case AMDGPUISD::COS_HW:
9388   case AMDGPUISD::SIN_HW:
9389   case AMDGPUISD::FMIN3:
9390   case AMDGPUISD::FMAX3:
9391   case AMDGPUISD::FMED3:
9392   case AMDGPUISD::FMAD_FTZ:
9393   case AMDGPUISD::RCP:
9394   case AMDGPUISD::RSQ:
9395   case AMDGPUISD::RCP_IFLAG:
9396   case AMDGPUISD::LDEXP:
9397     return true;
9398   default:
9399     // fcopysign, select and others may be lowered to 32-bit bit operations
9400     // which don't zero the high bits.
9401     return false;
9402   }
9403 }
9404 
9405 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9406                                                    DAGCombinerInfo &DCI) const {
9407   if (!Subtarget->has16BitInsts() ||
9408       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9409     return SDValue();
9410 
9411   EVT VT = N->getValueType(0);
9412   if (VT != MVT::i32)
9413     return SDValue();
9414 
9415   SDValue Src = N->getOperand(0);
9416   if (Src.getValueType() != MVT::i16)
9417     return SDValue();
9418 
9419   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
9420   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
9421   if (Src.getOpcode() == ISD::BITCAST) {
9422     SDValue BCSrc = Src.getOperand(0);
9423     if (BCSrc.getValueType() == MVT::f16 &&
9424         fp16SrcZerosHighBits(BCSrc.getOpcode()))
9425       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
9426   }
9427 
9428   return SDValue();
9429 }
9430 
9431 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9432                                                         DAGCombinerInfo &DCI)
9433                                                         const {
9434   SDValue Src = N->getOperand(0);
9435   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9436 
9437   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9438       VTSign->getVT() == MVT::i8) ||
9439       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9440       VTSign->getVT() == MVT::i16)) &&
9441       Src.hasOneUse()) {
9442     auto *M = cast<MemSDNode>(Src);
9443     SDValue Ops[] = {
9444       Src.getOperand(0), // Chain
9445       Src.getOperand(1), // rsrc
9446       Src.getOperand(2), // vindex
9447       Src.getOperand(3), // voffset
9448       Src.getOperand(4), // soffset
9449       Src.getOperand(5), // offset
9450       Src.getOperand(6),
9451       Src.getOperand(7)
9452     };
9453     // replace with BUFFER_LOAD_BYTE/SHORT
9454     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9455                                          Src.getOperand(0).getValueType());
9456     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9457                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9458     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9459                                                           ResList,
9460                                                           Ops, M->getMemoryVT(),
9461                                                           M->getMemOperand());
9462     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9463                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9464   }
9465   return SDValue();
9466 }
9467 
9468 SDValue SITargetLowering::performClassCombine(SDNode *N,
9469                                               DAGCombinerInfo &DCI) const {
9470   SelectionDAG &DAG = DCI.DAG;
9471   SDValue Mask = N->getOperand(1);
9472 
9473   // fp_class x, 0 -> false
9474   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9475     if (CMask->isNullValue())
9476       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9477   }
9478 
9479   if (N->getOperand(0).isUndef())
9480     return DAG.getUNDEF(MVT::i1);
9481 
9482   return SDValue();
9483 }
9484 
9485 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9486                                             DAGCombinerInfo &DCI) const {
9487   EVT VT = N->getValueType(0);
9488   SDValue N0 = N->getOperand(0);
9489 
9490   if (N0.isUndef())
9491     return N0;
9492 
9493   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9494                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9495     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9496                            N->getFlags());
9497   }
9498 
9499   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9500     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9501                            N0.getOperand(0), N->getFlags());
9502   }
9503 
9504   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9505 }
9506 
9507 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9508                                        unsigned MaxDepth) const {
9509   unsigned Opcode = Op.getOpcode();
9510   if (Opcode == ISD::FCANONICALIZE)
9511     return true;
9512 
9513   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9514     auto F = CFP->getValueAPF();
9515     if (F.isNaN() && F.isSignaling())
9516       return false;
9517     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9518   }
9519 
9520   // If source is a result of another standard FP operation it is already in
9521   // canonical form.
9522   if (MaxDepth == 0)
9523     return false;
9524 
9525   switch (Opcode) {
9526   // These will flush denorms if required.
9527   case ISD::FADD:
9528   case ISD::FSUB:
9529   case ISD::FMUL:
9530   case ISD::FCEIL:
9531   case ISD::FFLOOR:
9532   case ISD::FMA:
9533   case ISD::FMAD:
9534   case ISD::FSQRT:
9535   case ISD::FDIV:
9536   case ISD::FREM:
9537   case ISD::FP_ROUND:
9538   case ISD::FP_EXTEND:
9539   case AMDGPUISD::FMUL_LEGACY:
9540   case AMDGPUISD::FMAD_FTZ:
9541   case AMDGPUISD::RCP:
9542   case AMDGPUISD::RSQ:
9543   case AMDGPUISD::RSQ_CLAMP:
9544   case AMDGPUISD::RCP_LEGACY:
9545   case AMDGPUISD::RCP_IFLAG:
9546   case AMDGPUISD::DIV_SCALE:
9547   case AMDGPUISD::DIV_FMAS:
9548   case AMDGPUISD::DIV_FIXUP:
9549   case AMDGPUISD::FRACT:
9550   case AMDGPUISD::LDEXP:
9551   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9552   case AMDGPUISD::CVT_F32_UBYTE0:
9553   case AMDGPUISD::CVT_F32_UBYTE1:
9554   case AMDGPUISD::CVT_F32_UBYTE2:
9555   case AMDGPUISD::CVT_F32_UBYTE3:
9556     return true;
9557 
9558   // It can/will be lowered or combined as a bit operation.
9559   // Need to check their input recursively to handle.
9560   case ISD::FNEG:
9561   case ISD::FABS:
9562   case ISD::FCOPYSIGN:
9563     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9564 
9565   case ISD::FSIN:
9566   case ISD::FCOS:
9567   case ISD::FSINCOS:
9568     return Op.getValueType().getScalarType() != MVT::f16;
9569 
9570   case ISD::FMINNUM:
9571   case ISD::FMAXNUM:
9572   case ISD::FMINNUM_IEEE:
9573   case ISD::FMAXNUM_IEEE:
9574   case AMDGPUISD::CLAMP:
9575   case AMDGPUISD::FMED3:
9576   case AMDGPUISD::FMAX3:
9577   case AMDGPUISD::FMIN3: {
9578     // FIXME: Shouldn't treat the generic operations different based these.
9579     // However, we aren't really required to flush the result from
9580     // minnum/maxnum..
9581 
9582     // snans will be quieted, so we only need to worry about denormals.
9583     if (Subtarget->supportsMinMaxDenormModes() ||
9584         denormalsEnabledForType(DAG, Op.getValueType()))
9585       return true;
9586 
9587     // Flushing may be required.
9588     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9589     // targets need to check their input recursively.
9590 
9591     // FIXME: Does this apply with clamp? It's implemented with max.
9592     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9593       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9594         return false;
9595     }
9596 
9597     return true;
9598   }
9599   case ISD::SELECT: {
9600     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9601            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9602   }
9603   case ISD::BUILD_VECTOR: {
9604     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9605       SDValue SrcOp = Op.getOperand(i);
9606       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9607         return false;
9608     }
9609 
9610     return true;
9611   }
9612   case ISD::EXTRACT_VECTOR_ELT:
9613   case ISD::EXTRACT_SUBVECTOR: {
9614     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9615   }
9616   case ISD::INSERT_VECTOR_ELT: {
9617     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9618            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9619   }
9620   case ISD::UNDEF:
9621     // Could be anything.
9622     return false;
9623 
9624   case ISD::BITCAST:
9625     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9626   case ISD::TRUNCATE: {
9627     // Hack round the mess we make when legalizing extract_vector_elt
9628     if (Op.getValueType() == MVT::i16) {
9629       SDValue TruncSrc = Op.getOperand(0);
9630       if (TruncSrc.getValueType() == MVT::i32 &&
9631           TruncSrc.getOpcode() == ISD::BITCAST &&
9632           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9633         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9634       }
9635     }
9636     return false;
9637   }
9638   case ISD::INTRINSIC_WO_CHAIN: {
9639     unsigned IntrinsicID
9640       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9641     // TODO: Handle more intrinsics
9642     switch (IntrinsicID) {
9643     case Intrinsic::amdgcn_cvt_pkrtz:
9644     case Intrinsic::amdgcn_cubeid:
9645     case Intrinsic::amdgcn_frexp_mant:
9646     case Intrinsic::amdgcn_fdot2:
9647     case Intrinsic::amdgcn_rcp:
9648     case Intrinsic::amdgcn_rsq:
9649     case Intrinsic::amdgcn_rsq_clamp:
9650     case Intrinsic::amdgcn_rcp_legacy:
9651     case Intrinsic::amdgcn_rsq_legacy:
9652     case Intrinsic::amdgcn_trig_preop:
9653       return true;
9654     default:
9655       break;
9656     }
9657 
9658     LLVM_FALLTHROUGH;
9659   }
9660   default:
9661     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9662            DAG.isKnownNeverSNaN(Op);
9663   }
9664 
9665   llvm_unreachable("invalid operation");
9666 }
9667 
9668 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
9669                                        unsigned MaxDepth) const {
9670   MachineRegisterInfo &MRI = MF.getRegInfo();
9671   MachineInstr *MI = MRI.getVRegDef(Reg);
9672   unsigned Opcode = MI->getOpcode();
9673 
9674   if (Opcode == AMDGPU::G_FCANONICALIZE)
9675     return true;
9676 
9677   if (Opcode == AMDGPU::G_FCONSTANT) {
9678     auto F = MI->getOperand(1).getFPImm()->getValueAPF();
9679     if (F.isNaN() && F.isSignaling())
9680       return false;
9681     return !F.isDenormal() || denormalsEnabledForType(MRI.getType(Reg), MF);
9682   }
9683 
9684   if (MaxDepth == 0)
9685     return false;
9686 
9687   switch (Opcode) {
9688   case AMDGPU::G_FMINNUM_IEEE:
9689   case AMDGPU::G_FMAXNUM_IEEE: {
9690     if (Subtarget->supportsMinMaxDenormModes() ||
9691         denormalsEnabledForType(MRI.getType(Reg), MF))
9692       return true;
9693     for (unsigned I = 1, E = MI->getNumOperands(); I != E; ++I) {
9694       if (!isCanonicalized(MI->getOperand(I).getReg(), MF, MaxDepth - 1))
9695         return false;
9696     }
9697     return true;
9698   }
9699   default:
9700     return denormalsEnabledForType(MRI.getType(Reg), MF) &&
9701            isKnownNeverSNaN(Reg, MRI);
9702   }
9703 
9704   llvm_unreachable("invalid operation");
9705 }
9706 
9707 // Constant fold canonicalize.
9708 SDValue SITargetLowering::getCanonicalConstantFP(
9709   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9710   // Flush denormals to 0 if not enabled.
9711   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9712     return DAG.getConstantFP(0.0, SL, VT);
9713 
9714   if (C.isNaN()) {
9715     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9716     if (C.isSignaling()) {
9717       // Quiet a signaling NaN.
9718       // FIXME: Is this supposed to preserve payload bits?
9719       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9720     }
9721 
9722     // Make sure it is the canonical NaN bitpattern.
9723     //
9724     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9725     // immediate?
9726     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9727       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9728   }
9729 
9730   // Already canonical.
9731   return DAG.getConstantFP(C, SL, VT);
9732 }
9733 
9734 static bool vectorEltWillFoldAway(SDValue Op) {
9735   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9736 }
9737 
9738 SDValue SITargetLowering::performFCanonicalizeCombine(
9739   SDNode *N,
9740   DAGCombinerInfo &DCI) const {
9741   SelectionDAG &DAG = DCI.DAG;
9742   SDValue N0 = N->getOperand(0);
9743   EVT VT = N->getValueType(0);
9744 
9745   // fcanonicalize undef -> qnan
9746   if (N0.isUndef()) {
9747     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9748     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9749   }
9750 
9751   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9752     EVT VT = N->getValueType(0);
9753     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9754   }
9755 
9756   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9757   //                                                   (fcanonicalize k)
9758   //
9759   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9760 
9761   // TODO: This could be better with wider vectors that will be split to v2f16,
9762   // and to consider uses since there aren't that many packed operations.
9763   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9764       isTypeLegal(MVT::v2f16)) {
9765     SDLoc SL(N);
9766     SDValue NewElts[2];
9767     SDValue Lo = N0.getOperand(0);
9768     SDValue Hi = N0.getOperand(1);
9769     EVT EltVT = Lo.getValueType();
9770 
9771     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9772       for (unsigned I = 0; I != 2; ++I) {
9773         SDValue Op = N0.getOperand(I);
9774         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9775           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9776                                               CFP->getValueAPF());
9777         } else if (Op.isUndef()) {
9778           // Handled below based on what the other operand is.
9779           NewElts[I] = Op;
9780         } else {
9781           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9782         }
9783       }
9784 
9785       // If one half is undef, and one is constant, perfer a splat vector rather
9786       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9787       // cheaper to use and may be free with a packed operation.
9788       if (NewElts[0].isUndef()) {
9789         if (isa<ConstantFPSDNode>(NewElts[1]))
9790           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9791             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9792       }
9793 
9794       if (NewElts[1].isUndef()) {
9795         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9796           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9797       }
9798 
9799       return DAG.getBuildVector(VT, SL, NewElts);
9800     }
9801   }
9802 
9803   unsigned SrcOpc = N0.getOpcode();
9804 
9805   // If it's free to do so, push canonicalizes further up the source, which may
9806   // find a canonical source.
9807   //
9808   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9809   // sNaNs.
9810   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9811     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9812     if (CRHS && N0.hasOneUse()) {
9813       SDLoc SL(N);
9814       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9815                                    N0.getOperand(0));
9816       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9817       DCI.AddToWorklist(Canon0.getNode());
9818 
9819       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9820     }
9821   }
9822 
9823   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9824 }
9825 
9826 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9827   switch (Opc) {
9828   case ISD::FMAXNUM:
9829   case ISD::FMAXNUM_IEEE:
9830     return AMDGPUISD::FMAX3;
9831   case ISD::SMAX:
9832     return AMDGPUISD::SMAX3;
9833   case ISD::UMAX:
9834     return AMDGPUISD::UMAX3;
9835   case ISD::FMINNUM:
9836   case ISD::FMINNUM_IEEE:
9837     return AMDGPUISD::FMIN3;
9838   case ISD::SMIN:
9839     return AMDGPUISD::SMIN3;
9840   case ISD::UMIN:
9841     return AMDGPUISD::UMIN3;
9842   default:
9843     llvm_unreachable("Not a min/max opcode");
9844   }
9845 }
9846 
9847 SDValue SITargetLowering::performIntMed3ImmCombine(
9848   SelectionDAG &DAG, const SDLoc &SL,
9849   SDValue Op0, SDValue Op1, bool Signed) const {
9850   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9851   if (!K1)
9852     return SDValue();
9853 
9854   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9855   if (!K0)
9856     return SDValue();
9857 
9858   if (Signed) {
9859     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9860       return SDValue();
9861   } else {
9862     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9863       return SDValue();
9864   }
9865 
9866   EVT VT = K0->getValueType(0);
9867   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9868   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9869     return DAG.getNode(Med3Opc, SL, VT,
9870                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9871   }
9872 
9873   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9874   if (VT == MVT::i16) {
9875     MVT NVT = MVT::i32;
9876     unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9877 
9878     SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9879     SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9880     SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9881 
9882     SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9883     return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9884   }
9885 
9886   return SDValue();
9887 }
9888 
9889 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9890   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9891     return C;
9892 
9893   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9894     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9895       return C;
9896   }
9897 
9898   return nullptr;
9899 }
9900 
9901 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9902                                                   const SDLoc &SL,
9903                                                   SDValue Op0,
9904                                                   SDValue Op1) const {
9905   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9906   if (!K1)
9907     return SDValue();
9908 
9909   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9910   if (!K0)
9911     return SDValue();
9912 
9913   // Ordered >= (although NaN inputs should have folded away by now).
9914   if (K0->getValueAPF() > K1->getValueAPF())
9915     return SDValue();
9916 
9917   const MachineFunction &MF = DAG.getMachineFunction();
9918   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9919 
9920   // TODO: Check IEEE bit enabled?
9921   EVT VT = Op0.getValueType();
9922   if (Info->getMode().DX10Clamp) {
9923     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9924     // hardware fmed3 behavior converting to a min.
9925     // FIXME: Should this be allowing -0.0?
9926     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9927       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9928   }
9929 
9930   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9931   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9932     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9933     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9934     // then give the other result, which is different from med3 with a NaN
9935     // input.
9936     SDValue Var = Op0.getOperand(0);
9937     if (!DAG.isKnownNeverSNaN(Var))
9938       return SDValue();
9939 
9940     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9941 
9942     if ((!K0->hasOneUse() ||
9943          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9944         (!K1->hasOneUse() ||
9945          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9946       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9947                          Var, SDValue(K0, 0), SDValue(K1, 0));
9948     }
9949   }
9950 
9951   return SDValue();
9952 }
9953 
9954 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9955                                                DAGCombinerInfo &DCI) const {
9956   SelectionDAG &DAG = DCI.DAG;
9957 
9958   EVT VT = N->getValueType(0);
9959   unsigned Opc = N->getOpcode();
9960   SDValue Op0 = N->getOperand(0);
9961   SDValue Op1 = N->getOperand(1);
9962 
9963   // Only do this if the inner op has one use since this will just increases
9964   // register pressure for no benefit.
9965 
9966   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9967       !VT.isVector() &&
9968       (VT == MVT::i32 || VT == MVT::f32 ||
9969        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9970     // max(max(a, b), c) -> max3(a, b, c)
9971     // min(min(a, b), c) -> min3(a, b, c)
9972     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9973       SDLoc DL(N);
9974       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9975                          DL,
9976                          N->getValueType(0),
9977                          Op0.getOperand(0),
9978                          Op0.getOperand(1),
9979                          Op1);
9980     }
9981 
9982     // Try commuted.
9983     // max(a, max(b, c)) -> max3(a, b, c)
9984     // min(a, min(b, c)) -> min3(a, b, c)
9985     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9986       SDLoc DL(N);
9987       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9988                          DL,
9989                          N->getValueType(0),
9990                          Op0,
9991                          Op1.getOperand(0),
9992                          Op1.getOperand(1));
9993     }
9994   }
9995 
9996   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9997   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9998     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9999       return Med3;
10000   }
10001 
10002   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
10003     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
10004       return Med3;
10005   }
10006 
10007   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
10008   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
10009        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
10010        (Opc == AMDGPUISD::FMIN_LEGACY &&
10011         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
10012       (VT == MVT::f32 || VT == MVT::f64 ||
10013        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
10014        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
10015       Op0.hasOneUse()) {
10016     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
10017       return Res;
10018   }
10019 
10020   return SDValue();
10021 }
10022 
10023 static bool isClampZeroToOne(SDValue A, SDValue B) {
10024   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
10025     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
10026       // FIXME: Should this be allowing -0.0?
10027       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
10028              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
10029     }
10030   }
10031 
10032   return false;
10033 }
10034 
10035 // FIXME: Should only worry about snans for version with chain.
10036 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
10037                                               DAGCombinerInfo &DCI) const {
10038   EVT VT = N->getValueType(0);
10039   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
10040   // NaNs. With a NaN input, the order of the operands may change the result.
10041 
10042   SelectionDAG &DAG = DCI.DAG;
10043   SDLoc SL(N);
10044 
10045   SDValue Src0 = N->getOperand(0);
10046   SDValue Src1 = N->getOperand(1);
10047   SDValue Src2 = N->getOperand(2);
10048 
10049   if (isClampZeroToOne(Src0, Src1)) {
10050     // const_a, const_b, x -> clamp is safe in all cases including signaling
10051     // nans.
10052     // FIXME: Should this be allowing -0.0?
10053     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
10054   }
10055 
10056   const MachineFunction &MF = DAG.getMachineFunction();
10057   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10058 
10059   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
10060   // handling no dx10-clamp?
10061   if (Info->getMode().DX10Clamp) {
10062     // If NaNs is clamped to 0, we are free to reorder the inputs.
10063 
10064     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10065       std::swap(Src0, Src1);
10066 
10067     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10068       std::swap(Src1, Src2);
10069 
10070     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10071       std::swap(Src0, Src1);
10072 
10073     if (isClampZeroToOne(Src1, Src2))
10074       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10075   }
10076 
10077   return SDValue();
10078 }
10079 
10080 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10081                                                  DAGCombinerInfo &DCI) const {
10082   SDValue Src0 = N->getOperand(0);
10083   SDValue Src1 = N->getOperand(1);
10084   if (Src0.isUndef() && Src1.isUndef())
10085     return DCI.DAG.getUNDEF(N->getValueType(0));
10086   return SDValue();
10087 }
10088 
10089 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10090 // expanded into a set of cmp/select instructions.
10091 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10092                                                 unsigned NumElem,
10093                                                 bool IsDivergentIdx) {
10094   if (UseDivergentRegisterIndexing)
10095     return false;
10096 
10097   unsigned VecSize = EltSize * NumElem;
10098 
10099   // Sub-dword vectors of size 2 dword or less have better implementation.
10100   if (VecSize <= 64 && EltSize < 32)
10101     return false;
10102 
10103   // Always expand the rest of sub-dword instructions, otherwise it will be
10104   // lowered via memory.
10105   if (EltSize < 32)
10106     return true;
10107 
10108   // Always do this if var-idx is divergent, otherwise it will become a loop.
10109   if (IsDivergentIdx)
10110     return true;
10111 
10112   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10113   unsigned NumInsts = NumElem /* Number of compares */ +
10114                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10115   return NumInsts <= 16;
10116 }
10117 
10118 static bool shouldExpandVectorDynExt(SDNode *N) {
10119   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10120   if (isa<ConstantSDNode>(Idx))
10121     return false;
10122 
10123   SDValue Vec = N->getOperand(0);
10124   EVT VecVT = Vec.getValueType();
10125   EVT EltVT = VecVT.getVectorElementType();
10126   unsigned EltSize = EltVT.getSizeInBits();
10127   unsigned NumElem = VecVT.getVectorNumElements();
10128 
10129   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
10130                                                     Idx->isDivergent());
10131 }
10132 
10133 SDValue SITargetLowering::performExtractVectorEltCombine(
10134   SDNode *N, DAGCombinerInfo &DCI) const {
10135   SDValue Vec = N->getOperand(0);
10136   SelectionDAG &DAG = DCI.DAG;
10137 
10138   EVT VecVT = Vec.getValueType();
10139   EVT EltVT = VecVT.getVectorElementType();
10140 
10141   if ((Vec.getOpcode() == ISD::FNEG ||
10142        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10143     SDLoc SL(N);
10144     EVT EltVT = N->getValueType(0);
10145     SDValue Idx = N->getOperand(1);
10146     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10147                               Vec.getOperand(0), Idx);
10148     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10149   }
10150 
10151   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10152   //    =>
10153   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10154   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10155   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10156   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10157     SDLoc SL(N);
10158     EVT EltVT = N->getValueType(0);
10159     SDValue Idx = N->getOperand(1);
10160     unsigned Opc = Vec.getOpcode();
10161 
10162     switch(Opc) {
10163     default:
10164       break;
10165       // TODO: Support other binary operations.
10166     case ISD::FADD:
10167     case ISD::FSUB:
10168     case ISD::FMUL:
10169     case ISD::ADD:
10170     case ISD::UMIN:
10171     case ISD::UMAX:
10172     case ISD::SMIN:
10173     case ISD::SMAX:
10174     case ISD::FMAXNUM:
10175     case ISD::FMINNUM:
10176     case ISD::FMAXNUM_IEEE:
10177     case ISD::FMINNUM_IEEE: {
10178       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10179                                  Vec.getOperand(0), Idx);
10180       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10181                                  Vec.getOperand(1), Idx);
10182 
10183       DCI.AddToWorklist(Elt0.getNode());
10184       DCI.AddToWorklist(Elt1.getNode());
10185       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10186     }
10187     }
10188   }
10189 
10190   unsigned VecSize = VecVT.getSizeInBits();
10191   unsigned EltSize = EltVT.getSizeInBits();
10192 
10193   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10194   if (::shouldExpandVectorDynExt(N)) {
10195     SDLoc SL(N);
10196     SDValue Idx = N->getOperand(1);
10197     SDValue V;
10198     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10199       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10200       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10201       if (I == 0)
10202         V = Elt;
10203       else
10204         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10205     }
10206     return V;
10207   }
10208 
10209   if (!DCI.isBeforeLegalize())
10210     return SDValue();
10211 
10212   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10213   // elements. This exposes more load reduction opportunities by replacing
10214   // multiple small extract_vector_elements with a single 32-bit extract.
10215   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10216   if (isa<MemSDNode>(Vec) &&
10217       EltSize <= 16 &&
10218       EltVT.isByteSized() &&
10219       VecSize > 32 &&
10220       VecSize % 32 == 0 &&
10221       Idx) {
10222     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10223 
10224     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10225     unsigned EltIdx = BitIndex / 32;
10226     unsigned LeftoverBitIdx = BitIndex % 32;
10227     SDLoc SL(N);
10228 
10229     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10230     DCI.AddToWorklist(Cast.getNode());
10231 
10232     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10233                               DAG.getConstant(EltIdx, SL, MVT::i32));
10234     DCI.AddToWorklist(Elt.getNode());
10235     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10236                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10237     DCI.AddToWorklist(Srl.getNode());
10238 
10239     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10240     DCI.AddToWorklist(Trunc.getNode());
10241     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10242   }
10243 
10244   return SDValue();
10245 }
10246 
10247 SDValue
10248 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10249                                                 DAGCombinerInfo &DCI) const {
10250   SDValue Vec = N->getOperand(0);
10251   SDValue Idx = N->getOperand(2);
10252   EVT VecVT = Vec.getValueType();
10253   EVT EltVT = VecVT.getVectorElementType();
10254 
10255   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10256   // => BUILD_VECTOR n x select (e, const-idx)
10257   if (!::shouldExpandVectorDynExt(N))
10258     return SDValue();
10259 
10260   SelectionDAG &DAG = DCI.DAG;
10261   SDLoc SL(N);
10262   SDValue Ins = N->getOperand(1);
10263   EVT IdxVT = Idx.getValueType();
10264 
10265   SmallVector<SDValue, 16> Ops;
10266   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10267     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10268     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10269     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10270     Ops.push_back(V);
10271   }
10272 
10273   return DAG.getBuildVector(VecVT, SL, Ops);
10274 }
10275 
10276 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10277                                           const SDNode *N0,
10278                                           const SDNode *N1) const {
10279   EVT VT = N0->getValueType(0);
10280 
10281   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10282   // support denormals ever.
10283   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10284        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10285         getSubtarget()->hasMadF16())) &&
10286        isOperationLegal(ISD::FMAD, VT))
10287     return ISD::FMAD;
10288 
10289   const TargetOptions &Options = DAG.getTarget().Options;
10290   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10291        (N0->getFlags().hasAllowContract() &&
10292         N1->getFlags().hasAllowContract())) &&
10293       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10294     return ISD::FMA;
10295   }
10296 
10297   return 0;
10298 }
10299 
10300 // For a reassociatable opcode perform:
10301 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10302 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10303                                                SelectionDAG &DAG) const {
10304   EVT VT = N->getValueType(0);
10305   if (VT != MVT::i32 && VT != MVT::i64)
10306     return SDValue();
10307 
10308   unsigned Opc = N->getOpcode();
10309   SDValue Op0 = N->getOperand(0);
10310   SDValue Op1 = N->getOperand(1);
10311 
10312   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10313     return SDValue();
10314 
10315   if (Op0->isDivergent())
10316     std::swap(Op0, Op1);
10317 
10318   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10319     return SDValue();
10320 
10321   SDValue Op2 = Op1.getOperand(1);
10322   Op1 = Op1.getOperand(0);
10323   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10324     return SDValue();
10325 
10326   if (Op1->isDivergent())
10327     std::swap(Op1, Op2);
10328 
10329   // If either operand is constant this will conflict with
10330   // DAGCombiner::ReassociateOps().
10331   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
10332       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
10333     return SDValue();
10334 
10335   SDLoc SL(N);
10336   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10337   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10338 }
10339 
10340 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10341                            EVT VT,
10342                            SDValue N0, SDValue N1, SDValue N2,
10343                            bool Signed) {
10344   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10345   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10346   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10347   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10348 }
10349 
10350 SDValue SITargetLowering::performAddCombine(SDNode *N,
10351                                             DAGCombinerInfo &DCI) const {
10352   SelectionDAG &DAG = DCI.DAG;
10353   EVT VT = N->getValueType(0);
10354   SDLoc SL(N);
10355   SDValue LHS = N->getOperand(0);
10356   SDValue RHS = N->getOperand(1);
10357 
10358   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10359       && Subtarget->hasMad64_32() &&
10360       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10361       VT.getScalarSizeInBits() <= 64) {
10362     if (LHS.getOpcode() != ISD::MUL)
10363       std::swap(LHS, RHS);
10364 
10365     SDValue MulLHS = LHS.getOperand(0);
10366     SDValue MulRHS = LHS.getOperand(1);
10367     SDValue AddRHS = RHS;
10368 
10369     // TODO: Maybe restrict if SGPR inputs.
10370     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10371         numBitsUnsigned(MulRHS, DAG) <= 32) {
10372       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10373       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10374       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10375       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10376     }
10377 
10378     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
10379       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10380       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10381       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10382       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10383     }
10384 
10385     return SDValue();
10386   }
10387 
10388   if (SDValue V = reassociateScalarOps(N, DAG)) {
10389     return V;
10390   }
10391 
10392   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10393     return SDValue();
10394 
10395   // add x, zext (setcc) => addcarry x, 0, setcc
10396   // add x, sext (setcc) => subcarry x, 0, setcc
10397   unsigned Opc = LHS.getOpcode();
10398   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10399       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10400     std::swap(RHS, LHS);
10401 
10402   Opc = RHS.getOpcode();
10403   switch (Opc) {
10404   default: break;
10405   case ISD::ZERO_EXTEND:
10406   case ISD::SIGN_EXTEND:
10407   case ISD::ANY_EXTEND: {
10408     auto Cond = RHS.getOperand(0);
10409     // If this won't be a real VOPC output, we would still need to insert an
10410     // extra instruction anyway.
10411     if (!isBoolSGPR(Cond))
10412       break;
10413     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10414     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10415     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10416     return DAG.getNode(Opc, SL, VTList, Args);
10417   }
10418   case ISD::ADDCARRY: {
10419     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10420     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10421     if (!C || C->getZExtValue() != 0) break;
10422     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10423     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10424   }
10425   }
10426   return SDValue();
10427 }
10428 
10429 SDValue SITargetLowering::performSubCombine(SDNode *N,
10430                                             DAGCombinerInfo &DCI) const {
10431   SelectionDAG &DAG = DCI.DAG;
10432   EVT VT = N->getValueType(0);
10433 
10434   if (VT != MVT::i32)
10435     return SDValue();
10436 
10437   SDLoc SL(N);
10438   SDValue LHS = N->getOperand(0);
10439   SDValue RHS = N->getOperand(1);
10440 
10441   // sub x, zext (setcc) => subcarry x, 0, setcc
10442   // sub x, sext (setcc) => addcarry x, 0, setcc
10443   unsigned Opc = RHS.getOpcode();
10444   switch (Opc) {
10445   default: break;
10446   case ISD::ZERO_EXTEND:
10447   case ISD::SIGN_EXTEND:
10448   case ISD::ANY_EXTEND: {
10449     auto Cond = RHS.getOperand(0);
10450     // If this won't be a real VOPC output, we would still need to insert an
10451     // extra instruction anyway.
10452     if (!isBoolSGPR(Cond))
10453       break;
10454     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10455     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10456     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10457     return DAG.getNode(Opc, SL, VTList, Args);
10458   }
10459   }
10460 
10461   if (LHS.getOpcode() == ISD::SUBCARRY) {
10462     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10463     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10464     if (!C || !C->isNullValue())
10465       return SDValue();
10466     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10467     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10468   }
10469   return SDValue();
10470 }
10471 
10472 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10473   DAGCombinerInfo &DCI) const {
10474 
10475   if (N->getValueType(0) != MVT::i32)
10476     return SDValue();
10477 
10478   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10479   if (!C || C->getZExtValue() != 0)
10480     return SDValue();
10481 
10482   SelectionDAG &DAG = DCI.DAG;
10483   SDValue LHS = N->getOperand(0);
10484 
10485   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10486   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10487   unsigned LHSOpc = LHS.getOpcode();
10488   unsigned Opc = N->getOpcode();
10489   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10490       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10491     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10492     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10493   }
10494   return SDValue();
10495 }
10496 
10497 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10498                                              DAGCombinerInfo &DCI) const {
10499   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10500     return SDValue();
10501 
10502   SelectionDAG &DAG = DCI.DAG;
10503   EVT VT = N->getValueType(0);
10504 
10505   SDLoc SL(N);
10506   SDValue LHS = N->getOperand(0);
10507   SDValue RHS = N->getOperand(1);
10508 
10509   // These should really be instruction patterns, but writing patterns with
10510   // source modiifiers is a pain.
10511 
10512   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10513   if (LHS.getOpcode() == ISD::FADD) {
10514     SDValue A = LHS.getOperand(0);
10515     if (A == LHS.getOperand(1)) {
10516       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10517       if (FusedOp != 0) {
10518         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10519         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10520       }
10521     }
10522   }
10523 
10524   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10525   if (RHS.getOpcode() == ISD::FADD) {
10526     SDValue A = RHS.getOperand(0);
10527     if (A == RHS.getOperand(1)) {
10528       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10529       if (FusedOp != 0) {
10530         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10531         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10532       }
10533     }
10534   }
10535 
10536   return SDValue();
10537 }
10538 
10539 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10540                                              DAGCombinerInfo &DCI) const {
10541   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10542     return SDValue();
10543 
10544   SelectionDAG &DAG = DCI.DAG;
10545   SDLoc SL(N);
10546   EVT VT = N->getValueType(0);
10547   assert(!VT.isVector());
10548 
10549   // Try to get the fneg to fold into the source modifier. This undoes generic
10550   // DAG combines and folds them into the mad.
10551   //
10552   // Only do this if we are not trying to support denormals. v_mad_f32 does
10553   // not support denormals ever.
10554   SDValue LHS = N->getOperand(0);
10555   SDValue RHS = N->getOperand(1);
10556   if (LHS.getOpcode() == ISD::FADD) {
10557     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10558     SDValue A = LHS.getOperand(0);
10559     if (A == LHS.getOperand(1)) {
10560       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10561       if (FusedOp != 0){
10562         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10563         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10564 
10565         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10566       }
10567     }
10568   }
10569 
10570   if (RHS.getOpcode() == ISD::FADD) {
10571     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10572 
10573     SDValue A = RHS.getOperand(0);
10574     if (A == RHS.getOperand(1)) {
10575       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10576       if (FusedOp != 0){
10577         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10578         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10579       }
10580     }
10581   }
10582 
10583   return SDValue();
10584 }
10585 
10586 SDValue SITargetLowering::performFMACombine(SDNode *N,
10587                                             DAGCombinerInfo &DCI) const {
10588   SelectionDAG &DAG = DCI.DAG;
10589   EVT VT = N->getValueType(0);
10590   SDLoc SL(N);
10591 
10592   if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
10593     return SDValue();
10594 
10595   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10596   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10597   SDValue Op1 = N->getOperand(0);
10598   SDValue Op2 = N->getOperand(1);
10599   SDValue FMA = N->getOperand(2);
10600 
10601   if (FMA.getOpcode() != ISD::FMA ||
10602       Op1.getOpcode() != ISD::FP_EXTEND ||
10603       Op2.getOpcode() != ISD::FP_EXTEND)
10604     return SDValue();
10605 
10606   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10607   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10608   // is sufficient to allow generaing fdot2.
10609   const TargetOptions &Options = DAG.getTarget().Options;
10610   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10611       (N->getFlags().hasAllowContract() &&
10612        FMA->getFlags().hasAllowContract())) {
10613     Op1 = Op1.getOperand(0);
10614     Op2 = Op2.getOperand(0);
10615     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10616         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10617       return SDValue();
10618 
10619     SDValue Vec1 = Op1.getOperand(0);
10620     SDValue Idx1 = Op1.getOperand(1);
10621     SDValue Vec2 = Op2.getOperand(0);
10622 
10623     SDValue FMAOp1 = FMA.getOperand(0);
10624     SDValue FMAOp2 = FMA.getOperand(1);
10625     SDValue FMAAcc = FMA.getOperand(2);
10626 
10627     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10628         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10629       return SDValue();
10630 
10631     FMAOp1 = FMAOp1.getOperand(0);
10632     FMAOp2 = FMAOp2.getOperand(0);
10633     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10634         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10635       return SDValue();
10636 
10637     SDValue Vec3 = FMAOp1.getOperand(0);
10638     SDValue Vec4 = FMAOp2.getOperand(0);
10639     SDValue Idx2 = FMAOp1.getOperand(1);
10640 
10641     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10642         // Idx1 and Idx2 cannot be the same.
10643         Idx1 == Idx2)
10644       return SDValue();
10645 
10646     if (Vec1 == Vec2 || Vec3 == Vec4)
10647       return SDValue();
10648 
10649     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10650       return SDValue();
10651 
10652     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10653         (Vec1 == Vec4 && Vec2 == Vec3)) {
10654       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10655                          DAG.getTargetConstant(0, SL, MVT::i1));
10656     }
10657   }
10658   return SDValue();
10659 }
10660 
10661 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10662                                               DAGCombinerInfo &DCI) const {
10663   SelectionDAG &DAG = DCI.DAG;
10664   SDLoc SL(N);
10665 
10666   SDValue LHS = N->getOperand(0);
10667   SDValue RHS = N->getOperand(1);
10668   EVT VT = LHS.getValueType();
10669   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10670 
10671   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10672   if (!CRHS) {
10673     CRHS = dyn_cast<ConstantSDNode>(LHS);
10674     if (CRHS) {
10675       std::swap(LHS, RHS);
10676       CC = getSetCCSwappedOperands(CC);
10677     }
10678   }
10679 
10680   if (CRHS) {
10681     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10682         isBoolSGPR(LHS.getOperand(0))) {
10683       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10684       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10685       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10686       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10687       if ((CRHS->isAllOnesValue() &&
10688            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10689           (CRHS->isNullValue() &&
10690            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10691         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10692                            DAG.getConstant(-1, SL, MVT::i1));
10693       if ((CRHS->isAllOnesValue() &&
10694            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10695           (CRHS->isNullValue() &&
10696            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10697         return LHS.getOperand(0);
10698     }
10699 
10700     uint64_t CRHSVal = CRHS->getZExtValue();
10701     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10702         LHS.getOpcode() == ISD::SELECT &&
10703         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10704         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10705         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10706         isBoolSGPR(LHS.getOperand(0))) {
10707       // Given CT != FT:
10708       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10709       // setcc (select cc, CT, CF), CF, ne => cc
10710       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10711       // setcc (select cc, CT, CF), CT, eq => cc
10712       uint64_t CT = LHS.getConstantOperandVal(1);
10713       uint64_t CF = LHS.getConstantOperandVal(2);
10714 
10715       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10716           (CT == CRHSVal && CC == ISD::SETNE))
10717         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10718                            DAG.getConstant(-1, SL, MVT::i1));
10719       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10720           (CT == CRHSVal && CC == ISD::SETEQ))
10721         return LHS.getOperand(0);
10722     }
10723   }
10724 
10725   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10726                                            VT != MVT::f16))
10727     return SDValue();
10728 
10729   // Match isinf/isfinite pattern
10730   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10731   // (fcmp one (fabs x), inf) -> (fp_class x,
10732   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10733   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10734     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10735     if (!CRHS)
10736       return SDValue();
10737 
10738     const APFloat &APF = CRHS->getValueAPF();
10739     if (APF.isInfinity() && !APF.isNegative()) {
10740       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10741                                  SIInstrFlags::N_INFINITY;
10742       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10743                                     SIInstrFlags::P_ZERO |
10744                                     SIInstrFlags::N_NORMAL |
10745                                     SIInstrFlags::P_NORMAL |
10746                                     SIInstrFlags::N_SUBNORMAL |
10747                                     SIInstrFlags::P_SUBNORMAL;
10748       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10749       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10750                          DAG.getConstant(Mask, SL, MVT::i32));
10751     }
10752   }
10753 
10754   return SDValue();
10755 }
10756 
10757 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10758                                                      DAGCombinerInfo &DCI) const {
10759   SelectionDAG &DAG = DCI.DAG;
10760   SDLoc SL(N);
10761   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10762 
10763   SDValue Src = N->getOperand(0);
10764   SDValue Shift = N->getOperand(0);
10765 
10766   // TODO: Extend type shouldn't matter (assuming legal types).
10767   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10768     Shift = Shift.getOperand(0);
10769 
10770   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10771     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10772     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10773     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10774     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10775     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10776     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10777       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
10778                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10779 
10780       unsigned ShiftOffset = 8 * Offset;
10781       if (Shift.getOpcode() == ISD::SHL)
10782         ShiftOffset -= C->getZExtValue();
10783       else
10784         ShiftOffset += C->getZExtValue();
10785 
10786       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10787         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10788                            MVT::f32, Shift);
10789       }
10790     }
10791   }
10792 
10793   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10794   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10795   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10796     // We simplified Src. If this node is not dead, visit it again so it is
10797     // folded properly.
10798     if (N->getOpcode() != ISD::DELETED_NODE)
10799       DCI.AddToWorklist(N);
10800     return SDValue(N, 0);
10801   }
10802 
10803   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10804   if (SDValue DemandedSrc =
10805           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10806     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10807 
10808   return SDValue();
10809 }
10810 
10811 SDValue SITargetLowering::performClampCombine(SDNode *N,
10812                                               DAGCombinerInfo &DCI) const {
10813   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10814   if (!CSrc)
10815     return SDValue();
10816 
10817   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10818   const APFloat &F = CSrc->getValueAPF();
10819   APFloat Zero = APFloat::getZero(F.getSemantics());
10820   if (F < Zero ||
10821       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10822     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10823   }
10824 
10825   APFloat One(F.getSemantics(), "1.0");
10826   if (F > One)
10827     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10828 
10829   return SDValue(CSrc, 0);
10830 }
10831 
10832 
10833 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10834                                             DAGCombinerInfo &DCI) const {
10835   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10836     return SDValue();
10837   switch (N->getOpcode()) {
10838   case ISD::ADD:
10839     return performAddCombine(N, DCI);
10840   case ISD::SUB:
10841     return performSubCombine(N, DCI);
10842   case ISD::ADDCARRY:
10843   case ISD::SUBCARRY:
10844     return performAddCarrySubCarryCombine(N, DCI);
10845   case ISD::FADD:
10846     return performFAddCombine(N, DCI);
10847   case ISD::FSUB:
10848     return performFSubCombine(N, DCI);
10849   case ISD::SETCC:
10850     return performSetCCCombine(N, DCI);
10851   case ISD::FMAXNUM:
10852   case ISD::FMINNUM:
10853   case ISD::FMAXNUM_IEEE:
10854   case ISD::FMINNUM_IEEE:
10855   case ISD::SMAX:
10856   case ISD::SMIN:
10857   case ISD::UMAX:
10858   case ISD::UMIN:
10859   case AMDGPUISD::FMIN_LEGACY:
10860   case AMDGPUISD::FMAX_LEGACY:
10861     return performMinMaxCombine(N, DCI);
10862   case ISD::FMA:
10863     return performFMACombine(N, DCI);
10864   case ISD::AND:
10865     return performAndCombine(N, DCI);
10866   case ISD::OR:
10867     return performOrCombine(N, DCI);
10868   case ISD::XOR:
10869     return performXorCombine(N, DCI);
10870   case ISD::ZERO_EXTEND:
10871     return performZeroExtendCombine(N, DCI);
10872   case ISD::SIGN_EXTEND_INREG:
10873     return performSignExtendInRegCombine(N , DCI);
10874   case AMDGPUISD::FP_CLASS:
10875     return performClassCombine(N, DCI);
10876   case ISD::FCANONICALIZE:
10877     return performFCanonicalizeCombine(N, DCI);
10878   case AMDGPUISD::RCP:
10879     return performRcpCombine(N, DCI);
10880   case AMDGPUISD::FRACT:
10881   case AMDGPUISD::RSQ:
10882   case AMDGPUISD::RCP_LEGACY:
10883   case AMDGPUISD::RCP_IFLAG:
10884   case AMDGPUISD::RSQ_CLAMP:
10885   case AMDGPUISD::LDEXP: {
10886     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10887     SDValue Src = N->getOperand(0);
10888     if (Src.isUndef())
10889       return Src;
10890     break;
10891   }
10892   case ISD::SINT_TO_FP:
10893   case ISD::UINT_TO_FP:
10894     return performUCharToFloatCombine(N, DCI);
10895   case AMDGPUISD::CVT_F32_UBYTE0:
10896   case AMDGPUISD::CVT_F32_UBYTE1:
10897   case AMDGPUISD::CVT_F32_UBYTE2:
10898   case AMDGPUISD::CVT_F32_UBYTE3:
10899     return performCvtF32UByteNCombine(N, DCI);
10900   case AMDGPUISD::FMED3:
10901     return performFMed3Combine(N, DCI);
10902   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10903     return performCvtPkRTZCombine(N, DCI);
10904   case AMDGPUISD::CLAMP:
10905     return performClampCombine(N, DCI);
10906   case ISD::SCALAR_TO_VECTOR: {
10907     SelectionDAG &DAG = DCI.DAG;
10908     EVT VT = N->getValueType(0);
10909 
10910     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10911     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10912       SDLoc SL(N);
10913       SDValue Src = N->getOperand(0);
10914       EVT EltVT = Src.getValueType();
10915       if (EltVT == MVT::f16)
10916         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10917 
10918       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10919       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10920     }
10921 
10922     break;
10923   }
10924   case ISD::EXTRACT_VECTOR_ELT:
10925     return performExtractVectorEltCombine(N, DCI);
10926   case ISD::INSERT_VECTOR_ELT:
10927     return performInsertVectorEltCombine(N, DCI);
10928   case ISD::LOAD: {
10929     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10930       return Widended;
10931     LLVM_FALLTHROUGH;
10932   }
10933   default: {
10934     if (!DCI.isBeforeLegalize()) {
10935       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
10936         return performMemSDNodeCombine(MemNode, DCI);
10937     }
10938 
10939     break;
10940   }
10941   }
10942 
10943   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10944 }
10945 
10946 /// Helper function for adjustWritemask
10947 static unsigned SubIdx2Lane(unsigned Idx) {
10948   switch (Idx) {
10949   default: return ~0u;
10950   case AMDGPU::sub0: return 0;
10951   case AMDGPU::sub1: return 1;
10952   case AMDGPU::sub2: return 2;
10953   case AMDGPU::sub3: return 3;
10954   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10955   }
10956 }
10957 
10958 /// Adjust the writemask of MIMG instructions
10959 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10960                                           SelectionDAG &DAG) const {
10961   unsigned Opcode = Node->getMachineOpcode();
10962 
10963   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10964   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10965   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10966     return Node; // not implemented for D16
10967 
10968   SDNode *Users[5] = { nullptr };
10969   unsigned Lane = 0;
10970   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10971   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10972   unsigned NewDmask = 0;
10973   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10974   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10975   bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
10976                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10977   unsigned TFCLane = 0;
10978   bool HasChain = Node->getNumValues() > 1;
10979 
10980   if (OldDmask == 0) {
10981     // These are folded out, but on the chance it happens don't assert.
10982     return Node;
10983   }
10984 
10985   unsigned OldBitsSet = countPopulation(OldDmask);
10986   // Work out which is the TFE/LWE lane if that is enabled.
10987   if (UsesTFC) {
10988     TFCLane = OldBitsSet;
10989   }
10990 
10991   // Try to figure out the used register components
10992   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10993        I != E; ++I) {
10994 
10995     // Don't look at users of the chain.
10996     if (I.getUse().getResNo() != 0)
10997       continue;
10998 
10999     // Abort if we can't understand the usage
11000     if (!I->isMachineOpcode() ||
11001         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
11002       return Node;
11003 
11004     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
11005     // Note that subregs are packed, i.e. Lane==0 is the first bit set
11006     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
11007     // set, etc.
11008     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
11009     if (Lane == ~0u)
11010       return Node;
11011 
11012     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
11013     if (UsesTFC && Lane == TFCLane) {
11014       Users[Lane] = *I;
11015     } else {
11016       // Set which texture component corresponds to the lane.
11017       unsigned Comp;
11018       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
11019         Comp = countTrailingZeros(Dmask);
11020         Dmask &= ~(1 << Comp);
11021       }
11022 
11023       // Abort if we have more than one user per component.
11024       if (Users[Lane])
11025         return Node;
11026 
11027       Users[Lane] = *I;
11028       NewDmask |= 1 << Comp;
11029     }
11030   }
11031 
11032   // Don't allow 0 dmask, as hardware assumes one channel enabled.
11033   bool NoChannels = !NewDmask;
11034   if (NoChannels) {
11035     if (!UsesTFC) {
11036       // No uses of the result and not using TFC. Then do nothing.
11037       return Node;
11038     }
11039     // If the original dmask has one channel - then nothing to do
11040     if (OldBitsSet == 1)
11041       return Node;
11042     // Use an arbitrary dmask - required for the instruction to work
11043     NewDmask = 1;
11044   }
11045   // Abort if there's no change
11046   if (NewDmask == OldDmask)
11047     return Node;
11048 
11049   unsigned BitsSet = countPopulation(NewDmask);
11050 
11051   // Check for TFE or LWE - increase the number of channels by one to account
11052   // for the extra return value
11053   // This will need adjustment for D16 if this is also included in
11054   // adjustWriteMask (this function) but at present D16 are excluded.
11055   unsigned NewChannels = BitsSet + UsesTFC;
11056 
11057   int NewOpcode =
11058       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
11059   assert(NewOpcode != -1 &&
11060          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
11061          "failed to find equivalent MIMG op");
11062 
11063   // Adjust the writemask in the node
11064   SmallVector<SDValue, 12> Ops;
11065   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
11066   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
11067   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11068 
11069   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11070 
11071   MVT ResultVT = NewChannels == 1 ?
11072     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11073                            NewChannels == 5 ? 8 : NewChannels);
11074   SDVTList NewVTList = HasChain ?
11075     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11076 
11077 
11078   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11079                                               NewVTList, Ops);
11080 
11081   if (HasChain) {
11082     // Update chain.
11083     DAG.setNodeMemRefs(NewNode, Node->memoperands());
11084     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11085   }
11086 
11087   if (NewChannels == 1) {
11088     assert(Node->hasNUsesOfValue(1, 0));
11089     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11090                                       SDLoc(Node), Users[Lane]->getValueType(0),
11091                                       SDValue(NewNode, 0));
11092     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11093     return nullptr;
11094   }
11095 
11096   // Update the users of the node with the new indices
11097   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11098     SDNode *User = Users[i];
11099     if (!User) {
11100       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11101       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11102       if (i || !NoChannels)
11103         continue;
11104     } else {
11105       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11106       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11107     }
11108 
11109     switch (Idx) {
11110     default: break;
11111     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11112     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11113     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11114     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11115     }
11116   }
11117 
11118   DAG.RemoveDeadNode(Node);
11119   return nullptr;
11120 }
11121 
11122 static bool isFrameIndexOp(SDValue Op) {
11123   if (Op.getOpcode() == ISD::AssertZext)
11124     Op = Op.getOperand(0);
11125 
11126   return isa<FrameIndexSDNode>(Op);
11127 }
11128 
11129 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11130 /// with frame index operands.
11131 /// LLVM assumes that inputs are to these instructions are registers.
11132 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11133                                                         SelectionDAG &DAG) const {
11134   if (Node->getOpcode() == ISD::CopyToReg) {
11135     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11136     SDValue SrcVal = Node->getOperand(2);
11137 
11138     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11139     // to try understanding copies to physical registers.
11140     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11141       SDLoc SL(Node);
11142       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11143       SDValue VReg = DAG.getRegister(
11144         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11145 
11146       SDNode *Glued = Node->getGluedNode();
11147       SDValue ToVReg
11148         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11149                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11150       SDValue ToResultReg
11151         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11152                            VReg, ToVReg.getValue(1));
11153       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11154       DAG.RemoveDeadNode(Node);
11155       return ToResultReg.getNode();
11156     }
11157   }
11158 
11159   SmallVector<SDValue, 8> Ops;
11160   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11161     if (!isFrameIndexOp(Node->getOperand(i))) {
11162       Ops.push_back(Node->getOperand(i));
11163       continue;
11164     }
11165 
11166     SDLoc DL(Node);
11167     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11168                                      Node->getOperand(i).getValueType(),
11169                                      Node->getOperand(i)), 0));
11170   }
11171 
11172   return DAG.UpdateNodeOperands(Node, Ops);
11173 }
11174 
11175 /// Fold the instructions after selecting them.
11176 /// Returns null if users were already updated.
11177 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11178                                           SelectionDAG &DAG) const {
11179   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11180   unsigned Opcode = Node->getMachineOpcode();
11181 
11182   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11183       !TII->isGather4(Opcode) &&
11184       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11185     return adjustWritemask(Node, DAG);
11186   }
11187 
11188   if (Opcode == AMDGPU::INSERT_SUBREG ||
11189       Opcode == AMDGPU::REG_SEQUENCE) {
11190     legalizeTargetIndependentNode(Node, DAG);
11191     return Node;
11192   }
11193 
11194   switch (Opcode) {
11195   case AMDGPU::V_DIV_SCALE_F32_e64:
11196   case AMDGPU::V_DIV_SCALE_F64_e64: {
11197     // Satisfy the operand register constraint when one of the inputs is
11198     // undefined. Ordinarily each undef value will have its own implicit_def of
11199     // a vreg, so force these to use a single register.
11200     SDValue Src0 = Node->getOperand(1);
11201     SDValue Src1 = Node->getOperand(3);
11202     SDValue Src2 = Node->getOperand(5);
11203 
11204     if ((Src0.isMachineOpcode() &&
11205          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11206         (Src0 == Src1 || Src0 == Src2))
11207       break;
11208 
11209     MVT VT = Src0.getValueType().getSimpleVT();
11210     const TargetRegisterClass *RC =
11211         getRegClassFor(VT, Src0.getNode()->isDivergent());
11212 
11213     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11214     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11215 
11216     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11217                                       UndefReg, Src0, SDValue());
11218 
11219     // src0 must be the same register as src1 or src2, even if the value is
11220     // undefined, so make sure we don't violate this constraint.
11221     if (Src0.isMachineOpcode() &&
11222         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11223       if (Src1.isMachineOpcode() &&
11224           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11225         Src0 = Src1;
11226       else if (Src2.isMachineOpcode() &&
11227                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11228         Src0 = Src2;
11229       else {
11230         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11231         Src0 = UndefReg;
11232         Src1 = UndefReg;
11233       }
11234     } else
11235       break;
11236 
11237     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11238     Ops[1] = Src0;
11239     Ops[3] = Src1;
11240     Ops[5] = Src2;
11241     Ops.push_back(ImpDef.getValue(1));
11242     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11243   }
11244   default:
11245     break;
11246   }
11247 
11248   return Node;
11249 }
11250 
11251 // Any MIMG instructions that use tfe or lwe require an initialization of the
11252 // result register that will be written in the case of a memory access failure.
11253 // The required code is also added to tie this init code to the result of the
11254 // img instruction.
11255 void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
11256   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11257   const SIRegisterInfo &TRI = TII->getRegisterInfo();
11258   MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11259   MachineBasicBlock &MBB = *MI.getParent();
11260 
11261   MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
11262   MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
11263   MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
11264 
11265   if (!TFE && !LWE) // intersect_ray
11266     return;
11267 
11268   unsigned TFEVal = TFE ? TFE->getImm() : 0;
11269   unsigned LWEVal = LWE->getImm();
11270   unsigned D16Val = D16 ? D16->getImm() : 0;
11271 
11272   if (!TFEVal && !LWEVal)
11273     return;
11274 
11275   // At least one of TFE or LWE are non-zero
11276   // We have to insert a suitable initialization of the result value and
11277   // tie this to the dest of the image instruction.
11278 
11279   const DebugLoc &DL = MI.getDebugLoc();
11280 
11281   int DstIdx =
11282       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
11283 
11284   // Calculate which dword we have to initialize to 0.
11285   MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
11286 
11287   // check that dmask operand is found.
11288   assert(MO_Dmask && "Expected dmask operand in instruction");
11289 
11290   unsigned dmask = MO_Dmask->getImm();
11291   // Determine the number of active lanes taking into account the
11292   // Gather4 special case
11293   unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask);
11294 
11295   bool Packed = !Subtarget->hasUnpackedD16VMem();
11296 
11297   unsigned InitIdx =
11298       D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
11299 
11300   // Abandon attempt if the dst size isn't large enough
11301   // - this is in fact an error but this is picked up elsewhere and
11302   // reported correctly.
11303   uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
11304   if (DstSize < InitIdx)
11305     return;
11306 
11307   // Create a register for the intialization value.
11308   Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11309   unsigned NewDst = 0; // Final initialized value will be in here
11310 
11311   // If PRTStrictNull feature is enabled (the default) then initialize
11312   // all the result registers to 0, otherwise just the error indication
11313   // register (VGPRn+1)
11314   unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
11315   unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
11316 
11317   BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
11318   for (; SizeLeft; SizeLeft--, CurrIdx++) {
11319     NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11320     // Initialize dword
11321     Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
11322     BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
11323       .addImm(0);
11324     // Insert into the super-reg
11325     BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
11326       .addReg(PrevDst)
11327       .addReg(SubReg)
11328       .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
11329 
11330     PrevDst = NewDst;
11331   }
11332 
11333   // Add as an implicit operand
11334   MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
11335 
11336   // Tie the just added implicit operand to the dst
11337   MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
11338 }
11339 
11340 /// Assign the register class depending on the number of
11341 /// bits set in the writemask
11342 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11343                                                      SDNode *Node) const {
11344   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11345 
11346   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11347 
11348   if (TII->isVOP3(MI.getOpcode())) {
11349     // Make sure constant bus requirements are respected.
11350     TII->legalizeOperandsVOP3(MRI, MI);
11351 
11352     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11353     // This saves a chain-copy of registers and better ballance register
11354     // use between vgpr and agpr as agpr tuples tend to be big.
11355     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
11356       unsigned Opc = MI.getOpcode();
11357       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11358       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11359                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11360         if (I == -1)
11361           break;
11362         MachineOperand &Op = MI.getOperand(I);
11363         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
11364              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
11365             !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg()))
11366           continue;
11367         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11368         if (!Src || !Src->isCopy() ||
11369             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11370           continue;
11371         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11372         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11373         // All uses of agpr64 and agpr32 can also accept vgpr except for
11374         // v_accvgpr_read, but we do not produce agpr reads during selection,
11375         // so no use checks are needed.
11376         MRI.setRegClass(Op.getReg(), NewRC);
11377       }
11378     }
11379 
11380     return;
11381   }
11382 
11383   // Replace unused atomics with the no return version.
11384   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11385   if (NoRetAtomicOp != -1) {
11386     if (!Node->hasAnyUseOfValue(0)) {
11387       int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
11388                                                AMDGPU::OpName::cpol);
11389       if (CPolIdx != -1) {
11390         MachineOperand &CPol = MI.getOperand(CPolIdx);
11391         CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC);
11392       }
11393       MI.RemoveOperand(0);
11394       MI.setDesc(TII->get(NoRetAtomicOp));
11395       return;
11396     }
11397 
11398     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11399     // instruction, because the return type of these instructions is a vec2 of
11400     // the memory type, so it can be tied to the input operand.
11401     // This means these instructions always have a use, so we need to add a
11402     // special case to check if the atomic has only one extract_subreg use,
11403     // which itself has no uses.
11404     if ((Node->hasNUsesOfValue(1, 0) &&
11405          Node->use_begin()->isMachineOpcode() &&
11406          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11407          !Node->use_begin()->hasAnyUseOfValue(0))) {
11408       Register Def = MI.getOperand(0).getReg();
11409 
11410       // Change this into a noret atomic.
11411       MI.setDesc(TII->get(NoRetAtomicOp));
11412       MI.RemoveOperand(0);
11413 
11414       // If we only remove the def operand from the atomic instruction, the
11415       // extract_subreg will be left with a use of a vreg without a def.
11416       // So we need to insert an implicit_def to avoid machine verifier
11417       // errors.
11418       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11419               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11420     }
11421     return;
11422   }
11423 
11424   if (TII->isMIMG(MI) && !MI.mayStore())
11425     AddIMGInit(MI);
11426 }
11427 
11428 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11429                               uint64_t Val) {
11430   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11431   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11432 }
11433 
11434 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11435                                                 const SDLoc &DL,
11436                                                 SDValue Ptr) const {
11437   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11438 
11439   // Build the half of the subregister with the constants before building the
11440   // full 128-bit register. If we are building multiple resource descriptors,
11441   // this will allow CSEing of the 2-component register.
11442   const SDValue Ops0[] = {
11443     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11444     buildSMovImm32(DAG, DL, 0),
11445     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11446     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11447     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11448   };
11449 
11450   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11451                                                 MVT::v2i32, Ops0), 0);
11452 
11453   // Combine the constants and the pointer.
11454   const SDValue Ops1[] = {
11455     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11456     Ptr,
11457     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11458     SubRegHi,
11459     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11460   };
11461 
11462   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11463 }
11464 
11465 /// Return a resource descriptor with the 'Add TID' bit enabled
11466 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11467 ///        of the resource descriptor) to create an offset, which is added to
11468 ///        the resource pointer.
11469 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11470                                            SDValue Ptr, uint32_t RsrcDword1,
11471                                            uint64_t RsrcDword2And3) const {
11472   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11473   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11474   if (RsrcDword1) {
11475     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11476                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11477                     0);
11478   }
11479 
11480   SDValue DataLo = buildSMovImm32(DAG, DL,
11481                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11482   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11483 
11484   const SDValue Ops[] = {
11485     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11486     PtrLo,
11487     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11488     PtrHi,
11489     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11490     DataLo,
11491     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11492     DataHi,
11493     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11494   };
11495 
11496   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11497 }
11498 
11499 //===----------------------------------------------------------------------===//
11500 //                         SI Inline Assembly Support
11501 //===----------------------------------------------------------------------===//
11502 
11503 std::pair<unsigned, const TargetRegisterClass *>
11504 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
11505                                                StringRef Constraint,
11506                                                MVT VT) const {
11507   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
11508 
11509   const TargetRegisterClass *RC = nullptr;
11510   if (Constraint.size() == 1) {
11511     const unsigned BitWidth = VT.getSizeInBits();
11512     switch (Constraint[0]) {
11513     default:
11514       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11515     case 's':
11516     case 'r':
11517       switch (BitWidth) {
11518       case 16:
11519         RC = &AMDGPU::SReg_32RegClass;
11520         break;
11521       case 64:
11522         RC = &AMDGPU::SGPR_64RegClass;
11523         break;
11524       default:
11525         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11526         if (!RC)
11527           return std::make_pair(0U, nullptr);
11528         break;
11529       }
11530       break;
11531     case 'v':
11532       switch (BitWidth) {
11533       case 16:
11534         RC = &AMDGPU::VGPR_32RegClass;
11535         break;
11536       default:
11537         RC = TRI->getVGPRClassForBitWidth(BitWidth);
11538         if (!RC)
11539           return std::make_pair(0U, nullptr);
11540         break;
11541       }
11542       break;
11543     case 'a':
11544       if (!Subtarget->hasMAIInsts())
11545         break;
11546       switch (BitWidth) {
11547       case 16:
11548         RC = &AMDGPU::AGPR_32RegClass;
11549         break;
11550       default:
11551         RC = TRI->getAGPRClassForBitWidth(BitWidth);
11552         if (!RC)
11553           return std::make_pair(0U, nullptr);
11554         break;
11555       }
11556       break;
11557     }
11558     // We actually support i128, i16 and f16 as inline parameters
11559     // even if they are not reported as legal
11560     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11561                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11562       return std::make_pair(0U, RC);
11563   }
11564 
11565   if (Constraint.size() > 1) {
11566     if (Constraint[1] == 'v') {
11567       RC = &AMDGPU::VGPR_32RegClass;
11568     } else if (Constraint[1] == 's') {
11569       RC = &AMDGPU::SGPR_32RegClass;
11570     } else if (Constraint[1] == 'a') {
11571       RC = &AMDGPU::AGPR_32RegClass;
11572     }
11573 
11574     if (RC) {
11575       uint32_t Idx;
11576       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
11577       if (!Failed && Idx < RC->getNumRegs())
11578         return std::make_pair(RC->getRegister(Idx), RC);
11579     }
11580   }
11581 
11582   // FIXME: Returns VS_32 for physical SGPR constraints
11583   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11584 }
11585 
11586 static bool isImmConstraint(StringRef Constraint) {
11587   if (Constraint.size() == 1) {
11588     switch (Constraint[0]) {
11589     default: break;
11590     case 'I':
11591     case 'J':
11592     case 'A':
11593     case 'B':
11594     case 'C':
11595       return true;
11596     }
11597   } else if (Constraint == "DA" ||
11598              Constraint == "DB") {
11599     return true;
11600   }
11601   return false;
11602 }
11603 
11604 SITargetLowering::ConstraintType
11605 SITargetLowering::getConstraintType(StringRef Constraint) const {
11606   if (Constraint.size() == 1) {
11607     switch (Constraint[0]) {
11608     default: break;
11609     case 's':
11610     case 'v':
11611     case 'a':
11612       return C_RegisterClass;
11613     }
11614   }
11615   if (isImmConstraint(Constraint)) {
11616     return C_Other;
11617   }
11618   return TargetLowering::getConstraintType(Constraint);
11619 }
11620 
11621 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11622   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11623     Val = Val & maskTrailingOnes<uint64_t>(Size);
11624   }
11625   return Val;
11626 }
11627 
11628 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11629                                                     std::string &Constraint,
11630                                                     std::vector<SDValue> &Ops,
11631                                                     SelectionDAG &DAG) const {
11632   if (isImmConstraint(Constraint)) {
11633     uint64_t Val;
11634     if (getAsmOperandConstVal(Op, Val) &&
11635         checkAsmConstraintVal(Op, Constraint, Val)) {
11636       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11637       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11638     }
11639   } else {
11640     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11641   }
11642 }
11643 
11644 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11645   unsigned Size = Op.getScalarValueSizeInBits();
11646   if (Size > 64)
11647     return false;
11648 
11649   if (Size == 16 && !Subtarget->has16BitInsts())
11650     return false;
11651 
11652   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11653     Val = C->getSExtValue();
11654     return true;
11655   }
11656   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11657     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11658     return true;
11659   }
11660   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11661     if (Size != 16 || Op.getNumOperands() != 2)
11662       return false;
11663     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11664       return false;
11665     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11666       Val = C->getSExtValue();
11667       return true;
11668     }
11669     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11670       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11671       return true;
11672     }
11673   }
11674 
11675   return false;
11676 }
11677 
11678 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11679                                              const std::string &Constraint,
11680                                              uint64_t Val) const {
11681   if (Constraint.size() == 1) {
11682     switch (Constraint[0]) {
11683     case 'I':
11684       return AMDGPU::isInlinableIntLiteral(Val);
11685     case 'J':
11686       return isInt<16>(Val);
11687     case 'A':
11688       return checkAsmConstraintValA(Op, Val);
11689     case 'B':
11690       return isInt<32>(Val);
11691     case 'C':
11692       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11693              AMDGPU::isInlinableIntLiteral(Val);
11694     default:
11695       break;
11696     }
11697   } else if (Constraint.size() == 2) {
11698     if (Constraint == "DA") {
11699       int64_t HiBits = static_cast<int32_t>(Val >> 32);
11700       int64_t LoBits = static_cast<int32_t>(Val);
11701       return checkAsmConstraintValA(Op, HiBits, 32) &&
11702              checkAsmConstraintValA(Op, LoBits, 32);
11703     }
11704     if (Constraint == "DB") {
11705       return true;
11706     }
11707   }
11708   llvm_unreachable("Invalid asm constraint");
11709 }
11710 
11711 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
11712                                               uint64_t Val,
11713                                               unsigned MaxSize) const {
11714   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
11715   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11716   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11717       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11718       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11719     return true;
11720   }
11721   return false;
11722 }
11723 
11724 static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
11725   switch (UnalignedClassID) {
11726   case AMDGPU::VReg_64RegClassID:
11727     return AMDGPU::VReg_64_Align2RegClassID;
11728   case AMDGPU::VReg_96RegClassID:
11729     return AMDGPU::VReg_96_Align2RegClassID;
11730   case AMDGPU::VReg_128RegClassID:
11731     return AMDGPU::VReg_128_Align2RegClassID;
11732   case AMDGPU::VReg_160RegClassID:
11733     return AMDGPU::VReg_160_Align2RegClassID;
11734   case AMDGPU::VReg_192RegClassID:
11735     return AMDGPU::VReg_192_Align2RegClassID;
11736   case AMDGPU::VReg_256RegClassID:
11737     return AMDGPU::VReg_256_Align2RegClassID;
11738   case AMDGPU::VReg_512RegClassID:
11739     return AMDGPU::VReg_512_Align2RegClassID;
11740   case AMDGPU::VReg_1024RegClassID:
11741     return AMDGPU::VReg_1024_Align2RegClassID;
11742   case AMDGPU::AReg_64RegClassID:
11743     return AMDGPU::AReg_64_Align2RegClassID;
11744   case AMDGPU::AReg_96RegClassID:
11745     return AMDGPU::AReg_96_Align2RegClassID;
11746   case AMDGPU::AReg_128RegClassID:
11747     return AMDGPU::AReg_128_Align2RegClassID;
11748   case AMDGPU::AReg_160RegClassID:
11749     return AMDGPU::AReg_160_Align2RegClassID;
11750   case AMDGPU::AReg_192RegClassID:
11751     return AMDGPU::AReg_192_Align2RegClassID;
11752   case AMDGPU::AReg_256RegClassID:
11753     return AMDGPU::AReg_256_Align2RegClassID;
11754   case AMDGPU::AReg_512RegClassID:
11755     return AMDGPU::AReg_512_Align2RegClassID;
11756   case AMDGPU::AReg_1024RegClassID:
11757     return AMDGPU::AReg_1024_Align2RegClassID;
11758   default:
11759     return -1;
11760   }
11761 }
11762 
11763 // Figure out which registers should be reserved for stack access. Only after
11764 // the function is legalized do we know all of the non-spill stack objects or if
11765 // calls are present.
11766 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
11767   MachineRegisterInfo &MRI = MF.getRegInfo();
11768   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11769   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
11770   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11771   const SIInstrInfo *TII = ST.getInstrInfo();
11772 
11773   if (Info->isEntryFunction()) {
11774     // Callable functions have fixed registers used for stack access.
11775     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
11776   }
11777 
11778   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
11779                              Info->getStackPtrOffsetReg()));
11780   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
11781     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
11782 
11783   // We need to worry about replacing the default register with itself in case
11784   // of MIR testcases missing the MFI.
11785   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
11786     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
11787 
11788   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
11789     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
11790 
11791   Info->limitOccupancy(MF);
11792 
11793   if (ST.isWave32() && !MF.empty()) {
11794     for (auto &MBB : MF) {
11795       for (auto &MI : MBB) {
11796         TII->fixImplicitOperands(MI);
11797       }
11798     }
11799   }
11800 
11801   // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
11802   // classes if required. Ideally the register class constraints would differ
11803   // per-subtarget, but there's no easy way to achieve that right now. This is
11804   // not a problem for VGPRs because the correctly aligned VGPR class is implied
11805   // from using them as the register class for legal types.
11806   if (ST.needsAlignedVGPRs()) {
11807     for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
11808       const Register Reg = Register::index2VirtReg(I);
11809       const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
11810       if (!RC)
11811         continue;
11812       int NewClassID = getAlignedAGPRClassID(RC->getID());
11813       if (NewClassID != -1)
11814         MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
11815     }
11816   }
11817 
11818   TargetLoweringBase::finalizeLowering(MF);
11819 
11820   // Allocate a VGPR for future SGPR Spill if
11821   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
11822   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
11823   if (VGPRReserveforSGPRSpill && TRI->spillSGPRToVGPR() &&
11824       !Info->VGPRReservedForSGPRSpill && !Info->isEntryFunction())
11825     Info->reserveVGPRforSGPRSpills(MF);
11826 }
11827 
11828 void SITargetLowering::computeKnownBitsForFrameIndex(
11829   const int FI, KnownBits &Known, const MachineFunction &MF) const {
11830   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
11831 
11832   // Set the high bits to zero based on the maximum allowed scratch size per
11833   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
11834   // calculation won't overflow, so assume the sign bit is never set.
11835   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
11836 }
11837 
11838 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
11839                                    KnownBits &Known, unsigned Dim) {
11840   unsigned MaxValue =
11841       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
11842   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
11843 }
11844 
11845 void SITargetLowering::computeKnownBitsForTargetInstr(
11846     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
11847     const MachineRegisterInfo &MRI, unsigned Depth) const {
11848   const MachineInstr *MI = MRI.getVRegDef(R);
11849   switch (MI->getOpcode()) {
11850   case AMDGPU::G_INTRINSIC: {
11851     switch (MI->getIntrinsicID()) {
11852     case Intrinsic::amdgcn_workitem_id_x:
11853       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
11854       break;
11855     case Intrinsic::amdgcn_workitem_id_y:
11856       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
11857       break;
11858     case Intrinsic::amdgcn_workitem_id_z:
11859       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
11860       break;
11861     case Intrinsic::amdgcn_mbcnt_lo:
11862     case Intrinsic::amdgcn_mbcnt_hi: {
11863       // These return at most the wavefront size - 1.
11864       unsigned Size = MRI.getType(R).getSizeInBits();
11865       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
11866       break;
11867     }
11868     case Intrinsic::amdgcn_groupstaticsize: {
11869       // We can report everything over the maximum size as 0. We can't report
11870       // based on the actual size because we don't know if it's accurate or not
11871       // at any given point.
11872       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
11873       break;
11874     }
11875     }
11876     break;
11877   }
11878   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
11879     Known.Zero.setHighBits(24);
11880     break;
11881   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
11882     Known.Zero.setHighBits(16);
11883     break;
11884   }
11885 }
11886 
11887 Align SITargetLowering::computeKnownAlignForTargetInstr(
11888   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
11889   unsigned Depth) const {
11890   const MachineInstr *MI = MRI.getVRegDef(R);
11891   switch (MI->getOpcode()) {
11892   case AMDGPU::G_INTRINSIC:
11893   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
11894     // FIXME: Can this move to generic code? What about the case where the call
11895     // site specifies a lower alignment?
11896     Intrinsic::ID IID = MI->getIntrinsicID();
11897     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
11898     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
11899     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
11900       return *RetAlign;
11901     return Align(1);
11902   }
11903   default:
11904     return Align(1);
11905   }
11906 }
11907 
11908 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11909   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
11910   const Align CacheLineAlign = Align(64);
11911 
11912   // Pre-GFX10 target did not benefit from loop alignment
11913   if (!ML || DisableLoopAlignment ||
11914       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
11915       getSubtarget()->hasInstFwdPrefetchBug())
11916     return PrefAlign;
11917 
11918   // On GFX10 I$ is 4 x 64 bytes cache lines.
11919   // By default prefetcher keeps one cache line behind and reads two ahead.
11920   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
11921   // behind and one ahead.
11922   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
11923   // If loop fits 64 bytes it always spans no more than two cache lines and
11924   // does not need an alignment.
11925   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
11926   // Else if loop is less or equal 192 bytes we need two lines behind.
11927 
11928   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11929   const MachineBasicBlock *Header = ML->getHeader();
11930   if (Header->getAlignment() != PrefAlign)
11931     return Header->getAlignment(); // Already processed.
11932 
11933   unsigned LoopSize = 0;
11934   for (const MachineBasicBlock *MBB : ML->blocks()) {
11935     // If inner loop block is aligned assume in average half of the alignment
11936     // size to be added as nops.
11937     if (MBB != Header)
11938       LoopSize += MBB->getAlignment().value() / 2;
11939 
11940     for (const MachineInstr &MI : *MBB) {
11941       LoopSize += TII->getInstSizeInBytes(MI);
11942       if (LoopSize > 192)
11943         return PrefAlign;
11944     }
11945   }
11946 
11947   if (LoopSize <= 64)
11948     return PrefAlign;
11949 
11950   if (LoopSize <= 128)
11951     return CacheLineAlign;
11952 
11953   // If any of parent loops is surrounded by prefetch instructions do not
11954   // insert new for inner loop, which would reset parent's settings.
11955   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
11956     if (MachineBasicBlock *Exit = P->getExitBlock()) {
11957       auto I = Exit->getFirstNonDebugInstr();
11958       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
11959         return CacheLineAlign;
11960     }
11961   }
11962 
11963   MachineBasicBlock *Pre = ML->getLoopPreheader();
11964   MachineBasicBlock *Exit = ML->getExitBlock();
11965 
11966   if (Pre && Exit) {
11967     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
11968             TII->get(AMDGPU::S_INST_PREFETCH))
11969       .addImm(1); // prefetch 2 lines behind PC
11970 
11971     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
11972             TII->get(AMDGPU::S_INST_PREFETCH))
11973       .addImm(2); // prefetch 1 line behind PC
11974   }
11975 
11976   return CacheLineAlign;
11977 }
11978 
11979 LLVM_ATTRIBUTE_UNUSED
11980 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
11981   assert(N->getOpcode() == ISD::CopyFromReg);
11982   do {
11983     // Follow the chain until we find an INLINEASM node.
11984     N = N->getOperand(0).getNode();
11985     if (N->getOpcode() == ISD::INLINEASM ||
11986         N->getOpcode() == ISD::INLINEASM_BR)
11987       return true;
11988   } while (N->getOpcode() == ISD::CopyFromReg);
11989   return false;
11990 }
11991 
11992 bool SITargetLowering::isSDNodeSourceOfDivergence(
11993     const SDNode *N, FunctionLoweringInfo *FLI,
11994     LegacyDivergenceAnalysis *KDA) const {
11995   switch (N->getOpcode()) {
11996   case ISD::CopyFromReg: {
11997     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
11998     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
11999     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12000     Register Reg = R->getReg();
12001 
12002     // FIXME: Why does this need to consider isLiveIn?
12003     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
12004       return !TRI->isSGPRReg(MRI, Reg);
12005 
12006     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
12007       return KDA->isDivergent(V);
12008 
12009     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
12010     return !TRI->isSGPRReg(MRI, Reg);
12011   }
12012   case ISD::LOAD: {
12013     const LoadSDNode *L = cast<LoadSDNode>(N);
12014     unsigned AS = L->getAddressSpace();
12015     // A flat load may access private memory.
12016     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
12017   }
12018   case ISD::CALLSEQ_END:
12019     return true;
12020   case ISD::INTRINSIC_WO_CHAIN:
12021     return AMDGPU::isIntrinsicSourceOfDivergence(
12022         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
12023   case ISD::INTRINSIC_W_CHAIN:
12024     return AMDGPU::isIntrinsicSourceOfDivergence(
12025         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
12026   case AMDGPUISD::ATOMIC_CMP_SWAP:
12027   case AMDGPUISD::ATOMIC_INC:
12028   case AMDGPUISD::ATOMIC_DEC:
12029   case AMDGPUISD::ATOMIC_LOAD_FMIN:
12030   case AMDGPUISD::ATOMIC_LOAD_FMAX:
12031   case AMDGPUISD::BUFFER_ATOMIC_SWAP:
12032   case AMDGPUISD::BUFFER_ATOMIC_ADD:
12033   case AMDGPUISD::BUFFER_ATOMIC_SUB:
12034   case AMDGPUISD::BUFFER_ATOMIC_SMIN:
12035   case AMDGPUISD::BUFFER_ATOMIC_UMIN:
12036   case AMDGPUISD::BUFFER_ATOMIC_SMAX:
12037   case AMDGPUISD::BUFFER_ATOMIC_UMAX:
12038   case AMDGPUISD::BUFFER_ATOMIC_AND:
12039   case AMDGPUISD::BUFFER_ATOMIC_OR:
12040   case AMDGPUISD::BUFFER_ATOMIC_XOR:
12041   case AMDGPUISD::BUFFER_ATOMIC_INC:
12042   case AMDGPUISD::BUFFER_ATOMIC_DEC:
12043   case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
12044   case AMDGPUISD::BUFFER_ATOMIC_CSUB:
12045   case AMDGPUISD::BUFFER_ATOMIC_FADD:
12046   case AMDGPUISD::BUFFER_ATOMIC_FMIN:
12047   case AMDGPUISD::BUFFER_ATOMIC_FMAX:
12048     // Target-specific read-modify-write atomics are sources of divergence.
12049     return true;
12050   default:
12051     if (auto *A = dyn_cast<AtomicSDNode>(N)) {
12052       // Generic read-modify-write atomics are sources of divergence.
12053       return A->readMem() && A->writeMem();
12054     }
12055     return false;
12056   }
12057 }
12058 
12059 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
12060                                                EVT VT) const {
12061   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
12062   case MVT::f32:
12063     return hasFP32Denormals(DAG.getMachineFunction());
12064   case MVT::f64:
12065   case MVT::f16:
12066     return hasFP64FP16Denormals(DAG.getMachineFunction());
12067   default:
12068     return false;
12069   }
12070 }
12071 
12072 bool SITargetLowering::denormalsEnabledForType(LLT Ty,
12073                                                MachineFunction &MF) const {
12074   switch (Ty.getScalarSizeInBits()) {
12075   case 32:
12076     return hasFP32Denormals(MF);
12077   case 64:
12078   case 16:
12079     return hasFP64FP16Denormals(MF);
12080   default:
12081     return false;
12082   }
12083 }
12084 
12085 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
12086                                                     const SelectionDAG &DAG,
12087                                                     bool SNaN,
12088                                                     unsigned Depth) const {
12089   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
12090     const MachineFunction &MF = DAG.getMachineFunction();
12091     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12092 
12093     if (Info->getMode().DX10Clamp)
12094       return true; // Clamped to 0.
12095     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
12096   }
12097 
12098   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
12099                                                             SNaN, Depth);
12100 }
12101 
12102 // Global FP atomic instructions have a hardcoded FP mode and do not support
12103 // FP32 denormals, and only support v2f16 denormals.
12104 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
12105   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
12106   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
12107   if (&Flt == &APFloat::IEEEsingle())
12108     return DenormMode == DenormalMode::getPreserveSign();
12109   return DenormMode == DenormalMode::getIEEE();
12110 }
12111 
12112 TargetLowering::AtomicExpansionKind
12113 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
12114   switch (RMW->getOperation()) {
12115   case AtomicRMWInst::FAdd: {
12116     Type *Ty = RMW->getType();
12117 
12118     // We don't have a way to support 16-bit atomics now, so just leave them
12119     // as-is.
12120     if (Ty->isHalfTy())
12121       return AtomicExpansionKind::None;
12122 
12123     if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
12124       return AtomicExpansionKind::CmpXChg;
12125 
12126     unsigned AS = RMW->getPointerAddressSpace();
12127 
12128     if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) &&
12129          Subtarget->hasAtomicFaddInsts()) {
12130       // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
12131       // floating point atomic instructions. May generate more efficient code,
12132       // but may not respect rounding and denormal modes, and may give incorrect
12133       // results for certain memory destinations.
12134       if (RMW->getFunction()
12135               ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12136               .getValueAsString() != "true")
12137         return AtomicExpansionKind::CmpXChg;
12138 
12139       if (Subtarget->hasGFX90AInsts()) {
12140         if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS)
12141           return AtomicExpansionKind::CmpXChg;
12142 
12143         auto SSID = RMW->getSyncScopeID();
12144         if (SSID == SyncScope::System ||
12145             SSID == RMW->getContext().getOrInsertSyncScopeID("one-as"))
12146           return AtomicExpansionKind::CmpXChg;
12147 
12148         return AtomicExpansionKind::None;
12149       }
12150 
12151       if (AS == AMDGPUAS::FLAT_ADDRESS)
12152         return AtomicExpansionKind::CmpXChg;
12153 
12154       return RMW->use_empty() ? AtomicExpansionKind::None
12155                               : AtomicExpansionKind::CmpXChg;
12156     }
12157 
12158     // DS FP atomics do repect the denormal mode, but the rounding mode is fixed
12159     // to round-to-nearest-even.
12160     // The only exception is DS_ADD_F64 which never flushes regardless of mode.
12161     if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) {
12162       if (!Ty->isDoubleTy())
12163         return AtomicExpansionKind::None;
12164 
12165       return (fpModeMatchesGlobalFPAtomicMode(RMW) ||
12166               RMW->getFunction()
12167                       ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12168                       .getValueAsString() == "true")
12169                  ? AtomicExpansionKind::None
12170                  : AtomicExpansionKind::CmpXChg;
12171     }
12172 
12173     return AtomicExpansionKind::CmpXChg;
12174   }
12175   default:
12176     break;
12177   }
12178 
12179   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
12180 }
12181 
12182 const TargetRegisterClass *
12183 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
12184   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
12185   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12186   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
12187     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
12188                                                : &AMDGPU::SReg_32RegClass;
12189   if (!TRI->isSGPRClass(RC) && !isDivergent)
12190     return TRI->getEquivalentSGPRClass(RC);
12191   else if (TRI->isSGPRClass(RC) && isDivergent)
12192     return TRI->getEquivalentVGPRClass(RC);
12193 
12194   return RC;
12195 }
12196 
12197 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
12198 // uniform values (as produced by the mask results of control flow intrinsics)
12199 // used outside of divergent blocks. The phi users need to also be treated as
12200 // always uniform.
12201 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
12202                       unsigned WaveSize) {
12203   // FIXME: We asssume we never cast the mask results of a control flow
12204   // intrinsic.
12205   // Early exit if the type won't be consistent as a compile time hack.
12206   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
12207   if (!IT || IT->getBitWidth() != WaveSize)
12208     return false;
12209 
12210   if (!isa<Instruction>(V))
12211     return false;
12212   if (!Visited.insert(V).second)
12213     return false;
12214   bool Result = false;
12215   for (auto U : V->users()) {
12216     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
12217       if (V == U->getOperand(1)) {
12218         switch (Intrinsic->getIntrinsicID()) {
12219         default:
12220           Result = false;
12221           break;
12222         case Intrinsic::amdgcn_if_break:
12223         case Intrinsic::amdgcn_if:
12224         case Intrinsic::amdgcn_else:
12225           Result = true;
12226           break;
12227         }
12228       }
12229       if (V == U->getOperand(0)) {
12230         switch (Intrinsic->getIntrinsicID()) {
12231         default:
12232           Result = false;
12233           break;
12234         case Intrinsic::amdgcn_end_cf:
12235         case Intrinsic::amdgcn_loop:
12236           Result = true;
12237           break;
12238         }
12239       }
12240     } else {
12241       Result = hasCFUser(U, Visited, WaveSize);
12242     }
12243     if (Result)
12244       break;
12245   }
12246   return Result;
12247 }
12248 
12249 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
12250                                                const Value *V) const {
12251   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
12252     if (CI->isInlineAsm()) {
12253       // FIXME: This cannot give a correct answer. This should only trigger in
12254       // the case where inline asm returns mixed SGPR and VGPR results, used
12255       // outside the defining block. We don't have a specific result to
12256       // consider, so this assumes if any value is SGPR, the overall register
12257       // also needs to be SGPR.
12258       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
12259       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
12260           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
12261       for (auto &TC : TargetConstraints) {
12262         if (TC.Type == InlineAsm::isOutput) {
12263           ComputeConstraintToUse(TC, SDValue());
12264           unsigned AssignedReg;
12265           const TargetRegisterClass *RC;
12266           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
12267               SIRI, TC.ConstraintCode, TC.ConstraintVT);
12268           if (RC) {
12269             MachineRegisterInfo &MRI = MF.getRegInfo();
12270             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
12271               return true;
12272             else if (SIRI->isSGPRClass(RC))
12273               return true;
12274           }
12275         }
12276       }
12277     }
12278   }
12279   SmallPtrSet<const Value *, 16> Visited;
12280   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
12281 }
12282 
12283 std::pair<InstructionCost, MVT>
12284 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
12285                                           Type *Ty) const {
12286   std::pair<InstructionCost, MVT> Cost =
12287       TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
12288   auto Size = DL.getTypeSizeInBits(Ty);
12289   // Maximum load or store can handle 8 dwords for scalar and 4 for
12290   // vector ALU. Let's assume anything above 8 dwords is expensive
12291   // even if legal.
12292   if (Size <= 256)
12293     return Cost;
12294 
12295   Cost.first = (Size + 255) / 256;
12296   return Cost;
12297 }
12298