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/CodeGen/Analysis.h"
23 #include "llvm/CodeGen/FunctionLoweringInfo.h"
24 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
25 #include "llvm/CodeGen/MachineLoopInfo.h"
26 #include "llvm/IR/DiagnosticInfo.h"
27 #include "llvm/IR/IntrinsicsAMDGPU.h"
28 #include "llvm/IR/IntrinsicsR600.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/KnownBits.h"
31 
32 using namespace llvm;
33 
34 #define DEBUG_TYPE "si-lower"
35 
36 STATISTIC(NumTailCalls, "Number of tail calls");
37 
38 static cl::opt<bool> DisableLoopAlignment(
39   "amdgpu-disable-loop-alignment",
40   cl::desc("Do not align and prefetch loops"),
41   cl::init(false));
42 
43 static cl::opt<bool> VGPRReserveforSGPRSpill(
44     "amdgpu-reserve-vgpr-for-sgpr-spill",
45     cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true));
46 
47 static cl::opt<bool> UseDivergentRegisterIndexing(
48   "amdgpu-use-divergent-register-indexing",
49   cl::Hidden,
50   cl::desc("Use indirect register addressing for divergent indexes"),
51   cl::init(false));
52 
53 static bool hasFP32Denormals(const MachineFunction &MF) {
54   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
55   return Info->getMode().allFP32Denormals();
56 }
57 
58 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
59   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
60   return Info->getMode().allFP64FP16Denormals();
61 }
62 
63 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
64   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
65   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
66     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
67       return AMDGPU::SGPR0 + Reg;
68     }
69   }
70   llvm_unreachable("Cannot allocate sgpr");
71 }
72 
73 SITargetLowering::SITargetLowering(const TargetMachine &TM,
74                                    const GCNSubtarget &STI)
75     : AMDGPUTargetLowering(TM, STI),
76       Subtarget(&STI) {
77   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
78   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
79 
80   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
81   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
82 
83   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
84 
85   const SIRegisterInfo *TRI = STI.getRegisterInfo();
86   const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class();
87 
88   addRegisterClass(MVT::f64, V64RegClass);
89   addRegisterClass(MVT::v2f32, V64RegClass);
90 
91   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
92   addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96));
93 
94   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
95   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
96 
97   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
98   addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128));
99 
100   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
101   addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160));
102 
103   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
104   addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256));
105 
106   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
107   addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256));
108 
109   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
110   addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512));
111 
112   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
113   addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512));
114 
115   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
116   addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024));
117 
118   if (Subtarget->has16BitInsts()) {
119     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
120     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
121 
122     // Unless there are also VOP3P operations, not operations are really legal.
123     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
124     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
125     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
126     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
127   }
128 
129   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
130   addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024));
131 
132   computeRegisterProperties(Subtarget->getRegisterInfo());
133 
134   // The boolean content concept here is too inflexible. Compares only ever
135   // really produce a 1-bit result. Any copy/extend from these will turn into a
136   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
137   // it's what most targets use.
138   setBooleanContents(ZeroOrOneBooleanContent);
139   setBooleanVectorContents(ZeroOrOneBooleanContent);
140 
141   // We need to custom lower vector stores from local memory
142   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
143   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
144   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
145   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
146   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
147   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
148   setOperationAction(ISD::LOAD, MVT::i1, Custom);
149   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
150 
151   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
152   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
153   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
154   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
155   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
156   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
157   setOperationAction(ISD::STORE, MVT::i1, Custom);
158   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
159 
160   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
161   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
162   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
163   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
164   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
165   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
166   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
167   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
168   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
169   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
170   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
171   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
172   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
173   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
174   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
175   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
176 
177   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
178   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
179   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
180   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
181   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
182 
183   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
184   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
185 
186   setOperationAction(ISD::SELECT, MVT::i1, Promote);
187   setOperationAction(ISD::SELECT, MVT::i64, Custom);
188   setOperationAction(ISD::SELECT, MVT::f64, Promote);
189   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
190 
191   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
192   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
193   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
194   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
195   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
196 
197   setOperationAction(ISD::SETCC, MVT::i1, Promote);
198   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
199   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
200   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
201 
202   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
203   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
204   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
205   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
206   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
207   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
208   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
209   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
210 
211   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
212   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
213   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
214   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
215   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
216   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
217   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
218   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
219 
220   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
221   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
222   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
223   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
224   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
225   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
226 
227   setOperationAction(ISD::UADDO, MVT::i32, Legal);
228   setOperationAction(ISD::USUBO, MVT::i32, Legal);
229 
230   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
231   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
232 
233   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
234   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
235   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
236 
237 #if 0
238   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
239   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
240 #endif
241 
242   // We only support LOAD/STORE and vector manipulation ops for vectors
243   // with > 4 elements.
244   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
245                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
246                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
247                   MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) {
248     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
249       switch (Op) {
250       case ISD::LOAD:
251       case ISD::STORE:
252       case ISD::BUILD_VECTOR:
253       case ISD::BITCAST:
254       case ISD::EXTRACT_VECTOR_ELT:
255       case ISD::INSERT_VECTOR_ELT:
256       case ISD::INSERT_SUBVECTOR:
257       case ISD::EXTRACT_SUBVECTOR:
258       case ISD::SCALAR_TO_VECTOR:
259         break;
260       case ISD::CONCAT_VECTORS:
261         setOperationAction(Op, VT, Custom);
262         break;
263       default:
264         setOperationAction(Op, VT, Expand);
265         break;
266       }
267     }
268   }
269 
270   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
271 
272   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
273   // is expanded to avoid having two separate loops in case the index is a VGPR.
274 
275   // Most operations are naturally 32-bit vector operations. We only support
276   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
277   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
278     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
279     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
280 
281     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
282     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
283 
284     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
285     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
286 
287     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
288     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
289   }
290 
291   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
292     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
293     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
294 
295     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
296     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
297 
298     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
299     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
300 
301     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
302     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
303   }
304 
305   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
306     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
307     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
308 
309     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
310     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
311 
312     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
313     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
314 
315     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
316     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
317   }
318 
319   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
320     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
321     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
322 
323     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
324     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
325 
326     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
327     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
328 
329     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
330     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
331   }
332 
333   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
334   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
335   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
336   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
337 
338   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
339   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
340 
341   // Avoid stack access for these.
342   // TODO: Generalize to more vector types.
343   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
344   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
345   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
346   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
347 
348   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
349   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
350   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
351   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
352   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
353 
354   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
355   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
356   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
357 
358   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
359   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
360   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
361   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
362 
363   // Deal with vec3 vector operations when widened to vec4.
364   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
365   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
366   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
367   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
368 
369   // Deal with vec5 vector operations when widened to vec8.
370   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
371   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
372   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
373   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
374 
375   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
376   // and output demarshalling
377   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
378   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
379 
380   // We can't return success/failure, only the old value,
381   // let LLVM add the comparison
382   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
383   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
384 
385   if (Subtarget->hasFlatAddressSpace()) {
386     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
387     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
388   }
389 
390   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
391   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
392 
393   // FIXME: This should be narrowed to i32, but that only happens if i64 is
394   // illegal.
395   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
396   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
397   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
398 
399   // On SI this is s_memtime and s_memrealtime on VI.
400   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
401   setOperationAction(ISD::TRAP, MVT::Other, Custom);
402   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
403 
404   if (Subtarget->has16BitInsts()) {
405     setOperationAction(ISD::FPOW, MVT::f16, Promote);
406     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
407     setOperationAction(ISD::FLOG, MVT::f16, Custom);
408     setOperationAction(ISD::FEXP, MVT::f16, Custom);
409     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
410   }
411 
412   if (Subtarget->hasMadMacF32Insts())
413     setOperationAction(ISD::FMAD, MVT::f32, Legal);
414 
415   if (!Subtarget->hasBFI()) {
416     // fcopysign can be done in a single instruction with BFI.
417     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
418     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
419   }
420 
421   if (!Subtarget->hasBCNT(32))
422     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
423 
424   if (!Subtarget->hasBCNT(64))
425     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
426 
427   if (Subtarget->hasFFBH())
428     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
429 
430   if (Subtarget->hasFFBL())
431     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
432 
433   // We only really have 32-bit BFE instructions (and 16-bit on VI).
434   //
435   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
436   // effort to match them now. We want this to be false for i64 cases when the
437   // extraction isn't restricted to the upper or lower half. Ideally we would
438   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
439   // span the midpoint are probably relatively rare, so don't worry about them
440   // for now.
441   if (Subtarget->hasBFE())
442     setHasExtractBitsInsn(true);
443 
444   // Clamp modifier on add/sub
445   if (Subtarget->hasIntClamp()) {
446     setOperationAction(ISD::UADDSAT, MVT::i32, Legal);
447     setOperationAction(ISD::USUBSAT, MVT::i32, Legal);
448   }
449 
450   if (Subtarget->hasAddNoCarry()) {
451     setOperationAction(ISD::SADDSAT, MVT::i16, Legal);
452     setOperationAction(ISD::SSUBSAT, MVT::i16, Legal);
453     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
454     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
455   }
456 
457   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
458   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
459   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
460   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
461 
462 
463   // These are really only legal for ieee_mode functions. We should be avoiding
464   // them for functions that don't have ieee_mode enabled, so just say they are
465   // legal.
466   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
467   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
468   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
469   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
470 
471 
472   if (Subtarget->haveRoundOpsF64()) {
473     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
474     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
475     setOperationAction(ISD::FRINT, MVT::f64, Legal);
476   } else {
477     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
478     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
479     setOperationAction(ISD::FRINT, MVT::f64, Custom);
480     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
481   }
482 
483   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
484 
485   setOperationAction(ISD::FSIN, MVT::f32, Custom);
486   setOperationAction(ISD::FCOS, MVT::f32, Custom);
487   setOperationAction(ISD::FDIV, MVT::f32, Custom);
488   setOperationAction(ISD::FDIV, MVT::f64, Custom);
489 
490   if (Subtarget->has16BitInsts()) {
491     setOperationAction(ISD::Constant, MVT::i16, Legal);
492 
493     setOperationAction(ISD::SMIN, MVT::i16, Legal);
494     setOperationAction(ISD::SMAX, MVT::i16, Legal);
495 
496     setOperationAction(ISD::UMIN, MVT::i16, Legal);
497     setOperationAction(ISD::UMAX, MVT::i16, Legal);
498 
499     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
500     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
501 
502     setOperationAction(ISD::ROTR, MVT::i16, Expand);
503     setOperationAction(ISD::ROTL, MVT::i16, Expand);
504 
505     setOperationAction(ISD::SDIV, MVT::i16, Promote);
506     setOperationAction(ISD::UDIV, MVT::i16, Promote);
507     setOperationAction(ISD::SREM, MVT::i16, Promote);
508     setOperationAction(ISD::UREM, MVT::i16, Promote);
509     setOperationAction(ISD::UADDSAT, MVT::i16, Legal);
510     setOperationAction(ISD::USUBSAT, MVT::i16, Legal);
511 
512     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
513 
514     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
515     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
516     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
517     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
518     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
519 
520     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
521 
522     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
523 
524     setOperationAction(ISD::LOAD, MVT::i16, Custom);
525 
526     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
527 
528     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
529     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
530     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
531     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
532 
533     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
534     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
535 
536     // F16 - Constant Actions.
537     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
538 
539     // F16 - Load/Store Actions.
540     setOperationAction(ISD::LOAD, MVT::f16, Promote);
541     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
542     setOperationAction(ISD::STORE, MVT::f16, Promote);
543     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
544 
545     // F16 - VOP1 Actions.
546     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
547     setOperationAction(ISD::FCOS, MVT::f16, Custom);
548     setOperationAction(ISD::FSIN, MVT::f16, Custom);
549 
550     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
551     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
552 
553     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
554     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
555     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
556     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
557     setOperationAction(ISD::FROUND, MVT::f16, Custom);
558 
559     // F16 - VOP2 Actions.
560     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
561     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
562 
563     setOperationAction(ISD::FDIV, MVT::f16, Custom);
564 
565     // F16 - VOP3 Actions.
566     setOperationAction(ISD::FMA, MVT::f16, Legal);
567     if (STI.hasMadF16())
568       setOperationAction(ISD::FMAD, MVT::f16, Legal);
569 
570     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
571       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
572         switch (Op) {
573         case ISD::LOAD:
574         case ISD::STORE:
575         case ISD::BUILD_VECTOR:
576         case ISD::BITCAST:
577         case ISD::EXTRACT_VECTOR_ELT:
578         case ISD::INSERT_VECTOR_ELT:
579         case ISD::INSERT_SUBVECTOR:
580         case ISD::EXTRACT_SUBVECTOR:
581         case ISD::SCALAR_TO_VECTOR:
582           break;
583         case ISD::CONCAT_VECTORS:
584           setOperationAction(Op, VT, Custom);
585           break;
586         default:
587           setOperationAction(Op, VT, Expand);
588           break;
589         }
590       }
591     }
592 
593     // v_perm_b32 can handle either of these.
594     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
595     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
596     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
597 
598     // XXX - Do these do anything? Vector constants turn into build_vector.
599     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
600     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
601 
602     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
603     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
604 
605     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
606     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
607     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
608     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
609 
610     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
611     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
612     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
613     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
614 
615     setOperationAction(ISD::AND, MVT::v2i16, Promote);
616     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
617     setOperationAction(ISD::OR, MVT::v2i16, Promote);
618     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
619     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
620     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
621 
622     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
623     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
624     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
625     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
626 
627     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
628     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
629     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
630     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
631 
632     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
633     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
634     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
635     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
636 
637     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
638     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
639     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
640 
641     if (!Subtarget->hasVOP3PInsts()) {
642       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
643       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
644     }
645 
646     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
647     // This isn't really legal, but this avoids the legalizer unrolling it (and
648     // allows matching fneg (fabs x) patterns)
649     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
650 
651     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
652     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
653     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
654     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
655 
656     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
657     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
658 
659     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
660     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
661   }
662 
663   if (Subtarget->hasVOP3PInsts()) {
664     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
665     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
666     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
667     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
668     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
669     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
670     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
671     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
672     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
673     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
674 
675     setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal);
676     setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal);
677     setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal);
678     setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal);
679 
680     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
681     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
682     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
683 
684     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
685     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
686 
687     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
688 
689     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
690     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
691 
692     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
693     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
694 
695     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
696     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
697     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
698     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
699     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
700     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
701 
702     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
703     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
704     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
705     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
706 
707     setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom);
708     setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom);
709     setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom);
710     setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom);
711 
712     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
713     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
714     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
715 
716     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
717     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
718 
719     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
720     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
721     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
722 
723     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
724     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
725     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
726 
727     if (Subtarget->hasPackedFP32Ops()) {
728       setOperationAction(ISD::FADD, MVT::v2f32, Legal);
729       setOperationAction(ISD::FMUL, MVT::v2f32, Legal);
730       setOperationAction(ISD::FMA,  MVT::v2f32, Legal);
731       setOperationAction(ISD::FNEG, MVT::v2f32, Legal);
732 
733       for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) {
734         setOperationAction(ISD::FADD, VT, Custom);
735         setOperationAction(ISD::FMUL, VT, Custom);
736         setOperationAction(ISD::FMA, VT, Custom);
737       }
738     }
739   }
740 
741   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
742   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
743 
744   if (Subtarget->has16BitInsts()) {
745     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
746     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
747     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
748     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
749   } else {
750     // Legalization hack.
751     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
752     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
753 
754     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
755     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
756   }
757 
758   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
759     setOperationAction(ISD::SELECT, VT, Custom);
760   }
761 
762   setOperationAction(ISD::SMULO, MVT::i64, Custom);
763   setOperationAction(ISD::UMULO, MVT::i64, Custom);
764 
765   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
766   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
767   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
768   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
769   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
770   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
771   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
772 
773   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
774   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
775   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom);
776   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom);
777   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
778   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
779   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
780   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
781   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
782   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
783   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
784 
785   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
786   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
787   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
788   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom);
789   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom);
790   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
791   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
792   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
793   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
794   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
795 
796   setTargetDAGCombine(ISD::ADD);
797   setTargetDAGCombine(ISD::ADDCARRY);
798   setTargetDAGCombine(ISD::SUB);
799   setTargetDAGCombine(ISD::SUBCARRY);
800   setTargetDAGCombine(ISD::FADD);
801   setTargetDAGCombine(ISD::FSUB);
802   setTargetDAGCombine(ISD::FMINNUM);
803   setTargetDAGCombine(ISD::FMAXNUM);
804   setTargetDAGCombine(ISD::FMINNUM_IEEE);
805   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
806   setTargetDAGCombine(ISD::FMA);
807   setTargetDAGCombine(ISD::SMIN);
808   setTargetDAGCombine(ISD::SMAX);
809   setTargetDAGCombine(ISD::UMIN);
810   setTargetDAGCombine(ISD::UMAX);
811   setTargetDAGCombine(ISD::SETCC);
812   setTargetDAGCombine(ISD::AND);
813   setTargetDAGCombine(ISD::OR);
814   setTargetDAGCombine(ISD::XOR);
815   setTargetDAGCombine(ISD::SINT_TO_FP);
816   setTargetDAGCombine(ISD::UINT_TO_FP);
817   setTargetDAGCombine(ISD::FCANONICALIZE);
818   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
819   setTargetDAGCombine(ISD::ZERO_EXTEND);
820   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
821   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
822   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
823 
824   // All memory operations. Some folding on the pointer operand is done to help
825   // matching the constant offsets in the addressing modes.
826   setTargetDAGCombine(ISD::LOAD);
827   setTargetDAGCombine(ISD::STORE);
828   setTargetDAGCombine(ISD::ATOMIC_LOAD);
829   setTargetDAGCombine(ISD::ATOMIC_STORE);
830   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
831   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
832   setTargetDAGCombine(ISD::ATOMIC_SWAP);
833   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
834   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
835   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
836   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
837   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
838   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
839   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
840   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
841   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
842   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
843   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
844   setTargetDAGCombine(ISD::INTRINSIC_VOID);
845   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
846 
847   // FIXME: In other contexts we pretend this is a per-function property.
848   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
849 
850   setSchedulingPreference(Sched::RegPressure);
851 }
852 
853 const GCNSubtarget *SITargetLowering::getSubtarget() const {
854   return Subtarget;
855 }
856 
857 //===----------------------------------------------------------------------===//
858 // TargetLowering queries
859 //===----------------------------------------------------------------------===//
860 
861 // v_mad_mix* support a conversion from f16 to f32.
862 //
863 // There is only one special case when denormals are enabled we don't currently,
864 // where this is OK to use.
865 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
866                                        EVT DestVT, EVT SrcVT) const {
867   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
868           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
869     DestVT.getScalarType() == MVT::f32 &&
870     SrcVT.getScalarType() == MVT::f16 &&
871     // TODO: This probably only requires no input flushing?
872     !hasFP32Denormals(DAG.getMachineFunction());
873 }
874 
875 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
876   // SI has some legal vector types, but no legal vector operations. Say no
877   // shuffles are legal in order to prefer scalarizing some vector operations.
878   return false;
879 }
880 
881 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
882                                                     CallingConv::ID CC,
883                                                     EVT VT) const {
884   if (CC == CallingConv::AMDGPU_KERNEL)
885     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
886 
887   if (VT.isVector()) {
888     EVT ScalarVT = VT.getScalarType();
889     unsigned Size = ScalarVT.getSizeInBits();
890     if (Size == 16) {
891       if (Subtarget->has16BitInsts())
892         return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
893       return VT.isInteger() ? MVT::i32 : MVT::f32;
894     }
895 
896     if (Size < 16)
897       return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
898     return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
899   }
900 
901   if (VT.getSizeInBits() > 32)
902     return MVT::i32;
903 
904   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
905 }
906 
907 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
908                                                          CallingConv::ID CC,
909                                                          EVT VT) const {
910   if (CC == CallingConv::AMDGPU_KERNEL)
911     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
912 
913   if (VT.isVector()) {
914     unsigned NumElts = VT.getVectorNumElements();
915     EVT ScalarVT = VT.getScalarType();
916     unsigned Size = ScalarVT.getSizeInBits();
917 
918     // FIXME: Should probably promote 8-bit vectors to i16.
919     if (Size == 16 && Subtarget->has16BitInsts())
920       return (NumElts + 1) / 2;
921 
922     if (Size <= 32)
923       return NumElts;
924 
925     if (Size > 32)
926       return NumElts * ((Size + 31) / 32);
927   } else if (VT.getSizeInBits() > 32)
928     return (VT.getSizeInBits() + 31) / 32;
929 
930   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
931 }
932 
933 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
934   LLVMContext &Context, CallingConv::ID CC,
935   EVT VT, EVT &IntermediateVT,
936   unsigned &NumIntermediates, MVT &RegisterVT) const {
937   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
938     unsigned NumElts = VT.getVectorNumElements();
939     EVT ScalarVT = VT.getScalarType();
940     unsigned Size = ScalarVT.getSizeInBits();
941     // FIXME: We should fix the ABI to be the same on targets without 16-bit
942     // support, but unless we can properly handle 3-vectors, it will be still be
943     // inconsistent.
944     if (Size == 16 && Subtarget->has16BitInsts()) {
945       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
946       IntermediateVT = RegisterVT;
947       NumIntermediates = (NumElts + 1) / 2;
948       return NumIntermediates;
949     }
950 
951     if (Size == 32) {
952       RegisterVT = ScalarVT.getSimpleVT();
953       IntermediateVT = RegisterVT;
954       NumIntermediates = NumElts;
955       return NumIntermediates;
956     }
957 
958     if (Size < 16 && Subtarget->has16BitInsts()) {
959       // FIXME: Should probably form v2i16 pieces
960       RegisterVT = MVT::i16;
961       IntermediateVT = ScalarVT;
962       NumIntermediates = NumElts;
963       return NumIntermediates;
964     }
965 
966 
967     if (Size != 16 && Size <= 32) {
968       RegisterVT = MVT::i32;
969       IntermediateVT = ScalarVT;
970       NumIntermediates = NumElts;
971       return NumIntermediates;
972     }
973 
974     if (Size > 32) {
975       RegisterVT = MVT::i32;
976       IntermediateVT = RegisterVT;
977       NumIntermediates = NumElts * ((Size + 31) / 32);
978       return NumIntermediates;
979     }
980   }
981 
982   return TargetLowering::getVectorTypeBreakdownForCallingConv(
983     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
984 }
985 
986 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
987   assert(DMaskLanes != 0);
988 
989   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
990     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
991     return EVT::getVectorVT(Ty->getContext(),
992                             EVT::getEVT(VT->getElementType()),
993                             NumElts);
994   }
995 
996   return EVT::getEVT(Ty);
997 }
998 
999 // Peek through TFE struct returns to only use the data size.
1000 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
1001   auto *ST = dyn_cast<StructType>(Ty);
1002   if (!ST)
1003     return memVTFromImageData(Ty, DMaskLanes);
1004 
1005   // Some intrinsics return an aggregate type - special case to work out the
1006   // correct memVT.
1007   //
1008   // Only limited forms of aggregate type currently expected.
1009   if (ST->getNumContainedTypes() != 2 ||
1010       !ST->getContainedType(1)->isIntegerTy(32))
1011     return EVT();
1012   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
1013 }
1014 
1015 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1016                                           const CallInst &CI,
1017                                           MachineFunction &MF,
1018                                           unsigned IntrID) const {
1019   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1020           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1021     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1022                                                   (Intrinsic::ID)IntrID);
1023     if (Attr.hasFnAttribute(Attribute::ReadNone))
1024       return false;
1025 
1026     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1027 
1028     if (RsrcIntr->IsImage) {
1029       Info.ptrVal =
1030           MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1031       Info.align.reset();
1032     } else {
1033       Info.ptrVal =
1034           MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1035     }
1036 
1037     Info.flags = MachineMemOperand::MODereferenceable;
1038     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
1039       unsigned DMaskLanes = 4;
1040 
1041       if (RsrcIntr->IsImage) {
1042         const AMDGPU::ImageDimIntrinsicInfo *Intr
1043           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1044         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1045           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1046 
1047         if (!BaseOpcode->Gather4) {
1048           // If this isn't a gather, we may have excess loaded elements in the
1049           // IR type. Check the dmask for the real number of elements loaded.
1050           unsigned DMask
1051             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1052           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1053         }
1054 
1055         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1056       } else
1057         Info.memVT = EVT::getEVT(CI.getType());
1058 
1059       // FIXME: What does alignment mean for an image?
1060       Info.opc = ISD::INTRINSIC_W_CHAIN;
1061       Info.flags |= MachineMemOperand::MOLoad;
1062     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
1063       Info.opc = ISD::INTRINSIC_VOID;
1064 
1065       Type *DataTy = CI.getArgOperand(0)->getType();
1066       if (RsrcIntr->IsImage) {
1067         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1068         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1069         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1070       } else
1071         Info.memVT = EVT::getEVT(DataTy);
1072 
1073       Info.flags |= MachineMemOperand::MOStore;
1074     } else {
1075       // Atomic
1076       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1077                                             ISD::INTRINSIC_W_CHAIN;
1078       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1079       Info.flags = MachineMemOperand::MOLoad |
1080                    MachineMemOperand::MOStore |
1081                    MachineMemOperand::MODereferenceable;
1082 
1083       // XXX - Should this be volatile without known ordering?
1084       Info.flags |= MachineMemOperand::MOVolatile;
1085     }
1086     return true;
1087   }
1088 
1089   switch (IntrID) {
1090   case Intrinsic::amdgcn_atomic_inc:
1091   case Intrinsic::amdgcn_atomic_dec:
1092   case Intrinsic::amdgcn_ds_ordered_add:
1093   case Intrinsic::amdgcn_ds_ordered_swap:
1094   case Intrinsic::amdgcn_ds_fadd:
1095   case Intrinsic::amdgcn_ds_fmin:
1096   case Intrinsic::amdgcn_ds_fmax: {
1097     Info.opc = ISD::INTRINSIC_W_CHAIN;
1098     Info.memVT = MVT::getVT(CI.getType());
1099     Info.ptrVal = CI.getOperand(0);
1100     Info.align.reset();
1101     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1102 
1103     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1104     if (!Vol->isZero())
1105       Info.flags |= MachineMemOperand::MOVolatile;
1106 
1107     return true;
1108   }
1109   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1110     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1111 
1112     Info.opc = ISD::INTRINSIC_W_CHAIN;
1113     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1114     Info.ptrVal =
1115         MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1116     Info.align.reset();
1117     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1118 
1119     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1120     if (!Vol || !Vol->isZero())
1121       Info.flags |= MachineMemOperand::MOVolatile;
1122 
1123     return true;
1124   }
1125   case Intrinsic::amdgcn_ds_append:
1126   case Intrinsic::amdgcn_ds_consume: {
1127     Info.opc = ISD::INTRINSIC_W_CHAIN;
1128     Info.memVT = MVT::getVT(CI.getType());
1129     Info.ptrVal = CI.getOperand(0);
1130     Info.align.reset();
1131     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1132 
1133     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1134     if (!Vol->isZero())
1135       Info.flags |= MachineMemOperand::MOVolatile;
1136 
1137     return true;
1138   }
1139   case Intrinsic::amdgcn_global_atomic_csub: {
1140     Info.opc = ISD::INTRINSIC_W_CHAIN;
1141     Info.memVT = MVT::getVT(CI.getType());
1142     Info.ptrVal = CI.getOperand(0);
1143     Info.align.reset();
1144     Info.flags = MachineMemOperand::MOLoad |
1145                  MachineMemOperand::MOStore |
1146                  MachineMemOperand::MOVolatile;
1147     return true;
1148   }
1149   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1150     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1151     Info.opc = ISD::INTRINSIC_W_CHAIN;
1152     Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1153     Info.ptrVal =
1154         MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1155     Info.align.reset();
1156     Info.flags = MachineMemOperand::MOLoad |
1157                  MachineMemOperand::MODereferenceable;
1158     return true;
1159   }
1160   case Intrinsic::amdgcn_global_atomic_fadd:
1161   case Intrinsic::amdgcn_global_atomic_fmin:
1162   case Intrinsic::amdgcn_global_atomic_fmax:
1163   case Intrinsic::amdgcn_flat_atomic_fadd:
1164   case Intrinsic::amdgcn_flat_atomic_fmin:
1165   case Intrinsic::amdgcn_flat_atomic_fmax: {
1166     Info.opc = ISD::INTRINSIC_W_CHAIN;
1167     Info.memVT = MVT::getVT(CI.getType());
1168     Info.ptrVal = CI.getOperand(0);
1169     Info.align.reset();
1170     Info.flags = MachineMemOperand::MOLoad |
1171                  MachineMemOperand::MOStore |
1172                  MachineMemOperand::MODereferenceable |
1173                  MachineMemOperand::MOVolatile;
1174     return true;
1175   }
1176   case Intrinsic::amdgcn_ds_gws_init:
1177   case Intrinsic::amdgcn_ds_gws_barrier:
1178   case Intrinsic::amdgcn_ds_gws_sema_v:
1179   case Intrinsic::amdgcn_ds_gws_sema_br:
1180   case Intrinsic::amdgcn_ds_gws_sema_p:
1181   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1182     Info.opc = ISD::INTRINSIC_VOID;
1183 
1184     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1185     Info.ptrVal =
1186         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1187 
1188     // This is an abstract access, but we need to specify a type and size.
1189     Info.memVT = MVT::i32;
1190     Info.size = 4;
1191     Info.align = Align(4);
1192 
1193     Info.flags = MachineMemOperand::MOStore;
1194     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1195       Info.flags = MachineMemOperand::MOLoad;
1196     return true;
1197   }
1198   default:
1199     return false;
1200   }
1201 }
1202 
1203 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1204                                             SmallVectorImpl<Value*> &Ops,
1205                                             Type *&AccessTy) const {
1206   switch (II->getIntrinsicID()) {
1207   case Intrinsic::amdgcn_atomic_inc:
1208   case Intrinsic::amdgcn_atomic_dec:
1209   case Intrinsic::amdgcn_ds_ordered_add:
1210   case Intrinsic::amdgcn_ds_ordered_swap:
1211   case Intrinsic::amdgcn_ds_append:
1212   case Intrinsic::amdgcn_ds_consume:
1213   case Intrinsic::amdgcn_ds_fadd:
1214   case Intrinsic::amdgcn_ds_fmin:
1215   case Intrinsic::amdgcn_ds_fmax:
1216   case Intrinsic::amdgcn_global_atomic_fadd:
1217   case Intrinsic::amdgcn_flat_atomic_fadd:
1218   case Intrinsic::amdgcn_flat_atomic_fmin:
1219   case Intrinsic::amdgcn_flat_atomic_fmax:
1220   case Intrinsic::amdgcn_global_atomic_csub: {
1221     Value *Ptr = II->getArgOperand(0);
1222     AccessTy = II->getType();
1223     Ops.push_back(Ptr);
1224     return true;
1225   }
1226   default:
1227     return false;
1228   }
1229 }
1230 
1231 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1232   if (!Subtarget->hasFlatInstOffsets()) {
1233     // Flat instructions do not have offsets, and only have the register
1234     // address.
1235     return AM.BaseOffs == 0 && AM.Scale == 0;
1236   }
1237 
1238   return AM.Scale == 0 &&
1239          (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1240                                   AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS,
1241                                   /*Signed=*/false));
1242 }
1243 
1244 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1245   if (Subtarget->hasFlatGlobalInsts())
1246     return AM.Scale == 0 &&
1247            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1248                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1249                                     /*Signed=*/true));
1250 
1251   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1252       // Assume the we will use FLAT for all global memory accesses
1253       // on VI.
1254       // FIXME: This assumption is currently wrong.  On VI we still use
1255       // MUBUF instructions for the r + i addressing mode.  As currently
1256       // implemented, the MUBUF instructions only work on buffer < 4GB.
1257       // It may be possible to support > 4GB buffers with MUBUF instructions,
1258       // by setting the stride value in the resource descriptor which would
1259       // increase the size limit to (stride * 4GB).  However, this is risky,
1260       // because it has never been validated.
1261     return isLegalFlatAddressingMode(AM);
1262   }
1263 
1264   return isLegalMUBUFAddressingMode(AM);
1265 }
1266 
1267 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1268   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1269   // additionally can do r + r + i with addr64. 32-bit has more addressing
1270   // mode options. Depending on the resource constant, it can also do
1271   // (i64 r0) + (i32 r1) * (i14 i).
1272   //
1273   // Private arrays end up using a scratch buffer most of the time, so also
1274   // assume those use MUBUF instructions. Scratch loads / stores are currently
1275   // implemented as mubuf instructions with offen bit set, so slightly
1276   // different than the normal addr64.
1277   if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1278     return false;
1279 
1280   // FIXME: Since we can split immediate into soffset and immediate offset,
1281   // would it make sense to allow any immediate?
1282 
1283   switch (AM.Scale) {
1284   case 0: // r + i or just i, depending on HasBaseReg.
1285     return true;
1286   case 1:
1287     return true; // We have r + r or r + i.
1288   case 2:
1289     if (AM.HasBaseReg) {
1290       // Reject 2 * r + r.
1291       return false;
1292     }
1293 
1294     // Allow 2 * r as r + r
1295     // Or  2 * r + i is allowed as r + r + i.
1296     return true;
1297   default: // Don't allow n * r
1298     return false;
1299   }
1300 }
1301 
1302 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1303                                              const AddrMode &AM, Type *Ty,
1304                                              unsigned AS, Instruction *I) const {
1305   // No global is ever allowed as a base.
1306   if (AM.BaseGV)
1307     return false;
1308 
1309   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1310     return isLegalGlobalAddressingMode(AM);
1311 
1312   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1313       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1314       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1315     // If the offset isn't a multiple of 4, it probably isn't going to be
1316     // correctly aligned.
1317     // FIXME: Can we get the real alignment here?
1318     if (AM.BaseOffs % 4 != 0)
1319       return isLegalMUBUFAddressingMode(AM);
1320 
1321     // There are no SMRD extloads, so if we have to do a small type access we
1322     // will use a MUBUF load.
1323     // FIXME?: We also need to do this if unaligned, but we don't know the
1324     // alignment here.
1325     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1326       return isLegalGlobalAddressingMode(AM);
1327 
1328     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1329       // SMRD instructions have an 8-bit, dword offset on SI.
1330       if (!isUInt<8>(AM.BaseOffs / 4))
1331         return false;
1332     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1333       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1334       // in 8-bits, it can use a smaller encoding.
1335       if (!isUInt<32>(AM.BaseOffs / 4))
1336         return false;
1337     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1338       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1339       if (!isUInt<20>(AM.BaseOffs))
1340         return false;
1341     } else
1342       llvm_unreachable("unhandled generation");
1343 
1344     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1345       return true;
1346 
1347     if (AM.Scale == 1 && AM.HasBaseReg)
1348       return true;
1349 
1350     return false;
1351 
1352   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1353     return isLegalMUBUFAddressingMode(AM);
1354   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1355              AS == AMDGPUAS::REGION_ADDRESS) {
1356     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1357     // field.
1358     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1359     // an 8-bit dword offset but we don't know the alignment here.
1360     if (!isUInt<16>(AM.BaseOffs))
1361       return false;
1362 
1363     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1364       return true;
1365 
1366     if (AM.Scale == 1 && AM.HasBaseReg)
1367       return true;
1368 
1369     return false;
1370   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1371              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1372     // For an unknown address space, this usually means that this is for some
1373     // reason being used for pure arithmetic, and not based on some addressing
1374     // computation. We don't have instructions that compute pointers with any
1375     // addressing modes, so treat them as having no offset like flat
1376     // instructions.
1377     return isLegalFlatAddressingMode(AM);
1378   }
1379 
1380   // Assume a user alias of global for unknown address spaces.
1381   return isLegalGlobalAddressingMode(AM);
1382 }
1383 
1384 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1385                                         const SelectionDAG &DAG) const {
1386   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1387     return (MemVT.getSizeInBits() <= 4 * 32);
1388   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1389     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1390     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1391   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1392     return (MemVT.getSizeInBits() <= 2 * 32);
1393   }
1394   return true;
1395 }
1396 
1397 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1398     unsigned Size, unsigned AddrSpace, Align Alignment,
1399     MachineMemOperand::Flags Flags, bool *IsFast) const {
1400   if (IsFast)
1401     *IsFast = false;
1402 
1403   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1404       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1405     // Check if alignment requirements for ds_read/write instructions are
1406     // disabled.
1407     if (Subtarget->hasUnalignedDSAccessEnabled() &&
1408         !Subtarget->hasLDSMisalignedBug()) {
1409       if (IsFast)
1410         *IsFast = Alignment != Align(2);
1411       return true;
1412     }
1413 
1414     if (Size == 64) {
1415       // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1416       // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1417       // with adjacent offsets.
1418       bool AlignedBy4 = Alignment >= Align(4);
1419       if (IsFast)
1420         *IsFast = AlignedBy4;
1421 
1422       return AlignedBy4;
1423     }
1424     if (Size == 96) {
1425       // ds_read/write_b96 require 16-byte alignment on gfx8 and older.
1426       bool Aligned = Alignment >= Align(16);
1427       if (IsFast)
1428         *IsFast = Aligned;
1429 
1430       return Aligned;
1431     }
1432     if (Size == 128) {
1433       // ds_read/write_b128 require 16-byte alignment on gfx8 and older, but we
1434       // can do a 8 byte aligned, 16 byte access in a single operation using
1435       // ds_read2/write2_b64.
1436       bool Aligned = Alignment >= Align(8);
1437       if (IsFast)
1438         *IsFast = Aligned;
1439 
1440       return Aligned;
1441     }
1442   }
1443 
1444   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1445     bool AlignedBy4 = Alignment >= Align(4);
1446     if (IsFast)
1447       *IsFast = AlignedBy4;
1448 
1449     return AlignedBy4 ||
1450            Subtarget->enableFlatScratch() ||
1451            Subtarget->hasUnalignedScratchAccess();
1452   }
1453 
1454   // FIXME: We have to be conservative here and assume that flat operations
1455   // will access scratch.  If we had access to the IR function, then we
1456   // could determine if any private memory was used in the function.
1457   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1458       !Subtarget->hasUnalignedScratchAccess()) {
1459     bool AlignedBy4 = Alignment >= Align(4);
1460     if (IsFast)
1461       *IsFast = AlignedBy4;
1462 
1463     return AlignedBy4;
1464   }
1465 
1466   if (Subtarget->hasUnalignedBufferAccessEnabled() &&
1467       !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1468         AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1469     // If we have an uniform constant load, it still requires using a slow
1470     // buffer instruction if unaligned.
1471     if (IsFast) {
1472       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1473       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1474       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1475                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1476         Alignment >= Align(4) : Alignment != Align(2);
1477     }
1478 
1479     return true;
1480   }
1481 
1482   // Smaller than dword value must be aligned.
1483   if (Size < 32)
1484     return false;
1485 
1486   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1487   // byte-address are ignored, thus forcing Dword alignment.
1488   // This applies to private, global, and constant memory.
1489   if (IsFast)
1490     *IsFast = true;
1491 
1492   return Size >= 32 && Alignment >= Align(4);
1493 }
1494 
1495 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1496     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1497     bool *IsFast) const {
1498   if (IsFast)
1499     *IsFast = false;
1500 
1501   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1502   // which isn't a simple VT.
1503   // Until MVT is extended to handle this, simply check for the size and
1504   // rely on the condition below: allow accesses if the size is a multiple of 4.
1505   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1506                            VT.getStoreSize() > 16)) {
1507     return false;
1508   }
1509 
1510   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1511                                             Alignment, Flags, IsFast);
1512 }
1513 
1514 EVT SITargetLowering::getOptimalMemOpType(
1515     const MemOp &Op, const AttributeList &FuncAttributes) const {
1516   // FIXME: Should account for address space here.
1517 
1518   // The default fallback uses the private pointer size as a guess for a type to
1519   // use. Make sure we switch these to 64-bit accesses.
1520 
1521   if (Op.size() >= 16 &&
1522       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1523     return MVT::v4i32;
1524 
1525   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1526     return MVT::v2i32;
1527 
1528   // Use the default.
1529   return MVT::Other;
1530 }
1531 
1532 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1533   const MemSDNode *MemNode = cast<MemSDNode>(N);
1534   const Value *Ptr = MemNode->getMemOperand()->getValue();
1535   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1536   return I && I->getMetadata("amdgpu.noclobber");
1537 }
1538 
1539 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1540   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1541          AS == AMDGPUAS::PRIVATE_ADDRESS;
1542 }
1543 
1544 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1545                                            unsigned DestAS) const {
1546   // Flat -> private/local is a simple truncate.
1547   // Flat -> global is no-op
1548   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1549     return true;
1550 
1551   const GCNTargetMachine &TM =
1552       static_cast<const GCNTargetMachine &>(getTargetMachine());
1553   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1554 }
1555 
1556 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1557   const MemSDNode *MemNode = cast<MemSDNode>(N);
1558 
1559   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1560 }
1561 
1562 TargetLoweringBase::LegalizeTypeAction
1563 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1564   int NumElts = VT.getVectorNumElements();
1565   if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1566     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1567   return TargetLoweringBase::getPreferredVectorAction(VT);
1568 }
1569 
1570 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1571                                                          Type *Ty) const {
1572   // FIXME: Could be smarter if called for vector constants.
1573   return true;
1574 }
1575 
1576 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1577   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1578     switch (Op) {
1579     case ISD::LOAD:
1580     case ISD::STORE:
1581 
1582     // These operations are done with 32-bit instructions anyway.
1583     case ISD::AND:
1584     case ISD::OR:
1585     case ISD::XOR:
1586     case ISD::SELECT:
1587       // TODO: Extensions?
1588       return true;
1589     default:
1590       return false;
1591     }
1592   }
1593 
1594   // SimplifySetCC uses this function to determine whether or not it should
1595   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1596   if (VT == MVT::i1 && Op == ISD::SETCC)
1597     return false;
1598 
1599   return TargetLowering::isTypeDesirableForOp(Op, VT);
1600 }
1601 
1602 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1603                                                    const SDLoc &SL,
1604                                                    SDValue Chain,
1605                                                    uint64_t Offset) const {
1606   const DataLayout &DL = DAG.getDataLayout();
1607   MachineFunction &MF = DAG.getMachineFunction();
1608   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1609 
1610   const ArgDescriptor *InputPtrReg;
1611   const TargetRegisterClass *RC;
1612   LLT ArgTy;
1613 
1614   std::tie(InputPtrReg, RC, ArgTy) =
1615       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1616 
1617   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1618   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1619   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1620     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1621 
1622   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1623 }
1624 
1625 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1626                                             const SDLoc &SL) const {
1627   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1628                                                FIRST_IMPLICIT);
1629   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1630 }
1631 
1632 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1633                                          const SDLoc &SL, SDValue Val,
1634                                          bool Signed,
1635                                          const ISD::InputArg *Arg) const {
1636   // First, if it is a widened vector, narrow it.
1637   if (VT.isVector() &&
1638       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1639     EVT NarrowedVT =
1640         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1641                          VT.getVectorNumElements());
1642     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1643                       DAG.getConstant(0, SL, MVT::i32));
1644   }
1645 
1646   // Then convert the vector elements or scalar value.
1647   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1648       VT.bitsLT(MemVT)) {
1649     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1650     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1651   }
1652 
1653   if (MemVT.isFloatingPoint())
1654     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1655   else if (Signed)
1656     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1657   else
1658     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1659 
1660   return Val;
1661 }
1662 
1663 SDValue SITargetLowering::lowerKernargMemParameter(
1664     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1665     uint64_t Offset, Align Alignment, bool Signed,
1666     const ISD::InputArg *Arg) const {
1667   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1668 
1669   // Try to avoid using an extload by loading earlier than the argument address,
1670   // and extracting the relevant bits. The load should hopefully be merged with
1671   // the previous argument.
1672   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1673     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1674     int64_t AlignDownOffset = alignDown(Offset, 4);
1675     int64_t OffsetDiff = Offset - AlignDownOffset;
1676 
1677     EVT IntVT = MemVT.changeTypeToInteger();
1678 
1679     // TODO: If we passed in the base kernel offset we could have a better
1680     // alignment than 4, but we don't really need it.
1681     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1682     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1683                                MachineMemOperand::MODereferenceable |
1684                                    MachineMemOperand::MOInvariant);
1685 
1686     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1687     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1688 
1689     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1690     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1691     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1692 
1693 
1694     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1695   }
1696 
1697   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1698   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1699                              MachineMemOperand::MODereferenceable |
1700                                  MachineMemOperand::MOInvariant);
1701 
1702   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1703   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1704 }
1705 
1706 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1707                                               const SDLoc &SL, SDValue Chain,
1708                                               const ISD::InputArg &Arg) const {
1709   MachineFunction &MF = DAG.getMachineFunction();
1710   MachineFrameInfo &MFI = MF.getFrameInfo();
1711 
1712   if (Arg.Flags.isByVal()) {
1713     unsigned Size = Arg.Flags.getByValSize();
1714     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1715     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1716   }
1717 
1718   unsigned ArgOffset = VA.getLocMemOffset();
1719   unsigned ArgSize = VA.getValVT().getStoreSize();
1720 
1721   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1722 
1723   // Create load nodes to retrieve arguments from the stack.
1724   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1725   SDValue ArgValue;
1726 
1727   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1728   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1729   MVT MemVT = VA.getValVT();
1730 
1731   switch (VA.getLocInfo()) {
1732   default:
1733     break;
1734   case CCValAssign::BCvt:
1735     MemVT = VA.getLocVT();
1736     break;
1737   case CCValAssign::SExt:
1738     ExtType = ISD::SEXTLOAD;
1739     break;
1740   case CCValAssign::ZExt:
1741     ExtType = ISD::ZEXTLOAD;
1742     break;
1743   case CCValAssign::AExt:
1744     ExtType = ISD::EXTLOAD;
1745     break;
1746   }
1747 
1748   ArgValue = DAG.getExtLoad(
1749     ExtType, SL, VA.getLocVT(), Chain, FIN,
1750     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1751     MemVT);
1752   return ArgValue;
1753 }
1754 
1755 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1756   const SIMachineFunctionInfo &MFI,
1757   EVT VT,
1758   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1759   const ArgDescriptor *Reg;
1760   const TargetRegisterClass *RC;
1761   LLT Ty;
1762 
1763   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1764   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1765 }
1766 
1767 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1768                                CallingConv::ID CallConv,
1769                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1770                                FunctionType *FType,
1771                                SIMachineFunctionInfo *Info) {
1772   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1773     const ISD::InputArg *Arg = &Ins[I];
1774 
1775     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1776            "vector type argument should have been split");
1777 
1778     // First check if it's a PS input addr.
1779     if (CallConv == CallingConv::AMDGPU_PS &&
1780         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1781       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1782 
1783       // Inconveniently only the first part of the split is marked as isSplit,
1784       // so skip to the end. We only want to increment PSInputNum once for the
1785       // entire split argument.
1786       if (Arg->Flags.isSplit()) {
1787         while (!Arg->Flags.isSplitEnd()) {
1788           assert((!Arg->VT.isVector() ||
1789                   Arg->VT.getScalarSizeInBits() == 16) &&
1790                  "unexpected vector split in ps argument type");
1791           if (!SkipArg)
1792             Splits.push_back(*Arg);
1793           Arg = &Ins[++I];
1794         }
1795       }
1796 
1797       if (SkipArg) {
1798         // We can safely skip PS inputs.
1799         Skipped.set(Arg->getOrigArgIndex());
1800         ++PSInputNum;
1801         continue;
1802       }
1803 
1804       Info->markPSInputAllocated(PSInputNum);
1805       if (Arg->Used)
1806         Info->markPSInputEnabled(PSInputNum);
1807 
1808       ++PSInputNum;
1809     }
1810 
1811     Splits.push_back(*Arg);
1812   }
1813 }
1814 
1815 // Allocate special inputs passed in VGPRs.
1816 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1817                                                       MachineFunction &MF,
1818                                                       const SIRegisterInfo &TRI,
1819                                                       SIMachineFunctionInfo &Info) const {
1820   const LLT S32 = LLT::scalar(32);
1821   MachineRegisterInfo &MRI = MF.getRegInfo();
1822 
1823   if (Info.hasWorkItemIDX()) {
1824     Register Reg = AMDGPU::VGPR0;
1825     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1826 
1827     CCInfo.AllocateReg(Reg);
1828     unsigned Mask = (Subtarget->hasPackedTID() &&
1829                      Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
1830     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1831   }
1832 
1833   if (Info.hasWorkItemIDY()) {
1834     assert(Info.hasWorkItemIDX());
1835     if (Subtarget->hasPackedTID()) {
1836       Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1837                                                         0x3ff << 10));
1838     } else {
1839       unsigned Reg = AMDGPU::VGPR1;
1840       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1841 
1842       CCInfo.AllocateReg(Reg);
1843       Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1844     }
1845   }
1846 
1847   if (Info.hasWorkItemIDZ()) {
1848     assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
1849     if (Subtarget->hasPackedTID()) {
1850       Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1851                                                         0x3ff << 20));
1852     } else {
1853       unsigned Reg = AMDGPU::VGPR2;
1854       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1855 
1856       CCInfo.AllocateReg(Reg);
1857       Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1858     }
1859   }
1860 }
1861 
1862 // Try to allocate a VGPR at the end of the argument list, or if no argument
1863 // VGPRs are left allocating a stack slot.
1864 // If \p Mask is is given it indicates bitfield position in the register.
1865 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1866 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1867                                          ArgDescriptor Arg = ArgDescriptor()) {
1868   if (Arg.isSet())
1869     return ArgDescriptor::createArg(Arg, Mask);
1870 
1871   ArrayRef<MCPhysReg> ArgVGPRs
1872     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1873   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1874   if (RegIdx == ArgVGPRs.size()) {
1875     // Spill to stack required.
1876     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1877 
1878     return ArgDescriptor::createStack(Offset, Mask);
1879   }
1880 
1881   unsigned Reg = ArgVGPRs[RegIdx];
1882   Reg = CCInfo.AllocateReg(Reg);
1883   assert(Reg != AMDGPU::NoRegister);
1884 
1885   MachineFunction &MF = CCInfo.getMachineFunction();
1886   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1887   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1888   return ArgDescriptor::createRegister(Reg, Mask);
1889 }
1890 
1891 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1892                                              const TargetRegisterClass *RC,
1893                                              unsigned NumArgRegs) {
1894   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1895   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1896   if (RegIdx == ArgSGPRs.size())
1897     report_fatal_error("ran out of SGPRs for arguments");
1898 
1899   unsigned Reg = ArgSGPRs[RegIdx];
1900   Reg = CCInfo.AllocateReg(Reg);
1901   assert(Reg != AMDGPU::NoRegister);
1902 
1903   MachineFunction &MF = CCInfo.getMachineFunction();
1904   MF.addLiveIn(Reg, RC);
1905   return ArgDescriptor::createRegister(Reg);
1906 }
1907 
1908 // If this has a fixed position, we still should allocate the register in the
1909 // CCInfo state. Technically we could get away with this for values passed
1910 // outside of the normal argument range.
1911 static void allocateFixedSGPRInputImpl(CCState &CCInfo,
1912                                        const TargetRegisterClass *RC,
1913                                        MCRegister Reg) {
1914   Reg = CCInfo.AllocateReg(Reg);
1915   assert(Reg != AMDGPU::NoRegister);
1916   MachineFunction &MF = CCInfo.getMachineFunction();
1917   MF.addLiveIn(Reg, RC);
1918 }
1919 
1920 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
1921   if (Arg) {
1922     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
1923                                Arg.getRegister());
1924   } else
1925     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1926 }
1927 
1928 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
1929   if (Arg) {
1930     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
1931                                Arg.getRegister());
1932   } else
1933     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1934 }
1935 
1936 /// Allocate implicit function VGPR arguments at the end of allocated user
1937 /// arguments.
1938 void SITargetLowering::allocateSpecialInputVGPRs(
1939   CCState &CCInfo, MachineFunction &MF,
1940   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1941   const unsigned Mask = 0x3ff;
1942   ArgDescriptor Arg;
1943 
1944   if (Info.hasWorkItemIDX()) {
1945     Arg = allocateVGPR32Input(CCInfo, Mask);
1946     Info.setWorkItemIDX(Arg);
1947   }
1948 
1949   if (Info.hasWorkItemIDY()) {
1950     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1951     Info.setWorkItemIDY(Arg);
1952   }
1953 
1954   if (Info.hasWorkItemIDZ())
1955     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1956 }
1957 
1958 /// Allocate implicit function VGPR arguments in fixed registers.
1959 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1960   CCState &CCInfo, MachineFunction &MF,
1961   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1962   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1963   if (!Reg)
1964     report_fatal_error("failed to allocated VGPR for implicit arguments");
1965 
1966   const unsigned Mask = 0x3ff;
1967   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1968   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1969   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1970 }
1971 
1972 void SITargetLowering::allocateSpecialInputSGPRs(
1973   CCState &CCInfo,
1974   MachineFunction &MF,
1975   const SIRegisterInfo &TRI,
1976   SIMachineFunctionInfo &Info) const {
1977   auto &ArgInfo = Info.getArgInfo();
1978 
1979   // TODO: Unify handling with private memory pointers.
1980 
1981   if (Info.hasDispatchPtr())
1982     allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
1983 
1984   if (Info.hasQueuePtr())
1985     allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
1986 
1987   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
1988   // constant offset from the kernarg segment.
1989   if (Info.hasImplicitArgPtr())
1990     allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
1991 
1992   if (Info.hasDispatchID())
1993     allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
1994 
1995   // flat_scratch_init is not applicable for non-kernel functions.
1996 
1997   if (Info.hasWorkGroupIDX())
1998     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
1999 
2000   if (Info.hasWorkGroupIDY())
2001     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2002 
2003   if (Info.hasWorkGroupIDZ())
2004     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2005 }
2006 
2007 // Allocate special inputs passed in user SGPRs.
2008 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2009                                             MachineFunction &MF,
2010                                             const SIRegisterInfo &TRI,
2011                                             SIMachineFunctionInfo &Info) const {
2012   if (Info.hasImplicitBufferPtr()) {
2013     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2014     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2015     CCInfo.AllocateReg(ImplicitBufferPtrReg);
2016   }
2017 
2018   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2019   if (Info.hasPrivateSegmentBuffer()) {
2020     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2021     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2022     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2023   }
2024 
2025   if (Info.hasDispatchPtr()) {
2026     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2027     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2028     CCInfo.AllocateReg(DispatchPtrReg);
2029   }
2030 
2031   if (Info.hasQueuePtr()) {
2032     Register QueuePtrReg = Info.addQueuePtr(TRI);
2033     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2034     CCInfo.AllocateReg(QueuePtrReg);
2035   }
2036 
2037   if (Info.hasKernargSegmentPtr()) {
2038     MachineRegisterInfo &MRI = MF.getRegInfo();
2039     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2040     CCInfo.AllocateReg(InputPtrReg);
2041 
2042     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2043     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2044   }
2045 
2046   if (Info.hasDispatchID()) {
2047     Register DispatchIDReg = Info.addDispatchID(TRI);
2048     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2049     CCInfo.AllocateReg(DispatchIDReg);
2050   }
2051 
2052   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2053     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2054     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2055     CCInfo.AllocateReg(FlatScratchInitReg);
2056   }
2057 
2058   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2059   // these from the dispatch pointer.
2060 }
2061 
2062 // Allocate special input registers that are initialized per-wave.
2063 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2064                                            MachineFunction &MF,
2065                                            SIMachineFunctionInfo &Info,
2066                                            CallingConv::ID CallConv,
2067                                            bool IsShader) const {
2068   if (Info.hasWorkGroupIDX()) {
2069     Register Reg = Info.addWorkGroupIDX();
2070     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2071     CCInfo.AllocateReg(Reg);
2072   }
2073 
2074   if (Info.hasWorkGroupIDY()) {
2075     Register Reg = Info.addWorkGroupIDY();
2076     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2077     CCInfo.AllocateReg(Reg);
2078   }
2079 
2080   if (Info.hasWorkGroupIDZ()) {
2081     Register Reg = Info.addWorkGroupIDZ();
2082     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2083     CCInfo.AllocateReg(Reg);
2084   }
2085 
2086   if (Info.hasWorkGroupInfo()) {
2087     Register Reg = Info.addWorkGroupInfo();
2088     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2089     CCInfo.AllocateReg(Reg);
2090   }
2091 
2092   if (Info.hasPrivateSegmentWaveByteOffset()) {
2093     // Scratch wave offset passed in system SGPR.
2094     unsigned PrivateSegmentWaveByteOffsetReg;
2095 
2096     if (IsShader) {
2097       PrivateSegmentWaveByteOffsetReg =
2098         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2099 
2100       // This is true if the scratch wave byte offset doesn't have a fixed
2101       // location.
2102       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2103         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2104         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2105       }
2106     } else
2107       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2108 
2109     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2110     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2111   }
2112 }
2113 
2114 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2115                                      MachineFunction &MF,
2116                                      const SIRegisterInfo &TRI,
2117                                      SIMachineFunctionInfo &Info) {
2118   // Now that we've figured out where the scratch register inputs are, see if
2119   // should reserve the arguments and use them directly.
2120   MachineFrameInfo &MFI = MF.getFrameInfo();
2121   bool HasStackObjects = MFI.hasStackObjects();
2122   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2123 
2124   // Record that we know we have non-spill stack objects so we don't need to
2125   // check all stack objects later.
2126   if (HasStackObjects)
2127     Info.setHasNonSpillStackObjects(true);
2128 
2129   // Everything live out of a block is spilled with fast regalloc, so it's
2130   // almost certain that spilling will be required.
2131   if (TM.getOptLevel() == CodeGenOpt::None)
2132     HasStackObjects = true;
2133 
2134   // For now assume stack access is needed in any callee functions, so we need
2135   // the scratch registers to pass in.
2136   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2137 
2138   if (!ST.enableFlatScratch()) {
2139     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2140       // If we have stack objects, we unquestionably need the private buffer
2141       // resource. For the Code Object V2 ABI, this will be the first 4 user
2142       // SGPR inputs. We can reserve those and use them directly.
2143 
2144       Register PrivateSegmentBufferReg =
2145           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2146       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2147     } else {
2148       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2149       // We tentatively reserve the last registers (skipping the last registers
2150       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2151       // we'll replace these with the ones immediately after those which were
2152       // really allocated. In the prologue copies will be inserted from the
2153       // argument to these reserved registers.
2154 
2155       // Without HSA, relocations are used for the scratch pointer and the
2156       // buffer resource setup is always inserted in the prologue. Scratch wave
2157       // offset is still in an input SGPR.
2158       Info.setScratchRSrcReg(ReservedBufferReg);
2159     }
2160   }
2161 
2162   MachineRegisterInfo &MRI = MF.getRegInfo();
2163 
2164   // For entry functions we have to set up the stack pointer if we use it,
2165   // whereas non-entry functions get this "for free". This means there is no
2166   // intrinsic advantage to using S32 over S34 in cases where we do not have
2167   // calls but do need a frame pointer (i.e. if we are requested to have one
2168   // because frame pointer elimination is disabled). To keep things simple we
2169   // only ever use S32 as the call ABI stack pointer, and so using it does not
2170   // imply we need a separate frame pointer.
2171   //
2172   // Try to use s32 as the SP, but move it if it would interfere with input
2173   // arguments. This won't work with calls though.
2174   //
2175   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2176   // registers.
2177   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2178     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2179   } else {
2180     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2181 
2182     if (MFI.hasCalls())
2183       report_fatal_error("call in graphics shader with too many input SGPRs");
2184 
2185     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2186       if (!MRI.isLiveIn(Reg)) {
2187         Info.setStackPtrOffsetReg(Reg);
2188         break;
2189       }
2190     }
2191 
2192     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2193       report_fatal_error("failed to find register for SP");
2194   }
2195 
2196   // hasFP should be accurate for entry functions even before the frame is
2197   // finalized, because it does not rely on the known stack size, only
2198   // properties like whether variable sized objects are present.
2199   if (ST.getFrameLowering()->hasFP(MF)) {
2200     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2201   }
2202 }
2203 
2204 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2205   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2206   return !Info->isEntryFunction();
2207 }
2208 
2209 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2210 
2211 }
2212 
2213 void SITargetLowering::insertCopiesSplitCSR(
2214   MachineBasicBlock *Entry,
2215   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2216   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2217 
2218   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2219   if (!IStart)
2220     return;
2221 
2222   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2223   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2224   MachineBasicBlock::iterator MBBI = Entry->begin();
2225   for (const MCPhysReg *I = IStart; *I; ++I) {
2226     const TargetRegisterClass *RC = nullptr;
2227     if (AMDGPU::SReg_64RegClass.contains(*I))
2228       RC = &AMDGPU::SGPR_64RegClass;
2229     else if (AMDGPU::SReg_32RegClass.contains(*I))
2230       RC = &AMDGPU::SGPR_32RegClass;
2231     else
2232       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2233 
2234     Register NewVR = MRI->createVirtualRegister(RC);
2235     // Create copy from CSR to a virtual register.
2236     Entry->addLiveIn(*I);
2237     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2238       .addReg(*I);
2239 
2240     // Insert the copy-back instructions right before the terminator.
2241     for (auto *Exit : Exits)
2242       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2243               TII->get(TargetOpcode::COPY), *I)
2244         .addReg(NewVR);
2245   }
2246 }
2247 
2248 SDValue SITargetLowering::LowerFormalArguments(
2249     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2250     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2251     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2252   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2253 
2254   MachineFunction &MF = DAG.getMachineFunction();
2255   const Function &Fn = MF.getFunction();
2256   FunctionType *FType = MF.getFunction().getFunctionType();
2257   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2258 
2259   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2260     DiagnosticInfoUnsupported NoGraphicsHSA(
2261         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2262     DAG.getContext()->diagnose(NoGraphicsHSA);
2263     return DAG.getEntryNode();
2264   }
2265 
2266   SmallVector<ISD::InputArg, 16> Splits;
2267   SmallVector<CCValAssign, 16> ArgLocs;
2268   BitVector Skipped(Ins.size());
2269   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2270                  *DAG.getContext());
2271 
2272   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2273   bool IsKernel = AMDGPU::isKernel(CallConv);
2274   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2275 
2276   if (IsGraphics) {
2277     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2278            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2279            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2280            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2281            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2282            !Info->hasWorkItemIDZ());
2283   }
2284 
2285   if (CallConv == CallingConv::AMDGPU_PS) {
2286     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2287 
2288     // At least one interpolation mode must be enabled or else the GPU will
2289     // hang.
2290     //
2291     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2292     // set PSInputAddr, the user wants to enable some bits after the compilation
2293     // based on run-time states. Since we can't know what the final PSInputEna
2294     // will look like, so we shouldn't do anything here and the user should take
2295     // responsibility for the correct programming.
2296     //
2297     // Otherwise, the following restrictions apply:
2298     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2299     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2300     //   enabled too.
2301     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2302         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2303       CCInfo.AllocateReg(AMDGPU::VGPR0);
2304       CCInfo.AllocateReg(AMDGPU::VGPR1);
2305       Info->markPSInputAllocated(0);
2306       Info->markPSInputEnabled(0);
2307     }
2308     if (Subtarget->isAmdPalOS()) {
2309       // For isAmdPalOS, the user does not enable some bits after compilation
2310       // based on run-time states; the register values being generated here are
2311       // the final ones set in hardware. Therefore we need to apply the
2312       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2313       // a bit is set in PSInputAddr but not PSInputEnable is where the
2314       // frontend set up an input arg for a particular interpolation mode, but
2315       // nothing uses that input arg. Really we should have an earlier pass
2316       // that removes such an arg.)
2317       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2318       if ((PsInputBits & 0x7F) == 0 ||
2319           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2320         Info->markPSInputEnabled(
2321             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2322     }
2323   } else if (IsKernel) {
2324     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2325   } else {
2326     Splits.append(Ins.begin(), Ins.end());
2327   }
2328 
2329   if (IsEntryFunc) {
2330     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2331     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2332   } else {
2333     // For the fixed ABI, pass workitem IDs in the last argument register.
2334     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2335       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2336   }
2337 
2338   if (IsKernel) {
2339     analyzeFormalArgumentsCompute(CCInfo, Ins);
2340   } else {
2341     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2342     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2343   }
2344 
2345   SmallVector<SDValue, 16> Chains;
2346 
2347   // FIXME: This is the minimum kernel argument alignment. We should improve
2348   // this to the maximum alignment of the arguments.
2349   //
2350   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2351   // kern arg offset.
2352   const Align KernelArgBaseAlign = Align(16);
2353 
2354   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2355     const ISD::InputArg &Arg = Ins[i];
2356     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2357       InVals.push_back(DAG.getUNDEF(Arg.VT));
2358       continue;
2359     }
2360 
2361     CCValAssign &VA = ArgLocs[ArgIdx++];
2362     MVT VT = VA.getLocVT();
2363 
2364     if (IsEntryFunc && VA.isMemLoc()) {
2365       VT = Ins[i].VT;
2366       EVT MemVT = VA.getLocVT();
2367 
2368       const uint64_t Offset = VA.getLocMemOffset();
2369       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2370 
2371       if (Arg.Flags.isByRef()) {
2372         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2373 
2374         const GCNTargetMachine &TM =
2375             static_cast<const GCNTargetMachine &>(getTargetMachine());
2376         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2377                                     Arg.Flags.getPointerAddrSpace())) {
2378           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2379                                      Arg.Flags.getPointerAddrSpace());
2380         }
2381 
2382         InVals.push_back(Ptr);
2383         continue;
2384       }
2385 
2386       SDValue Arg = lowerKernargMemParameter(
2387         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2388       Chains.push_back(Arg.getValue(1));
2389 
2390       auto *ParamTy =
2391         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2392       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2393           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2394                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2395         // On SI local pointers are just offsets into LDS, so they are always
2396         // less than 16-bits.  On CI and newer they could potentially be
2397         // real pointers, so we can't guarantee their size.
2398         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2399                           DAG.getValueType(MVT::i16));
2400       }
2401 
2402       InVals.push_back(Arg);
2403       continue;
2404     } else if (!IsEntryFunc && VA.isMemLoc()) {
2405       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2406       InVals.push_back(Val);
2407       if (!Arg.Flags.isByVal())
2408         Chains.push_back(Val.getValue(1));
2409       continue;
2410     }
2411 
2412     assert(VA.isRegLoc() && "Parameter must be in a register!");
2413 
2414     Register Reg = VA.getLocReg();
2415     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2416     EVT ValVT = VA.getValVT();
2417 
2418     Reg = MF.addLiveIn(Reg, RC);
2419     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2420 
2421     if (Arg.Flags.isSRet()) {
2422       // The return object should be reasonably addressable.
2423 
2424       // FIXME: This helps when the return is a real sret. If it is a
2425       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2426       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2427       unsigned NumBits
2428         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2429       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2430         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2431     }
2432 
2433     // If this is an 8 or 16-bit value, it is really passed promoted
2434     // to 32 bits. Insert an assert[sz]ext to capture this, then
2435     // truncate to the right size.
2436     switch (VA.getLocInfo()) {
2437     case CCValAssign::Full:
2438       break;
2439     case CCValAssign::BCvt:
2440       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2441       break;
2442     case CCValAssign::SExt:
2443       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2444                         DAG.getValueType(ValVT));
2445       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2446       break;
2447     case CCValAssign::ZExt:
2448       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2449                         DAG.getValueType(ValVT));
2450       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2451       break;
2452     case CCValAssign::AExt:
2453       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2454       break;
2455     default:
2456       llvm_unreachable("Unknown loc info!");
2457     }
2458 
2459     InVals.push_back(Val);
2460   }
2461 
2462   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2463     // Special inputs come after user arguments.
2464     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2465   }
2466 
2467   // Start adding system SGPRs.
2468   if (IsEntryFunc) {
2469     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2470   } else {
2471     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2472     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2473   }
2474 
2475   auto &ArgUsageInfo =
2476     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2477   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2478 
2479   unsigned StackArgSize = CCInfo.getNextStackOffset();
2480   Info->setBytesInStackArgArea(StackArgSize);
2481 
2482   return Chains.empty() ? Chain :
2483     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2484 }
2485 
2486 // TODO: If return values can't fit in registers, we should return as many as
2487 // possible in registers before passing on stack.
2488 bool SITargetLowering::CanLowerReturn(
2489   CallingConv::ID CallConv,
2490   MachineFunction &MF, bool IsVarArg,
2491   const SmallVectorImpl<ISD::OutputArg> &Outs,
2492   LLVMContext &Context) const {
2493   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2494   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2495   // for shaders. Vector types should be explicitly handled by CC.
2496   if (AMDGPU::isEntryFunctionCC(CallConv))
2497     return true;
2498 
2499   SmallVector<CCValAssign, 16> RVLocs;
2500   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2501   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2502 }
2503 
2504 SDValue
2505 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2506                               bool isVarArg,
2507                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2508                               const SmallVectorImpl<SDValue> &OutVals,
2509                               const SDLoc &DL, SelectionDAG &DAG) const {
2510   MachineFunction &MF = DAG.getMachineFunction();
2511   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2512 
2513   if (AMDGPU::isKernel(CallConv)) {
2514     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2515                                              OutVals, DL, DAG);
2516   }
2517 
2518   bool IsShader = AMDGPU::isShader(CallConv);
2519 
2520   Info->setIfReturnsVoid(Outs.empty());
2521   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2522 
2523   // CCValAssign - represent the assignment of the return value to a location.
2524   SmallVector<CCValAssign, 48> RVLocs;
2525   SmallVector<ISD::OutputArg, 48> Splits;
2526 
2527   // CCState - Info about the registers and stack slots.
2528   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2529                  *DAG.getContext());
2530 
2531   // Analyze outgoing return values.
2532   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2533 
2534   SDValue Flag;
2535   SmallVector<SDValue, 48> RetOps;
2536   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2537 
2538   // Add return address for callable functions.
2539   if (!Info->isEntryFunction()) {
2540     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2541     SDValue ReturnAddrReg = CreateLiveInRegister(
2542       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2543 
2544     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2545         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2546         MVT::i64);
2547     Chain =
2548         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2549     Flag = Chain.getValue(1);
2550     RetOps.push_back(ReturnAddrVirtualReg);
2551   }
2552 
2553   // Copy the result values into the output registers.
2554   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2555        ++I, ++RealRVLocIdx) {
2556     CCValAssign &VA = RVLocs[I];
2557     assert(VA.isRegLoc() && "Can only return in registers!");
2558     // TODO: Partially return in registers if return values don't fit.
2559     SDValue Arg = OutVals[RealRVLocIdx];
2560 
2561     // Copied from other backends.
2562     switch (VA.getLocInfo()) {
2563     case CCValAssign::Full:
2564       break;
2565     case CCValAssign::BCvt:
2566       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2567       break;
2568     case CCValAssign::SExt:
2569       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2570       break;
2571     case CCValAssign::ZExt:
2572       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2573       break;
2574     case CCValAssign::AExt:
2575       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2576       break;
2577     default:
2578       llvm_unreachable("Unknown loc info!");
2579     }
2580 
2581     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2582     Flag = Chain.getValue(1);
2583     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2584   }
2585 
2586   // FIXME: Does sret work properly?
2587   if (!Info->isEntryFunction()) {
2588     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2589     const MCPhysReg *I =
2590       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2591     if (I) {
2592       for (; *I; ++I) {
2593         if (AMDGPU::SReg_64RegClass.contains(*I))
2594           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2595         else if (AMDGPU::SReg_32RegClass.contains(*I))
2596           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2597         else
2598           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2599       }
2600     }
2601   }
2602 
2603   // Update chain and glue.
2604   RetOps[0] = Chain;
2605   if (Flag.getNode())
2606     RetOps.push_back(Flag);
2607 
2608   unsigned Opc = AMDGPUISD::ENDPGM;
2609   if (!IsWaveEnd)
2610     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2611   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2612 }
2613 
2614 SDValue SITargetLowering::LowerCallResult(
2615     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2616     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2617     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2618     SDValue ThisVal) const {
2619   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2620 
2621   // Assign locations to each value returned by this call.
2622   SmallVector<CCValAssign, 16> RVLocs;
2623   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2624                  *DAG.getContext());
2625   CCInfo.AnalyzeCallResult(Ins, RetCC);
2626 
2627   // Copy all of the result registers out of their specified physreg.
2628   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2629     CCValAssign VA = RVLocs[i];
2630     SDValue Val;
2631 
2632     if (VA.isRegLoc()) {
2633       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2634       Chain = Val.getValue(1);
2635       InFlag = Val.getValue(2);
2636     } else if (VA.isMemLoc()) {
2637       report_fatal_error("TODO: return values in memory");
2638     } else
2639       llvm_unreachable("unknown argument location type");
2640 
2641     switch (VA.getLocInfo()) {
2642     case CCValAssign::Full:
2643       break;
2644     case CCValAssign::BCvt:
2645       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2646       break;
2647     case CCValAssign::ZExt:
2648       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2649                         DAG.getValueType(VA.getValVT()));
2650       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2651       break;
2652     case CCValAssign::SExt:
2653       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2654                         DAG.getValueType(VA.getValVT()));
2655       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2656       break;
2657     case CCValAssign::AExt:
2658       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2659       break;
2660     default:
2661       llvm_unreachable("Unknown loc info!");
2662     }
2663 
2664     InVals.push_back(Val);
2665   }
2666 
2667   return Chain;
2668 }
2669 
2670 // Add code to pass special inputs required depending on used features separate
2671 // from the explicit user arguments present in the IR.
2672 void SITargetLowering::passSpecialInputs(
2673     CallLoweringInfo &CLI,
2674     CCState &CCInfo,
2675     const SIMachineFunctionInfo &Info,
2676     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2677     SmallVectorImpl<SDValue> &MemOpChains,
2678     SDValue Chain) const {
2679   // If we don't have a call site, this was a call inserted by
2680   // legalization. These can never use special inputs.
2681   if (!CLI.CB)
2682     return;
2683 
2684   SelectionDAG &DAG = CLI.DAG;
2685   const SDLoc &DL = CLI.DL;
2686 
2687   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2688   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2689 
2690   const AMDGPUFunctionArgInfo *CalleeArgInfo
2691     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2692   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2693     auto &ArgUsageInfo =
2694       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2695     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2696   }
2697 
2698   // TODO: Unify with private memory register handling. This is complicated by
2699   // the fact that at least in kernels, the input argument is not necessarily
2700   // in the same location as the input.
2701   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2702     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2703     AMDGPUFunctionArgInfo::QUEUE_PTR,
2704     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
2705     AMDGPUFunctionArgInfo::DISPATCH_ID,
2706     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2707     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2708     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
2709   };
2710 
2711   for (auto InputID : InputRegs) {
2712     const ArgDescriptor *OutgoingArg;
2713     const TargetRegisterClass *ArgRC;
2714     LLT ArgTy;
2715 
2716     std::tie(OutgoingArg, ArgRC, ArgTy) =
2717         CalleeArgInfo->getPreloadedValue(InputID);
2718     if (!OutgoingArg)
2719       continue;
2720 
2721     const ArgDescriptor *IncomingArg;
2722     const TargetRegisterClass *IncomingArgRC;
2723     LLT Ty;
2724     std::tie(IncomingArg, IncomingArgRC, Ty) =
2725         CallerArgInfo.getPreloadedValue(InputID);
2726     assert(IncomingArgRC == ArgRC);
2727 
2728     // All special arguments are ints for now.
2729     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2730     SDValue InputReg;
2731 
2732     if (IncomingArg) {
2733       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2734     } else {
2735       // The implicit arg ptr is special because it doesn't have a corresponding
2736       // input for kernels, and is computed from the kernarg segment pointer.
2737       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2738       InputReg = getImplicitArgPtr(DAG, DL);
2739     }
2740 
2741     if (OutgoingArg->isRegister()) {
2742       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2743       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2744         report_fatal_error("failed to allocate implicit input argument");
2745     } else {
2746       unsigned SpecialArgOffset =
2747           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2748       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2749                                               SpecialArgOffset);
2750       MemOpChains.push_back(ArgStore);
2751     }
2752   }
2753 
2754   // Pack workitem IDs into a single register or pass it as is if already
2755   // packed.
2756   const ArgDescriptor *OutgoingArg;
2757   const TargetRegisterClass *ArgRC;
2758   LLT Ty;
2759 
2760   std::tie(OutgoingArg, ArgRC, Ty) =
2761       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2762   if (!OutgoingArg)
2763     std::tie(OutgoingArg, ArgRC, Ty) =
2764         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2765   if (!OutgoingArg)
2766     std::tie(OutgoingArg, ArgRC, Ty) =
2767         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2768   if (!OutgoingArg)
2769     return;
2770 
2771   const ArgDescriptor *IncomingArgX = std::get<0>(
2772       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2773   const ArgDescriptor *IncomingArgY = std::get<0>(
2774       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2775   const ArgDescriptor *IncomingArgZ = std::get<0>(
2776       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2777 
2778   SDValue InputReg;
2779   SDLoc SL;
2780 
2781   // If incoming ids are not packed we need to pack them.
2782   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX)
2783     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2784 
2785   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
2786     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2787     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2788                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2789     InputReg = InputReg.getNode() ?
2790                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2791   }
2792 
2793   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
2794     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2795     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2796                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2797     InputReg = InputReg.getNode() ?
2798                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2799   }
2800 
2801   if (!InputReg.getNode()) {
2802     // Workitem ids are already packed, any of present incoming arguments
2803     // will carry all required fields.
2804     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2805       IncomingArgX ? *IncomingArgX :
2806       IncomingArgY ? *IncomingArgY :
2807                      *IncomingArgZ, ~0u);
2808     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2809   }
2810 
2811   if (OutgoingArg->isRegister()) {
2812     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2813     CCInfo.AllocateReg(OutgoingArg->getRegister());
2814   } else {
2815     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2816     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2817                                             SpecialArgOffset);
2818     MemOpChains.push_back(ArgStore);
2819   }
2820 }
2821 
2822 static bool canGuaranteeTCO(CallingConv::ID CC) {
2823   return CC == CallingConv::Fast;
2824 }
2825 
2826 /// Return true if we might ever do TCO for calls with this calling convention.
2827 static bool mayTailCallThisCC(CallingConv::ID CC) {
2828   switch (CC) {
2829   case CallingConv::C:
2830     return true;
2831   default:
2832     return canGuaranteeTCO(CC);
2833   }
2834 }
2835 
2836 bool SITargetLowering::isEligibleForTailCallOptimization(
2837     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2838     const SmallVectorImpl<ISD::OutputArg> &Outs,
2839     const SmallVectorImpl<SDValue> &OutVals,
2840     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2841   if (!mayTailCallThisCC(CalleeCC))
2842     return false;
2843 
2844   MachineFunction &MF = DAG.getMachineFunction();
2845   const Function &CallerF = MF.getFunction();
2846   CallingConv::ID CallerCC = CallerF.getCallingConv();
2847   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2848   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2849 
2850   // Kernels aren't callable, and don't have a live in return address so it
2851   // doesn't make sense to do a tail call with entry functions.
2852   if (!CallerPreserved)
2853     return false;
2854 
2855   bool CCMatch = CallerCC == CalleeCC;
2856 
2857   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2858     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2859       return true;
2860     return false;
2861   }
2862 
2863   // TODO: Can we handle var args?
2864   if (IsVarArg)
2865     return false;
2866 
2867   for (const Argument &Arg : CallerF.args()) {
2868     if (Arg.hasByValAttr())
2869       return false;
2870   }
2871 
2872   LLVMContext &Ctx = *DAG.getContext();
2873 
2874   // Check that the call results are passed in the same way.
2875   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2876                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2877                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2878     return false;
2879 
2880   // The callee has to preserve all registers the caller needs to preserve.
2881   if (!CCMatch) {
2882     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2883     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2884       return false;
2885   }
2886 
2887   // Nothing more to check if the callee is taking no arguments.
2888   if (Outs.empty())
2889     return true;
2890 
2891   SmallVector<CCValAssign, 16> ArgLocs;
2892   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2893 
2894   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2895 
2896   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2897   // If the stack arguments for this call do not fit into our own save area then
2898   // the call cannot be made tail.
2899   // TODO: Is this really necessary?
2900   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2901     return false;
2902 
2903   const MachineRegisterInfo &MRI = MF.getRegInfo();
2904   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2905 }
2906 
2907 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2908   if (!CI->isTailCall())
2909     return false;
2910 
2911   const Function *ParentFn = CI->getParent()->getParent();
2912   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2913     return false;
2914   return true;
2915 }
2916 
2917 // The wave scratch offset register is used as the global base pointer.
2918 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2919                                     SmallVectorImpl<SDValue> &InVals) const {
2920   SelectionDAG &DAG = CLI.DAG;
2921   const SDLoc &DL = CLI.DL;
2922   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2923   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2924   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2925   SDValue Chain = CLI.Chain;
2926   SDValue Callee = CLI.Callee;
2927   bool &IsTailCall = CLI.IsTailCall;
2928   CallingConv::ID CallConv = CLI.CallConv;
2929   bool IsVarArg = CLI.IsVarArg;
2930   bool IsSibCall = false;
2931   bool IsThisReturn = false;
2932   MachineFunction &MF = DAG.getMachineFunction();
2933 
2934   if (Callee.isUndef() || isNullConstant(Callee)) {
2935     if (!CLI.IsTailCall) {
2936       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2937         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2938     }
2939 
2940     return Chain;
2941   }
2942 
2943   if (IsVarArg) {
2944     return lowerUnhandledCall(CLI, InVals,
2945                               "unsupported call to variadic function ");
2946   }
2947 
2948   if (!CLI.CB)
2949     report_fatal_error("unsupported libcall legalization");
2950 
2951   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
2952       !CLI.CB->getCalledFunction() && CallConv != CallingConv::AMDGPU_Gfx) {
2953     return lowerUnhandledCall(CLI, InVals,
2954                               "unsupported indirect call to function ");
2955   }
2956 
2957   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2958     return lowerUnhandledCall(CLI, InVals,
2959                               "unsupported required tail call to function ");
2960   }
2961 
2962   if (AMDGPU::isShader(CallConv)) {
2963     // Note the issue is with the CC of the called function, not of the call
2964     // itself.
2965     return lowerUnhandledCall(CLI, InVals,
2966                               "unsupported call to a shader function ");
2967   }
2968 
2969   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
2970       CallConv != CallingConv::AMDGPU_Gfx) {
2971     // Only allow calls with specific calling conventions.
2972     return lowerUnhandledCall(CLI, InVals,
2973                               "unsupported calling convention for call from "
2974                               "graphics shader of function ");
2975   }
2976 
2977   if (IsTailCall) {
2978     IsTailCall = isEligibleForTailCallOptimization(
2979       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2980     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
2981       report_fatal_error("failed to perform tail call elimination on a call "
2982                          "site marked musttail");
2983     }
2984 
2985     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2986 
2987     // A sibling call is one where we're under the usual C ABI and not planning
2988     // to change that but can still do a tail call:
2989     if (!TailCallOpt && IsTailCall)
2990       IsSibCall = true;
2991 
2992     if (IsTailCall)
2993       ++NumTailCalls;
2994   }
2995 
2996   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2997   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2998   SmallVector<SDValue, 8> MemOpChains;
2999 
3000   // Analyze operands of the call, assigning locations to each operand.
3001   SmallVector<CCValAssign, 16> ArgLocs;
3002   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3003   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3004 
3005   if (AMDGPUTargetMachine::EnableFixedFunctionABI &&
3006       CallConv != CallingConv::AMDGPU_Gfx) {
3007     // With a fixed ABI, allocate fixed registers before user arguments.
3008     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3009   }
3010 
3011   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3012 
3013   // Get a count of how many bytes are to be pushed on the stack.
3014   unsigned NumBytes = CCInfo.getNextStackOffset();
3015 
3016   if (IsSibCall) {
3017     // Since we're not changing the ABI to make this a tail call, the memory
3018     // operands are already available in the caller's incoming argument space.
3019     NumBytes = 0;
3020   }
3021 
3022   // FPDiff is the byte offset of the call's argument area from the callee's.
3023   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3024   // by this amount for a tail call. In a sibling call it must be 0 because the
3025   // caller will deallocate the entire stack and the callee still expects its
3026   // arguments to begin at SP+0. Completely unused for non-tail calls.
3027   int32_t FPDiff = 0;
3028   MachineFrameInfo &MFI = MF.getFrameInfo();
3029 
3030   // Adjust the stack pointer for the new arguments...
3031   // These operations are automatically eliminated by the prolog/epilog pass
3032   if (!IsSibCall) {
3033     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3034 
3035     if (!Subtarget->enableFlatScratch()) {
3036       SmallVector<SDValue, 4> CopyFromChains;
3037 
3038       // In the HSA case, this should be an identity copy.
3039       SDValue ScratchRSrcReg
3040         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3041       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3042       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3043       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3044     }
3045   }
3046 
3047   MVT PtrVT = MVT::i32;
3048 
3049   // Walk the register/memloc assignments, inserting copies/loads.
3050   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3051     CCValAssign &VA = ArgLocs[i];
3052     SDValue Arg = OutVals[i];
3053 
3054     // Promote the value if needed.
3055     switch (VA.getLocInfo()) {
3056     case CCValAssign::Full:
3057       break;
3058     case CCValAssign::BCvt:
3059       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3060       break;
3061     case CCValAssign::ZExt:
3062       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3063       break;
3064     case CCValAssign::SExt:
3065       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3066       break;
3067     case CCValAssign::AExt:
3068       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3069       break;
3070     case CCValAssign::FPExt:
3071       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3072       break;
3073     default:
3074       llvm_unreachable("Unknown loc info!");
3075     }
3076 
3077     if (VA.isRegLoc()) {
3078       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3079     } else {
3080       assert(VA.isMemLoc());
3081 
3082       SDValue DstAddr;
3083       MachinePointerInfo DstInfo;
3084 
3085       unsigned LocMemOffset = VA.getLocMemOffset();
3086       int32_t Offset = LocMemOffset;
3087 
3088       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3089       MaybeAlign Alignment;
3090 
3091       if (IsTailCall) {
3092         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3093         unsigned OpSize = Flags.isByVal() ?
3094           Flags.getByValSize() : VA.getValVT().getStoreSize();
3095 
3096         // FIXME: We can have better than the minimum byval required alignment.
3097         Alignment =
3098             Flags.isByVal()
3099                 ? Flags.getNonZeroByValAlign()
3100                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3101 
3102         Offset = Offset + FPDiff;
3103         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3104 
3105         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3106         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3107 
3108         // Make sure any stack arguments overlapping with where we're storing
3109         // are loaded before this eventual operation. Otherwise they'll be
3110         // clobbered.
3111 
3112         // FIXME: Why is this really necessary? This seems to just result in a
3113         // lot of code to copy the stack and write them back to the same
3114         // locations, which are supposed to be immutable?
3115         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3116       } else {
3117         DstAddr = PtrOff;
3118         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3119         Alignment =
3120             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3121       }
3122 
3123       if (Outs[i].Flags.isByVal()) {
3124         SDValue SizeNode =
3125             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3126         SDValue Cpy =
3127             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3128                           Outs[i].Flags.getNonZeroByValAlign(),
3129                           /*isVol = */ false, /*AlwaysInline = */ true,
3130                           /*isTailCall = */ false, DstInfo,
3131                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3132 
3133         MemOpChains.push_back(Cpy);
3134       } else {
3135         SDValue Store =
3136             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3137         MemOpChains.push_back(Store);
3138       }
3139     }
3140   }
3141 
3142   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
3143       CallConv != CallingConv::AMDGPU_Gfx) {
3144     // Copy special input registers after user input arguments.
3145     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3146   }
3147 
3148   if (!MemOpChains.empty())
3149     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3150 
3151   // Build a sequence of copy-to-reg nodes chained together with token chain
3152   // and flag operands which copy the outgoing args into the appropriate regs.
3153   SDValue InFlag;
3154   for (auto &RegToPass : RegsToPass) {
3155     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3156                              RegToPass.second, InFlag);
3157     InFlag = Chain.getValue(1);
3158   }
3159 
3160 
3161   SDValue PhysReturnAddrReg;
3162   if (IsTailCall) {
3163     // Since the return is being combined with the call, we need to pass on the
3164     // return address.
3165 
3166     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3167     SDValue ReturnAddrReg = CreateLiveInRegister(
3168       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3169 
3170     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3171                                         MVT::i64);
3172     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3173     InFlag = Chain.getValue(1);
3174   }
3175 
3176   // We don't usually want to end the call-sequence here because we would tidy
3177   // the frame up *after* the call, however in the ABI-changing tail-call case
3178   // we've carefully laid out the parameters so that when sp is reset they'll be
3179   // in the correct location.
3180   if (IsTailCall && !IsSibCall) {
3181     Chain = DAG.getCALLSEQ_END(Chain,
3182                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3183                                DAG.getTargetConstant(0, DL, MVT::i32),
3184                                InFlag, DL);
3185     InFlag = Chain.getValue(1);
3186   }
3187 
3188   std::vector<SDValue> Ops;
3189   Ops.push_back(Chain);
3190   Ops.push_back(Callee);
3191   // Add a redundant copy of the callee global which will not be legalized, as
3192   // we need direct access to the callee later.
3193   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3194     const GlobalValue *GV = GSD->getGlobal();
3195     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3196   } else {
3197     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3198   }
3199 
3200   if (IsTailCall) {
3201     // Each tail call may have to adjust the stack by a different amount, so
3202     // this information must travel along with the operation for eventual
3203     // consumption by emitEpilogue.
3204     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3205 
3206     Ops.push_back(PhysReturnAddrReg);
3207   }
3208 
3209   // Add argument registers to the end of the list so that they are known live
3210   // into the call.
3211   for (auto &RegToPass : RegsToPass) {
3212     Ops.push_back(DAG.getRegister(RegToPass.first,
3213                                   RegToPass.second.getValueType()));
3214   }
3215 
3216   // Add a register mask operand representing the call-preserved registers.
3217 
3218   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3219   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3220   assert(Mask && "Missing call preserved mask for calling convention");
3221   Ops.push_back(DAG.getRegisterMask(Mask));
3222 
3223   if (InFlag.getNode())
3224     Ops.push_back(InFlag);
3225 
3226   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3227 
3228   // If we're doing a tall call, use a TC_RETURN here rather than an
3229   // actual call instruction.
3230   if (IsTailCall) {
3231     MFI.setHasTailCall();
3232     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3233   }
3234 
3235   // Returns a chain and a flag for retval copy to use.
3236   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3237   Chain = Call.getValue(0);
3238   InFlag = Call.getValue(1);
3239 
3240   uint64_t CalleePopBytes = NumBytes;
3241   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3242                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3243                              InFlag, DL);
3244   if (!Ins.empty())
3245     InFlag = Chain.getValue(1);
3246 
3247   // Handle result values, copying them out of physregs into vregs that we
3248   // return.
3249   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3250                          InVals, IsThisReturn,
3251                          IsThisReturn ? OutVals[0] : SDValue());
3252 }
3253 
3254 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3255 // except for applying the wave size scale to the increment amount.
3256 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3257     SDValue Op, SelectionDAG &DAG) const {
3258   const MachineFunction &MF = DAG.getMachineFunction();
3259   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3260 
3261   SDLoc dl(Op);
3262   EVT VT = Op.getValueType();
3263   SDValue Tmp1 = Op;
3264   SDValue Tmp2 = Op.getValue(1);
3265   SDValue Tmp3 = Op.getOperand(2);
3266   SDValue Chain = Tmp1.getOperand(0);
3267 
3268   Register SPReg = Info->getStackPtrOffsetReg();
3269 
3270   // Chain the dynamic stack allocation so that it doesn't modify the stack
3271   // pointer when other instructions are using the stack.
3272   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3273 
3274   SDValue Size  = Tmp2.getOperand(1);
3275   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3276   Chain = SP.getValue(1);
3277   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3278   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3279   const TargetFrameLowering *TFL = ST.getFrameLowering();
3280   unsigned Opc =
3281     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3282     ISD::ADD : ISD::SUB;
3283 
3284   SDValue ScaledSize = DAG.getNode(
3285       ISD::SHL, dl, VT, Size,
3286       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3287 
3288   Align StackAlign = TFL->getStackAlign();
3289   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3290   if (Alignment && *Alignment > StackAlign) {
3291     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3292                        DAG.getConstant(-(uint64_t)Alignment->value()
3293                                            << ST.getWavefrontSizeLog2(),
3294                                        dl, VT));
3295   }
3296 
3297   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3298   Tmp2 = DAG.getCALLSEQ_END(
3299       Chain, DAG.getIntPtrConstant(0, dl, true),
3300       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3301 
3302   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3303 }
3304 
3305 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3306                                                   SelectionDAG &DAG) const {
3307   // We only handle constant sizes here to allow non-entry block, static sized
3308   // allocas. A truly dynamic value is more difficult to support because we
3309   // don't know if the size value is uniform or not. If the size isn't uniform,
3310   // we would need to do a wave reduction to get the maximum size to know how
3311   // much to increment the uniform stack pointer.
3312   SDValue Size = Op.getOperand(1);
3313   if (isa<ConstantSDNode>(Size))
3314       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3315 
3316   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3317 }
3318 
3319 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3320                                              const MachineFunction &MF) const {
3321   Register Reg = StringSwitch<Register>(RegName)
3322     .Case("m0", AMDGPU::M0)
3323     .Case("exec", AMDGPU::EXEC)
3324     .Case("exec_lo", AMDGPU::EXEC_LO)
3325     .Case("exec_hi", AMDGPU::EXEC_HI)
3326     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3327     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3328     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3329     .Default(Register());
3330 
3331   if (Reg == AMDGPU::NoRegister) {
3332     report_fatal_error(Twine("invalid register name \""
3333                              + StringRef(RegName)  + "\"."));
3334 
3335   }
3336 
3337   if (!Subtarget->hasFlatScrRegister() &&
3338        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3339     report_fatal_error(Twine("invalid register \""
3340                              + StringRef(RegName)  + "\" for subtarget."));
3341   }
3342 
3343   switch (Reg) {
3344   case AMDGPU::M0:
3345   case AMDGPU::EXEC_LO:
3346   case AMDGPU::EXEC_HI:
3347   case AMDGPU::FLAT_SCR_LO:
3348   case AMDGPU::FLAT_SCR_HI:
3349     if (VT.getSizeInBits() == 32)
3350       return Reg;
3351     break;
3352   case AMDGPU::EXEC:
3353   case AMDGPU::FLAT_SCR:
3354     if (VT.getSizeInBits() == 64)
3355       return Reg;
3356     break;
3357   default:
3358     llvm_unreachable("missing register type checking");
3359   }
3360 
3361   report_fatal_error(Twine("invalid type for register \""
3362                            + StringRef(RegName) + "\"."));
3363 }
3364 
3365 // If kill is not the last instruction, split the block so kill is always a
3366 // proper terminator.
3367 MachineBasicBlock *
3368 SITargetLowering::splitKillBlock(MachineInstr &MI,
3369                                  MachineBasicBlock *BB) const {
3370   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3371   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3372   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3373   return SplitBB;
3374 }
3375 
3376 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3377 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3378 // be the first instruction in the remainder block.
3379 //
3380 /// \returns { LoopBody, Remainder }
3381 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3382 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3383   MachineFunction *MF = MBB.getParent();
3384   MachineBasicBlock::iterator I(&MI);
3385 
3386   // To insert the loop we need to split the block. Move everything after this
3387   // point to a new block, and insert a new empty block between the two.
3388   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3389   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3390   MachineFunction::iterator MBBI(MBB);
3391   ++MBBI;
3392 
3393   MF->insert(MBBI, LoopBB);
3394   MF->insert(MBBI, RemainderBB);
3395 
3396   LoopBB->addSuccessor(LoopBB);
3397   LoopBB->addSuccessor(RemainderBB);
3398 
3399   // Move the rest of the block into a new block.
3400   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3401 
3402   if (InstInLoop) {
3403     auto Next = std::next(I);
3404 
3405     // Move instruction to loop body.
3406     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3407 
3408     // Move the rest of the block.
3409     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3410   } else {
3411     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3412   }
3413 
3414   MBB.addSuccessor(LoopBB);
3415 
3416   return std::make_pair(LoopBB, RemainderBB);
3417 }
3418 
3419 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3420 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3421   MachineBasicBlock *MBB = MI.getParent();
3422   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3423   auto I = MI.getIterator();
3424   auto E = std::next(I);
3425 
3426   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3427     .addImm(0);
3428 
3429   MIBundleBuilder Bundler(*MBB, I, E);
3430   finalizeBundle(*MBB, Bundler.begin());
3431 }
3432 
3433 MachineBasicBlock *
3434 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3435                                          MachineBasicBlock *BB) const {
3436   const DebugLoc &DL = MI.getDebugLoc();
3437 
3438   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3439 
3440   MachineBasicBlock *LoopBB;
3441   MachineBasicBlock *RemainderBB;
3442   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3443 
3444   // Apparently kill flags are only valid if the def is in the same block?
3445   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3446     Src->setIsKill(false);
3447 
3448   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3449 
3450   MachineBasicBlock::iterator I = LoopBB->end();
3451 
3452   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3453     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3454 
3455   // Clear TRAP_STS.MEM_VIOL
3456   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3457     .addImm(0)
3458     .addImm(EncodedReg);
3459 
3460   bundleInstWithWaitcnt(MI);
3461 
3462   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3463 
3464   // Load and check TRAP_STS.MEM_VIOL
3465   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3466     .addImm(EncodedReg);
3467 
3468   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3469   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3470     .addReg(Reg, RegState::Kill)
3471     .addImm(0);
3472   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3473     .addMBB(LoopBB);
3474 
3475   return RemainderBB;
3476 }
3477 
3478 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3479 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3480 // will only do one iteration. In the worst case, this will loop 64 times.
3481 //
3482 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3483 static MachineBasicBlock::iterator
3484 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3485                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3486                        const DebugLoc &DL, const MachineOperand &Idx,
3487                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3488                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3489                        Register &SGPRIdxReg) {
3490 
3491   MachineFunction *MF = OrigBB.getParent();
3492   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3493   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3494   MachineBasicBlock::iterator I = LoopBB.begin();
3495 
3496   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3497   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3498   Register NewExec = MRI.createVirtualRegister(BoolRC);
3499   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3500   Register CondReg = MRI.createVirtualRegister(BoolRC);
3501 
3502   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3503     .addReg(InitReg)
3504     .addMBB(&OrigBB)
3505     .addReg(ResultReg)
3506     .addMBB(&LoopBB);
3507 
3508   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3509     .addReg(InitSaveExecReg)
3510     .addMBB(&OrigBB)
3511     .addReg(NewExec)
3512     .addMBB(&LoopBB);
3513 
3514   // Read the next variant <- also loop target.
3515   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3516       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3517 
3518   // Compare the just read M0 value to all possible Idx values.
3519   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3520       .addReg(CurrentIdxReg)
3521       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3522 
3523   // Update EXEC, save the original EXEC value to VCC.
3524   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3525                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3526           NewExec)
3527     .addReg(CondReg, RegState::Kill);
3528 
3529   MRI.setSimpleHint(NewExec, CondReg);
3530 
3531   if (UseGPRIdxMode) {
3532     if (Offset == 0) {
3533       SGPRIdxReg = CurrentIdxReg;
3534     } else {
3535       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3536       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3537           .addReg(CurrentIdxReg, RegState::Kill)
3538           .addImm(Offset);
3539     }
3540   } else {
3541     // Move index from VCC into M0
3542     if (Offset == 0) {
3543       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3544         .addReg(CurrentIdxReg, RegState::Kill);
3545     } else {
3546       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3547         .addReg(CurrentIdxReg, RegState::Kill)
3548         .addImm(Offset);
3549     }
3550   }
3551 
3552   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3553   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3554   MachineInstr *InsertPt =
3555     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3556                                                   : AMDGPU::S_XOR_B64_term), Exec)
3557       .addReg(Exec)
3558       .addReg(NewExec);
3559 
3560   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3561   // s_cbranch_scc0?
3562 
3563   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3564   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3565     .addMBB(&LoopBB);
3566 
3567   return InsertPt->getIterator();
3568 }
3569 
3570 // This has slightly sub-optimal regalloc when the source vector is killed by
3571 // the read. The register allocator does not understand that the kill is
3572 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3573 // subregister from it, using 1 more VGPR than necessary. This was saved when
3574 // this was expanded after register allocation.
3575 static MachineBasicBlock::iterator
3576 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3577                unsigned InitResultReg, unsigned PhiReg, int Offset,
3578                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3579   MachineFunction *MF = MBB.getParent();
3580   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3581   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3582   MachineRegisterInfo &MRI = MF->getRegInfo();
3583   const DebugLoc &DL = MI.getDebugLoc();
3584   MachineBasicBlock::iterator I(&MI);
3585 
3586   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3587   Register DstReg = MI.getOperand(0).getReg();
3588   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3589   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3590   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3591   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3592 
3593   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3594 
3595   // Save the EXEC mask
3596   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3597     .addReg(Exec);
3598 
3599   MachineBasicBlock *LoopBB;
3600   MachineBasicBlock *RemainderBB;
3601   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3602 
3603   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3604 
3605   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3606                                       InitResultReg, DstReg, PhiReg, TmpExec,
3607                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3608 
3609   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3610   MachineFunction::iterator MBBI(LoopBB);
3611   ++MBBI;
3612   MF->insert(MBBI, LandingPad);
3613   LoopBB->removeSuccessor(RemainderBB);
3614   LandingPad->addSuccessor(RemainderBB);
3615   LoopBB->addSuccessor(LandingPad);
3616   MachineBasicBlock::iterator First = LandingPad->begin();
3617   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3618     .addReg(SaveExec);
3619 
3620   return InsPt;
3621 }
3622 
3623 // Returns subreg index, offset
3624 static std::pair<unsigned, int>
3625 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3626                             const TargetRegisterClass *SuperRC,
3627                             unsigned VecReg,
3628                             int Offset) {
3629   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3630 
3631   // Skip out of bounds offsets, or else we would end up using an undefined
3632   // register.
3633   if (Offset >= NumElts || Offset < 0)
3634     return std::make_pair(AMDGPU::sub0, Offset);
3635 
3636   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3637 }
3638 
3639 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3640                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3641                                  int Offset) {
3642   MachineBasicBlock *MBB = MI.getParent();
3643   const DebugLoc &DL = MI.getDebugLoc();
3644   MachineBasicBlock::iterator I(&MI);
3645 
3646   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3647 
3648   assert(Idx->getReg() != AMDGPU::NoRegister);
3649 
3650   if (Offset == 0) {
3651     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3652   } else {
3653     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3654         .add(*Idx)
3655         .addImm(Offset);
3656   }
3657 }
3658 
3659 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3660                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3661                                    int Offset) {
3662   MachineBasicBlock *MBB = MI.getParent();
3663   const DebugLoc &DL = MI.getDebugLoc();
3664   MachineBasicBlock::iterator I(&MI);
3665 
3666   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3667 
3668   if (Offset == 0)
3669     return Idx->getReg();
3670 
3671   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3672   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3673       .add(*Idx)
3674       .addImm(Offset);
3675   return Tmp;
3676 }
3677 
3678 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3679                                           MachineBasicBlock &MBB,
3680                                           const GCNSubtarget &ST) {
3681   const SIInstrInfo *TII = ST.getInstrInfo();
3682   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3683   MachineFunction *MF = MBB.getParent();
3684   MachineRegisterInfo &MRI = MF->getRegInfo();
3685 
3686   Register Dst = MI.getOperand(0).getReg();
3687   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3688   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3689   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3690 
3691   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3692   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3693 
3694   unsigned SubReg;
3695   std::tie(SubReg, Offset)
3696     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3697 
3698   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3699 
3700   // Check for a SGPR index.
3701   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3702     MachineBasicBlock::iterator I(&MI);
3703     const DebugLoc &DL = MI.getDebugLoc();
3704 
3705     if (UseGPRIdxMode) {
3706       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3707       // to avoid interfering with other uses, so probably requires a new
3708       // optimization pass.
3709       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3710 
3711       const MCInstrDesc &GPRIDXDesc =
3712           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3713       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3714           .addReg(SrcReg)
3715           .addReg(Idx)
3716           .addImm(SubReg);
3717     } else {
3718       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3719 
3720       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3721         .addReg(SrcReg, 0, SubReg)
3722         .addReg(SrcReg, RegState::Implicit);
3723     }
3724 
3725     MI.eraseFromParent();
3726 
3727     return &MBB;
3728   }
3729 
3730   // Control flow needs to be inserted if indexing with a VGPR.
3731   const DebugLoc &DL = MI.getDebugLoc();
3732   MachineBasicBlock::iterator I(&MI);
3733 
3734   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3735   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3736 
3737   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3738 
3739   Register SGPRIdxReg;
3740   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3741                               UseGPRIdxMode, SGPRIdxReg);
3742 
3743   MachineBasicBlock *LoopBB = InsPt->getParent();
3744 
3745   if (UseGPRIdxMode) {
3746     const MCInstrDesc &GPRIDXDesc =
3747         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3748 
3749     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3750         .addReg(SrcReg)
3751         .addReg(SGPRIdxReg)
3752         .addImm(SubReg);
3753   } else {
3754     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3755       .addReg(SrcReg, 0, SubReg)
3756       .addReg(SrcReg, RegState::Implicit);
3757   }
3758 
3759   MI.eraseFromParent();
3760 
3761   return LoopBB;
3762 }
3763 
3764 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3765                                           MachineBasicBlock &MBB,
3766                                           const GCNSubtarget &ST) {
3767   const SIInstrInfo *TII = ST.getInstrInfo();
3768   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3769   MachineFunction *MF = MBB.getParent();
3770   MachineRegisterInfo &MRI = MF->getRegInfo();
3771 
3772   Register Dst = MI.getOperand(0).getReg();
3773   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3774   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3775   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3776   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3777   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3778   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3779 
3780   // This can be an immediate, but will be folded later.
3781   assert(Val->getReg());
3782 
3783   unsigned SubReg;
3784   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3785                                                          SrcVec->getReg(),
3786                                                          Offset);
3787   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3788 
3789   if (Idx->getReg() == AMDGPU::NoRegister) {
3790     MachineBasicBlock::iterator I(&MI);
3791     const DebugLoc &DL = MI.getDebugLoc();
3792 
3793     assert(Offset == 0);
3794 
3795     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3796         .add(*SrcVec)
3797         .add(*Val)
3798         .addImm(SubReg);
3799 
3800     MI.eraseFromParent();
3801     return &MBB;
3802   }
3803 
3804   // Check for a SGPR index.
3805   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3806     MachineBasicBlock::iterator I(&MI);
3807     const DebugLoc &DL = MI.getDebugLoc();
3808 
3809     if (UseGPRIdxMode) {
3810       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3811 
3812       const MCInstrDesc &GPRIDXDesc =
3813           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3814       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3815           .addReg(SrcVec->getReg())
3816           .add(*Val)
3817           .addReg(Idx)
3818           .addImm(SubReg);
3819     } else {
3820       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3821 
3822       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3823           TRI.getRegSizeInBits(*VecRC), 32, false);
3824       BuildMI(MBB, I, DL, MovRelDesc, Dst)
3825           .addReg(SrcVec->getReg())
3826           .add(*Val)
3827           .addImm(SubReg);
3828     }
3829     MI.eraseFromParent();
3830     return &MBB;
3831   }
3832 
3833   // Control flow needs to be inserted if indexing with a VGPR.
3834   if (Val->isReg())
3835     MRI.clearKillFlags(Val->getReg());
3836 
3837   const DebugLoc &DL = MI.getDebugLoc();
3838 
3839   Register PhiReg = MRI.createVirtualRegister(VecRC);
3840 
3841   Register SGPRIdxReg;
3842   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
3843                               UseGPRIdxMode, SGPRIdxReg);
3844   MachineBasicBlock *LoopBB = InsPt->getParent();
3845 
3846   if (UseGPRIdxMode) {
3847     const MCInstrDesc &GPRIDXDesc =
3848         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3849 
3850     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3851         .addReg(PhiReg)
3852         .add(*Val)
3853         .addReg(SGPRIdxReg)
3854         .addImm(AMDGPU::sub0);
3855   } else {
3856     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3857         TRI.getRegSizeInBits(*VecRC), 32, false);
3858     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3859         .addReg(PhiReg)
3860         .add(*Val)
3861         .addImm(AMDGPU::sub0);
3862   }
3863 
3864   MI.eraseFromParent();
3865   return LoopBB;
3866 }
3867 
3868 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3869   MachineInstr &MI, MachineBasicBlock *BB) const {
3870 
3871   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3872   MachineFunction *MF = BB->getParent();
3873   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3874 
3875   switch (MI.getOpcode()) {
3876   case AMDGPU::S_UADDO_PSEUDO:
3877   case AMDGPU::S_USUBO_PSEUDO: {
3878     const DebugLoc &DL = MI.getDebugLoc();
3879     MachineOperand &Dest0 = MI.getOperand(0);
3880     MachineOperand &Dest1 = MI.getOperand(1);
3881     MachineOperand &Src0 = MI.getOperand(2);
3882     MachineOperand &Src1 = MI.getOperand(3);
3883 
3884     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3885                        ? AMDGPU::S_ADD_I32
3886                        : AMDGPU::S_SUB_I32;
3887     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3888 
3889     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3890         .addImm(1)
3891         .addImm(0);
3892 
3893     MI.eraseFromParent();
3894     return BB;
3895   }
3896   case AMDGPU::S_ADD_U64_PSEUDO:
3897   case AMDGPU::S_SUB_U64_PSEUDO: {
3898     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3899     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3900     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3901     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3902     const DebugLoc &DL = MI.getDebugLoc();
3903 
3904     MachineOperand &Dest = MI.getOperand(0);
3905     MachineOperand &Src0 = MI.getOperand(1);
3906     MachineOperand &Src1 = MI.getOperand(2);
3907 
3908     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3909     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3910 
3911     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3912         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3913     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3914         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3915 
3916     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3917         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3918     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3919         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3920 
3921     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3922 
3923     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3924     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3925     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3926     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3927     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3928         .addReg(DestSub0)
3929         .addImm(AMDGPU::sub0)
3930         .addReg(DestSub1)
3931         .addImm(AMDGPU::sub1);
3932     MI.eraseFromParent();
3933     return BB;
3934   }
3935   case AMDGPU::V_ADD_U64_PSEUDO:
3936   case AMDGPU::V_SUB_U64_PSEUDO: {
3937     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3938     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3939     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3940     const DebugLoc &DL = MI.getDebugLoc();
3941 
3942     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
3943 
3944     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3945 
3946     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3947     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3948 
3949     Register CarryReg = MRI.createVirtualRegister(CarryRC);
3950     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
3951 
3952     MachineOperand &Dest = MI.getOperand(0);
3953     MachineOperand &Src0 = MI.getOperand(1);
3954     MachineOperand &Src1 = MI.getOperand(2);
3955 
3956     const TargetRegisterClass *Src0RC = Src0.isReg()
3957                                             ? MRI.getRegClass(Src0.getReg())
3958                                             : &AMDGPU::VReg_64RegClass;
3959     const TargetRegisterClass *Src1RC = Src1.isReg()
3960                                             ? MRI.getRegClass(Src1.getReg())
3961                                             : &AMDGPU::VReg_64RegClass;
3962 
3963     const TargetRegisterClass *Src0SubRC =
3964         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
3965     const TargetRegisterClass *Src1SubRC =
3966         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
3967 
3968     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
3969         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
3970     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
3971         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
3972 
3973     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
3974         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
3975     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
3976         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
3977 
3978     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
3979     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3980                                .addReg(CarryReg, RegState::Define)
3981                                .add(SrcReg0Sub0)
3982                                .add(SrcReg1Sub0)
3983                                .addImm(0); // clamp bit
3984 
3985     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
3986     MachineInstr *HiHalf =
3987         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3988             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
3989             .add(SrcReg0Sub1)
3990             .add(SrcReg1Sub1)
3991             .addReg(CarryReg, RegState::Kill)
3992             .addImm(0); // clamp bit
3993 
3994     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3995         .addReg(DestSub0)
3996         .addImm(AMDGPU::sub0)
3997         .addReg(DestSub1)
3998         .addImm(AMDGPU::sub1);
3999     TII->legalizeOperands(*LoHalf);
4000     TII->legalizeOperands(*HiHalf);
4001     MI.eraseFromParent();
4002     return BB;
4003   }
4004   case AMDGPU::S_ADD_CO_PSEUDO:
4005   case AMDGPU::S_SUB_CO_PSEUDO: {
4006     // This pseudo has a chance to be selected
4007     // only from uniform add/subcarry node. All the VGPR operands
4008     // therefore assumed to be splat vectors.
4009     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4010     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4011     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4012     MachineBasicBlock::iterator MII = MI;
4013     const DebugLoc &DL = MI.getDebugLoc();
4014     MachineOperand &Dest = MI.getOperand(0);
4015     MachineOperand &CarryDest = MI.getOperand(1);
4016     MachineOperand &Src0 = MI.getOperand(2);
4017     MachineOperand &Src1 = MI.getOperand(3);
4018     MachineOperand &Src2 = MI.getOperand(4);
4019     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4020                        ? AMDGPU::S_ADDC_U32
4021                        : AMDGPU::S_SUBB_U32;
4022     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4023       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4024       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4025           .addReg(Src0.getReg());
4026       Src0.setReg(RegOp0);
4027     }
4028     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4029       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4030       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4031           .addReg(Src1.getReg());
4032       Src1.setReg(RegOp1);
4033     }
4034     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4035     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4036       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4037           .addReg(Src2.getReg());
4038       Src2.setReg(RegOp2);
4039     }
4040 
4041     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4042     if (TRI->getRegSizeInBits(*Src2RC) == 64) {
4043       if (ST.hasScalarCompareEq64()) {
4044         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4045             .addReg(Src2.getReg())
4046             .addImm(0);
4047       } else {
4048         const TargetRegisterClass *SubRC =
4049             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4050         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4051             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4052         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4053             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4054         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4055 
4056         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4057             .add(Src2Sub0)
4058             .add(Src2Sub1);
4059 
4060         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4061             .addReg(Src2_32, RegState::Kill)
4062             .addImm(0);
4063       }
4064     } else {
4065       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4066           .addReg(Src2.getReg())
4067           .addImm(0);
4068     }
4069 
4070     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4071 
4072     BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg())
4073       .addReg(AMDGPU::SCC);
4074     MI.eraseFromParent();
4075     return BB;
4076   }
4077   case AMDGPU::SI_INIT_M0: {
4078     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4079             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4080         .add(MI.getOperand(0));
4081     MI.eraseFromParent();
4082     return BB;
4083   }
4084   case AMDGPU::GET_GROUPSTATICSIZE: {
4085     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4086            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4087     DebugLoc DL = MI.getDebugLoc();
4088     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4089         .add(MI.getOperand(0))
4090         .addImm(MFI->getLDSSize());
4091     MI.eraseFromParent();
4092     return BB;
4093   }
4094   case AMDGPU::SI_INDIRECT_SRC_V1:
4095   case AMDGPU::SI_INDIRECT_SRC_V2:
4096   case AMDGPU::SI_INDIRECT_SRC_V4:
4097   case AMDGPU::SI_INDIRECT_SRC_V8:
4098   case AMDGPU::SI_INDIRECT_SRC_V16:
4099   case AMDGPU::SI_INDIRECT_SRC_V32:
4100     return emitIndirectSrc(MI, *BB, *getSubtarget());
4101   case AMDGPU::SI_INDIRECT_DST_V1:
4102   case AMDGPU::SI_INDIRECT_DST_V2:
4103   case AMDGPU::SI_INDIRECT_DST_V4:
4104   case AMDGPU::SI_INDIRECT_DST_V8:
4105   case AMDGPU::SI_INDIRECT_DST_V16:
4106   case AMDGPU::SI_INDIRECT_DST_V32:
4107     return emitIndirectDst(MI, *BB, *getSubtarget());
4108   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4109   case AMDGPU::SI_KILL_I1_PSEUDO:
4110     return splitKillBlock(MI, BB);
4111   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4112     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4113     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4114     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4115 
4116     Register Dst = MI.getOperand(0).getReg();
4117     Register Src0 = MI.getOperand(1).getReg();
4118     Register Src1 = MI.getOperand(2).getReg();
4119     const DebugLoc &DL = MI.getDebugLoc();
4120     Register SrcCond = MI.getOperand(3).getReg();
4121 
4122     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4123     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4124     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4125     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4126 
4127     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4128       .addReg(SrcCond);
4129     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4130       .addImm(0)
4131       .addReg(Src0, 0, AMDGPU::sub0)
4132       .addImm(0)
4133       .addReg(Src1, 0, AMDGPU::sub0)
4134       .addReg(SrcCondCopy);
4135     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4136       .addImm(0)
4137       .addReg(Src0, 0, AMDGPU::sub1)
4138       .addImm(0)
4139       .addReg(Src1, 0, AMDGPU::sub1)
4140       .addReg(SrcCondCopy);
4141 
4142     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4143       .addReg(DstLo)
4144       .addImm(AMDGPU::sub0)
4145       .addReg(DstHi)
4146       .addImm(AMDGPU::sub1);
4147     MI.eraseFromParent();
4148     return BB;
4149   }
4150   case AMDGPU::SI_BR_UNDEF: {
4151     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4152     const DebugLoc &DL = MI.getDebugLoc();
4153     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4154                            .add(MI.getOperand(0));
4155     Br->getOperand(1).setIsUndef(true); // read undef SCC
4156     MI.eraseFromParent();
4157     return BB;
4158   }
4159   case AMDGPU::ADJCALLSTACKUP:
4160   case AMDGPU::ADJCALLSTACKDOWN: {
4161     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4162     MachineInstrBuilder MIB(*MF, &MI);
4163     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4164        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4165     return BB;
4166   }
4167   case AMDGPU::SI_CALL_ISEL: {
4168     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4169     const DebugLoc &DL = MI.getDebugLoc();
4170 
4171     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4172 
4173     MachineInstrBuilder MIB;
4174     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4175 
4176     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
4177       MIB.add(MI.getOperand(I));
4178 
4179     MIB.cloneMemRefs(MI);
4180     MI.eraseFromParent();
4181     return BB;
4182   }
4183   case AMDGPU::V_ADD_CO_U32_e32:
4184   case AMDGPU::V_SUB_CO_U32_e32:
4185   case AMDGPU::V_SUBREV_CO_U32_e32: {
4186     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4187     const DebugLoc &DL = MI.getDebugLoc();
4188     unsigned Opc = MI.getOpcode();
4189 
4190     bool NeedClampOperand = false;
4191     if (TII->pseudoToMCOpcode(Opc) == -1) {
4192       Opc = AMDGPU::getVOPe64(Opc);
4193       NeedClampOperand = true;
4194     }
4195 
4196     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4197     if (TII->isVOP3(*I)) {
4198       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4199       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4200       I.addReg(TRI->getVCC(), RegState::Define);
4201     }
4202     I.add(MI.getOperand(1))
4203      .add(MI.getOperand(2));
4204     if (NeedClampOperand)
4205       I.addImm(0); // clamp bit for e64 encoding
4206 
4207     TII->legalizeOperands(*I);
4208 
4209     MI.eraseFromParent();
4210     return BB;
4211   }
4212   case AMDGPU::DS_GWS_INIT:
4213   case AMDGPU::DS_GWS_SEMA_V:
4214   case AMDGPU::DS_GWS_SEMA_BR:
4215   case AMDGPU::DS_GWS_SEMA_P:
4216   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4217   case AMDGPU::DS_GWS_BARRIER:
4218     // A s_waitcnt 0 is required to be the instruction immediately following.
4219     if (getSubtarget()->hasGWSAutoReplay()) {
4220       bundleInstWithWaitcnt(MI);
4221       return BB;
4222     }
4223 
4224     return emitGWSMemViolTestLoop(MI, BB);
4225   case AMDGPU::S_SETREG_B32: {
4226     // Try to optimize cases that only set the denormal mode or rounding mode.
4227     //
4228     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4229     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4230     // instead.
4231     //
4232     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4233     // allow you to have a no side effect instruction in the output of a
4234     // sideeffecting pattern.
4235     unsigned ID, Offset, Width;
4236     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4237     if (ID != AMDGPU::Hwreg::ID_MODE)
4238       return BB;
4239 
4240     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4241     const unsigned SetMask = WidthMask << Offset;
4242 
4243     if (getSubtarget()->hasDenormModeInst()) {
4244       unsigned SetDenormOp = 0;
4245       unsigned SetRoundOp = 0;
4246 
4247       // The dedicated instructions can only set the whole denorm or round mode
4248       // at once, not a subset of bits in either.
4249       if (SetMask ==
4250           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4251         // If this fully sets both the round and denorm mode, emit the two
4252         // dedicated instructions for these.
4253         SetRoundOp = AMDGPU::S_ROUND_MODE;
4254         SetDenormOp = AMDGPU::S_DENORM_MODE;
4255       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4256         SetRoundOp = AMDGPU::S_ROUND_MODE;
4257       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4258         SetDenormOp = AMDGPU::S_DENORM_MODE;
4259       }
4260 
4261       if (SetRoundOp || SetDenormOp) {
4262         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4263         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4264         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4265           unsigned ImmVal = Def->getOperand(1).getImm();
4266           if (SetRoundOp) {
4267             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4268                 .addImm(ImmVal & 0xf);
4269 
4270             // If we also have the denorm mode, get just the denorm mode bits.
4271             ImmVal >>= 4;
4272           }
4273 
4274           if (SetDenormOp) {
4275             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4276                 .addImm(ImmVal & 0xf);
4277           }
4278 
4279           MI.eraseFromParent();
4280           return BB;
4281         }
4282       }
4283     }
4284 
4285     // If only FP bits are touched, used the no side effects pseudo.
4286     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4287                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4288       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4289 
4290     return BB;
4291   }
4292   default:
4293     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4294   }
4295 }
4296 
4297 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4298   return isTypeLegal(VT.getScalarType());
4299 }
4300 
4301 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4302   // This currently forces unfolding various combinations of fsub into fma with
4303   // free fneg'd operands. As long as we have fast FMA (controlled by
4304   // isFMAFasterThanFMulAndFAdd), we should perform these.
4305 
4306   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4307   // most of these combines appear to be cycle neutral but save on instruction
4308   // count / code size.
4309   return true;
4310 }
4311 
4312 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4313                                          EVT VT) const {
4314   if (!VT.isVector()) {
4315     return MVT::i1;
4316   }
4317   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4318 }
4319 
4320 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4321   // TODO: Should i16 be used always if legal? For now it would force VALU
4322   // shifts.
4323   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4324 }
4325 
4326 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4327   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4328              ? Ty.changeElementSize(16)
4329              : Ty.changeElementSize(32);
4330 }
4331 
4332 // Answering this is somewhat tricky and depends on the specific device which
4333 // have different rates for fma or all f64 operations.
4334 //
4335 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4336 // regardless of which device (although the number of cycles differs between
4337 // devices), so it is always profitable for f64.
4338 //
4339 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4340 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4341 // which we can always do even without fused FP ops since it returns the same
4342 // result as the separate operations and since it is always full
4343 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4344 // however does not support denormals, so we do report fma as faster if we have
4345 // a fast fma device and require denormals.
4346 //
4347 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4348                                                   EVT VT) const {
4349   VT = VT.getScalarType();
4350 
4351   switch (VT.getSimpleVT().SimpleTy) {
4352   case MVT::f32: {
4353     // If mad is not available this depends only on if f32 fma is full rate.
4354     if (!Subtarget->hasMadMacF32Insts())
4355       return Subtarget->hasFastFMAF32();
4356 
4357     // Otherwise f32 mad is always full rate and returns the same result as
4358     // the separate operations so should be preferred over fma.
4359     // However does not support denomals.
4360     if (hasFP32Denormals(MF))
4361       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4362 
4363     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4364     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4365   }
4366   case MVT::f64:
4367     return true;
4368   case MVT::f16:
4369     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4370   default:
4371     break;
4372   }
4373 
4374   return false;
4375 }
4376 
4377 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4378                                    const SDNode *N) const {
4379   // TODO: Check future ftz flag
4380   // v_mad_f32/v_mac_f32 do not support denormals.
4381   EVT VT = N->getValueType(0);
4382   if (VT == MVT::f32)
4383     return Subtarget->hasMadMacF32Insts() &&
4384            !hasFP32Denormals(DAG.getMachineFunction());
4385   if (VT == MVT::f16) {
4386     return Subtarget->hasMadF16() &&
4387            !hasFP64FP16Denormals(DAG.getMachineFunction());
4388   }
4389 
4390   return false;
4391 }
4392 
4393 //===----------------------------------------------------------------------===//
4394 // Custom DAG Lowering Operations
4395 //===----------------------------------------------------------------------===//
4396 
4397 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4398 // wider vector type is legal.
4399 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4400                                              SelectionDAG &DAG) const {
4401   unsigned Opc = Op.getOpcode();
4402   EVT VT = Op.getValueType();
4403   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4404 
4405   SDValue Lo, Hi;
4406   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4407 
4408   SDLoc SL(Op);
4409   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4410                              Op->getFlags());
4411   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4412                              Op->getFlags());
4413 
4414   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4415 }
4416 
4417 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4418 // wider vector type is legal.
4419 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4420                                               SelectionDAG &DAG) const {
4421   unsigned Opc = Op.getOpcode();
4422   EVT VT = Op.getValueType();
4423   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4424          VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32);
4425 
4426   SDValue Lo0, Hi0;
4427   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4428   SDValue Lo1, Hi1;
4429   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4430 
4431   SDLoc SL(Op);
4432 
4433   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4434                              Op->getFlags());
4435   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4436                              Op->getFlags());
4437 
4438   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4439 }
4440 
4441 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4442                                               SelectionDAG &DAG) const {
4443   unsigned Opc = Op.getOpcode();
4444   EVT VT = Op.getValueType();
4445   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4446          VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32);
4447 
4448   SDValue Lo0, Hi0;
4449   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4450   SDValue Lo1, Hi1;
4451   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4452   SDValue Lo2, Hi2;
4453   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4454 
4455   SDLoc SL(Op);
4456 
4457   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4458                              Op->getFlags());
4459   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4460                              Op->getFlags());
4461 
4462   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4463 }
4464 
4465 
4466 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4467   switch (Op.getOpcode()) {
4468   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4469   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4470   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4471   case ISD::LOAD: {
4472     SDValue Result = LowerLOAD(Op, DAG);
4473     assert((!Result.getNode() ||
4474             Result.getNode()->getNumValues() == 2) &&
4475            "Load should return a value and a chain");
4476     return Result;
4477   }
4478 
4479   case ISD::FSIN:
4480   case ISD::FCOS:
4481     return LowerTrig(Op, DAG);
4482   case ISD::SELECT: return LowerSELECT(Op, DAG);
4483   case ISD::FDIV: return LowerFDIV(Op, DAG);
4484   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4485   case ISD::STORE: return LowerSTORE(Op, DAG);
4486   case ISD::GlobalAddress: {
4487     MachineFunction &MF = DAG.getMachineFunction();
4488     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4489     return LowerGlobalAddress(MFI, Op, DAG);
4490   }
4491   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4492   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4493   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4494   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4495   case ISD::INSERT_SUBVECTOR:
4496     return lowerINSERT_SUBVECTOR(Op, DAG);
4497   case ISD::INSERT_VECTOR_ELT:
4498     return lowerINSERT_VECTOR_ELT(Op, DAG);
4499   case ISD::EXTRACT_VECTOR_ELT:
4500     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4501   case ISD::VECTOR_SHUFFLE:
4502     return lowerVECTOR_SHUFFLE(Op, DAG);
4503   case ISD::BUILD_VECTOR:
4504     return lowerBUILD_VECTOR(Op, DAG);
4505   case ISD::FP_ROUND:
4506     return lowerFP_ROUND(Op, DAG);
4507   case ISD::TRAP:
4508     return lowerTRAP(Op, DAG);
4509   case ISD::DEBUGTRAP:
4510     return lowerDEBUGTRAP(Op, DAG);
4511   case ISD::FABS:
4512   case ISD::FNEG:
4513   case ISD::FCANONICALIZE:
4514   case ISD::BSWAP:
4515     return splitUnaryVectorOp(Op, DAG);
4516   case ISD::FMINNUM:
4517   case ISD::FMAXNUM:
4518     return lowerFMINNUM_FMAXNUM(Op, DAG);
4519   case ISD::FMA:
4520     return splitTernaryVectorOp(Op, DAG);
4521   case ISD::SHL:
4522   case ISD::SRA:
4523   case ISD::SRL:
4524   case ISD::ADD:
4525   case ISD::SUB:
4526   case ISD::MUL:
4527   case ISD::SMIN:
4528   case ISD::SMAX:
4529   case ISD::UMIN:
4530   case ISD::UMAX:
4531   case ISD::FADD:
4532   case ISD::FMUL:
4533   case ISD::FMINNUM_IEEE:
4534   case ISD::FMAXNUM_IEEE:
4535   case ISD::UADDSAT:
4536   case ISD::USUBSAT:
4537   case ISD::SADDSAT:
4538   case ISD::SSUBSAT:
4539     return splitBinaryVectorOp(Op, DAG);
4540   case ISD::SMULO:
4541   case ISD::UMULO:
4542     return lowerXMULO(Op, DAG);
4543   case ISD::DYNAMIC_STACKALLOC:
4544     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4545   }
4546   return SDValue();
4547 }
4548 
4549 // Used for D16: Casts the result of an instruction into the right vector,
4550 // packs values if loads return unpacked values.
4551 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4552                                        const SDLoc &DL,
4553                                        SelectionDAG &DAG, bool Unpacked) {
4554   if (!LoadVT.isVector())
4555     return Result;
4556 
4557   // Cast back to the original packed type or to a larger type that is a
4558   // multiple of 32 bit for D16. Widening the return type is a required for
4559   // legalization.
4560   EVT FittingLoadVT = LoadVT;
4561   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4562     FittingLoadVT =
4563         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4564                          LoadVT.getVectorNumElements() + 1);
4565   }
4566 
4567   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4568     // Truncate to v2i16/v4i16.
4569     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4570 
4571     // Workaround legalizer not scalarizing truncate after vector op
4572     // legalization but not creating intermediate vector trunc.
4573     SmallVector<SDValue, 4> Elts;
4574     DAG.ExtractVectorElements(Result, Elts);
4575     for (SDValue &Elt : Elts)
4576       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4577 
4578     // Pad illegal v1i16/v3fi6 to v4i16
4579     if ((LoadVT.getVectorNumElements() % 2) == 1)
4580       Elts.push_back(DAG.getUNDEF(MVT::i16));
4581 
4582     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4583 
4584     // Bitcast to original type (v2f16/v4f16).
4585     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4586   }
4587 
4588   // Cast back to the original packed type.
4589   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4590 }
4591 
4592 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4593                                               MemSDNode *M,
4594                                               SelectionDAG &DAG,
4595                                               ArrayRef<SDValue> Ops,
4596                                               bool IsIntrinsic) const {
4597   SDLoc DL(M);
4598 
4599   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4600   EVT LoadVT = M->getValueType(0);
4601 
4602   EVT EquivLoadVT = LoadVT;
4603   if (LoadVT.isVector()) {
4604     if (Unpacked) {
4605       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4606                                      LoadVT.getVectorNumElements());
4607     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4608       // Widen v3f16 to legal type
4609       EquivLoadVT =
4610           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4611                            LoadVT.getVectorNumElements() + 1);
4612     }
4613   }
4614 
4615   // Change from v4f16/v2f16 to EquivLoadVT.
4616   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4617 
4618   SDValue Load
4619     = DAG.getMemIntrinsicNode(
4620       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4621       VTList, Ops, M->getMemoryVT(),
4622       M->getMemOperand());
4623 
4624   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4625 
4626   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4627 }
4628 
4629 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4630                                              SelectionDAG &DAG,
4631                                              ArrayRef<SDValue> Ops) const {
4632   SDLoc DL(M);
4633   EVT LoadVT = M->getValueType(0);
4634   EVT EltType = LoadVT.getScalarType();
4635   EVT IntVT = LoadVT.changeTypeToInteger();
4636 
4637   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4638 
4639   unsigned Opc =
4640       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4641 
4642   if (IsD16) {
4643     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4644   }
4645 
4646   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4647   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4648     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4649 
4650   if (isTypeLegal(LoadVT)) {
4651     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4652                                M->getMemOperand(), DAG);
4653   }
4654 
4655   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4656   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4657   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4658                                         M->getMemOperand(), DAG);
4659   return DAG.getMergeValues(
4660       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4661       DL);
4662 }
4663 
4664 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4665                                   SDNode *N, SelectionDAG &DAG) {
4666   EVT VT = N->getValueType(0);
4667   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4668   unsigned CondCode = CD->getZExtValue();
4669   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4670     return DAG.getUNDEF(VT);
4671 
4672   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4673 
4674   SDValue LHS = N->getOperand(1);
4675   SDValue RHS = N->getOperand(2);
4676 
4677   SDLoc DL(N);
4678 
4679   EVT CmpVT = LHS.getValueType();
4680   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4681     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4682       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4683     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4684     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4685   }
4686 
4687   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4688 
4689   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4690   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4691 
4692   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4693                               DAG.getCondCode(CCOpcode));
4694   if (VT.bitsEq(CCVT))
4695     return SetCC;
4696   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4697 }
4698 
4699 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4700                                   SDNode *N, SelectionDAG &DAG) {
4701   EVT VT = N->getValueType(0);
4702   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4703 
4704   unsigned CondCode = CD->getZExtValue();
4705   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4706     return DAG.getUNDEF(VT);
4707 
4708   SDValue Src0 = N->getOperand(1);
4709   SDValue Src1 = N->getOperand(2);
4710   EVT CmpVT = Src0.getValueType();
4711   SDLoc SL(N);
4712 
4713   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4714     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4715     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4716   }
4717 
4718   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4719   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4720   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4721   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4722   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4723                               Src1, DAG.getCondCode(CCOpcode));
4724   if (VT.bitsEq(CCVT))
4725     return SetCC;
4726   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4727 }
4728 
4729 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4730                                     SelectionDAG &DAG) {
4731   EVT VT = N->getValueType(0);
4732   SDValue Src = N->getOperand(1);
4733   SDLoc SL(N);
4734 
4735   if (Src.getOpcode() == ISD::SETCC) {
4736     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4737     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4738                        Src.getOperand(1), Src.getOperand(2));
4739   }
4740   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4741     // (ballot 0) -> 0
4742     if (Arg->isNullValue())
4743       return DAG.getConstant(0, SL, VT);
4744 
4745     // (ballot 1) -> EXEC/EXEC_LO
4746     if (Arg->isOne()) {
4747       Register Exec;
4748       if (VT.getScalarSizeInBits() == 32)
4749         Exec = AMDGPU::EXEC_LO;
4750       else if (VT.getScalarSizeInBits() == 64)
4751         Exec = AMDGPU::EXEC;
4752       else
4753         return SDValue();
4754 
4755       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4756     }
4757   }
4758 
4759   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4760   // ISD::SETNE)
4761   return DAG.getNode(
4762       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4763       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4764 }
4765 
4766 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4767                                           SmallVectorImpl<SDValue> &Results,
4768                                           SelectionDAG &DAG) const {
4769   switch (N->getOpcode()) {
4770   case ISD::INSERT_VECTOR_ELT: {
4771     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4772       Results.push_back(Res);
4773     return;
4774   }
4775   case ISD::EXTRACT_VECTOR_ELT: {
4776     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4777       Results.push_back(Res);
4778     return;
4779   }
4780   case ISD::INTRINSIC_WO_CHAIN: {
4781     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4782     switch (IID) {
4783     case Intrinsic::amdgcn_cvt_pkrtz: {
4784       SDValue Src0 = N->getOperand(1);
4785       SDValue Src1 = N->getOperand(2);
4786       SDLoc SL(N);
4787       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4788                                 Src0, Src1);
4789       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4790       return;
4791     }
4792     case Intrinsic::amdgcn_cvt_pknorm_i16:
4793     case Intrinsic::amdgcn_cvt_pknorm_u16:
4794     case Intrinsic::amdgcn_cvt_pk_i16:
4795     case Intrinsic::amdgcn_cvt_pk_u16: {
4796       SDValue Src0 = N->getOperand(1);
4797       SDValue Src1 = N->getOperand(2);
4798       SDLoc SL(N);
4799       unsigned Opcode;
4800 
4801       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4802         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4803       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4804         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4805       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4806         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4807       else
4808         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4809 
4810       EVT VT = N->getValueType(0);
4811       if (isTypeLegal(VT))
4812         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4813       else {
4814         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4815         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4816       }
4817       return;
4818     }
4819     }
4820     break;
4821   }
4822   case ISD::INTRINSIC_W_CHAIN: {
4823     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4824       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4825         // FIXME: Hacky
4826         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
4827           Results.push_back(Res.getOperand(I));
4828         }
4829       } else {
4830         Results.push_back(Res);
4831         Results.push_back(Res.getValue(1));
4832       }
4833       return;
4834     }
4835 
4836     break;
4837   }
4838   case ISD::SELECT: {
4839     SDLoc SL(N);
4840     EVT VT = N->getValueType(0);
4841     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4842     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4843     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4844 
4845     EVT SelectVT = NewVT;
4846     if (NewVT.bitsLT(MVT::i32)) {
4847       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4848       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4849       SelectVT = MVT::i32;
4850     }
4851 
4852     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4853                                     N->getOperand(0), LHS, RHS);
4854 
4855     if (NewVT != SelectVT)
4856       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4857     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4858     return;
4859   }
4860   case ISD::FNEG: {
4861     if (N->getValueType(0) != MVT::v2f16)
4862       break;
4863 
4864     SDLoc SL(N);
4865     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4866 
4867     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4868                              BC,
4869                              DAG.getConstant(0x80008000, SL, MVT::i32));
4870     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4871     return;
4872   }
4873   case ISD::FABS: {
4874     if (N->getValueType(0) != MVT::v2f16)
4875       break;
4876 
4877     SDLoc SL(N);
4878     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4879 
4880     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4881                              BC,
4882                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4883     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4884     return;
4885   }
4886   default:
4887     break;
4888   }
4889 }
4890 
4891 /// Helper function for LowerBRCOND
4892 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4893 
4894   SDNode *Parent = Value.getNode();
4895   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4896        I != E; ++I) {
4897 
4898     if (I.getUse().get() != Value)
4899       continue;
4900 
4901     if (I->getOpcode() == Opcode)
4902       return *I;
4903   }
4904   return nullptr;
4905 }
4906 
4907 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4908   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4909     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4910     case Intrinsic::amdgcn_if:
4911       return AMDGPUISD::IF;
4912     case Intrinsic::amdgcn_else:
4913       return AMDGPUISD::ELSE;
4914     case Intrinsic::amdgcn_loop:
4915       return AMDGPUISD::LOOP;
4916     case Intrinsic::amdgcn_end_cf:
4917       llvm_unreachable("should not occur");
4918     default:
4919       return 0;
4920     }
4921   }
4922 
4923   // break, if_break, else_break are all only used as inputs to loop, not
4924   // directly as branch conditions.
4925   return 0;
4926 }
4927 
4928 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4929   const Triple &TT = getTargetMachine().getTargetTriple();
4930   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4931           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4932          AMDGPU::shouldEmitConstantsToTextSection(TT);
4933 }
4934 
4935 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4936   // FIXME: Either avoid relying on address space here or change the default
4937   // address space for functions to avoid the explicit check.
4938   return (GV->getValueType()->isFunctionTy() ||
4939           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
4940          !shouldEmitFixup(GV) &&
4941          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4942 }
4943 
4944 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4945   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4946 }
4947 
4948 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
4949   if (!GV->hasExternalLinkage())
4950     return true;
4951 
4952   const auto OS = getTargetMachine().getTargetTriple().getOS();
4953   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
4954 }
4955 
4956 /// This transforms the control flow intrinsics to get the branch destination as
4957 /// last parameter, also switches branch target with BR if the need arise
4958 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4959                                       SelectionDAG &DAG) const {
4960   SDLoc DL(BRCOND);
4961 
4962   SDNode *Intr = BRCOND.getOperand(1).getNode();
4963   SDValue Target = BRCOND.getOperand(2);
4964   SDNode *BR = nullptr;
4965   SDNode *SetCC = nullptr;
4966 
4967   if (Intr->getOpcode() == ISD::SETCC) {
4968     // As long as we negate the condition everything is fine
4969     SetCC = Intr;
4970     Intr = SetCC->getOperand(0).getNode();
4971 
4972   } else {
4973     // Get the target from BR if we don't negate the condition
4974     BR = findUser(BRCOND, ISD::BR);
4975     assert(BR && "brcond missing unconditional branch user");
4976     Target = BR->getOperand(1);
4977   }
4978 
4979   unsigned CFNode = isCFIntrinsic(Intr);
4980   if (CFNode == 0) {
4981     // This is a uniform branch so we don't need to legalize.
4982     return BRCOND;
4983   }
4984 
4985   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4986                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4987 
4988   assert(!SetCC ||
4989         (SetCC->getConstantOperandVal(1) == 1 &&
4990          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
4991                                                              ISD::SETNE));
4992 
4993   // operands of the new intrinsic call
4994   SmallVector<SDValue, 4> Ops;
4995   if (HaveChain)
4996     Ops.push_back(BRCOND.getOperand(0));
4997 
4998   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
4999   Ops.push_back(Target);
5000 
5001   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5002 
5003   // build the new intrinsic call
5004   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5005 
5006   if (!HaveChain) {
5007     SDValue Ops[] =  {
5008       SDValue(Result, 0),
5009       BRCOND.getOperand(0)
5010     };
5011 
5012     Result = DAG.getMergeValues(Ops, DL).getNode();
5013   }
5014 
5015   if (BR) {
5016     // Give the branch instruction our target
5017     SDValue Ops[] = {
5018       BR->getOperand(0),
5019       BRCOND.getOperand(2)
5020     };
5021     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5022     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5023   }
5024 
5025   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5026 
5027   // Copy the intrinsic results to registers
5028   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5029     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5030     if (!CopyToReg)
5031       continue;
5032 
5033     Chain = DAG.getCopyToReg(
5034       Chain, DL,
5035       CopyToReg->getOperand(1),
5036       SDValue(Result, i - 1),
5037       SDValue());
5038 
5039     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5040   }
5041 
5042   // Remove the old intrinsic from the chain
5043   DAG.ReplaceAllUsesOfValueWith(
5044     SDValue(Intr, Intr->getNumValues() - 1),
5045     Intr->getOperand(0));
5046 
5047   return Chain;
5048 }
5049 
5050 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5051                                           SelectionDAG &DAG) const {
5052   MVT VT = Op.getSimpleValueType();
5053   SDLoc DL(Op);
5054   // Checking the depth
5055   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5056     return DAG.getConstant(0, DL, VT);
5057 
5058   MachineFunction &MF = DAG.getMachineFunction();
5059   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5060   // Check for kernel and shader functions
5061   if (Info->isEntryFunction())
5062     return DAG.getConstant(0, DL, VT);
5063 
5064   MachineFrameInfo &MFI = MF.getFrameInfo();
5065   // There is a call to @llvm.returnaddress in this function
5066   MFI.setReturnAddressIsTaken(true);
5067 
5068   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5069   // Get the return address reg and mark it as an implicit live-in
5070   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5071 
5072   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5073 }
5074 
5075 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5076                                             SDValue Op,
5077                                             const SDLoc &DL,
5078                                             EVT VT) const {
5079   return Op.getValueType().bitsLE(VT) ?
5080       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5081     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5082                 DAG.getTargetConstant(0, DL, MVT::i32));
5083 }
5084 
5085 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5086   assert(Op.getValueType() == MVT::f16 &&
5087          "Do not know how to custom lower FP_ROUND for non-f16 type");
5088 
5089   SDValue Src = Op.getOperand(0);
5090   EVT SrcVT = Src.getValueType();
5091   if (SrcVT != MVT::f64)
5092     return Op;
5093 
5094   SDLoc DL(Op);
5095 
5096   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5097   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5098   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5099 }
5100 
5101 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5102                                                SelectionDAG &DAG) const {
5103   EVT VT = Op.getValueType();
5104   const MachineFunction &MF = DAG.getMachineFunction();
5105   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5106   bool IsIEEEMode = Info->getMode().IEEE;
5107 
5108   // FIXME: Assert during selection that this is only selected for
5109   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5110   // mode functions, but this happens to be OK since it's only done in cases
5111   // where there is known no sNaN.
5112   if (IsIEEEMode)
5113     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5114 
5115   if (VT == MVT::v4f16)
5116     return splitBinaryVectorOp(Op, DAG);
5117   return Op;
5118 }
5119 
5120 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5121   EVT VT = Op.getValueType();
5122   SDLoc SL(Op);
5123   SDValue LHS = Op.getOperand(0);
5124   SDValue RHS = Op.getOperand(1);
5125   bool isSigned = Op.getOpcode() == ISD::SMULO;
5126 
5127   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5128     const APInt &C = RHSC->getAPIntValue();
5129     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5130     if (C.isPowerOf2()) {
5131       // smulo(x, signed_min) is same as umulo(x, signed_min).
5132       bool UseArithShift = isSigned && !C.isMinSignedValue();
5133       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5134       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5135       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5136           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5137                       SL, VT, Result, ShiftAmt),
5138           LHS, ISD::SETNE);
5139       return DAG.getMergeValues({ Result, Overflow }, SL);
5140     }
5141   }
5142 
5143   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5144   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5145                             SL, VT, LHS, RHS);
5146 
5147   SDValue Sign = isSigned
5148     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5149                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5150     : DAG.getConstant(0, SL, VT);
5151   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5152 
5153   return DAG.getMergeValues({ Result, Overflow }, SL);
5154 }
5155 
5156 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5157   SDLoc SL(Op);
5158   SDValue Chain = Op.getOperand(0);
5159 
5160   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5161       !Subtarget->isTrapHandlerEnabled())
5162     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5163 
5164   MachineFunction &MF = DAG.getMachineFunction();
5165   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5166   Register UserSGPR = Info->getQueuePtrUserSGPR();
5167   assert(UserSGPR != AMDGPU::NoRegister);
5168   SDValue QueuePtr = CreateLiveInRegister(
5169     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5170   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5171   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5172                                    QueuePtr, SDValue());
5173   SDValue Ops[] = {
5174     ToReg,
5175     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
5176     SGPR01,
5177     ToReg.getValue(1)
5178   };
5179   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5180 }
5181 
5182 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5183   SDLoc SL(Op);
5184   SDValue Chain = Op.getOperand(0);
5185   MachineFunction &MF = DAG.getMachineFunction();
5186 
5187   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5188       !Subtarget->isTrapHandlerEnabled()) {
5189     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5190                                      "debugtrap handler not supported",
5191                                      Op.getDebugLoc(),
5192                                      DS_Warning);
5193     LLVMContext &Ctx = MF.getFunction().getContext();
5194     Ctx.diagnose(NoTrap);
5195     return Chain;
5196   }
5197 
5198   SDValue Ops[] = {
5199     Chain,
5200     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
5201   };
5202   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5203 }
5204 
5205 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5206                                              SelectionDAG &DAG) const {
5207   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5208   if (Subtarget->hasApertureRegs()) {
5209     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5210         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5211         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5212     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5213         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5214         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5215     unsigned Encoding =
5216         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5217         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5218         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5219 
5220     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5221     SDValue ApertureReg = SDValue(
5222         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5223     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5224     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5225   }
5226 
5227   MachineFunction &MF = DAG.getMachineFunction();
5228   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5229   Register UserSGPR = Info->getQueuePtrUserSGPR();
5230   assert(UserSGPR != AMDGPU::NoRegister);
5231 
5232   SDValue QueuePtr = CreateLiveInRegister(
5233     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5234 
5235   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5236   // private_segment_aperture_base_hi.
5237   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5238 
5239   SDValue Ptr =
5240       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5241 
5242   // TODO: Use custom target PseudoSourceValue.
5243   // TODO: We should use the value from the IR intrinsic call, but it might not
5244   // be available and how do we get it?
5245   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5246   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5247                      commonAlignment(Align(64), StructOffset),
5248                      MachineMemOperand::MODereferenceable |
5249                          MachineMemOperand::MOInvariant);
5250 }
5251 
5252 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5253                                              SelectionDAG &DAG) const {
5254   SDLoc SL(Op);
5255   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5256 
5257   SDValue Src = ASC->getOperand(0);
5258   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5259 
5260   const AMDGPUTargetMachine &TM =
5261     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5262 
5263   // flat -> local/private
5264   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5265     unsigned DestAS = ASC->getDestAddressSpace();
5266 
5267     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5268         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5269       unsigned NullVal = TM.getNullPointerValue(DestAS);
5270       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5271       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5272       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5273 
5274       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
5275                          NonNull, Ptr, SegmentNullPtr);
5276     }
5277   }
5278 
5279   // local/private -> flat
5280   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5281     unsigned SrcAS = ASC->getSrcAddressSpace();
5282 
5283     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5284         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5285       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5286       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5287 
5288       SDValue NonNull
5289         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5290 
5291       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5292       SDValue CvtPtr
5293         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5294 
5295       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5296                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5297                          FlatNullPtr);
5298     }
5299   }
5300 
5301   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5302       Src.getValueType() == MVT::i64)
5303     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5304 
5305   // global <-> flat are no-ops and never emitted.
5306 
5307   const MachineFunction &MF = DAG.getMachineFunction();
5308   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5309     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5310   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5311 
5312   return DAG.getUNDEF(ASC->getValueType(0));
5313 }
5314 
5315 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5316 // the small vector and inserting them into the big vector. That is better than
5317 // the default expansion of doing it via a stack slot. Even though the use of
5318 // the stack slot would be optimized away afterwards, the stack slot itself
5319 // remains.
5320 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5321                                                 SelectionDAG &DAG) const {
5322   SDValue Vec = Op.getOperand(0);
5323   SDValue Ins = Op.getOperand(1);
5324   SDValue Idx = Op.getOperand(2);
5325   EVT VecVT = Vec.getValueType();
5326   EVT InsVT = Ins.getValueType();
5327   EVT EltVT = VecVT.getVectorElementType();
5328   unsigned InsNumElts = InsVT.getVectorNumElements();
5329   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5330   SDLoc SL(Op);
5331 
5332   for (unsigned I = 0; I != InsNumElts; ++I) {
5333     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5334                               DAG.getConstant(I, SL, MVT::i32));
5335     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5336                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5337   }
5338   return Vec;
5339 }
5340 
5341 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5342                                                  SelectionDAG &DAG) const {
5343   SDValue Vec = Op.getOperand(0);
5344   SDValue InsVal = Op.getOperand(1);
5345   SDValue Idx = Op.getOperand(2);
5346   EVT VecVT = Vec.getValueType();
5347   EVT EltVT = VecVT.getVectorElementType();
5348   unsigned VecSize = VecVT.getSizeInBits();
5349   unsigned EltSize = EltVT.getSizeInBits();
5350 
5351 
5352   assert(VecSize <= 64);
5353 
5354   unsigned NumElts = VecVT.getVectorNumElements();
5355   SDLoc SL(Op);
5356   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5357 
5358   if (NumElts == 4 && EltSize == 16 && KIdx) {
5359     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5360 
5361     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5362                                  DAG.getConstant(0, SL, MVT::i32));
5363     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5364                                  DAG.getConstant(1, SL, MVT::i32));
5365 
5366     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5367     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5368 
5369     unsigned Idx = KIdx->getZExtValue();
5370     bool InsertLo = Idx < 2;
5371     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5372       InsertLo ? LoVec : HiVec,
5373       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5374       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5375 
5376     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5377 
5378     SDValue Concat = InsertLo ?
5379       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5380       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5381 
5382     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5383   }
5384 
5385   if (isa<ConstantSDNode>(Idx))
5386     return SDValue();
5387 
5388   MVT IntVT = MVT::getIntegerVT(VecSize);
5389 
5390   // Avoid stack access for dynamic indexing.
5391   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5392 
5393   // Create a congruent vector with the target value in each element so that
5394   // the required element can be masked and ORed into the target vector.
5395   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5396                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5397 
5398   assert(isPowerOf2_32(EltSize));
5399   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5400 
5401   // Convert vector index to bit-index.
5402   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5403 
5404   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5405   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5406                             DAG.getConstant(0xffff, SL, IntVT),
5407                             ScaledIdx);
5408 
5409   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5410   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5411                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5412 
5413   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5414   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5415 }
5416 
5417 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5418                                                   SelectionDAG &DAG) const {
5419   SDLoc SL(Op);
5420 
5421   EVT ResultVT = Op.getValueType();
5422   SDValue Vec = Op.getOperand(0);
5423   SDValue Idx = Op.getOperand(1);
5424   EVT VecVT = Vec.getValueType();
5425   unsigned VecSize = VecVT.getSizeInBits();
5426   EVT EltVT = VecVT.getVectorElementType();
5427   assert(VecSize <= 64);
5428 
5429   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5430 
5431   // Make sure we do any optimizations that will make it easier to fold
5432   // source modifiers before obscuring it with bit operations.
5433 
5434   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5435   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5436     return Combined;
5437 
5438   unsigned EltSize = EltVT.getSizeInBits();
5439   assert(isPowerOf2_32(EltSize));
5440 
5441   MVT IntVT = MVT::getIntegerVT(VecSize);
5442   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5443 
5444   // Convert vector index to bit-index (* EltSize)
5445   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5446 
5447   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5448   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5449 
5450   if (ResultVT == MVT::f16) {
5451     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5452     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5453   }
5454 
5455   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5456 }
5457 
5458 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5459   assert(Elt % 2 == 0);
5460   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5461 }
5462 
5463 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5464                                               SelectionDAG &DAG) const {
5465   SDLoc SL(Op);
5466   EVT ResultVT = Op.getValueType();
5467   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5468 
5469   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5470   EVT EltVT = PackVT.getVectorElementType();
5471   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5472 
5473   // vector_shuffle <0,1,6,7> lhs, rhs
5474   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5475   //
5476   // vector_shuffle <6,7,2,3> lhs, rhs
5477   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5478   //
5479   // vector_shuffle <6,7,0,1> lhs, rhs
5480   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5481 
5482   // Avoid scalarizing when both halves are reading from consecutive elements.
5483   SmallVector<SDValue, 4> Pieces;
5484   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5485     if (elementPairIsContiguous(SVN->getMask(), I)) {
5486       const int Idx = SVN->getMaskElt(I);
5487       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5488       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5489       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5490                                     PackVT, SVN->getOperand(VecIdx),
5491                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5492       Pieces.push_back(SubVec);
5493     } else {
5494       const int Idx0 = SVN->getMaskElt(I);
5495       const int Idx1 = SVN->getMaskElt(I + 1);
5496       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5497       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5498       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5499       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5500 
5501       SDValue Vec0 = SVN->getOperand(VecIdx0);
5502       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5503                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5504 
5505       SDValue Vec1 = SVN->getOperand(VecIdx1);
5506       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5507                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5508       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5509     }
5510   }
5511 
5512   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5513 }
5514 
5515 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5516                                             SelectionDAG &DAG) const {
5517   SDLoc SL(Op);
5518   EVT VT = Op.getValueType();
5519 
5520   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5521     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5522 
5523     // Turn into pair of packed build_vectors.
5524     // TODO: Special case for constants that can be materialized with s_mov_b64.
5525     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5526                                     { Op.getOperand(0), Op.getOperand(1) });
5527     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5528                                     { Op.getOperand(2), Op.getOperand(3) });
5529 
5530     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5531     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5532 
5533     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5534     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5535   }
5536 
5537   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5538   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5539 
5540   SDValue Lo = Op.getOperand(0);
5541   SDValue Hi = Op.getOperand(1);
5542 
5543   // Avoid adding defined bits with the zero_extend.
5544   if (Hi.isUndef()) {
5545     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5546     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5547     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5548   }
5549 
5550   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5551   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5552 
5553   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5554                               DAG.getConstant(16, SL, MVT::i32));
5555   if (Lo.isUndef())
5556     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5557 
5558   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5559   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5560 
5561   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5562   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5563 }
5564 
5565 bool
5566 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5567   // We can fold offsets for anything that doesn't require a GOT relocation.
5568   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5569           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5570           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5571          !shouldEmitGOTReloc(GA->getGlobal());
5572 }
5573 
5574 static SDValue
5575 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5576                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5577                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5578   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5579   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5580   // lowered to the following code sequence:
5581   //
5582   // For constant address space:
5583   //   s_getpc_b64 s[0:1]
5584   //   s_add_u32 s0, s0, $symbol
5585   //   s_addc_u32 s1, s1, 0
5586   //
5587   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5588   //   a fixup or relocation is emitted to replace $symbol with a literal
5589   //   constant, which is a pc-relative offset from the encoding of the $symbol
5590   //   operand to the global variable.
5591   //
5592   // For global address space:
5593   //   s_getpc_b64 s[0:1]
5594   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5595   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5596   //
5597   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5598   //   fixups or relocations are emitted to replace $symbol@*@lo and
5599   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5600   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5601   //   operand to the global variable.
5602   //
5603   // What we want here is an offset from the value returned by s_getpc
5604   // (which is the address of the s_add_u32 instruction) to the global
5605   // variable, but since the encoding of $symbol starts 4 bytes after the start
5606   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5607   // small. This requires us to add 4 to the global variable offset in order to
5608   // compute the correct address. Similarly for the s_addc_u32 instruction, the
5609   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
5610   // instruction.
5611   SDValue PtrLo =
5612       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5613   SDValue PtrHi;
5614   if (GAFlags == SIInstrInfo::MO_NONE) {
5615     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5616   } else {
5617     PtrHi =
5618         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
5619   }
5620   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5621 }
5622 
5623 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5624                                              SDValue Op,
5625                                              SelectionDAG &DAG) const {
5626   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5627   SDLoc DL(GSD);
5628   EVT PtrVT = Op.getValueType();
5629 
5630   const GlobalValue *GV = GSD->getGlobal();
5631   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5632        shouldUseLDSConstAddress(GV)) ||
5633       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5634       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
5635     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5636         GV->hasExternalLinkage()) {
5637       Type *Ty = GV->getValueType();
5638       // HIP uses an unsized array `extern __shared__ T s[]` or similar
5639       // zero-sized type in other languages to declare the dynamic shared
5640       // memory which size is not known at the compile time. They will be
5641       // allocated by the runtime and placed directly after the static
5642       // allocated ones. They all share the same offset.
5643       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
5644         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
5645         // Adjust alignment for that dynamic shared memory array.
5646         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
5647         return SDValue(
5648             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
5649       }
5650     }
5651     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5652   }
5653 
5654   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5655     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5656                                             SIInstrInfo::MO_ABS32_LO);
5657     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5658   }
5659 
5660   if (shouldEmitFixup(GV))
5661     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5662   else if (shouldEmitPCReloc(GV))
5663     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5664                                    SIInstrInfo::MO_REL32);
5665 
5666   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5667                                             SIInstrInfo::MO_GOTPCREL32);
5668 
5669   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5670   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5671   const DataLayout &DataLayout = DAG.getDataLayout();
5672   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
5673   MachinePointerInfo PtrInfo
5674     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5675 
5676   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
5677                      MachineMemOperand::MODereferenceable |
5678                          MachineMemOperand::MOInvariant);
5679 }
5680 
5681 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5682                                    const SDLoc &DL, SDValue V) const {
5683   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5684   // the destination register.
5685   //
5686   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5687   // so we will end up with redundant moves to m0.
5688   //
5689   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5690 
5691   // A Null SDValue creates a glue result.
5692   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5693                                   V, Chain);
5694   return SDValue(M0, 0);
5695 }
5696 
5697 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5698                                                  SDValue Op,
5699                                                  MVT VT,
5700                                                  unsigned Offset) const {
5701   SDLoc SL(Op);
5702   SDValue Param = lowerKernargMemParameter(
5703       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
5704   // The local size values will have the hi 16-bits as zero.
5705   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5706                      DAG.getValueType(VT));
5707 }
5708 
5709 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5710                                         EVT VT) {
5711   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5712                                       "non-hsa intrinsic with hsa target",
5713                                       DL.getDebugLoc());
5714   DAG.getContext()->diagnose(BadIntrin);
5715   return DAG.getUNDEF(VT);
5716 }
5717 
5718 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5719                                          EVT VT) {
5720   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5721                                       "intrinsic not supported on subtarget",
5722                                       DL.getDebugLoc());
5723   DAG.getContext()->diagnose(BadIntrin);
5724   return DAG.getUNDEF(VT);
5725 }
5726 
5727 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5728                                     ArrayRef<SDValue> Elts) {
5729   assert(!Elts.empty());
5730   MVT Type;
5731   unsigned NumElts;
5732 
5733   if (Elts.size() == 1) {
5734     Type = MVT::f32;
5735     NumElts = 1;
5736   } else if (Elts.size() == 2) {
5737     Type = MVT::v2f32;
5738     NumElts = 2;
5739   } else if (Elts.size() == 3) {
5740     Type = MVT::v3f32;
5741     NumElts = 3;
5742   } else if (Elts.size() <= 4) {
5743     Type = MVT::v4f32;
5744     NumElts = 4;
5745   } else if (Elts.size() <= 8) {
5746     Type = MVT::v8f32;
5747     NumElts = 8;
5748   } else {
5749     assert(Elts.size() <= 16);
5750     Type = MVT::v16f32;
5751     NumElts = 16;
5752   }
5753 
5754   SmallVector<SDValue, 16> VecElts(NumElts);
5755   for (unsigned i = 0; i < Elts.size(); ++i) {
5756     SDValue Elt = Elts[i];
5757     if (Elt.getValueType() != MVT::f32)
5758       Elt = DAG.getBitcast(MVT::f32, Elt);
5759     VecElts[i] = Elt;
5760   }
5761   for (unsigned i = Elts.size(); i < NumElts; ++i)
5762     VecElts[i] = DAG.getUNDEF(MVT::f32);
5763 
5764   if (NumElts == 1)
5765     return VecElts[0];
5766   return DAG.getBuildVector(Type, DL, VecElts);
5767 }
5768 
5769 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5770                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5771   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5772 
5773   uint64_t Value = CachePolicyConst->getZExtValue();
5774   SDLoc DL(CachePolicy);
5775   if (GLC) {
5776     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5777     Value &= ~(uint64_t)0x1;
5778   }
5779   if (SLC) {
5780     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5781     Value &= ~(uint64_t)0x2;
5782   }
5783   if (DLC) {
5784     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5785     Value &= ~(uint64_t)0x4;
5786   }
5787 
5788   return Value == 0;
5789 }
5790 
5791 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5792                               SDValue Src, int ExtraElts) {
5793   EVT SrcVT = Src.getValueType();
5794 
5795   SmallVector<SDValue, 8> Elts;
5796 
5797   if (SrcVT.isVector())
5798     DAG.ExtractVectorElements(Src, Elts);
5799   else
5800     Elts.push_back(Src);
5801 
5802   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5803   while (ExtraElts--)
5804     Elts.push_back(Undef);
5805 
5806   return DAG.getBuildVector(CastVT, DL, Elts);
5807 }
5808 
5809 // Re-construct the required return value for a image load intrinsic.
5810 // This is more complicated due to the optional use TexFailCtrl which means the required
5811 // return type is an aggregate
5812 static SDValue constructRetValue(SelectionDAG &DAG,
5813                                  MachineSDNode *Result,
5814                                  ArrayRef<EVT> ResultTypes,
5815                                  bool IsTexFail, bool Unpacked, bool IsD16,
5816                                  int DMaskPop, int NumVDataDwords,
5817                                  const SDLoc &DL, LLVMContext &Context) {
5818   // Determine the required return type. This is the same regardless of IsTexFail flag
5819   EVT ReqRetVT = ResultTypes[0];
5820   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5821   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5822     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5823 
5824   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5825     DMaskPop : (DMaskPop + 1) / 2;
5826 
5827   MVT DataDwordVT = NumDataDwords == 1 ?
5828     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5829 
5830   MVT MaskPopVT = MaskPopDwords == 1 ?
5831     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5832 
5833   SDValue Data(Result, 0);
5834   SDValue TexFail;
5835 
5836   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
5837     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5838     if (MaskPopVT.isVector()) {
5839       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5840                          SDValue(Result, 0), ZeroIdx);
5841     } else {
5842       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5843                          SDValue(Result, 0), ZeroIdx);
5844     }
5845   }
5846 
5847   if (DataDwordVT.isVector())
5848     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5849                           NumDataDwords - MaskPopDwords);
5850 
5851   if (IsD16)
5852     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5853 
5854   EVT LegalReqRetVT = ReqRetVT;
5855   if (!ReqRetVT.isVector()) {
5856     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5857   } else {
5858     // We need to widen the return vector to a legal type
5859     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
5860         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
5861       LegalReqRetVT =
5862           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
5863                            ReqRetVT.getVectorNumElements() + 1);
5864     }
5865   }
5866   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
5867 
5868   if (IsTexFail) {
5869     TexFail =
5870         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
5871                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5872 
5873     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5874   }
5875 
5876   if (Result->getNumValues() == 1)
5877     return Data;
5878 
5879   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5880 }
5881 
5882 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5883                          SDValue *LWE, bool &IsTexFail) {
5884   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5885 
5886   uint64_t Value = TexFailCtrlConst->getZExtValue();
5887   if (Value) {
5888     IsTexFail = true;
5889   }
5890 
5891   SDLoc DL(TexFailCtrlConst);
5892   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5893   Value &= ~(uint64_t)0x1;
5894   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5895   Value &= ~(uint64_t)0x2;
5896 
5897   return Value == 0;
5898 }
5899 
5900 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op,
5901                                         MVT PackVectorVT,
5902                                         SmallVectorImpl<SDValue> &PackedAddrs,
5903                                         unsigned DimIdx, unsigned EndIdx,
5904                                         unsigned NumGradients) {
5905   SDLoc DL(Op);
5906   for (unsigned I = DimIdx; I < EndIdx; I++) {
5907     SDValue Addr = Op.getOperand(I);
5908 
5909     // Gradients are packed with undef for each coordinate.
5910     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
5911     // 1D: undef,dx/dh; undef,dx/dv
5912     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
5913     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
5914     if (((I + 1) >= EndIdx) ||
5915         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
5916                                          I == DimIdx + NumGradients - 1))) {
5917       if (Addr.getValueType() != MVT::i16)
5918         Addr = DAG.getBitcast(MVT::i16, Addr);
5919       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
5920     } else {
5921       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
5922       I++;
5923     }
5924     Addr = DAG.getBitcast(MVT::f32, Addr);
5925     PackedAddrs.push_back(Addr);
5926   }
5927 }
5928 
5929 SDValue SITargetLowering::lowerImage(SDValue Op,
5930                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5931                                      SelectionDAG &DAG, bool WithChain) const {
5932   SDLoc DL(Op);
5933   MachineFunction &MF = DAG.getMachineFunction();
5934   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5935   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5936       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5937   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5938   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5939       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5940   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5941       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5942   unsigned IntrOpcode = Intr->BaseOpcode;
5943   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
5944 
5945   SmallVector<EVT, 3> ResultTypes(Op->values());
5946   SmallVector<EVT, 3> OrigResultTypes(Op->values());
5947   bool IsD16 = false;
5948   bool IsG16 = false;
5949   bool IsA16 = false;
5950   SDValue VData;
5951   int NumVDataDwords;
5952   bool AdjustRetType = false;
5953 
5954   // Offset of intrinsic arguments
5955   const unsigned ArgOffset = WithChain ? 2 : 1;
5956 
5957   unsigned DMask;
5958   unsigned DMaskLanes = 0;
5959 
5960   if (BaseOpcode->Atomic) {
5961     VData = Op.getOperand(2);
5962 
5963     bool Is64Bit = VData.getValueType() == MVT::i64;
5964     if (BaseOpcode->AtomicX2) {
5965       SDValue VData2 = Op.getOperand(3);
5966       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5967                                  {VData, VData2});
5968       if (Is64Bit)
5969         VData = DAG.getBitcast(MVT::v4i32, VData);
5970 
5971       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5972       DMask = Is64Bit ? 0xf : 0x3;
5973       NumVDataDwords = Is64Bit ? 4 : 2;
5974     } else {
5975       DMask = Is64Bit ? 0x3 : 0x1;
5976       NumVDataDwords = Is64Bit ? 2 : 1;
5977     }
5978   } else {
5979     auto *DMaskConst =
5980         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
5981     DMask = DMaskConst->getZExtValue();
5982     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
5983 
5984     if (BaseOpcode->Store) {
5985       VData = Op.getOperand(2);
5986 
5987       MVT StoreVT = VData.getSimpleValueType();
5988       if (StoreVT.getScalarType() == MVT::f16) {
5989         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5990           return Op; // D16 is unsupported for this instruction
5991 
5992         IsD16 = true;
5993         VData = handleD16VData(VData, DAG, true);
5994       }
5995 
5996       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
5997     } else {
5998       // Work out the num dwords based on the dmask popcount and underlying type
5999       // and whether packing is supported.
6000       MVT LoadVT = ResultTypes[0].getSimpleVT();
6001       if (LoadVT.getScalarType() == MVT::f16) {
6002         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6003           return Op; // D16 is unsupported for this instruction
6004 
6005         IsD16 = true;
6006       }
6007 
6008       // Confirm that the return type is large enough for the dmask specified
6009       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6010           (!LoadVT.isVector() && DMaskLanes > 1))
6011           return Op;
6012 
6013       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6014       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6015       // instructions.
6016       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6017           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6018         NumVDataDwords = (DMaskLanes + 1) / 2;
6019       else
6020         NumVDataDwords = DMaskLanes;
6021 
6022       AdjustRetType = true;
6023     }
6024   }
6025 
6026   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6027   SmallVector<SDValue, 4> VAddrs;
6028 
6029   // Optimize _L to _LZ when _L is zero
6030   if (LZMappingInfo) {
6031     if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>(
6032             Op.getOperand(ArgOffset + Intr->LodIndex))) {
6033       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
6034         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
6035         VAddrEnd--;                      // remove 'lod'
6036       }
6037     }
6038   }
6039 
6040   // Optimize _mip away, when 'lod' is zero
6041   if (MIPMappingInfo) {
6042     if (auto *ConstantLod = dyn_cast<ConstantSDNode>(
6043             Op.getOperand(ArgOffset + Intr->MipIndex))) {
6044       if (ConstantLod->isNullValue()) {
6045         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
6046         VAddrEnd--;                           // remove 'mip'
6047       }
6048     }
6049   }
6050 
6051   // Push back extra arguments.
6052   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++)
6053     VAddrs.push_back(Op.getOperand(ArgOffset + I));
6054 
6055   // Check for 16 bit addresses or derivatives and pack if true.
6056   MVT VAddrVT =
6057       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6058   MVT VAddrScalarVT = VAddrVT.getScalarType();
6059   MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6060   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6061 
6062   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6063   VAddrScalarVT = VAddrVT.getScalarType();
6064   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6065   if (IsA16 || IsG16) {
6066     if (IsA16) {
6067       if (!ST->hasA16()) {
6068         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6069                              "support 16 bit addresses\n");
6070         return Op;
6071       }
6072       if (!IsG16) {
6073         LLVM_DEBUG(
6074             dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6075                       "need 16 bit derivatives but got 32 bit derivatives\n");
6076         return Op;
6077       }
6078     } else if (!ST->hasG16()) {
6079       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6080                            "support 16 bit derivatives\n");
6081       return Op;
6082     }
6083 
6084     if (BaseOpcode->Gradients && !IsA16) {
6085       if (!ST->hasG16()) {
6086         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6087                              "support 16 bit derivatives\n");
6088         return Op;
6089       }
6090       // Activate g16
6091       const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6092           AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6093       IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6094     }
6095 
6096     // Don't compress addresses for G16
6097     const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6098     packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs,
6099                                 ArgOffset + Intr->GradientStart, PackEndIdx,
6100                                 Intr->NumGradients);
6101 
6102     if (!IsA16) {
6103       // Add uncompressed address
6104       for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6105         VAddrs.push_back(Op.getOperand(I));
6106     }
6107   } else {
6108     for (unsigned I = ArgOffset + Intr->GradientStart; I < VAddrEnd; I++)
6109       VAddrs.push_back(Op.getOperand(I));
6110   }
6111 
6112   // If the register allocator cannot place the address registers contiguously
6113   // without introducing moves, then using the non-sequential address encoding
6114   // is always preferable, since it saves VALU instructions and is usually a
6115   // wash in terms of code size or even better.
6116   //
6117   // However, we currently have no way of hinting to the register allocator that
6118   // MIMG addresses should be placed contiguously when it is possible to do so,
6119   // so force non-NSA for the common 2-address case as a heuristic.
6120   //
6121   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6122   // allocation when possible.
6123   bool UseNSA =
6124       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
6125   SDValue VAddr;
6126   if (!UseNSA)
6127     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6128 
6129   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6130   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6131   SDValue Unorm;
6132   if (!BaseOpcode->Sampler) {
6133     Unorm = True;
6134   } else {
6135     auto UnormConst =
6136         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6137 
6138     Unorm = UnormConst->getZExtValue() ? True : False;
6139   }
6140 
6141   SDValue TFE;
6142   SDValue LWE;
6143   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6144   bool IsTexFail = false;
6145   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6146     return Op;
6147 
6148   if (IsTexFail) {
6149     if (!DMaskLanes) {
6150       // Expecting to get an error flag since TFC is on - and dmask is 0
6151       // Force dmask to be at least 1 otherwise the instruction will fail
6152       DMask = 0x1;
6153       DMaskLanes = 1;
6154       NumVDataDwords = 1;
6155     }
6156     NumVDataDwords += 1;
6157     AdjustRetType = true;
6158   }
6159 
6160   // Has something earlier tagged that the return type needs adjusting
6161   // This happens if the instruction is a load or has set TexFailCtrl flags
6162   if (AdjustRetType) {
6163     // NumVDataDwords reflects the true number of dwords required in the return type
6164     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6165       // This is a no-op load. This can be eliminated
6166       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6167       if (isa<MemSDNode>(Op))
6168         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6169       return Undef;
6170     }
6171 
6172     EVT NewVT = NumVDataDwords > 1 ?
6173                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6174                 : MVT::i32;
6175 
6176     ResultTypes[0] = NewVT;
6177     if (ResultTypes.size() == 3) {
6178       // Original result was aggregate type used for TexFailCtrl results
6179       // The actual instruction returns as a vector type which has now been
6180       // created. Remove the aggregate result.
6181       ResultTypes.erase(&ResultTypes[1]);
6182     }
6183   }
6184 
6185   SDValue GLC;
6186   SDValue SLC;
6187   SDValue DLC;
6188   if (BaseOpcode->Atomic) {
6189     GLC = True; // TODO no-return optimization
6190     if (!parseCachePolicy(Op.getOperand(ArgOffset + Intr->CachePolicyIndex),
6191                           DAG, nullptr, &SLC, IsGFX10Plus ? &DLC : nullptr))
6192       return Op;
6193   } else {
6194     if (!parseCachePolicy(Op.getOperand(ArgOffset + Intr->CachePolicyIndex),
6195                           DAG, &GLC, &SLC, IsGFX10Plus ? &DLC : nullptr))
6196       return Op;
6197   }
6198 
6199   SmallVector<SDValue, 26> Ops;
6200   if (BaseOpcode->Store || BaseOpcode->Atomic)
6201     Ops.push_back(VData); // vdata
6202   if (UseNSA)
6203     append_range(Ops, VAddrs);
6204   else
6205     Ops.push_back(VAddr);
6206   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6207   if (BaseOpcode->Sampler)
6208     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6209   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6210   if (IsGFX10Plus)
6211     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6212   Ops.push_back(Unorm);
6213   if (!IsGFX10Plus)
6214     Ops.push_back(DAG.getTargetConstant(0, SDLoc(), MVT::i1));
6215   if (IsGFX10Plus)
6216     Ops.push_back(DLC);
6217   Ops.push_back(GLC);
6218   Ops.push_back(SLC);
6219   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6220                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6221   if (IsGFX10Plus)
6222     Ops.push_back(IsA16 ? True : False);
6223   if (!Subtarget->hasGFX90AInsts()) {
6224     Ops.push_back(TFE); //tfe
6225   } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6226     report_fatal_error("TFE is not supported on this GPU");
6227   }
6228   Ops.push_back(LWE); // lwe
6229   if (!IsGFX10Plus)
6230     Ops.push_back(DimInfo->DA ? True : False);
6231   if (BaseOpcode->HasD16)
6232     Ops.push_back(IsD16 ? True : False);
6233   if (isa<MemSDNode>(Op))
6234     Ops.push_back(Op.getOperand(0)); // chain
6235 
6236   int NumVAddrDwords =
6237       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6238   int Opcode = -1;
6239 
6240   if (IsGFX10Plus) {
6241     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6242                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6243                                           : AMDGPU::MIMGEncGfx10Default,
6244                                    NumVDataDwords, NumVAddrDwords);
6245   } else {
6246     if (Subtarget->hasGFX90AInsts()) {
6247       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6248                                      NumVDataDwords, NumVAddrDwords);
6249       if (Opcode == -1)
6250         report_fatal_error(
6251             "requested image instruction is not supported on this GPU");
6252     }
6253     if (Opcode == -1 &&
6254         Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6255       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6256                                      NumVDataDwords, NumVAddrDwords);
6257     if (Opcode == -1)
6258       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6259                                      NumVDataDwords, NumVAddrDwords);
6260   }
6261   assert(Opcode != -1);
6262 
6263   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6264   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6265     MachineMemOperand *MemRef = MemOp->getMemOperand();
6266     DAG.setNodeMemRefs(NewNode, {MemRef});
6267   }
6268 
6269   if (BaseOpcode->AtomicX2) {
6270     SmallVector<SDValue, 1> Elt;
6271     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6272     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6273   } else if (!BaseOpcode->Store) {
6274     return constructRetValue(DAG, NewNode,
6275                              OrigResultTypes, IsTexFail,
6276                              Subtarget->hasUnpackedD16VMem(), IsD16,
6277                              DMaskLanes, NumVDataDwords, DL,
6278                              *DAG.getContext());
6279   }
6280 
6281   return SDValue(NewNode, 0);
6282 }
6283 
6284 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6285                                        SDValue Offset, SDValue CachePolicy,
6286                                        SelectionDAG &DAG) const {
6287   MachineFunction &MF = DAG.getMachineFunction();
6288 
6289   const DataLayout &DataLayout = DAG.getDataLayout();
6290   Align Alignment =
6291       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6292 
6293   MachineMemOperand *MMO = MF.getMachineMemOperand(
6294       MachinePointerInfo(),
6295       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6296           MachineMemOperand::MOInvariant,
6297       VT.getStoreSize(), Alignment);
6298 
6299   if (!Offset->isDivergent()) {
6300     SDValue Ops[] = {
6301         Rsrc,
6302         Offset, // Offset
6303         CachePolicy
6304     };
6305 
6306     // Widen vec3 load to vec4.
6307     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6308       EVT WidenedVT =
6309           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6310       auto WidenedOp = DAG.getMemIntrinsicNode(
6311           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6312           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6313       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6314                                    DAG.getVectorIdxConstant(0, DL));
6315       return Subvector;
6316     }
6317 
6318     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6319                                    DAG.getVTList(VT), Ops, VT, MMO);
6320   }
6321 
6322   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6323   // assume that the buffer is unswizzled.
6324   SmallVector<SDValue, 4> Loads;
6325   unsigned NumLoads = 1;
6326   MVT LoadVT = VT.getSimpleVT();
6327   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6328   assert((LoadVT.getScalarType() == MVT::i32 ||
6329           LoadVT.getScalarType() == MVT::f32));
6330 
6331   if (NumElts == 8 || NumElts == 16) {
6332     NumLoads = NumElts / 4;
6333     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6334   }
6335 
6336   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6337   SDValue Ops[] = {
6338       DAG.getEntryNode(),                               // Chain
6339       Rsrc,                                             // rsrc
6340       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6341       {},                                               // voffset
6342       {},                                               // soffset
6343       {},                                               // offset
6344       CachePolicy,                                      // cachepolicy
6345       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6346   };
6347 
6348   // Use the alignment to ensure that the required offsets will fit into the
6349   // immediate offsets.
6350   setBufferOffsets(Offset, DAG, &Ops[3],
6351                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6352 
6353   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6354   for (unsigned i = 0; i < NumLoads; ++i) {
6355     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6356     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6357                                         LoadVT, MMO, DAG));
6358   }
6359 
6360   if (NumElts == 8 || NumElts == 16)
6361     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6362 
6363   return Loads[0];
6364 }
6365 
6366 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6367                                                   SelectionDAG &DAG) const {
6368   MachineFunction &MF = DAG.getMachineFunction();
6369   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6370 
6371   EVT VT = Op.getValueType();
6372   SDLoc DL(Op);
6373   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6374 
6375   // TODO: Should this propagate fast-math-flags?
6376 
6377   switch (IntrinsicID) {
6378   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6379     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6380       return emitNonHSAIntrinsicError(DAG, DL, VT);
6381     return getPreloadedValue(DAG, *MFI, VT,
6382                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6383   }
6384   case Intrinsic::amdgcn_dispatch_ptr:
6385   case Intrinsic::amdgcn_queue_ptr: {
6386     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6387       DiagnosticInfoUnsupported BadIntrin(
6388           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6389           DL.getDebugLoc());
6390       DAG.getContext()->diagnose(BadIntrin);
6391       return DAG.getUNDEF(VT);
6392     }
6393 
6394     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6395       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6396     return getPreloadedValue(DAG, *MFI, VT, RegID);
6397   }
6398   case Intrinsic::amdgcn_implicitarg_ptr: {
6399     if (MFI->isEntryFunction())
6400       return getImplicitArgPtr(DAG, DL);
6401     return getPreloadedValue(DAG, *MFI, VT,
6402                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6403   }
6404   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6405     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6406       // This only makes sense to call in a kernel, so just lower to null.
6407       return DAG.getConstant(0, DL, VT);
6408     }
6409 
6410     return getPreloadedValue(DAG, *MFI, VT,
6411                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6412   }
6413   case Intrinsic::amdgcn_dispatch_id: {
6414     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6415   }
6416   case Intrinsic::amdgcn_rcp:
6417     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6418   case Intrinsic::amdgcn_rsq:
6419     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6420   case Intrinsic::amdgcn_rsq_legacy:
6421     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6422       return emitRemovedIntrinsicError(DAG, DL, VT);
6423     return SDValue();
6424   case Intrinsic::amdgcn_rcp_legacy:
6425     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6426       return emitRemovedIntrinsicError(DAG, DL, VT);
6427     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6428   case Intrinsic::amdgcn_rsq_clamp: {
6429     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6430       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6431 
6432     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6433     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6434     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6435 
6436     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6437     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6438                               DAG.getConstantFP(Max, DL, VT));
6439     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6440                        DAG.getConstantFP(Min, DL, VT));
6441   }
6442   case Intrinsic::r600_read_ngroups_x:
6443     if (Subtarget->isAmdHsaOS())
6444       return emitNonHSAIntrinsicError(DAG, DL, VT);
6445 
6446     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6447                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6448                                     false);
6449   case Intrinsic::r600_read_ngroups_y:
6450     if (Subtarget->isAmdHsaOS())
6451       return emitNonHSAIntrinsicError(DAG, DL, VT);
6452 
6453     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6454                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6455                                     false);
6456   case Intrinsic::r600_read_ngroups_z:
6457     if (Subtarget->isAmdHsaOS())
6458       return emitNonHSAIntrinsicError(DAG, DL, VT);
6459 
6460     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6461                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6462                                     false);
6463   case Intrinsic::r600_read_global_size_x:
6464     if (Subtarget->isAmdHsaOS())
6465       return emitNonHSAIntrinsicError(DAG, DL, VT);
6466 
6467     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6468                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6469                                     Align(4), false);
6470   case Intrinsic::r600_read_global_size_y:
6471     if (Subtarget->isAmdHsaOS())
6472       return emitNonHSAIntrinsicError(DAG, DL, VT);
6473 
6474     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6475                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6476                                     Align(4), false);
6477   case Intrinsic::r600_read_global_size_z:
6478     if (Subtarget->isAmdHsaOS())
6479       return emitNonHSAIntrinsicError(DAG, DL, VT);
6480 
6481     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6482                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6483                                     Align(4), false);
6484   case Intrinsic::r600_read_local_size_x:
6485     if (Subtarget->isAmdHsaOS())
6486       return emitNonHSAIntrinsicError(DAG, DL, VT);
6487 
6488     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6489                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6490   case Intrinsic::r600_read_local_size_y:
6491     if (Subtarget->isAmdHsaOS())
6492       return emitNonHSAIntrinsicError(DAG, DL, VT);
6493 
6494     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6495                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6496   case Intrinsic::r600_read_local_size_z:
6497     if (Subtarget->isAmdHsaOS())
6498       return emitNonHSAIntrinsicError(DAG, DL, VT);
6499 
6500     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6501                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6502   case Intrinsic::amdgcn_workgroup_id_x:
6503     return getPreloadedValue(DAG, *MFI, VT,
6504                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6505   case Intrinsic::amdgcn_workgroup_id_y:
6506     return getPreloadedValue(DAG, *MFI, VT,
6507                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6508   case Intrinsic::amdgcn_workgroup_id_z:
6509     return getPreloadedValue(DAG, *MFI, VT,
6510                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6511   case Intrinsic::amdgcn_workitem_id_x:
6512     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6513                           SDLoc(DAG.getEntryNode()),
6514                           MFI->getArgInfo().WorkItemIDX);
6515   case Intrinsic::amdgcn_workitem_id_y:
6516     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6517                           SDLoc(DAG.getEntryNode()),
6518                           MFI->getArgInfo().WorkItemIDY);
6519   case Intrinsic::amdgcn_workitem_id_z:
6520     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6521                           SDLoc(DAG.getEntryNode()),
6522                           MFI->getArgInfo().WorkItemIDZ);
6523   case Intrinsic::amdgcn_wavefrontsize:
6524     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6525                            SDLoc(Op), MVT::i32);
6526   case Intrinsic::amdgcn_s_buffer_load: {
6527     bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6528     SDValue GLC;
6529     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
6530     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
6531                           IsGFX10Plus ? &DLC : nullptr))
6532       return Op;
6533     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6534                         DAG);
6535   }
6536   case Intrinsic::amdgcn_fdiv_fast:
6537     return lowerFDIV_FAST(Op, DAG);
6538   case Intrinsic::amdgcn_sin:
6539     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6540 
6541   case Intrinsic::amdgcn_cos:
6542     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6543 
6544   case Intrinsic::amdgcn_mul_u24:
6545     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6546   case Intrinsic::amdgcn_mul_i24:
6547     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6548 
6549   case Intrinsic::amdgcn_log_clamp: {
6550     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6551       return SDValue();
6552 
6553     return emitRemovedIntrinsicError(DAG, DL, VT);
6554   }
6555   case Intrinsic::amdgcn_ldexp:
6556     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6557                        Op.getOperand(1), Op.getOperand(2));
6558 
6559   case Intrinsic::amdgcn_fract:
6560     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6561 
6562   case Intrinsic::amdgcn_class:
6563     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6564                        Op.getOperand(1), Op.getOperand(2));
6565   case Intrinsic::amdgcn_div_fmas:
6566     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6567                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6568                        Op.getOperand(4));
6569 
6570   case Intrinsic::amdgcn_div_fixup:
6571     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6572                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6573 
6574   case Intrinsic::amdgcn_div_scale: {
6575     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6576 
6577     // Translate to the operands expected by the machine instruction. The
6578     // first parameter must be the same as the first instruction.
6579     SDValue Numerator = Op.getOperand(1);
6580     SDValue Denominator = Op.getOperand(2);
6581 
6582     // Note this order is opposite of the machine instruction's operations,
6583     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6584     // intrinsic has the numerator as the first operand to match a normal
6585     // division operation.
6586 
6587     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6588 
6589     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6590                        Denominator, Numerator);
6591   }
6592   case Intrinsic::amdgcn_icmp: {
6593     // There is a Pat that handles this variant, so return it as-is.
6594     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6595         Op.getConstantOperandVal(2) == 0 &&
6596         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6597       return Op;
6598     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6599   }
6600   case Intrinsic::amdgcn_fcmp: {
6601     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6602   }
6603   case Intrinsic::amdgcn_ballot:
6604     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6605   case Intrinsic::amdgcn_fmed3:
6606     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6607                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6608   case Intrinsic::amdgcn_fdot2:
6609     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6610                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6611                        Op.getOperand(4));
6612   case Intrinsic::amdgcn_fmul_legacy:
6613     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6614                        Op.getOperand(1), Op.getOperand(2));
6615   case Intrinsic::amdgcn_sffbh:
6616     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6617   case Intrinsic::amdgcn_sbfe:
6618     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6619                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6620   case Intrinsic::amdgcn_ubfe:
6621     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6622                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6623   case Intrinsic::amdgcn_cvt_pkrtz:
6624   case Intrinsic::amdgcn_cvt_pknorm_i16:
6625   case Intrinsic::amdgcn_cvt_pknorm_u16:
6626   case Intrinsic::amdgcn_cvt_pk_i16:
6627   case Intrinsic::amdgcn_cvt_pk_u16: {
6628     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6629     EVT VT = Op.getValueType();
6630     unsigned Opcode;
6631 
6632     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6633       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6634     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6635       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6636     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6637       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6638     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6639       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6640     else
6641       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6642 
6643     if (isTypeLegal(VT))
6644       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6645 
6646     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6647                                Op.getOperand(1), Op.getOperand(2));
6648     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6649   }
6650   case Intrinsic::amdgcn_fmad_ftz:
6651     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6652                        Op.getOperand(2), Op.getOperand(3));
6653 
6654   case Intrinsic::amdgcn_if_break:
6655     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6656                                       Op->getOperand(1), Op->getOperand(2)), 0);
6657 
6658   case Intrinsic::amdgcn_groupstaticsize: {
6659     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6660     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6661       return Op;
6662 
6663     const Module *M = MF.getFunction().getParent();
6664     const GlobalValue *GV =
6665         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6666     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6667                                             SIInstrInfo::MO_ABS32_LO);
6668     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6669   }
6670   case Intrinsic::amdgcn_is_shared:
6671   case Intrinsic::amdgcn_is_private: {
6672     SDLoc SL(Op);
6673     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6674       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6675     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6676     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6677                                  Op.getOperand(1));
6678 
6679     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6680                                 DAG.getConstant(1, SL, MVT::i32));
6681     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6682   }
6683   case Intrinsic::amdgcn_alignbit:
6684     return DAG.getNode(ISD::FSHR, DL, VT,
6685                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6686   case Intrinsic::amdgcn_reloc_constant: {
6687     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6688     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6689     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6690     auto RelocSymbol = cast<GlobalVariable>(
6691         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6692     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6693                                             SIInstrInfo::MO_ABS32_LO);
6694     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6695   }
6696   default:
6697     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6698             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6699       return lowerImage(Op, ImageDimIntr, DAG, false);
6700 
6701     return Op;
6702   }
6703 }
6704 
6705 // This function computes an appropriate offset to pass to
6706 // MachineMemOperand::setOffset() based on the offset inputs to
6707 // an intrinsic.  If any of the offsets are non-contstant or
6708 // if VIndex is non-zero then this function returns 0.  Otherwise,
6709 // it returns the sum of VOffset, SOffset, and Offset.
6710 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6711                                       SDValue SOffset,
6712                                       SDValue Offset,
6713                                       SDValue VIndex = SDValue()) {
6714 
6715   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6716       !isa<ConstantSDNode>(Offset))
6717     return 0;
6718 
6719   if (VIndex) {
6720     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6721       return 0;
6722   }
6723 
6724   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6725          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6726          cast<ConstantSDNode>(Offset)->getSExtValue();
6727 }
6728 
6729 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
6730                                                      SelectionDAG &DAG,
6731                                                      unsigned NewOpcode) const {
6732   SDLoc DL(Op);
6733 
6734   SDValue VData = Op.getOperand(2);
6735   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6736   SDValue Ops[] = {
6737     Op.getOperand(0), // Chain
6738     VData,            // vdata
6739     Op.getOperand(3), // rsrc
6740     DAG.getConstant(0, DL, MVT::i32), // vindex
6741     Offsets.first,    // voffset
6742     Op.getOperand(5), // soffset
6743     Offsets.second,   // offset
6744     Op.getOperand(6), // cachepolicy
6745     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6746   };
6747 
6748   auto *M = cast<MemSDNode>(Op);
6749   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6750 
6751   EVT MemVT = VData.getValueType();
6752   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6753                                  M->getMemOperand());
6754 }
6755 
6756 SDValue
6757 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
6758                                                 unsigned NewOpcode) const {
6759   SDLoc DL(Op);
6760 
6761   SDValue VData = Op.getOperand(2);
6762   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6763   SDValue Ops[] = {
6764     Op.getOperand(0), // Chain
6765     VData,            // vdata
6766     Op.getOperand(3), // rsrc
6767     Op.getOperand(4), // vindex
6768     Offsets.first,    // voffset
6769     Op.getOperand(6), // soffset
6770     Offsets.second,   // offset
6771     Op.getOperand(7), // cachepolicy
6772     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6773   };
6774 
6775   auto *M = cast<MemSDNode>(Op);
6776   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6777                                                       Ops[3]));
6778 
6779   EVT MemVT = VData.getValueType();
6780   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6781                                  M->getMemOperand());
6782 }
6783 
6784 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6785                                                  SelectionDAG &DAG) const {
6786   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6787   SDLoc DL(Op);
6788 
6789   switch (IntrID) {
6790   case Intrinsic::amdgcn_ds_ordered_add:
6791   case Intrinsic::amdgcn_ds_ordered_swap: {
6792     MemSDNode *M = cast<MemSDNode>(Op);
6793     SDValue Chain = M->getOperand(0);
6794     SDValue M0 = M->getOperand(2);
6795     SDValue Value = M->getOperand(3);
6796     unsigned IndexOperand = M->getConstantOperandVal(7);
6797     unsigned WaveRelease = M->getConstantOperandVal(8);
6798     unsigned WaveDone = M->getConstantOperandVal(9);
6799 
6800     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6801     IndexOperand &= ~0x3f;
6802     unsigned CountDw = 0;
6803 
6804     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6805       CountDw = (IndexOperand >> 24) & 0xf;
6806       IndexOperand &= ~(0xf << 24);
6807 
6808       if (CountDw < 1 || CountDw > 4) {
6809         report_fatal_error(
6810             "ds_ordered_count: dword count must be between 1 and 4");
6811       }
6812     }
6813 
6814     if (IndexOperand)
6815       report_fatal_error("ds_ordered_count: bad index operand");
6816 
6817     if (WaveDone && !WaveRelease)
6818       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6819 
6820     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6821     unsigned ShaderType =
6822         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
6823     unsigned Offset0 = OrderedCountIndex << 2;
6824     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6825                        (Instruction << 4);
6826 
6827     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6828       Offset1 |= (CountDw - 1) << 6;
6829 
6830     unsigned Offset = Offset0 | (Offset1 << 8);
6831 
6832     SDValue Ops[] = {
6833       Chain,
6834       Value,
6835       DAG.getTargetConstant(Offset, DL, MVT::i16),
6836       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6837     };
6838     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6839                                    M->getVTList(), Ops, M->getMemoryVT(),
6840                                    M->getMemOperand());
6841   }
6842   case Intrinsic::amdgcn_ds_fadd: {
6843     MemSDNode *M = cast<MemSDNode>(Op);
6844     unsigned Opc;
6845     switch (IntrID) {
6846     case Intrinsic::amdgcn_ds_fadd:
6847       Opc = ISD::ATOMIC_LOAD_FADD;
6848       break;
6849     }
6850 
6851     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6852                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6853                          M->getMemOperand());
6854   }
6855   case Intrinsic::amdgcn_atomic_inc:
6856   case Intrinsic::amdgcn_atomic_dec:
6857   case Intrinsic::amdgcn_ds_fmin:
6858   case Intrinsic::amdgcn_ds_fmax: {
6859     MemSDNode *M = cast<MemSDNode>(Op);
6860     unsigned Opc;
6861     switch (IntrID) {
6862     case Intrinsic::amdgcn_atomic_inc:
6863       Opc = AMDGPUISD::ATOMIC_INC;
6864       break;
6865     case Intrinsic::amdgcn_atomic_dec:
6866       Opc = AMDGPUISD::ATOMIC_DEC;
6867       break;
6868     case Intrinsic::amdgcn_ds_fmin:
6869       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6870       break;
6871     case Intrinsic::amdgcn_ds_fmax:
6872       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6873       break;
6874     default:
6875       llvm_unreachable("Unknown intrinsic!");
6876     }
6877     SDValue Ops[] = {
6878       M->getOperand(0), // Chain
6879       M->getOperand(2), // Ptr
6880       M->getOperand(3)  // Value
6881     };
6882 
6883     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6884                                    M->getMemoryVT(), M->getMemOperand());
6885   }
6886   case Intrinsic::amdgcn_buffer_load:
6887   case Intrinsic::amdgcn_buffer_load_format: {
6888     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6889     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6890     unsigned IdxEn = 1;
6891     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6892       IdxEn = Idx->getZExtValue() != 0;
6893     SDValue Ops[] = {
6894       Op.getOperand(0), // Chain
6895       Op.getOperand(2), // rsrc
6896       Op.getOperand(3), // vindex
6897       SDValue(),        // voffset -- will be set by setBufferOffsets
6898       SDValue(),        // soffset -- will be set by setBufferOffsets
6899       SDValue(),        // offset -- will be set by setBufferOffsets
6900       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6901       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6902     };
6903 
6904     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6905     // We don't know the offset if vindex is non-zero, so clear it.
6906     if (IdxEn)
6907       Offset = 0;
6908 
6909     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6910         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6911 
6912     EVT VT = Op.getValueType();
6913     EVT IntVT = VT.changeTypeToInteger();
6914     auto *M = cast<MemSDNode>(Op);
6915     M->getMemOperand()->setOffset(Offset);
6916     EVT LoadVT = Op.getValueType();
6917 
6918     if (LoadVT.getScalarType() == MVT::f16)
6919       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6920                                  M, DAG, Ops);
6921 
6922     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6923     if (LoadVT.getScalarType() == MVT::i8 ||
6924         LoadVT.getScalarType() == MVT::i16)
6925       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6926 
6927     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6928                                M->getMemOperand(), DAG);
6929   }
6930   case Intrinsic::amdgcn_raw_buffer_load:
6931   case Intrinsic::amdgcn_raw_buffer_load_format: {
6932     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6933 
6934     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6935     SDValue Ops[] = {
6936       Op.getOperand(0), // Chain
6937       Op.getOperand(2), // rsrc
6938       DAG.getConstant(0, DL, MVT::i32), // vindex
6939       Offsets.first,    // voffset
6940       Op.getOperand(4), // soffset
6941       Offsets.second,   // offset
6942       Op.getOperand(5), // cachepolicy, swizzled buffer
6943       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6944     };
6945 
6946     auto *M = cast<MemSDNode>(Op);
6947     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6948     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6949   }
6950   case Intrinsic::amdgcn_struct_buffer_load:
6951   case Intrinsic::amdgcn_struct_buffer_load_format: {
6952     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6953 
6954     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6955     SDValue Ops[] = {
6956       Op.getOperand(0), // Chain
6957       Op.getOperand(2), // rsrc
6958       Op.getOperand(3), // vindex
6959       Offsets.first,    // voffset
6960       Op.getOperand(5), // soffset
6961       Offsets.second,   // offset
6962       Op.getOperand(6), // cachepolicy, swizzled buffer
6963       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6964     };
6965 
6966     auto *M = cast<MemSDNode>(Op);
6967     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
6968                                                         Ops[2]));
6969     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6970   }
6971   case Intrinsic::amdgcn_tbuffer_load: {
6972     MemSDNode *M = cast<MemSDNode>(Op);
6973     EVT LoadVT = Op.getValueType();
6974 
6975     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6976     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6977     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6978     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6979     unsigned IdxEn = 1;
6980     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6981       IdxEn = Idx->getZExtValue() != 0;
6982     SDValue Ops[] = {
6983       Op.getOperand(0),  // Chain
6984       Op.getOperand(2),  // rsrc
6985       Op.getOperand(3),  // vindex
6986       Op.getOperand(4),  // voffset
6987       Op.getOperand(5),  // soffset
6988       Op.getOperand(6),  // offset
6989       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6990       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6991       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
6992     };
6993 
6994     if (LoadVT.getScalarType() == MVT::f16)
6995       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6996                                  M, DAG, Ops);
6997     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6998                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6999                                DAG);
7000   }
7001   case Intrinsic::amdgcn_raw_tbuffer_load: {
7002     MemSDNode *M = cast<MemSDNode>(Op);
7003     EVT LoadVT = Op.getValueType();
7004     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7005 
7006     SDValue Ops[] = {
7007       Op.getOperand(0),  // Chain
7008       Op.getOperand(2),  // rsrc
7009       DAG.getConstant(0, DL, MVT::i32), // vindex
7010       Offsets.first,     // voffset
7011       Op.getOperand(4),  // soffset
7012       Offsets.second,    // offset
7013       Op.getOperand(5),  // format
7014       Op.getOperand(6),  // cachepolicy, swizzled buffer
7015       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7016     };
7017 
7018     if (LoadVT.getScalarType() == MVT::f16)
7019       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7020                                  M, DAG, Ops);
7021     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7022                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7023                                DAG);
7024   }
7025   case Intrinsic::amdgcn_struct_tbuffer_load: {
7026     MemSDNode *M = cast<MemSDNode>(Op);
7027     EVT LoadVT = Op.getValueType();
7028     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7029 
7030     SDValue Ops[] = {
7031       Op.getOperand(0),  // Chain
7032       Op.getOperand(2),  // rsrc
7033       Op.getOperand(3),  // vindex
7034       Offsets.first,     // voffset
7035       Op.getOperand(5),  // soffset
7036       Offsets.second,    // offset
7037       Op.getOperand(6),  // format
7038       Op.getOperand(7),  // cachepolicy, swizzled buffer
7039       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7040     };
7041 
7042     if (LoadVT.getScalarType() == MVT::f16)
7043       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7044                                  M, DAG, Ops);
7045     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7046                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7047                                DAG);
7048   }
7049   case Intrinsic::amdgcn_buffer_atomic_swap:
7050   case Intrinsic::amdgcn_buffer_atomic_add:
7051   case Intrinsic::amdgcn_buffer_atomic_sub:
7052   case Intrinsic::amdgcn_buffer_atomic_csub:
7053   case Intrinsic::amdgcn_buffer_atomic_smin:
7054   case Intrinsic::amdgcn_buffer_atomic_umin:
7055   case Intrinsic::amdgcn_buffer_atomic_smax:
7056   case Intrinsic::amdgcn_buffer_atomic_umax:
7057   case Intrinsic::amdgcn_buffer_atomic_and:
7058   case Intrinsic::amdgcn_buffer_atomic_or:
7059   case Intrinsic::amdgcn_buffer_atomic_xor:
7060   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7061     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7062     unsigned IdxEn = 1;
7063     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7064       IdxEn = Idx->getZExtValue() != 0;
7065     SDValue Ops[] = {
7066       Op.getOperand(0), // Chain
7067       Op.getOperand(2), // vdata
7068       Op.getOperand(3), // rsrc
7069       Op.getOperand(4), // vindex
7070       SDValue(),        // voffset -- will be set by setBufferOffsets
7071       SDValue(),        // soffset -- will be set by setBufferOffsets
7072       SDValue(),        // offset -- will be set by setBufferOffsets
7073       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7074       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7075     };
7076     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7077     // We don't know the offset if vindex is non-zero, so clear it.
7078     if (IdxEn)
7079       Offset = 0;
7080     EVT VT = Op.getValueType();
7081 
7082     auto *M = cast<MemSDNode>(Op);
7083     M->getMemOperand()->setOffset(Offset);
7084     unsigned Opcode = 0;
7085 
7086     switch (IntrID) {
7087     case Intrinsic::amdgcn_buffer_atomic_swap:
7088       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7089       break;
7090     case Intrinsic::amdgcn_buffer_atomic_add:
7091       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7092       break;
7093     case Intrinsic::amdgcn_buffer_atomic_sub:
7094       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7095       break;
7096     case Intrinsic::amdgcn_buffer_atomic_csub:
7097       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7098       break;
7099     case Intrinsic::amdgcn_buffer_atomic_smin:
7100       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7101       break;
7102     case Intrinsic::amdgcn_buffer_atomic_umin:
7103       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7104       break;
7105     case Intrinsic::amdgcn_buffer_atomic_smax:
7106       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7107       break;
7108     case Intrinsic::amdgcn_buffer_atomic_umax:
7109       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7110       break;
7111     case Intrinsic::amdgcn_buffer_atomic_and:
7112       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7113       break;
7114     case Intrinsic::amdgcn_buffer_atomic_or:
7115       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7116       break;
7117     case Intrinsic::amdgcn_buffer_atomic_xor:
7118       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7119       break;
7120     case Intrinsic::amdgcn_buffer_atomic_fadd:
7121       if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7122         DiagnosticInfoUnsupported
7123           NoFpRet(DAG.getMachineFunction().getFunction(),
7124                   "return versions of fp atomics not supported",
7125                   DL.getDebugLoc(), DS_Error);
7126         DAG.getContext()->diagnose(NoFpRet);
7127         return SDValue();
7128       }
7129       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7130       break;
7131     default:
7132       llvm_unreachable("unhandled atomic opcode");
7133     }
7134 
7135     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7136                                    M->getMemOperand());
7137   }
7138   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7139     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7140   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7141     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7142   case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7143     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7144   case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7145     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7146   case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7147     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7148   case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7149     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7150   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7151     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7152   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7153     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7154   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7155     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7156   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7157     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7158   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7159     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7160   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7161     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7162   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7163     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7164   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7165     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7166   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7167     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7168   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7169     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7170   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7171     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7172   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7173     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7174   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7175     return lowerStructBufferAtomicIntrin(Op, DAG,
7176                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7177   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7178     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7179   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7180     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7181   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7182     return lowerStructBufferAtomicIntrin(Op, DAG,
7183                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7184   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7185     return lowerStructBufferAtomicIntrin(Op, DAG,
7186                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7187   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7188     return lowerStructBufferAtomicIntrin(Op, DAG,
7189                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7190   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7191     return lowerStructBufferAtomicIntrin(Op, DAG,
7192                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7193   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7194     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7195   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7196     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7197   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7198     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7199   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7200     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7201   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7202     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7203 
7204   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7205     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7206     unsigned IdxEn = 1;
7207     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
7208       IdxEn = Idx->getZExtValue() != 0;
7209     SDValue Ops[] = {
7210       Op.getOperand(0), // Chain
7211       Op.getOperand(2), // src
7212       Op.getOperand(3), // cmp
7213       Op.getOperand(4), // rsrc
7214       Op.getOperand(5), // vindex
7215       SDValue(),        // voffset -- will be set by setBufferOffsets
7216       SDValue(),        // soffset -- will be set by setBufferOffsets
7217       SDValue(),        // offset -- will be set by setBufferOffsets
7218       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7219       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7220     };
7221     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7222     // We don't know the offset if vindex is non-zero, so clear it.
7223     if (IdxEn)
7224       Offset = 0;
7225     EVT VT = Op.getValueType();
7226     auto *M = cast<MemSDNode>(Op);
7227     M->getMemOperand()->setOffset(Offset);
7228 
7229     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7230                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7231   }
7232   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7233     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7234     SDValue Ops[] = {
7235       Op.getOperand(0), // Chain
7236       Op.getOperand(2), // src
7237       Op.getOperand(3), // cmp
7238       Op.getOperand(4), // rsrc
7239       DAG.getConstant(0, DL, MVT::i32), // vindex
7240       Offsets.first,    // voffset
7241       Op.getOperand(6), // soffset
7242       Offsets.second,   // offset
7243       Op.getOperand(7), // cachepolicy
7244       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7245     };
7246     EVT VT = Op.getValueType();
7247     auto *M = cast<MemSDNode>(Op);
7248     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
7249 
7250     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7251                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7252   }
7253   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7254     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7255     SDValue Ops[] = {
7256       Op.getOperand(0), // Chain
7257       Op.getOperand(2), // src
7258       Op.getOperand(3), // cmp
7259       Op.getOperand(4), // rsrc
7260       Op.getOperand(5), // vindex
7261       Offsets.first,    // voffset
7262       Op.getOperand(7), // soffset
7263       Offsets.second,   // offset
7264       Op.getOperand(8), // cachepolicy
7265       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7266     };
7267     EVT VT = Op.getValueType();
7268     auto *M = cast<MemSDNode>(Op);
7269     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
7270                                                         Ops[4]));
7271 
7272     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7273                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7274   }
7275   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7276     SDLoc DL(Op);
7277     MemSDNode *M = cast<MemSDNode>(Op);
7278     SDValue NodePtr = M->getOperand(2);
7279     SDValue RayExtent = M->getOperand(3);
7280     SDValue RayOrigin = M->getOperand(4);
7281     SDValue RayDir = M->getOperand(5);
7282     SDValue RayInvDir = M->getOperand(6);
7283     SDValue TDescr = M->getOperand(7);
7284 
7285     assert(NodePtr.getValueType() == MVT::i32 ||
7286            NodePtr.getValueType() == MVT::i64);
7287     assert(RayDir.getValueType() == MVT::v4f16 ||
7288            RayDir.getValueType() == MVT::v4f32);
7289 
7290     bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7291     bool Is64 = NodePtr.getValueType() == MVT::i64;
7292     unsigned Opcode = IsA16 ? Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16_nsa
7293                                    : AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16_nsa
7294                             : Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_nsa
7295                                    : AMDGPU::IMAGE_BVH_INTERSECT_RAY_nsa;
7296 
7297     SmallVector<SDValue, 16> Ops;
7298 
7299     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7300       SmallVector<SDValue, 3> Lanes;
7301       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7302       if (Lanes[0].getValueSizeInBits() == 32) {
7303         for (unsigned I = 0; I < 3; ++I)
7304           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7305       } else {
7306         if (IsAligned) {
7307           Ops.push_back(
7308             DAG.getBitcast(MVT::i32,
7309                            DAG.getBuildVector(MVT::v2f16, DL,
7310                                               { Lanes[0], Lanes[1] })));
7311           Ops.push_back(Lanes[2]);
7312         } else {
7313           SDValue Elt0 = Ops.pop_back_val();
7314           Ops.push_back(
7315             DAG.getBitcast(MVT::i32,
7316                            DAG.getBuildVector(MVT::v2f16, DL,
7317                                               { Elt0, Lanes[0] })));
7318           Ops.push_back(
7319             DAG.getBitcast(MVT::i32,
7320                            DAG.getBuildVector(MVT::v2f16, DL,
7321                                               { Lanes[1], Lanes[2] })));
7322         }
7323       }
7324     };
7325 
7326     if (Is64)
7327       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7328     else
7329       Ops.push_back(NodePtr);
7330 
7331     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7332     packLanes(RayOrigin, true);
7333     packLanes(RayDir, true);
7334     packLanes(RayInvDir, false);
7335     Ops.push_back(TDescr);
7336     if (IsA16)
7337       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7338     Ops.push_back(M->getChain());
7339 
7340     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7341     MachineMemOperand *MemRef = M->getMemOperand();
7342     DAG.setNodeMemRefs(NewNode, {MemRef});
7343     return SDValue(NewNode, 0);
7344   }
7345   case Intrinsic::amdgcn_global_atomic_fadd:
7346     if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7347       DiagnosticInfoUnsupported
7348         NoFpRet(DAG.getMachineFunction().getFunction(),
7349                 "return versions of fp atomics not supported",
7350                 DL.getDebugLoc(), DS_Error);
7351       DAG.getContext()->diagnose(NoFpRet);
7352       return SDValue();
7353     }
7354     LLVM_FALLTHROUGH;
7355   case Intrinsic::amdgcn_global_atomic_fmin:
7356   case Intrinsic::amdgcn_global_atomic_fmax:
7357   case Intrinsic::amdgcn_flat_atomic_fadd:
7358   case Intrinsic::amdgcn_flat_atomic_fmin:
7359   case Intrinsic::amdgcn_flat_atomic_fmax: {
7360     MemSDNode *M = cast<MemSDNode>(Op);
7361     SDValue Ops[] = {
7362       M->getOperand(0), // Chain
7363       M->getOperand(2), // Ptr
7364       M->getOperand(3)  // Value
7365     };
7366     unsigned Opcode = 0;
7367     switch (IntrID) {
7368     case Intrinsic::amdgcn_global_atomic_fadd:
7369     case Intrinsic::amdgcn_flat_atomic_fadd: {
7370       EVT VT = Op.getOperand(3).getValueType();
7371       return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7372                            DAG.getVTList(VT, MVT::Other), Ops,
7373                            M->getMemOperand());
7374     }
7375     case Intrinsic::amdgcn_global_atomic_fmin:
7376     case Intrinsic::amdgcn_flat_atomic_fmin: {
7377       Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7378       break;
7379     }
7380     case Intrinsic::amdgcn_global_atomic_fmax:
7381     case Intrinsic::amdgcn_flat_atomic_fmax: {
7382       Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7383       break;
7384     }
7385     default:
7386       llvm_unreachable("unhandled atomic opcode");
7387     }
7388     return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7389                                    M->getVTList(), Ops, M->getMemoryVT(),
7390                                    M->getMemOperand());
7391   }
7392   default:
7393 
7394     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7395             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7396       return lowerImage(Op, ImageDimIntr, DAG, true);
7397 
7398     return SDValue();
7399   }
7400 }
7401 
7402 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7403 // dwordx4 if on SI.
7404 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7405                                               SDVTList VTList,
7406                                               ArrayRef<SDValue> Ops, EVT MemVT,
7407                                               MachineMemOperand *MMO,
7408                                               SelectionDAG &DAG) const {
7409   EVT VT = VTList.VTs[0];
7410   EVT WidenedVT = VT;
7411   EVT WidenedMemVT = MemVT;
7412   if (!Subtarget->hasDwordx3LoadStores() &&
7413       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7414     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7415                                  WidenedVT.getVectorElementType(), 4);
7416     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7417                                     WidenedMemVT.getVectorElementType(), 4);
7418     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7419   }
7420 
7421   assert(VTList.NumVTs == 2);
7422   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7423 
7424   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7425                                        WidenedMemVT, MMO);
7426   if (WidenedVT != VT) {
7427     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7428                                DAG.getVectorIdxConstant(0, DL));
7429     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7430   }
7431   return NewOp;
7432 }
7433 
7434 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7435                                          bool ImageStore) const {
7436   EVT StoreVT = VData.getValueType();
7437 
7438   // No change for f16 and legal vector D16 types.
7439   if (!StoreVT.isVector())
7440     return VData;
7441 
7442   SDLoc DL(VData);
7443   unsigned NumElements = StoreVT.getVectorNumElements();
7444 
7445   if (Subtarget->hasUnpackedD16VMem()) {
7446     // We need to unpack the packed data to store.
7447     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7448     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7449 
7450     EVT EquivStoreVT =
7451         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7452     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7453     return DAG.UnrollVectorOp(ZExt.getNode());
7454   }
7455 
7456   // The sq block of gfx8.1 does not estimate register use correctly for d16
7457   // image store instructions. The data operand is computed as if it were not a
7458   // d16 image instruction.
7459   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7460     // Bitcast to i16
7461     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7462     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7463 
7464     // Decompose into scalars
7465     SmallVector<SDValue, 4> Elts;
7466     DAG.ExtractVectorElements(IntVData, Elts);
7467 
7468     // Group pairs of i16 into v2i16 and bitcast to i32
7469     SmallVector<SDValue, 4> PackedElts;
7470     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7471       SDValue Pair =
7472           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7473       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7474       PackedElts.push_back(IntPair);
7475     }
7476     if ((NumElements % 2) == 1) {
7477       // Handle v3i16
7478       unsigned I = Elts.size() / 2;
7479       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7480                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7481       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7482       PackedElts.push_back(IntPair);
7483     }
7484 
7485     // Pad using UNDEF
7486     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7487 
7488     // Build final vector
7489     EVT VecVT =
7490         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7491     return DAG.getBuildVector(VecVT, DL, PackedElts);
7492   }
7493 
7494   if (NumElements == 3) {
7495     EVT IntStoreVT =
7496         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7497     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7498 
7499     EVT WidenedStoreVT = EVT::getVectorVT(
7500         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7501     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7502                                          WidenedStoreVT.getStoreSizeInBits());
7503     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7504     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7505   }
7506 
7507   assert(isTypeLegal(StoreVT));
7508   return VData;
7509 }
7510 
7511 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7512                                               SelectionDAG &DAG) const {
7513   SDLoc DL(Op);
7514   SDValue Chain = Op.getOperand(0);
7515   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7516   MachineFunction &MF = DAG.getMachineFunction();
7517 
7518   switch (IntrinsicID) {
7519   case Intrinsic::amdgcn_exp_compr: {
7520     SDValue Src0 = Op.getOperand(4);
7521     SDValue Src1 = Op.getOperand(5);
7522     // Hack around illegal type on SI by directly selecting it.
7523     if (isTypeLegal(Src0.getValueType()))
7524       return SDValue();
7525 
7526     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7527     SDValue Undef = DAG.getUNDEF(MVT::f32);
7528     const SDValue Ops[] = {
7529       Op.getOperand(2), // tgt
7530       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7531       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7532       Undef, // src2
7533       Undef, // src3
7534       Op.getOperand(7), // vm
7535       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7536       Op.getOperand(3), // en
7537       Op.getOperand(0) // Chain
7538     };
7539 
7540     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7541     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7542   }
7543   case Intrinsic::amdgcn_s_barrier: {
7544     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7545       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7546       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7547       if (WGSize <= ST.getWavefrontSize())
7548         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7549                                           Op.getOperand(0)), 0);
7550     }
7551     return SDValue();
7552   };
7553   case Intrinsic::amdgcn_tbuffer_store: {
7554     SDValue VData = Op.getOperand(2);
7555     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7556     if (IsD16)
7557       VData = handleD16VData(VData, DAG);
7558     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7559     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7560     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7561     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7562     unsigned IdxEn = 1;
7563     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7564       IdxEn = Idx->getZExtValue() != 0;
7565     SDValue Ops[] = {
7566       Chain,
7567       VData,             // vdata
7568       Op.getOperand(3),  // rsrc
7569       Op.getOperand(4),  // vindex
7570       Op.getOperand(5),  // voffset
7571       Op.getOperand(6),  // soffset
7572       Op.getOperand(7),  // offset
7573       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7574       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7575       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
7576     };
7577     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7578                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7579     MemSDNode *M = cast<MemSDNode>(Op);
7580     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7581                                    M->getMemoryVT(), M->getMemOperand());
7582   }
7583 
7584   case Intrinsic::amdgcn_struct_tbuffer_store: {
7585     SDValue VData = Op.getOperand(2);
7586     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7587     if (IsD16)
7588       VData = handleD16VData(VData, DAG);
7589     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7590     SDValue Ops[] = {
7591       Chain,
7592       VData,             // vdata
7593       Op.getOperand(3),  // rsrc
7594       Op.getOperand(4),  // vindex
7595       Offsets.first,     // voffset
7596       Op.getOperand(6),  // soffset
7597       Offsets.second,    // offset
7598       Op.getOperand(7),  // format
7599       Op.getOperand(8),  // cachepolicy, swizzled buffer
7600       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
7601     };
7602     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7603                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7604     MemSDNode *M = cast<MemSDNode>(Op);
7605     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7606                                    M->getMemoryVT(), M->getMemOperand());
7607   }
7608 
7609   case Intrinsic::amdgcn_raw_tbuffer_store: {
7610     SDValue VData = Op.getOperand(2);
7611     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7612     if (IsD16)
7613       VData = handleD16VData(VData, DAG);
7614     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7615     SDValue Ops[] = {
7616       Chain,
7617       VData,             // vdata
7618       Op.getOperand(3),  // rsrc
7619       DAG.getConstant(0, DL, MVT::i32), // vindex
7620       Offsets.first,     // voffset
7621       Op.getOperand(5),  // soffset
7622       Offsets.second,    // offset
7623       Op.getOperand(6),  // format
7624       Op.getOperand(7),  // cachepolicy, swizzled buffer
7625       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
7626     };
7627     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7628                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7629     MemSDNode *M = cast<MemSDNode>(Op);
7630     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7631                                    M->getMemoryVT(), M->getMemOperand());
7632   }
7633 
7634   case Intrinsic::amdgcn_buffer_store:
7635   case Intrinsic::amdgcn_buffer_store_format: {
7636     SDValue VData = Op.getOperand(2);
7637     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7638     if (IsD16)
7639       VData = handleD16VData(VData, DAG);
7640     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7641     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7642     unsigned IdxEn = 1;
7643     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7644       IdxEn = Idx->getZExtValue() != 0;
7645     SDValue Ops[] = {
7646       Chain,
7647       VData,
7648       Op.getOperand(3), // rsrc
7649       Op.getOperand(4), // vindex
7650       SDValue(), // voffset -- will be set by setBufferOffsets
7651       SDValue(), // soffset -- will be set by setBufferOffsets
7652       SDValue(), // offset -- will be set by setBufferOffsets
7653       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7654       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7655     };
7656     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7657     // We don't know the offset if vindex is non-zero, so clear it.
7658     if (IdxEn)
7659       Offset = 0;
7660     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7661                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7662     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7663     MemSDNode *M = cast<MemSDNode>(Op);
7664     M->getMemOperand()->setOffset(Offset);
7665 
7666     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7667     EVT VDataType = VData.getValueType().getScalarType();
7668     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7669       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7670 
7671     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7672                                    M->getMemoryVT(), M->getMemOperand());
7673   }
7674 
7675   case Intrinsic::amdgcn_raw_buffer_store:
7676   case Intrinsic::amdgcn_raw_buffer_store_format: {
7677     const bool IsFormat =
7678         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7679 
7680     SDValue VData = Op.getOperand(2);
7681     EVT VDataVT = VData.getValueType();
7682     EVT EltType = VDataVT.getScalarType();
7683     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7684     if (IsD16) {
7685       VData = handleD16VData(VData, DAG);
7686       VDataVT = VData.getValueType();
7687     }
7688 
7689     if (!isTypeLegal(VDataVT)) {
7690       VData =
7691           DAG.getNode(ISD::BITCAST, DL,
7692                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7693     }
7694 
7695     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7696     SDValue Ops[] = {
7697       Chain,
7698       VData,
7699       Op.getOperand(3), // rsrc
7700       DAG.getConstant(0, DL, MVT::i32), // vindex
7701       Offsets.first,    // voffset
7702       Op.getOperand(5), // soffset
7703       Offsets.second,   // offset
7704       Op.getOperand(6), // cachepolicy, swizzled buffer
7705       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7706     };
7707     unsigned Opc =
7708         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7709     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7710     MemSDNode *M = cast<MemSDNode>(Op);
7711     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
7712 
7713     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7714     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7715       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7716 
7717     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7718                                    M->getMemoryVT(), M->getMemOperand());
7719   }
7720 
7721   case Intrinsic::amdgcn_struct_buffer_store:
7722   case Intrinsic::amdgcn_struct_buffer_store_format: {
7723     const bool IsFormat =
7724         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7725 
7726     SDValue VData = Op.getOperand(2);
7727     EVT VDataVT = VData.getValueType();
7728     EVT EltType = VDataVT.getScalarType();
7729     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7730 
7731     if (IsD16) {
7732       VData = handleD16VData(VData, DAG);
7733       VDataVT = VData.getValueType();
7734     }
7735 
7736     if (!isTypeLegal(VDataVT)) {
7737       VData =
7738           DAG.getNode(ISD::BITCAST, DL,
7739                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7740     }
7741 
7742     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7743     SDValue Ops[] = {
7744       Chain,
7745       VData,
7746       Op.getOperand(3), // rsrc
7747       Op.getOperand(4), // vindex
7748       Offsets.first,    // voffset
7749       Op.getOperand(6), // soffset
7750       Offsets.second,   // offset
7751       Op.getOperand(7), // cachepolicy, swizzled buffer
7752       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7753     };
7754     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7755                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7756     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7757     MemSDNode *M = cast<MemSDNode>(Op);
7758     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7759                                                         Ops[3]));
7760 
7761     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7762     EVT VDataType = VData.getValueType().getScalarType();
7763     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7764       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7765 
7766     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7767                                    M->getMemoryVT(), M->getMemOperand());
7768   }
7769   case Intrinsic::amdgcn_end_cf:
7770     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7771                                       Op->getOperand(2), Chain), 0);
7772 
7773   default: {
7774     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7775             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7776       return lowerImage(Op, ImageDimIntr, DAG, true);
7777 
7778     return Op;
7779   }
7780   }
7781 }
7782 
7783 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7784 // offset (the offset that is included in bounds checking and swizzling, to be
7785 // split between the instruction's voffset and immoffset fields) and soffset
7786 // (the offset that is excluded from bounds checking and swizzling, to go in
7787 // the instruction's soffset field).  This function takes the first kind of
7788 // offset and figures out how to split it between voffset and immoffset.
7789 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7790     SDValue Offset, SelectionDAG &DAG) const {
7791   SDLoc DL(Offset);
7792   const unsigned MaxImm = 4095;
7793   SDValue N0 = Offset;
7794   ConstantSDNode *C1 = nullptr;
7795 
7796   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7797     N0 = SDValue();
7798   else if (DAG.isBaseWithConstantOffset(N0)) {
7799     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7800     N0 = N0.getOperand(0);
7801   }
7802 
7803   if (C1) {
7804     unsigned ImmOffset = C1->getZExtValue();
7805     // If the immediate value is too big for the immoffset field, put the value
7806     // and -4096 into the immoffset field so that the value that is copied/added
7807     // for the voffset field is a multiple of 4096, and it stands more chance
7808     // of being CSEd with the copy/add for another similar load/store.
7809     // However, do not do that rounding down to a multiple of 4096 if that is a
7810     // negative number, as it appears to be illegal to have a negative offset
7811     // in the vgpr, even if adding the immediate offset makes it positive.
7812     unsigned Overflow = ImmOffset & ~MaxImm;
7813     ImmOffset -= Overflow;
7814     if ((int32_t)Overflow < 0) {
7815       Overflow += ImmOffset;
7816       ImmOffset = 0;
7817     }
7818     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7819     if (Overflow) {
7820       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7821       if (!N0)
7822         N0 = OverflowVal;
7823       else {
7824         SDValue Ops[] = { N0, OverflowVal };
7825         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7826       }
7827     }
7828   }
7829   if (!N0)
7830     N0 = DAG.getConstant(0, DL, MVT::i32);
7831   if (!C1)
7832     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7833   return {N0, SDValue(C1, 0)};
7834 }
7835 
7836 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7837 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7838 // pointed to by Offsets.
7839 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7840                                             SelectionDAG &DAG, SDValue *Offsets,
7841                                             Align Alignment) const {
7842   SDLoc DL(CombinedOffset);
7843   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7844     uint32_t Imm = C->getZExtValue();
7845     uint32_t SOffset, ImmOffset;
7846     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
7847                                  Alignment)) {
7848       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7849       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7850       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7851       return SOffset + ImmOffset;
7852     }
7853   }
7854   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7855     SDValue N0 = CombinedOffset.getOperand(0);
7856     SDValue N1 = CombinedOffset.getOperand(1);
7857     uint32_t SOffset, ImmOffset;
7858     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7859     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7860                                                 Subtarget, Alignment)) {
7861       Offsets[0] = N0;
7862       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7863       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7864       return 0;
7865     }
7866   }
7867   Offsets[0] = CombinedOffset;
7868   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7869   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7870   return 0;
7871 }
7872 
7873 // Handle 8 bit and 16 bit buffer loads
7874 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7875                                                      EVT LoadVT, SDLoc DL,
7876                                                      ArrayRef<SDValue> Ops,
7877                                                      MemSDNode *M) const {
7878   EVT IntVT = LoadVT.changeTypeToInteger();
7879   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7880          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7881 
7882   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7883   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7884                                                Ops, IntVT,
7885                                                M->getMemOperand());
7886   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7887   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7888 
7889   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7890 }
7891 
7892 // Handle 8 bit and 16 bit buffer stores
7893 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7894                                                       EVT VDataType, SDLoc DL,
7895                                                       SDValue Ops[],
7896                                                       MemSDNode *M) const {
7897   if (VDataType == MVT::f16)
7898     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7899 
7900   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7901   Ops[1] = BufferStoreExt;
7902   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7903                                  AMDGPUISD::BUFFER_STORE_SHORT;
7904   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7905   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7906                                      M->getMemOperand());
7907 }
7908 
7909 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7910                                  ISD::LoadExtType ExtType, SDValue Op,
7911                                  const SDLoc &SL, EVT VT) {
7912   if (VT.bitsLT(Op.getValueType()))
7913     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7914 
7915   switch (ExtType) {
7916   case ISD::SEXTLOAD:
7917     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7918   case ISD::ZEXTLOAD:
7919     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7920   case ISD::EXTLOAD:
7921     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7922   case ISD::NON_EXTLOAD:
7923     return Op;
7924   }
7925 
7926   llvm_unreachable("invalid ext type");
7927 }
7928 
7929 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7930   SelectionDAG &DAG = DCI.DAG;
7931   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7932     return SDValue();
7933 
7934   // FIXME: Constant loads should all be marked invariant.
7935   unsigned AS = Ld->getAddressSpace();
7936   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7937       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7938       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7939     return SDValue();
7940 
7941   // Don't do this early, since it may interfere with adjacent load merging for
7942   // illegal types. We can avoid losing alignment information for exotic types
7943   // pre-legalize.
7944   EVT MemVT = Ld->getMemoryVT();
7945   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7946       MemVT.getSizeInBits() >= 32)
7947     return SDValue();
7948 
7949   SDLoc SL(Ld);
7950 
7951   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7952          "unexpected vector extload");
7953 
7954   // TODO: Drop only high part of range.
7955   SDValue Ptr = Ld->getBasePtr();
7956   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7957                                 MVT::i32, SL, Ld->getChain(), Ptr,
7958                                 Ld->getOffset(),
7959                                 Ld->getPointerInfo(), MVT::i32,
7960                                 Ld->getAlignment(),
7961                                 Ld->getMemOperand()->getFlags(),
7962                                 Ld->getAAInfo(),
7963                                 nullptr); // Drop ranges
7964 
7965   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7966   if (MemVT.isFloatingPoint()) {
7967     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7968            "unexpected fp extload");
7969     TruncVT = MemVT.changeTypeToInteger();
7970   }
7971 
7972   SDValue Cvt = NewLoad;
7973   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7974     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7975                       DAG.getValueType(TruncVT));
7976   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7977              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7978     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7979   } else {
7980     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7981   }
7982 
7983   EVT VT = Ld->getValueType(0);
7984   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7985 
7986   DCI.AddToWorklist(Cvt.getNode());
7987 
7988   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7989   // the appropriate extension from the 32-bit load.
7990   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7991   DCI.AddToWorklist(Cvt.getNode());
7992 
7993   // Handle conversion back to floating point if necessary.
7994   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7995 
7996   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7997 }
7998 
7999 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8000   SDLoc DL(Op);
8001   LoadSDNode *Load = cast<LoadSDNode>(Op);
8002   ISD::LoadExtType ExtType = Load->getExtensionType();
8003   EVT MemVT = Load->getMemoryVT();
8004 
8005   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8006     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8007       return SDValue();
8008 
8009     // FIXME: Copied from PPC
8010     // First, load into 32 bits, then truncate to 1 bit.
8011 
8012     SDValue Chain = Load->getChain();
8013     SDValue BasePtr = Load->getBasePtr();
8014     MachineMemOperand *MMO = Load->getMemOperand();
8015 
8016     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8017 
8018     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8019                                    BasePtr, RealMemVT, MMO);
8020 
8021     if (!MemVT.isVector()) {
8022       SDValue Ops[] = {
8023         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8024         NewLD.getValue(1)
8025       };
8026 
8027       return DAG.getMergeValues(Ops, DL);
8028     }
8029 
8030     SmallVector<SDValue, 3> Elts;
8031     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8032       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8033                                 DAG.getConstant(I, DL, MVT::i32));
8034 
8035       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8036     }
8037 
8038     SDValue Ops[] = {
8039       DAG.getBuildVector(MemVT, DL, Elts),
8040       NewLD.getValue(1)
8041     };
8042 
8043     return DAG.getMergeValues(Ops, DL);
8044   }
8045 
8046   if (!MemVT.isVector())
8047     return SDValue();
8048 
8049   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8050          "Custom lowering for non-i32 vectors hasn't been implemented.");
8051 
8052   unsigned Alignment = Load->getAlignment();
8053   unsigned AS = Load->getAddressSpace();
8054   if (Subtarget->hasLDSMisalignedBug() &&
8055       AS == AMDGPUAS::FLAT_ADDRESS &&
8056       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8057     return SplitVectorLoad(Op, DAG);
8058   }
8059 
8060   MachineFunction &MF = DAG.getMachineFunction();
8061   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8062   // If there is a possibilty that flat instruction access scratch memory
8063   // then we need to use the same legalization rules we use for private.
8064   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8065       !Subtarget->hasMultiDwordFlatScratchAddressing())
8066     AS = MFI->hasFlatScratchInit() ?
8067          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8068 
8069   unsigned NumElements = MemVT.getVectorNumElements();
8070 
8071   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8072       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8073     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8074       if (MemVT.isPow2VectorType())
8075         return SDValue();
8076       return WidenOrSplitVectorLoad(Op, DAG);
8077     }
8078     // Non-uniform loads will be selected to MUBUF instructions, so they
8079     // have the same legalization requirements as global and private
8080     // loads.
8081     //
8082   }
8083 
8084   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8085       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8086       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8087     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8088         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8089         Alignment >= 4 && NumElements < 32) {
8090       if (MemVT.isPow2VectorType())
8091         return SDValue();
8092       return WidenOrSplitVectorLoad(Op, DAG);
8093     }
8094     // Non-uniform loads will be selected to MUBUF instructions, so they
8095     // have the same legalization requirements as global and private
8096     // loads.
8097     //
8098   }
8099   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8100       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8101       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8102       AS == AMDGPUAS::FLAT_ADDRESS) {
8103     if (NumElements > 4)
8104       return SplitVectorLoad(Op, DAG);
8105     // v3 loads not supported on SI.
8106     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8107       return WidenOrSplitVectorLoad(Op, DAG);
8108 
8109     // v3 and v4 loads are supported for private and global memory.
8110     return SDValue();
8111   }
8112   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8113     // Depending on the setting of the private_element_size field in the
8114     // resource descriptor, we can only make private accesses up to a certain
8115     // size.
8116     switch (Subtarget->getMaxPrivateElementSize()) {
8117     case 4: {
8118       SDValue Ops[2];
8119       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8120       return DAG.getMergeValues(Ops, DL);
8121     }
8122     case 8:
8123       if (NumElements > 2)
8124         return SplitVectorLoad(Op, DAG);
8125       return SDValue();
8126     case 16:
8127       // Same as global/flat
8128       if (NumElements > 4)
8129         return SplitVectorLoad(Op, DAG);
8130       // v3 loads not supported on SI.
8131       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8132         return WidenOrSplitVectorLoad(Op, DAG);
8133 
8134       return SDValue();
8135     default:
8136       llvm_unreachable("unsupported private_element_size");
8137     }
8138   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8139     // Use ds_read_b128 or ds_read_b96 when possible.
8140     if (Subtarget->hasDS96AndDS128() &&
8141         ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) ||
8142          MemVT.getStoreSize() == 12) &&
8143         allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8144                                            Load->getAlign()))
8145       return SDValue();
8146 
8147     if (NumElements > 2)
8148       return SplitVectorLoad(Op, DAG);
8149 
8150     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8151     // address is negative, then the instruction is incorrectly treated as
8152     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8153     // loads here to avoid emitting ds_read2_b32. We may re-combine the
8154     // load later in the SILoadStoreOptimizer.
8155     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
8156         NumElements == 2 && MemVT.getStoreSize() == 8 &&
8157         Load->getAlignment() < 8) {
8158       return SplitVectorLoad(Op, DAG);
8159     }
8160   }
8161 
8162   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8163                                       MemVT, *Load->getMemOperand())) {
8164     SDValue Ops[2];
8165     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8166     return DAG.getMergeValues(Ops, DL);
8167   }
8168 
8169   return SDValue();
8170 }
8171 
8172 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8173   EVT VT = Op.getValueType();
8174   assert(VT.getSizeInBits() == 64);
8175 
8176   SDLoc DL(Op);
8177   SDValue Cond = Op.getOperand(0);
8178 
8179   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8180   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8181 
8182   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8183   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8184 
8185   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8186   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8187 
8188   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8189 
8190   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8191   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8192 
8193   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8194 
8195   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8196   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8197 }
8198 
8199 // Catch division cases where we can use shortcuts with rcp and rsq
8200 // instructions.
8201 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8202                                               SelectionDAG &DAG) const {
8203   SDLoc SL(Op);
8204   SDValue LHS = Op.getOperand(0);
8205   SDValue RHS = Op.getOperand(1);
8206   EVT VT = Op.getValueType();
8207   const SDNodeFlags Flags = Op->getFlags();
8208 
8209   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8210 
8211   // Without !fpmath accuracy information, we can't do more because we don't
8212   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8213   if (!AllowInaccurateRcp)
8214     return SDValue();
8215 
8216   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8217     if (CLHS->isExactlyValue(1.0)) {
8218       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8219       // the CI documentation has a worst case error of 1 ulp.
8220       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8221       // use it as long as we aren't trying to use denormals.
8222       //
8223       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8224 
8225       // 1.0 / sqrt(x) -> rsq(x)
8226 
8227       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8228       // error seems really high at 2^29 ULP.
8229       if (RHS.getOpcode() == ISD::FSQRT)
8230         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8231 
8232       // 1.0 / x -> rcp(x)
8233       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8234     }
8235 
8236     // Same as for 1.0, but expand the sign out of the constant.
8237     if (CLHS->isExactlyValue(-1.0)) {
8238       // -1.0 / x -> rcp (fneg x)
8239       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8240       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8241     }
8242   }
8243 
8244   // Turn into multiply by the reciprocal.
8245   // x / y -> x * (1.0 / y)
8246   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8247   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8248 }
8249 
8250 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8251                                                 SelectionDAG &DAG) const {
8252   SDLoc SL(Op);
8253   SDValue X = Op.getOperand(0);
8254   SDValue Y = Op.getOperand(1);
8255   EVT VT = Op.getValueType();
8256   const SDNodeFlags Flags = Op->getFlags();
8257 
8258   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8259                             DAG.getTarget().Options.UnsafeFPMath;
8260   if (!AllowInaccurateDiv)
8261     return SDValue();
8262 
8263   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8264   SDValue One = DAG.getConstantFP(1.0, SL, VT);
8265 
8266   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8267   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8268 
8269   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8270   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8271   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8272   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8273   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8274   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8275 }
8276 
8277 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8278                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8279                           SDNodeFlags Flags) {
8280   if (GlueChain->getNumValues() <= 1) {
8281     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8282   }
8283 
8284   assert(GlueChain->getNumValues() == 3);
8285 
8286   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8287   switch (Opcode) {
8288   default: llvm_unreachable("no chain equivalent for opcode");
8289   case ISD::FMUL:
8290     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8291     break;
8292   }
8293 
8294   return DAG.getNode(Opcode, SL, VTList,
8295                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8296                      Flags);
8297 }
8298 
8299 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8300                            EVT VT, SDValue A, SDValue B, SDValue C,
8301                            SDValue GlueChain, SDNodeFlags Flags) {
8302   if (GlueChain->getNumValues() <= 1) {
8303     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8304   }
8305 
8306   assert(GlueChain->getNumValues() == 3);
8307 
8308   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8309   switch (Opcode) {
8310   default: llvm_unreachable("no chain equivalent for opcode");
8311   case ISD::FMA:
8312     Opcode = AMDGPUISD::FMA_W_CHAIN;
8313     break;
8314   }
8315 
8316   return DAG.getNode(Opcode, SL, VTList,
8317                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8318                      Flags);
8319 }
8320 
8321 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8322   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8323     return FastLowered;
8324 
8325   SDLoc SL(Op);
8326   SDValue Src0 = Op.getOperand(0);
8327   SDValue Src1 = Op.getOperand(1);
8328 
8329   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8330   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8331 
8332   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8333   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8334 
8335   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8336   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8337 
8338   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8339 }
8340 
8341 // Faster 2.5 ULP division that does not support denormals.
8342 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8343   SDLoc SL(Op);
8344   SDValue LHS = Op.getOperand(1);
8345   SDValue RHS = Op.getOperand(2);
8346 
8347   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8348 
8349   const APFloat K0Val(BitsToFloat(0x6f800000));
8350   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8351 
8352   const APFloat K1Val(BitsToFloat(0x2f800000));
8353   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8354 
8355   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8356 
8357   EVT SetCCVT =
8358     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8359 
8360   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8361 
8362   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8363 
8364   // TODO: Should this propagate fast-math-flags?
8365   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8366 
8367   // rcp does not support denormals.
8368   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8369 
8370   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8371 
8372   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8373 }
8374 
8375 // Returns immediate value for setting the F32 denorm mode when using the
8376 // S_DENORM_MODE instruction.
8377 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8378                                     const SDLoc &SL, const GCNSubtarget *ST) {
8379   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8380   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8381                                 ? FP_DENORM_FLUSH_NONE
8382                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8383 
8384   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8385   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8386 }
8387 
8388 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8389   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8390     return FastLowered;
8391 
8392   // The selection matcher assumes anything with a chain selecting to a
8393   // mayRaiseFPException machine instruction. Since we're introducing a chain
8394   // here, we need to explicitly report nofpexcept for the regular fdiv
8395   // lowering.
8396   SDNodeFlags Flags = Op->getFlags();
8397   Flags.setNoFPExcept(true);
8398 
8399   SDLoc SL(Op);
8400   SDValue LHS = Op.getOperand(0);
8401   SDValue RHS = Op.getOperand(1);
8402 
8403   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8404 
8405   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8406 
8407   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8408                                           {RHS, RHS, LHS}, Flags);
8409   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8410                                         {LHS, RHS, LHS}, Flags);
8411 
8412   // Denominator is scaled to not be denormal, so using rcp is ok.
8413   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8414                                   DenominatorScaled, Flags);
8415   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8416                                      DenominatorScaled, Flags);
8417 
8418   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8419                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8420                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8421   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8422 
8423   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8424 
8425   if (!HasFP32Denormals) {
8426     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8427     // lowering. The chain dependence is insufficient, and we need glue. We do
8428     // not need the glue variants in a strictfp function.
8429 
8430     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8431 
8432     SDNode *EnableDenorm;
8433     if (Subtarget->hasDenormModeInst()) {
8434       const SDValue EnableDenormValue =
8435           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8436 
8437       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8438                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8439     } else {
8440       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8441                                                         SL, MVT::i32);
8442       EnableDenorm =
8443           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8444                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8445     }
8446 
8447     SDValue Ops[3] = {
8448       NegDivScale0,
8449       SDValue(EnableDenorm, 0),
8450       SDValue(EnableDenorm, 1)
8451     };
8452 
8453     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8454   }
8455 
8456   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8457                              ApproxRcp, One, NegDivScale0, Flags);
8458 
8459   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8460                              ApproxRcp, Fma0, Flags);
8461 
8462   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8463                            Fma1, Fma1, Flags);
8464 
8465   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8466                              NumeratorScaled, Mul, Flags);
8467 
8468   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8469                              Fma2, Fma1, Mul, Fma2, Flags);
8470 
8471   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8472                              NumeratorScaled, Fma3, Flags);
8473 
8474   if (!HasFP32Denormals) {
8475     SDNode *DisableDenorm;
8476     if (Subtarget->hasDenormModeInst()) {
8477       const SDValue DisableDenormValue =
8478           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8479 
8480       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8481                                   Fma4.getValue(1), DisableDenormValue,
8482                                   Fma4.getValue(2)).getNode();
8483     } else {
8484       const SDValue DisableDenormValue =
8485           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8486 
8487       DisableDenorm = DAG.getMachineNode(
8488           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8489           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8490     }
8491 
8492     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8493                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8494     DAG.setRoot(OutputChain);
8495   }
8496 
8497   SDValue Scale = NumeratorScaled.getValue(1);
8498   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8499                              {Fma4, Fma1, Fma3, Scale}, Flags);
8500 
8501   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8502 }
8503 
8504 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8505   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
8506     return FastLowered;
8507 
8508   SDLoc SL(Op);
8509   SDValue X = Op.getOperand(0);
8510   SDValue Y = Op.getOperand(1);
8511 
8512   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8513 
8514   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8515 
8516   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8517 
8518   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8519 
8520   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8521 
8522   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8523 
8524   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8525 
8526   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8527 
8528   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8529 
8530   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8531   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8532 
8533   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8534                              NegDivScale0, Mul, DivScale1);
8535 
8536   SDValue Scale;
8537 
8538   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8539     // Workaround a hardware bug on SI where the condition output from div_scale
8540     // is not usable.
8541 
8542     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8543 
8544     // Figure out if the scale to use for div_fmas.
8545     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8546     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8547     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8548     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8549 
8550     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8551     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8552 
8553     SDValue Scale0Hi
8554       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8555     SDValue Scale1Hi
8556       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8557 
8558     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8559     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8560     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8561   } else {
8562     Scale = DivScale1.getValue(1);
8563   }
8564 
8565   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8566                              Fma4, Fma3, Mul, Scale);
8567 
8568   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8569 }
8570 
8571 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8572   EVT VT = Op.getValueType();
8573 
8574   if (VT == MVT::f32)
8575     return LowerFDIV32(Op, DAG);
8576 
8577   if (VT == MVT::f64)
8578     return LowerFDIV64(Op, DAG);
8579 
8580   if (VT == MVT::f16)
8581     return LowerFDIV16(Op, DAG);
8582 
8583   llvm_unreachable("Unexpected type for fdiv");
8584 }
8585 
8586 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8587   SDLoc DL(Op);
8588   StoreSDNode *Store = cast<StoreSDNode>(Op);
8589   EVT VT = Store->getMemoryVT();
8590 
8591   if (VT == MVT::i1) {
8592     return DAG.getTruncStore(Store->getChain(), DL,
8593        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8594        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8595   }
8596 
8597   assert(VT.isVector() &&
8598          Store->getValue().getValueType().getScalarType() == MVT::i32);
8599 
8600   unsigned AS = Store->getAddressSpace();
8601   if (Subtarget->hasLDSMisalignedBug() &&
8602       AS == AMDGPUAS::FLAT_ADDRESS &&
8603       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8604     return SplitVectorStore(Op, DAG);
8605   }
8606 
8607   MachineFunction &MF = DAG.getMachineFunction();
8608   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8609   // If there is a possibilty that flat instruction access scratch memory
8610   // then we need to use the same legalization rules we use for private.
8611   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8612       !Subtarget->hasMultiDwordFlatScratchAddressing())
8613     AS = MFI->hasFlatScratchInit() ?
8614          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8615 
8616   unsigned NumElements = VT.getVectorNumElements();
8617   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8618       AS == AMDGPUAS::FLAT_ADDRESS) {
8619     if (NumElements > 4)
8620       return SplitVectorStore(Op, DAG);
8621     // v3 stores not supported on SI.
8622     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8623       return SplitVectorStore(Op, DAG);
8624 
8625     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8626                                         VT, *Store->getMemOperand()))
8627       return expandUnalignedStore(Store, DAG);
8628 
8629     return SDValue();
8630   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8631     switch (Subtarget->getMaxPrivateElementSize()) {
8632     case 4:
8633       return scalarizeVectorStore(Store, DAG);
8634     case 8:
8635       if (NumElements > 2)
8636         return SplitVectorStore(Op, DAG);
8637       return SDValue();
8638     case 16:
8639       if (NumElements > 4 ||
8640           (NumElements == 3 && !Subtarget->enableFlatScratch()))
8641         return SplitVectorStore(Op, DAG);
8642       return SDValue();
8643     default:
8644       llvm_unreachable("unsupported private_element_size");
8645     }
8646   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8647     // Use ds_write_b128 or ds_write_b96 when possible.
8648     if (Subtarget->hasDS96AndDS128() &&
8649         ((Subtarget->useDS128() && VT.getStoreSize() == 16) ||
8650          (VT.getStoreSize() == 12)) &&
8651         allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
8652                                            Store->getAlign()))
8653       return SDValue();
8654 
8655     if (NumElements > 2)
8656       return SplitVectorStore(Op, DAG);
8657 
8658     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8659     // address is negative, then the instruction is incorrectly treated as
8660     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8661     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8662     // store later in the SILoadStoreOptimizer.
8663     if (!Subtarget->hasUsableDSOffset() &&
8664         NumElements == 2 && VT.getStoreSize() == 8 &&
8665         Store->getAlignment() < 8) {
8666       return SplitVectorStore(Op, DAG);
8667     }
8668 
8669     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8670                                         VT, *Store->getMemOperand())) {
8671       if (VT.isVector())
8672         return SplitVectorStore(Op, DAG);
8673       return expandUnalignedStore(Store, DAG);
8674     }
8675 
8676     return SDValue();
8677   } else {
8678     llvm_unreachable("unhandled address space");
8679   }
8680 }
8681 
8682 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8683   SDLoc DL(Op);
8684   EVT VT = Op.getValueType();
8685   SDValue Arg = Op.getOperand(0);
8686   SDValue TrigVal;
8687 
8688   // Propagate fast-math flags so that the multiply we introduce can be folded
8689   // if Arg is already the result of a multiply by constant.
8690   auto Flags = Op->getFlags();
8691 
8692   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
8693 
8694   if (Subtarget->hasTrigReducedRange()) {
8695     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8696     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
8697   } else {
8698     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8699   }
8700 
8701   switch (Op.getOpcode()) {
8702   case ISD::FCOS:
8703     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
8704   case ISD::FSIN:
8705     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
8706   default:
8707     llvm_unreachable("Wrong trig opcode");
8708   }
8709 }
8710 
8711 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8712   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8713   assert(AtomicNode->isCompareAndSwap());
8714   unsigned AS = AtomicNode->getAddressSpace();
8715 
8716   // No custom lowering required for local address space
8717   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
8718     return Op;
8719 
8720   // Non-local address space requires custom lowering for atomic compare
8721   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8722   SDLoc DL(Op);
8723   SDValue ChainIn = Op.getOperand(0);
8724   SDValue Addr = Op.getOperand(1);
8725   SDValue Old = Op.getOperand(2);
8726   SDValue New = Op.getOperand(3);
8727   EVT VT = Op.getValueType();
8728   MVT SimpleVT = VT.getSimpleVT();
8729   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8730 
8731   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8732   SDValue Ops[] = { ChainIn, Addr, NewOld };
8733 
8734   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8735                                  Ops, VT, AtomicNode->getMemOperand());
8736 }
8737 
8738 //===----------------------------------------------------------------------===//
8739 // Custom DAG optimizations
8740 //===----------------------------------------------------------------------===//
8741 
8742 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8743                                                      DAGCombinerInfo &DCI) const {
8744   EVT VT = N->getValueType(0);
8745   EVT ScalarVT = VT.getScalarType();
8746   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8747     return SDValue();
8748 
8749   SelectionDAG &DAG = DCI.DAG;
8750   SDLoc DL(N);
8751 
8752   SDValue Src = N->getOperand(0);
8753   EVT SrcVT = Src.getValueType();
8754 
8755   // TODO: We could try to match extracting the higher bytes, which would be
8756   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8757   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8758   // about in practice.
8759   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8760     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8761       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8762       DCI.AddToWorklist(Cvt.getNode());
8763 
8764       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8765       if (ScalarVT != MVT::f32) {
8766         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8767                           DAG.getTargetConstant(0, DL, MVT::i32));
8768       }
8769       return Cvt;
8770     }
8771   }
8772 
8773   return SDValue();
8774 }
8775 
8776 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8777 
8778 // This is a variant of
8779 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8780 //
8781 // The normal DAG combiner will do this, but only if the add has one use since
8782 // that would increase the number of instructions.
8783 //
8784 // This prevents us from seeing a constant offset that can be folded into a
8785 // memory instruction's addressing mode. If we know the resulting add offset of
8786 // a pointer can be folded into an addressing offset, we can replace the pointer
8787 // operand with the add of new constant offset. This eliminates one of the uses,
8788 // and may allow the remaining use to also be simplified.
8789 //
8790 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8791                                                unsigned AddrSpace,
8792                                                EVT MemVT,
8793                                                DAGCombinerInfo &DCI) const {
8794   SDValue N0 = N->getOperand(0);
8795   SDValue N1 = N->getOperand(1);
8796 
8797   // We only do this to handle cases where it's profitable when there are
8798   // multiple uses of the add, so defer to the standard combine.
8799   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8800       N0->hasOneUse())
8801     return SDValue();
8802 
8803   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8804   if (!CN1)
8805     return SDValue();
8806 
8807   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8808   if (!CAdd)
8809     return SDValue();
8810 
8811   // If the resulting offset is too large, we can't fold it into the addressing
8812   // mode offset.
8813   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8814   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8815 
8816   AddrMode AM;
8817   AM.HasBaseReg = true;
8818   AM.BaseOffs = Offset.getSExtValue();
8819   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8820     return SDValue();
8821 
8822   SelectionDAG &DAG = DCI.DAG;
8823   SDLoc SL(N);
8824   EVT VT = N->getValueType(0);
8825 
8826   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8827   SDValue COffset = DAG.getConstant(Offset, SL, VT);
8828 
8829   SDNodeFlags Flags;
8830   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8831                           (N0.getOpcode() == ISD::OR ||
8832                            N0->getFlags().hasNoUnsignedWrap()));
8833 
8834   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8835 }
8836 
8837 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
8838 /// by the chain and intrinsic ID. Theoretically we would also need to check the
8839 /// specific intrinsic, but they all place the pointer operand first.
8840 static unsigned getBasePtrIndex(const MemSDNode *N) {
8841   switch (N->getOpcode()) {
8842   case ISD::STORE:
8843   case ISD::INTRINSIC_W_CHAIN:
8844   case ISD::INTRINSIC_VOID:
8845     return 2;
8846   default:
8847     return 1;
8848   }
8849 }
8850 
8851 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8852                                                   DAGCombinerInfo &DCI) const {
8853   SelectionDAG &DAG = DCI.DAG;
8854   SDLoc SL(N);
8855 
8856   unsigned PtrIdx = getBasePtrIndex(N);
8857   SDValue Ptr = N->getOperand(PtrIdx);
8858 
8859   // TODO: We could also do this for multiplies.
8860   if (Ptr.getOpcode() == ISD::SHL) {
8861     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8862                                           N->getMemoryVT(), DCI);
8863     if (NewPtr) {
8864       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8865 
8866       NewOps[PtrIdx] = NewPtr;
8867       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8868     }
8869   }
8870 
8871   return SDValue();
8872 }
8873 
8874 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8875   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8876          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8877          (Opc == ISD::XOR && Val == 0);
8878 }
8879 
8880 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8881 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8882 // integer combine opportunities since most 64-bit operations are decomposed
8883 // this way.  TODO: We won't want this for SALU especially if it is an inline
8884 // immediate.
8885 SDValue SITargetLowering::splitBinaryBitConstantOp(
8886   DAGCombinerInfo &DCI,
8887   const SDLoc &SL,
8888   unsigned Opc, SDValue LHS,
8889   const ConstantSDNode *CRHS) const {
8890   uint64_t Val = CRHS->getZExtValue();
8891   uint32_t ValLo = Lo_32(Val);
8892   uint32_t ValHi = Hi_32(Val);
8893   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8894 
8895     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8896          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8897         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8898     // If we need to materialize a 64-bit immediate, it will be split up later
8899     // anyway. Avoid creating the harder to understand 64-bit immediate
8900     // materialization.
8901     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8902   }
8903 
8904   return SDValue();
8905 }
8906 
8907 // Returns true if argument is a boolean value which is not serialized into
8908 // memory or argument and does not require v_cndmask_b32 to be deserialized.
8909 static bool isBoolSGPR(SDValue V) {
8910   if (V.getValueType() != MVT::i1)
8911     return false;
8912   switch (V.getOpcode()) {
8913   default:
8914     break;
8915   case ISD::SETCC:
8916   case AMDGPUISD::FP_CLASS:
8917     return true;
8918   case ISD::AND:
8919   case ISD::OR:
8920   case ISD::XOR:
8921     return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
8922   }
8923   return false;
8924 }
8925 
8926 // If a constant has all zeroes or all ones within each byte return it.
8927 // Otherwise return 0.
8928 static uint32_t getConstantPermuteMask(uint32_t C) {
8929   // 0xff for any zero byte in the mask
8930   uint32_t ZeroByteMask = 0;
8931   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8932   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8933   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8934   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8935   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8936   if ((NonZeroByteMask & C) != NonZeroByteMask)
8937     return 0; // Partial bytes selected.
8938   return C;
8939 }
8940 
8941 // Check if a node selects whole bytes from its operand 0 starting at a byte
8942 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8943 // or -1 if not succeeded.
8944 // Note byte select encoding:
8945 // value 0-3 selects corresponding source byte;
8946 // value 0xc selects zero;
8947 // value 0xff selects 0xff.
8948 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8949   assert(V.getValueSizeInBits() == 32);
8950 
8951   if (V.getNumOperands() != 2)
8952     return ~0;
8953 
8954   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8955   if (!N1)
8956     return ~0;
8957 
8958   uint32_t C = N1->getZExtValue();
8959 
8960   switch (V.getOpcode()) {
8961   default:
8962     break;
8963   case ISD::AND:
8964     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8965       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8966     }
8967     break;
8968 
8969   case ISD::OR:
8970     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8971       return (0x03020100 & ~ConstMask) | ConstMask;
8972     }
8973     break;
8974 
8975   case ISD::SHL:
8976     if (C % 8)
8977       return ~0;
8978 
8979     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8980 
8981   case ISD::SRL:
8982     if (C % 8)
8983       return ~0;
8984 
8985     return uint32_t(0x0c0c0c0c03020100ull >> C);
8986   }
8987 
8988   return ~0;
8989 }
8990 
8991 SDValue SITargetLowering::performAndCombine(SDNode *N,
8992                                             DAGCombinerInfo &DCI) const {
8993   if (DCI.isBeforeLegalize())
8994     return SDValue();
8995 
8996   SelectionDAG &DAG = DCI.DAG;
8997   EVT VT = N->getValueType(0);
8998   SDValue LHS = N->getOperand(0);
8999   SDValue RHS = N->getOperand(1);
9000 
9001 
9002   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9003   if (VT == MVT::i64 && CRHS) {
9004     if (SDValue Split
9005         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9006       return Split;
9007   }
9008 
9009   if (CRHS && VT == MVT::i32) {
9010     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9011     // nb = number of trailing zeroes in mask
9012     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9013     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9014     uint64_t Mask = CRHS->getZExtValue();
9015     unsigned Bits = countPopulation(Mask);
9016     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9017         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9018       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9019         unsigned Shift = CShift->getZExtValue();
9020         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9021         unsigned Offset = NB + Shift;
9022         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9023           SDLoc SL(N);
9024           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9025                                     LHS->getOperand(0),
9026                                     DAG.getConstant(Offset, SL, MVT::i32),
9027                                     DAG.getConstant(Bits, SL, MVT::i32));
9028           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9029           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9030                                     DAG.getValueType(NarrowVT));
9031           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9032                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9033           return Shl;
9034         }
9035       }
9036     }
9037 
9038     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9039     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9040         isa<ConstantSDNode>(LHS.getOperand(2))) {
9041       uint32_t Sel = getConstantPermuteMask(Mask);
9042       if (!Sel)
9043         return SDValue();
9044 
9045       // Select 0xc for all zero bytes
9046       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9047       SDLoc DL(N);
9048       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9049                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9050     }
9051   }
9052 
9053   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9054   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9055   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9056     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9057     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9058 
9059     SDValue X = LHS.getOperand(0);
9060     SDValue Y = RHS.getOperand(0);
9061     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9062       return SDValue();
9063 
9064     if (LCC == ISD::SETO) {
9065       if (X != LHS.getOperand(1))
9066         return SDValue();
9067 
9068       if (RCC == ISD::SETUNE) {
9069         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9070         if (!C1 || !C1->isInfinity() || C1->isNegative())
9071           return SDValue();
9072 
9073         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9074                               SIInstrFlags::N_SUBNORMAL |
9075                               SIInstrFlags::N_ZERO |
9076                               SIInstrFlags::P_ZERO |
9077                               SIInstrFlags::P_SUBNORMAL |
9078                               SIInstrFlags::P_NORMAL;
9079 
9080         static_assert(((~(SIInstrFlags::S_NAN |
9081                           SIInstrFlags::Q_NAN |
9082                           SIInstrFlags::N_INFINITY |
9083                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9084                       "mask not equal");
9085 
9086         SDLoc DL(N);
9087         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9088                            X, DAG.getConstant(Mask, DL, MVT::i32));
9089       }
9090     }
9091   }
9092 
9093   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9094     std::swap(LHS, RHS);
9095 
9096   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9097       RHS.hasOneUse()) {
9098     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9099     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9100     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9101     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9102     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9103         (RHS.getOperand(0) == LHS.getOperand(0) &&
9104          LHS.getOperand(0) == LHS.getOperand(1))) {
9105       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9106       unsigned NewMask = LCC == ISD::SETO ?
9107         Mask->getZExtValue() & ~OrdMask :
9108         Mask->getZExtValue() & OrdMask;
9109 
9110       SDLoc DL(N);
9111       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9112                          DAG.getConstant(NewMask, DL, MVT::i32));
9113     }
9114   }
9115 
9116   if (VT == MVT::i32 &&
9117       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9118     // and x, (sext cc from i1) => select cc, x, 0
9119     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9120       std::swap(LHS, RHS);
9121     if (isBoolSGPR(RHS.getOperand(0)))
9122       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9123                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9124   }
9125 
9126   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9127   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9128   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9129       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9130     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9131     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9132     if (LHSMask != ~0u && RHSMask != ~0u) {
9133       // Canonicalize the expression in an attempt to have fewer unique masks
9134       // and therefore fewer registers used to hold the masks.
9135       if (LHSMask > RHSMask) {
9136         std::swap(LHSMask, RHSMask);
9137         std::swap(LHS, RHS);
9138       }
9139 
9140       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9141       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9142       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9143       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9144 
9145       // Check of we need to combine values from two sources within a byte.
9146       if (!(LHSUsedLanes & RHSUsedLanes) &&
9147           // If we select high and lower word keep it for SDWA.
9148           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9149           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9150         // Each byte in each mask is either selector mask 0-3, or has higher
9151         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9152         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9153         // mask which is not 0xff wins. By anding both masks we have a correct
9154         // result except that 0x0c shall be corrected to give 0x0c only.
9155         uint32_t Mask = LHSMask & RHSMask;
9156         for (unsigned I = 0; I < 32; I += 8) {
9157           uint32_t ByteSel = 0xff << I;
9158           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9159             Mask &= (0x0c << I) & 0xffffffff;
9160         }
9161 
9162         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9163         // or 0x0c.
9164         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9165         SDLoc DL(N);
9166 
9167         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9168                            LHS.getOperand(0), RHS.getOperand(0),
9169                            DAG.getConstant(Sel, DL, MVT::i32));
9170       }
9171     }
9172   }
9173 
9174   return SDValue();
9175 }
9176 
9177 SDValue SITargetLowering::performOrCombine(SDNode *N,
9178                                            DAGCombinerInfo &DCI) const {
9179   SelectionDAG &DAG = DCI.DAG;
9180   SDValue LHS = N->getOperand(0);
9181   SDValue RHS = N->getOperand(1);
9182 
9183   EVT VT = N->getValueType(0);
9184   if (VT == MVT::i1) {
9185     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9186     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9187         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9188       SDValue Src = LHS.getOperand(0);
9189       if (Src != RHS.getOperand(0))
9190         return SDValue();
9191 
9192       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9193       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9194       if (!CLHS || !CRHS)
9195         return SDValue();
9196 
9197       // Only 10 bits are used.
9198       static const uint32_t MaxMask = 0x3ff;
9199 
9200       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9201       SDLoc DL(N);
9202       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9203                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9204     }
9205 
9206     return SDValue();
9207   }
9208 
9209   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9210   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9211       LHS.getOpcode() == AMDGPUISD::PERM &&
9212       isa<ConstantSDNode>(LHS.getOperand(2))) {
9213     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9214     if (!Sel)
9215       return SDValue();
9216 
9217     Sel |= LHS.getConstantOperandVal(2);
9218     SDLoc DL(N);
9219     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9220                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9221   }
9222 
9223   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9224   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9225   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9226       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9227     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9228     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9229     if (LHSMask != ~0u && RHSMask != ~0u) {
9230       // Canonicalize the expression in an attempt to have fewer unique masks
9231       // and therefore fewer registers used to hold the masks.
9232       if (LHSMask > RHSMask) {
9233         std::swap(LHSMask, RHSMask);
9234         std::swap(LHS, RHS);
9235       }
9236 
9237       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9238       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9239       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9240       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9241 
9242       // Check of we need to combine values from two sources within a byte.
9243       if (!(LHSUsedLanes & RHSUsedLanes) &&
9244           // If we select high and lower word keep it for SDWA.
9245           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9246           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9247         // Kill zero bytes selected by other mask. Zero value is 0xc.
9248         LHSMask &= ~RHSUsedLanes;
9249         RHSMask &= ~LHSUsedLanes;
9250         // Add 4 to each active LHS lane
9251         LHSMask |= LHSUsedLanes & 0x04040404;
9252         // Combine masks
9253         uint32_t Sel = LHSMask | RHSMask;
9254         SDLoc DL(N);
9255 
9256         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9257                            LHS.getOperand(0), RHS.getOperand(0),
9258                            DAG.getConstant(Sel, DL, MVT::i32));
9259       }
9260     }
9261   }
9262 
9263   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9264     return SDValue();
9265 
9266   // TODO: This could be a generic combine with a predicate for extracting the
9267   // high half of an integer being free.
9268 
9269   // (or i64:x, (zero_extend i32:y)) ->
9270   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9271   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9272       RHS.getOpcode() != ISD::ZERO_EXTEND)
9273     std::swap(LHS, RHS);
9274 
9275   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9276     SDValue ExtSrc = RHS.getOperand(0);
9277     EVT SrcVT = ExtSrc.getValueType();
9278     if (SrcVT == MVT::i32) {
9279       SDLoc SL(N);
9280       SDValue LowLHS, HiBits;
9281       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9282       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9283 
9284       DCI.AddToWorklist(LowOr.getNode());
9285       DCI.AddToWorklist(HiBits.getNode());
9286 
9287       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9288                                 LowOr, HiBits);
9289       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9290     }
9291   }
9292 
9293   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9294   if (CRHS) {
9295     if (SDValue Split
9296           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
9297       return Split;
9298   }
9299 
9300   return SDValue();
9301 }
9302 
9303 SDValue SITargetLowering::performXorCombine(SDNode *N,
9304                                             DAGCombinerInfo &DCI) const {
9305   EVT VT = N->getValueType(0);
9306   if (VT != MVT::i64)
9307     return SDValue();
9308 
9309   SDValue LHS = N->getOperand(0);
9310   SDValue RHS = N->getOperand(1);
9311 
9312   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9313   if (CRHS) {
9314     if (SDValue Split
9315           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9316       return Split;
9317   }
9318 
9319   return SDValue();
9320 }
9321 
9322 // Instructions that will be lowered with a final instruction that zeros the
9323 // high result bits.
9324 // XXX - probably only need to list legal operations.
9325 static bool fp16SrcZerosHighBits(unsigned Opc) {
9326   switch (Opc) {
9327   case ISD::FADD:
9328   case ISD::FSUB:
9329   case ISD::FMUL:
9330   case ISD::FDIV:
9331   case ISD::FREM:
9332   case ISD::FMA:
9333   case ISD::FMAD:
9334   case ISD::FCANONICALIZE:
9335   case ISD::FP_ROUND:
9336   case ISD::UINT_TO_FP:
9337   case ISD::SINT_TO_FP:
9338   case ISD::FABS:
9339     // Fabs is lowered to a bit operation, but it's an and which will clear the
9340     // high bits anyway.
9341   case ISD::FSQRT:
9342   case ISD::FSIN:
9343   case ISD::FCOS:
9344   case ISD::FPOWI:
9345   case ISD::FPOW:
9346   case ISD::FLOG:
9347   case ISD::FLOG2:
9348   case ISD::FLOG10:
9349   case ISD::FEXP:
9350   case ISD::FEXP2:
9351   case ISD::FCEIL:
9352   case ISD::FTRUNC:
9353   case ISD::FRINT:
9354   case ISD::FNEARBYINT:
9355   case ISD::FROUND:
9356   case ISD::FFLOOR:
9357   case ISD::FMINNUM:
9358   case ISD::FMAXNUM:
9359   case AMDGPUISD::FRACT:
9360   case AMDGPUISD::CLAMP:
9361   case AMDGPUISD::COS_HW:
9362   case AMDGPUISD::SIN_HW:
9363   case AMDGPUISD::FMIN3:
9364   case AMDGPUISD::FMAX3:
9365   case AMDGPUISD::FMED3:
9366   case AMDGPUISD::FMAD_FTZ:
9367   case AMDGPUISD::RCP:
9368   case AMDGPUISD::RSQ:
9369   case AMDGPUISD::RCP_IFLAG:
9370   case AMDGPUISD::LDEXP:
9371     return true;
9372   default:
9373     // fcopysign, select and others may be lowered to 32-bit bit operations
9374     // which don't zero the high bits.
9375     return false;
9376   }
9377 }
9378 
9379 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9380                                                    DAGCombinerInfo &DCI) const {
9381   if (!Subtarget->has16BitInsts() ||
9382       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9383     return SDValue();
9384 
9385   EVT VT = N->getValueType(0);
9386   if (VT != MVT::i32)
9387     return SDValue();
9388 
9389   SDValue Src = N->getOperand(0);
9390   if (Src.getValueType() != MVT::i16)
9391     return SDValue();
9392 
9393   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
9394   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
9395   if (Src.getOpcode() == ISD::BITCAST) {
9396     SDValue BCSrc = Src.getOperand(0);
9397     if (BCSrc.getValueType() == MVT::f16 &&
9398         fp16SrcZerosHighBits(BCSrc.getOpcode()))
9399       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
9400   }
9401 
9402   return SDValue();
9403 }
9404 
9405 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9406                                                         DAGCombinerInfo &DCI)
9407                                                         const {
9408   SDValue Src = N->getOperand(0);
9409   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9410 
9411   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9412       VTSign->getVT() == MVT::i8) ||
9413       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9414       VTSign->getVT() == MVT::i16)) &&
9415       Src.hasOneUse()) {
9416     auto *M = cast<MemSDNode>(Src);
9417     SDValue Ops[] = {
9418       Src.getOperand(0), // Chain
9419       Src.getOperand(1), // rsrc
9420       Src.getOperand(2), // vindex
9421       Src.getOperand(3), // voffset
9422       Src.getOperand(4), // soffset
9423       Src.getOperand(5), // offset
9424       Src.getOperand(6),
9425       Src.getOperand(7)
9426     };
9427     // replace with BUFFER_LOAD_BYTE/SHORT
9428     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9429                                          Src.getOperand(0).getValueType());
9430     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9431                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9432     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9433                                                           ResList,
9434                                                           Ops, M->getMemoryVT(),
9435                                                           M->getMemOperand());
9436     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9437                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9438   }
9439   return SDValue();
9440 }
9441 
9442 SDValue SITargetLowering::performClassCombine(SDNode *N,
9443                                               DAGCombinerInfo &DCI) const {
9444   SelectionDAG &DAG = DCI.DAG;
9445   SDValue Mask = N->getOperand(1);
9446 
9447   // fp_class x, 0 -> false
9448   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9449     if (CMask->isNullValue())
9450       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9451   }
9452 
9453   if (N->getOperand(0).isUndef())
9454     return DAG.getUNDEF(MVT::i1);
9455 
9456   return SDValue();
9457 }
9458 
9459 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9460                                             DAGCombinerInfo &DCI) const {
9461   EVT VT = N->getValueType(0);
9462   SDValue N0 = N->getOperand(0);
9463 
9464   if (N0.isUndef())
9465     return N0;
9466 
9467   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9468                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9469     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9470                            N->getFlags());
9471   }
9472 
9473   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9474     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9475                            N0.getOperand(0), N->getFlags());
9476   }
9477 
9478   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9479 }
9480 
9481 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9482                                        unsigned MaxDepth) const {
9483   unsigned Opcode = Op.getOpcode();
9484   if (Opcode == ISD::FCANONICALIZE)
9485     return true;
9486 
9487   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9488     auto F = CFP->getValueAPF();
9489     if (F.isNaN() && F.isSignaling())
9490       return false;
9491     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9492   }
9493 
9494   // If source is a result of another standard FP operation it is already in
9495   // canonical form.
9496   if (MaxDepth == 0)
9497     return false;
9498 
9499   switch (Opcode) {
9500   // These will flush denorms if required.
9501   case ISD::FADD:
9502   case ISD::FSUB:
9503   case ISD::FMUL:
9504   case ISD::FCEIL:
9505   case ISD::FFLOOR:
9506   case ISD::FMA:
9507   case ISD::FMAD:
9508   case ISD::FSQRT:
9509   case ISD::FDIV:
9510   case ISD::FREM:
9511   case ISD::FP_ROUND:
9512   case ISD::FP_EXTEND:
9513   case AMDGPUISD::FMUL_LEGACY:
9514   case AMDGPUISD::FMAD_FTZ:
9515   case AMDGPUISD::RCP:
9516   case AMDGPUISD::RSQ:
9517   case AMDGPUISD::RSQ_CLAMP:
9518   case AMDGPUISD::RCP_LEGACY:
9519   case AMDGPUISD::RCP_IFLAG:
9520   case AMDGPUISD::DIV_SCALE:
9521   case AMDGPUISD::DIV_FMAS:
9522   case AMDGPUISD::DIV_FIXUP:
9523   case AMDGPUISD::FRACT:
9524   case AMDGPUISD::LDEXP:
9525   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9526   case AMDGPUISD::CVT_F32_UBYTE0:
9527   case AMDGPUISD::CVT_F32_UBYTE1:
9528   case AMDGPUISD::CVT_F32_UBYTE2:
9529   case AMDGPUISD::CVT_F32_UBYTE3:
9530     return true;
9531 
9532   // It can/will be lowered or combined as a bit operation.
9533   // Need to check their input recursively to handle.
9534   case ISD::FNEG:
9535   case ISD::FABS:
9536   case ISD::FCOPYSIGN:
9537     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9538 
9539   case ISD::FSIN:
9540   case ISD::FCOS:
9541   case ISD::FSINCOS:
9542     return Op.getValueType().getScalarType() != MVT::f16;
9543 
9544   case ISD::FMINNUM:
9545   case ISD::FMAXNUM:
9546   case ISD::FMINNUM_IEEE:
9547   case ISD::FMAXNUM_IEEE:
9548   case AMDGPUISD::CLAMP:
9549   case AMDGPUISD::FMED3:
9550   case AMDGPUISD::FMAX3:
9551   case AMDGPUISD::FMIN3: {
9552     // FIXME: Shouldn't treat the generic operations different based these.
9553     // However, we aren't really required to flush the result from
9554     // minnum/maxnum..
9555 
9556     // snans will be quieted, so we only need to worry about denormals.
9557     if (Subtarget->supportsMinMaxDenormModes() ||
9558         denormalsEnabledForType(DAG, Op.getValueType()))
9559       return true;
9560 
9561     // Flushing may be required.
9562     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9563     // targets need to check their input recursively.
9564 
9565     // FIXME: Does this apply with clamp? It's implemented with max.
9566     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9567       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9568         return false;
9569     }
9570 
9571     return true;
9572   }
9573   case ISD::SELECT: {
9574     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9575            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9576   }
9577   case ISD::BUILD_VECTOR: {
9578     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9579       SDValue SrcOp = Op.getOperand(i);
9580       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9581         return false;
9582     }
9583 
9584     return true;
9585   }
9586   case ISD::EXTRACT_VECTOR_ELT:
9587   case ISD::EXTRACT_SUBVECTOR: {
9588     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9589   }
9590   case ISD::INSERT_VECTOR_ELT: {
9591     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9592            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9593   }
9594   case ISD::UNDEF:
9595     // Could be anything.
9596     return false;
9597 
9598   case ISD::BITCAST: {
9599     // Hack round the mess we make when legalizing extract_vector_elt
9600     SDValue Src = Op.getOperand(0);
9601     if (Src.getValueType() == MVT::i16 &&
9602         Src.getOpcode() == ISD::TRUNCATE) {
9603       SDValue TruncSrc = Src.getOperand(0);
9604       if (TruncSrc.getValueType() == MVT::i32 &&
9605           TruncSrc.getOpcode() == ISD::BITCAST &&
9606           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9607         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9608       }
9609     }
9610 
9611     return false;
9612   }
9613   case ISD::INTRINSIC_WO_CHAIN: {
9614     unsigned IntrinsicID
9615       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9616     // TODO: Handle more intrinsics
9617     switch (IntrinsicID) {
9618     case Intrinsic::amdgcn_cvt_pkrtz:
9619     case Intrinsic::amdgcn_cubeid:
9620     case Intrinsic::amdgcn_frexp_mant:
9621     case Intrinsic::amdgcn_fdot2:
9622     case Intrinsic::amdgcn_rcp:
9623     case Intrinsic::amdgcn_rsq:
9624     case Intrinsic::amdgcn_rsq_clamp:
9625     case Intrinsic::amdgcn_rcp_legacy:
9626     case Intrinsic::amdgcn_rsq_legacy:
9627     case Intrinsic::amdgcn_trig_preop:
9628       return true;
9629     default:
9630       break;
9631     }
9632 
9633     LLVM_FALLTHROUGH;
9634   }
9635   default:
9636     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9637            DAG.isKnownNeverSNaN(Op);
9638   }
9639 
9640   llvm_unreachable("invalid operation");
9641 }
9642 
9643 // Constant fold canonicalize.
9644 SDValue SITargetLowering::getCanonicalConstantFP(
9645   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9646   // Flush denormals to 0 if not enabled.
9647   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9648     return DAG.getConstantFP(0.0, SL, VT);
9649 
9650   if (C.isNaN()) {
9651     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9652     if (C.isSignaling()) {
9653       // Quiet a signaling NaN.
9654       // FIXME: Is this supposed to preserve payload bits?
9655       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9656     }
9657 
9658     // Make sure it is the canonical NaN bitpattern.
9659     //
9660     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9661     // immediate?
9662     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9663       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9664   }
9665 
9666   // Already canonical.
9667   return DAG.getConstantFP(C, SL, VT);
9668 }
9669 
9670 static bool vectorEltWillFoldAway(SDValue Op) {
9671   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9672 }
9673 
9674 SDValue SITargetLowering::performFCanonicalizeCombine(
9675   SDNode *N,
9676   DAGCombinerInfo &DCI) const {
9677   SelectionDAG &DAG = DCI.DAG;
9678   SDValue N0 = N->getOperand(0);
9679   EVT VT = N->getValueType(0);
9680 
9681   // fcanonicalize undef -> qnan
9682   if (N0.isUndef()) {
9683     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9684     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9685   }
9686 
9687   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9688     EVT VT = N->getValueType(0);
9689     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9690   }
9691 
9692   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9693   //                                                   (fcanonicalize k)
9694   //
9695   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9696 
9697   // TODO: This could be better with wider vectors that will be split to v2f16,
9698   // and to consider uses since there aren't that many packed operations.
9699   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9700       isTypeLegal(MVT::v2f16)) {
9701     SDLoc SL(N);
9702     SDValue NewElts[2];
9703     SDValue Lo = N0.getOperand(0);
9704     SDValue Hi = N0.getOperand(1);
9705     EVT EltVT = Lo.getValueType();
9706 
9707     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9708       for (unsigned I = 0; I != 2; ++I) {
9709         SDValue Op = N0.getOperand(I);
9710         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9711           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9712                                               CFP->getValueAPF());
9713         } else if (Op.isUndef()) {
9714           // Handled below based on what the other operand is.
9715           NewElts[I] = Op;
9716         } else {
9717           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9718         }
9719       }
9720 
9721       // If one half is undef, and one is constant, perfer a splat vector rather
9722       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9723       // cheaper to use and may be free with a packed operation.
9724       if (NewElts[0].isUndef()) {
9725         if (isa<ConstantFPSDNode>(NewElts[1]))
9726           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9727             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9728       }
9729 
9730       if (NewElts[1].isUndef()) {
9731         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9732           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9733       }
9734 
9735       return DAG.getBuildVector(VT, SL, NewElts);
9736     }
9737   }
9738 
9739   unsigned SrcOpc = N0.getOpcode();
9740 
9741   // If it's free to do so, push canonicalizes further up the source, which may
9742   // find a canonical source.
9743   //
9744   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9745   // sNaNs.
9746   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9747     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9748     if (CRHS && N0.hasOneUse()) {
9749       SDLoc SL(N);
9750       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9751                                    N0.getOperand(0));
9752       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9753       DCI.AddToWorklist(Canon0.getNode());
9754 
9755       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9756     }
9757   }
9758 
9759   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9760 }
9761 
9762 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9763   switch (Opc) {
9764   case ISD::FMAXNUM:
9765   case ISD::FMAXNUM_IEEE:
9766     return AMDGPUISD::FMAX3;
9767   case ISD::SMAX:
9768     return AMDGPUISD::SMAX3;
9769   case ISD::UMAX:
9770     return AMDGPUISD::UMAX3;
9771   case ISD::FMINNUM:
9772   case ISD::FMINNUM_IEEE:
9773     return AMDGPUISD::FMIN3;
9774   case ISD::SMIN:
9775     return AMDGPUISD::SMIN3;
9776   case ISD::UMIN:
9777     return AMDGPUISD::UMIN3;
9778   default:
9779     llvm_unreachable("Not a min/max opcode");
9780   }
9781 }
9782 
9783 SDValue SITargetLowering::performIntMed3ImmCombine(
9784   SelectionDAG &DAG, const SDLoc &SL,
9785   SDValue Op0, SDValue Op1, bool Signed) const {
9786   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9787   if (!K1)
9788     return SDValue();
9789 
9790   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9791   if (!K0)
9792     return SDValue();
9793 
9794   if (Signed) {
9795     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9796       return SDValue();
9797   } else {
9798     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9799       return SDValue();
9800   }
9801 
9802   EVT VT = K0->getValueType(0);
9803   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9804   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9805     return DAG.getNode(Med3Opc, SL, VT,
9806                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9807   }
9808 
9809   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9810   MVT NVT = MVT::i32;
9811   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9812 
9813   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9814   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9815   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9816 
9817   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9818   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9819 }
9820 
9821 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9822   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9823     return C;
9824 
9825   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9826     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9827       return C;
9828   }
9829 
9830   return nullptr;
9831 }
9832 
9833 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9834                                                   const SDLoc &SL,
9835                                                   SDValue Op0,
9836                                                   SDValue Op1) const {
9837   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9838   if (!K1)
9839     return SDValue();
9840 
9841   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9842   if (!K0)
9843     return SDValue();
9844 
9845   // Ordered >= (although NaN inputs should have folded away by now).
9846   if (K0->getValueAPF() > K1->getValueAPF())
9847     return SDValue();
9848 
9849   const MachineFunction &MF = DAG.getMachineFunction();
9850   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9851 
9852   // TODO: Check IEEE bit enabled?
9853   EVT VT = Op0.getValueType();
9854   if (Info->getMode().DX10Clamp) {
9855     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9856     // hardware fmed3 behavior converting to a min.
9857     // FIXME: Should this be allowing -0.0?
9858     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9859       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9860   }
9861 
9862   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9863   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9864     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9865     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9866     // then give the other result, which is different from med3 with a NaN
9867     // input.
9868     SDValue Var = Op0.getOperand(0);
9869     if (!DAG.isKnownNeverSNaN(Var))
9870       return SDValue();
9871 
9872     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9873 
9874     if ((!K0->hasOneUse() ||
9875          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9876         (!K1->hasOneUse() ||
9877          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9878       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9879                          Var, SDValue(K0, 0), SDValue(K1, 0));
9880     }
9881   }
9882 
9883   return SDValue();
9884 }
9885 
9886 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9887                                                DAGCombinerInfo &DCI) const {
9888   SelectionDAG &DAG = DCI.DAG;
9889 
9890   EVT VT = N->getValueType(0);
9891   unsigned Opc = N->getOpcode();
9892   SDValue Op0 = N->getOperand(0);
9893   SDValue Op1 = N->getOperand(1);
9894 
9895   // Only do this if the inner op has one use since this will just increases
9896   // register pressure for no benefit.
9897 
9898   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9899       !VT.isVector() &&
9900       (VT == MVT::i32 || VT == MVT::f32 ||
9901        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9902     // max(max(a, b), c) -> max3(a, b, c)
9903     // min(min(a, b), c) -> min3(a, b, c)
9904     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9905       SDLoc DL(N);
9906       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9907                          DL,
9908                          N->getValueType(0),
9909                          Op0.getOperand(0),
9910                          Op0.getOperand(1),
9911                          Op1);
9912     }
9913 
9914     // Try commuted.
9915     // max(a, max(b, c)) -> max3(a, b, c)
9916     // min(a, min(b, c)) -> min3(a, b, c)
9917     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9918       SDLoc DL(N);
9919       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9920                          DL,
9921                          N->getValueType(0),
9922                          Op0,
9923                          Op1.getOperand(0),
9924                          Op1.getOperand(1));
9925     }
9926   }
9927 
9928   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9929   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9930     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9931       return Med3;
9932   }
9933 
9934   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9935     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9936       return Med3;
9937   }
9938 
9939   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9940   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9941        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9942        (Opc == AMDGPUISD::FMIN_LEGACY &&
9943         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9944       (VT == MVT::f32 || VT == MVT::f64 ||
9945        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9946        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9947       Op0.hasOneUse()) {
9948     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9949       return Res;
9950   }
9951 
9952   return SDValue();
9953 }
9954 
9955 static bool isClampZeroToOne(SDValue A, SDValue B) {
9956   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9957     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9958       // FIXME: Should this be allowing -0.0?
9959       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9960              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9961     }
9962   }
9963 
9964   return false;
9965 }
9966 
9967 // FIXME: Should only worry about snans for version with chain.
9968 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9969                                               DAGCombinerInfo &DCI) const {
9970   EVT VT = N->getValueType(0);
9971   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9972   // NaNs. With a NaN input, the order of the operands may change the result.
9973 
9974   SelectionDAG &DAG = DCI.DAG;
9975   SDLoc SL(N);
9976 
9977   SDValue Src0 = N->getOperand(0);
9978   SDValue Src1 = N->getOperand(1);
9979   SDValue Src2 = N->getOperand(2);
9980 
9981   if (isClampZeroToOne(Src0, Src1)) {
9982     // const_a, const_b, x -> clamp is safe in all cases including signaling
9983     // nans.
9984     // FIXME: Should this be allowing -0.0?
9985     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9986   }
9987 
9988   const MachineFunction &MF = DAG.getMachineFunction();
9989   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9990 
9991   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9992   // handling no dx10-clamp?
9993   if (Info->getMode().DX10Clamp) {
9994     // If NaNs is clamped to 0, we are free to reorder the inputs.
9995 
9996     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9997       std::swap(Src0, Src1);
9998 
9999     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10000       std::swap(Src1, Src2);
10001 
10002     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10003       std::swap(Src0, Src1);
10004 
10005     if (isClampZeroToOne(Src1, Src2))
10006       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10007   }
10008 
10009   return SDValue();
10010 }
10011 
10012 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10013                                                  DAGCombinerInfo &DCI) const {
10014   SDValue Src0 = N->getOperand(0);
10015   SDValue Src1 = N->getOperand(1);
10016   if (Src0.isUndef() && Src1.isUndef())
10017     return DCI.DAG.getUNDEF(N->getValueType(0));
10018   return SDValue();
10019 }
10020 
10021 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10022 // expanded into a set of cmp/select instructions.
10023 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10024                                                 unsigned NumElem,
10025                                                 bool IsDivergentIdx) {
10026   if (UseDivergentRegisterIndexing)
10027     return false;
10028 
10029   unsigned VecSize = EltSize * NumElem;
10030 
10031   // Sub-dword vectors of size 2 dword or less have better implementation.
10032   if (VecSize <= 64 && EltSize < 32)
10033     return false;
10034 
10035   // Always expand the rest of sub-dword instructions, otherwise it will be
10036   // lowered via memory.
10037   if (EltSize < 32)
10038     return true;
10039 
10040   // Always do this if var-idx is divergent, otherwise it will become a loop.
10041   if (IsDivergentIdx)
10042     return true;
10043 
10044   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10045   unsigned NumInsts = NumElem /* Number of compares */ +
10046                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10047   return NumInsts <= 16;
10048 }
10049 
10050 static bool shouldExpandVectorDynExt(SDNode *N) {
10051   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10052   if (isa<ConstantSDNode>(Idx))
10053     return false;
10054 
10055   SDValue Vec = N->getOperand(0);
10056   EVT VecVT = Vec.getValueType();
10057   EVT EltVT = VecVT.getVectorElementType();
10058   unsigned EltSize = EltVT.getSizeInBits();
10059   unsigned NumElem = VecVT.getVectorNumElements();
10060 
10061   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
10062                                                     Idx->isDivergent());
10063 }
10064 
10065 SDValue SITargetLowering::performExtractVectorEltCombine(
10066   SDNode *N, DAGCombinerInfo &DCI) const {
10067   SDValue Vec = N->getOperand(0);
10068   SelectionDAG &DAG = DCI.DAG;
10069 
10070   EVT VecVT = Vec.getValueType();
10071   EVT EltVT = VecVT.getVectorElementType();
10072 
10073   if ((Vec.getOpcode() == ISD::FNEG ||
10074        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10075     SDLoc SL(N);
10076     EVT EltVT = N->getValueType(0);
10077     SDValue Idx = N->getOperand(1);
10078     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10079                               Vec.getOperand(0), Idx);
10080     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10081   }
10082 
10083   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10084   //    =>
10085   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10086   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10087   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10088   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10089     SDLoc SL(N);
10090     EVT EltVT = N->getValueType(0);
10091     SDValue Idx = N->getOperand(1);
10092     unsigned Opc = Vec.getOpcode();
10093 
10094     switch(Opc) {
10095     default:
10096       break;
10097       // TODO: Support other binary operations.
10098     case ISD::FADD:
10099     case ISD::FSUB:
10100     case ISD::FMUL:
10101     case ISD::ADD:
10102     case ISD::UMIN:
10103     case ISD::UMAX:
10104     case ISD::SMIN:
10105     case ISD::SMAX:
10106     case ISD::FMAXNUM:
10107     case ISD::FMINNUM:
10108     case ISD::FMAXNUM_IEEE:
10109     case ISD::FMINNUM_IEEE: {
10110       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10111                                  Vec.getOperand(0), Idx);
10112       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10113                                  Vec.getOperand(1), Idx);
10114 
10115       DCI.AddToWorklist(Elt0.getNode());
10116       DCI.AddToWorklist(Elt1.getNode());
10117       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10118     }
10119     }
10120   }
10121 
10122   unsigned VecSize = VecVT.getSizeInBits();
10123   unsigned EltSize = EltVT.getSizeInBits();
10124 
10125   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10126   if (::shouldExpandVectorDynExt(N)) {
10127     SDLoc SL(N);
10128     SDValue Idx = N->getOperand(1);
10129     SDValue V;
10130     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10131       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10132       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10133       if (I == 0)
10134         V = Elt;
10135       else
10136         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10137     }
10138     return V;
10139   }
10140 
10141   if (!DCI.isBeforeLegalize())
10142     return SDValue();
10143 
10144   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10145   // elements. This exposes more load reduction opportunities by replacing
10146   // multiple small extract_vector_elements with a single 32-bit extract.
10147   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10148   if (isa<MemSDNode>(Vec) &&
10149       EltSize <= 16 &&
10150       EltVT.isByteSized() &&
10151       VecSize > 32 &&
10152       VecSize % 32 == 0 &&
10153       Idx) {
10154     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10155 
10156     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10157     unsigned EltIdx = BitIndex / 32;
10158     unsigned LeftoverBitIdx = BitIndex % 32;
10159     SDLoc SL(N);
10160 
10161     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10162     DCI.AddToWorklist(Cast.getNode());
10163 
10164     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10165                               DAG.getConstant(EltIdx, SL, MVT::i32));
10166     DCI.AddToWorklist(Elt.getNode());
10167     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10168                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10169     DCI.AddToWorklist(Srl.getNode());
10170 
10171     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10172     DCI.AddToWorklist(Trunc.getNode());
10173     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10174   }
10175 
10176   return SDValue();
10177 }
10178 
10179 SDValue
10180 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10181                                                 DAGCombinerInfo &DCI) const {
10182   SDValue Vec = N->getOperand(0);
10183   SDValue Idx = N->getOperand(2);
10184   EVT VecVT = Vec.getValueType();
10185   EVT EltVT = VecVT.getVectorElementType();
10186 
10187   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10188   // => BUILD_VECTOR n x select (e, const-idx)
10189   if (!::shouldExpandVectorDynExt(N))
10190     return SDValue();
10191 
10192   SelectionDAG &DAG = DCI.DAG;
10193   SDLoc SL(N);
10194   SDValue Ins = N->getOperand(1);
10195   EVT IdxVT = Idx.getValueType();
10196 
10197   SmallVector<SDValue, 16> Ops;
10198   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10199     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10200     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10201     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10202     Ops.push_back(V);
10203   }
10204 
10205   return DAG.getBuildVector(VecVT, SL, Ops);
10206 }
10207 
10208 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10209                                           const SDNode *N0,
10210                                           const SDNode *N1) const {
10211   EVT VT = N0->getValueType(0);
10212 
10213   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10214   // support denormals ever.
10215   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10216        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10217         getSubtarget()->hasMadF16())) &&
10218        isOperationLegal(ISD::FMAD, VT))
10219     return ISD::FMAD;
10220 
10221   const TargetOptions &Options = DAG.getTarget().Options;
10222   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10223        (N0->getFlags().hasAllowContract() &&
10224         N1->getFlags().hasAllowContract())) &&
10225       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10226     return ISD::FMA;
10227   }
10228 
10229   return 0;
10230 }
10231 
10232 // For a reassociatable opcode perform:
10233 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10234 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10235                                                SelectionDAG &DAG) const {
10236   EVT VT = N->getValueType(0);
10237   if (VT != MVT::i32 && VT != MVT::i64)
10238     return SDValue();
10239 
10240   unsigned Opc = N->getOpcode();
10241   SDValue Op0 = N->getOperand(0);
10242   SDValue Op1 = N->getOperand(1);
10243 
10244   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10245     return SDValue();
10246 
10247   if (Op0->isDivergent())
10248     std::swap(Op0, Op1);
10249 
10250   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10251     return SDValue();
10252 
10253   SDValue Op2 = Op1.getOperand(1);
10254   Op1 = Op1.getOperand(0);
10255   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10256     return SDValue();
10257 
10258   if (Op1->isDivergent())
10259     std::swap(Op1, Op2);
10260 
10261   // If either operand is constant this will conflict with
10262   // DAGCombiner::ReassociateOps().
10263   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
10264       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
10265     return SDValue();
10266 
10267   SDLoc SL(N);
10268   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10269   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10270 }
10271 
10272 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10273                            EVT VT,
10274                            SDValue N0, SDValue N1, SDValue N2,
10275                            bool Signed) {
10276   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10277   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10278   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10279   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10280 }
10281 
10282 SDValue SITargetLowering::performAddCombine(SDNode *N,
10283                                             DAGCombinerInfo &DCI) const {
10284   SelectionDAG &DAG = DCI.DAG;
10285   EVT VT = N->getValueType(0);
10286   SDLoc SL(N);
10287   SDValue LHS = N->getOperand(0);
10288   SDValue RHS = N->getOperand(1);
10289 
10290   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10291       && Subtarget->hasMad64_32() &&
10292       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10293       VT.getScalarSizeInBits() <= 64) {
10294     if (LHS.getOpcode() != ISD::MUL)
10295       std::swap(LHS, RHS);
10296 
10297     SDValue MulLHS = LHS.getOperand(0);
10298     SDValue MulRHS = LHS.getOperand(1);
10299     SDValue AddRHS = RHS;
10300 
10301     // TODO: Maybe restrict if SGPR inputs.
10302     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10303         numBitsUnsigned(MulRHS, DAG) <= 32) {
10304       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10305       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10306       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10307       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10308     }
10309 
10310     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
10311       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10312       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10313       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10314       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10315     }
10316 
10317     return SDValue();
10318   }
10319 
10320   if (SDValue V = reassociateScalarOps(N, DAG)) {
10321     return V;
10322   }
10323 
10324   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10325     return SDValue();
10326 
10327   // add x, zext (setcc) => addcarry x, 0, setcc
10328   // add x, sext (setcc) => subcarry x, 0, setcc
10329   unsigned Opc = LHS.getOpcode();
10330   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10331       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10332     std::swap(RHS, LHS);
10333 
10334   Opc = RHS.getOpcode();
10335   switch (Opc) {
10336   default: break;
10337   case ISD::ZERO_EXTEND:
10338   case ISD::SIGN_EXTEND:
10339   case ISD::ANY_EXTEND: {
10340     auto Cond = RHS.getOperand(0);
10341     // If this won't be a real VOPC output, we would still need to insert an
10342     // extra instruction anyway.
10343     if (!isBoolSGPR(Cond))
10344       break;
10345     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10346     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10347     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10348     return DAG.getNode(Opc, SL, VTList, Args);
10349   }
10350   case ISD::ADDCARRY: {
10351     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10352     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10353     if (!C || C->getZExtValue() != 0) break;
10354     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10355     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10356   }
10357   }
10358   return SDValue();
10359 }
10360 
10361 SDValue SITargetLowering::performSubCombine(SDNode *N,
10362                                             DAGCombinerInfo &DCI) const {
10363   SelectionDAG &DAG = DCI.DAG;
10364   EVT VT = N->getValueType(0);
10365 
10366   if (VT != MVT::i32)
10367     return SDValue();
10368 
10369   SDLoc SL(N);
10370   SDValue LHS = N->getOperand(0);
10371   SDValue RHS = N->getOperand(1);
10372 
10373   // sub x, zext (setcc) => subcarry x, 0, setcc
10374   // sub x, sext (setcc) => addcarry x, 0, setcc
10375   unsigned Opc = RHS.getOpcode();
10376   switch (Opc) {
10377   default: break;
10378   case ISD::ZERO_EXTEND:
10379   case ISD::SIGN_EXTEND:
10380   case ISD::ANY_EXTEND: {
10381     auto Cond = RHS.getOperand(0);
10382     // If this won't be a real VOPC output, we would still need to insert an
10383     // extra instruction anyway.
10384     if (!isBoolSGPR(Cond))
10385       break;
10386     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10387     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10388     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10389     return DAG.getNode(Opc, SL, VTList, Args);
10390   }
10391   }
10392 
10393   if (LHS.getOpcode() == ISD::SUBCARRY) {
10394     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10395     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10396     if (!C || !C->isNullValue())
10397       return SDValue();
10398     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10399     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10400   }
10401   return SDValue();
10402 }
10403 
10404 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10405   DAGCombinerInfo &DCI) const {
10406 
10407   if (N->getValueType(0) != MVT::i32)
10408     return SDValue();
10409 
10410   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10411   if (!C || C->getZExtValue() != 0)
10412     return SDValue();
10413 
10414   SelectionDAG &DAG = DCI.DAG;
10415   SDValue LHS = N->getOperand(0);
10416 
10417   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10418   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10419   unsigned LHSOpc = LHS.getOpcode();
10420   unsigned Opc = N->getOpcode();
10421   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10422       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10423     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10424     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10425   }
10426   return SDValue();
10427 }
10428 
10429 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10430                                              DAGCombinerInfo &DCI) const {
10431   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10432     return SDValue();
10433 
10434   SelectionDAG &DAG = DCI.DAG;
10435   EVT VT = N->getValueType(0);
10436 
10437   SDLoc SL(N);
10438   SDValue LHS = N->getOperand(0);
10439   SDValue RHS = N->getOperand(1);
10440 
10441   // These should really be instruction patterns, but writing patterns with
10442   // source modiifiers is a pain.
10443 
10444   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10445   if (LHS.getOpcode() == ISD::FADD) {
10446     SDValue A = LHS.getOperand(0);
10447     if (A == LHS.getOperand(1)) {
10448       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10449       if (FusedOp != 0) {
10450         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10451         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10452       }
10453     }
10454   }
10455 
10456   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10457   if (RHS.getOpcode() == ISD::FADD) {
10458     SDValue A = RHS.getOperand(0);
10459     if (A == RHS.getOperand(1)) {
10460       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10461       if (FusedOp != 0) {
10462         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10463         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10464       }
10465     }
10466   }
10467 
10468   return SDValue();
10469 }
10470 
10471 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10472                                              DAGCombinerInfo &DCI) const {
10473   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10474     return SDValue();
10475 
10476   SelectionDAG &DAG = DCI.DAG;
10477   SDLoc SL(N);
10478   EVT VT = N->getValueType(0);
10479   assert(!VT.isVector());
10480 
10481   // Try to get the fneg to fold into the source modifier. This undoes generic
10482   // DAG combines and folds them into the mad.
10483   //
10484   // Only do this if we are not trying to support denormals. v_mad_f32 does
10485   // not support denormals ever.
10486   SDValue LHS = N->getOperand(0);
10487   SDValue RHS = N->getOperand(1);
10488   if (LHS.getOpcode() == ISD::FADD) {
10489     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10490     SDValue A = LHS.getOperand(0);
10491     if (A == LHS.getOperand(1)) {
10492       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10493       if (FusedOp != 0){
10494         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10495         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10496 
10497         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10498       }
10499     }
10500   }
10501 
10502   if (RHS.getOpcode() == ISD::FADD) {
10503     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10504 
10505     SDValue A = RHS.getOperand(0);
10506     if (A == RHS.getOperand(1)) {
10507       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10508       if (FusedOp != 0){
10509         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10510         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10511       }
10512     }
10513   }
10514 
10515   return SDValue();
10516 }
10517 
10518 SDValue SITargetLowering::performFMACombine(SDNode *N,
10519                                             DAGCombinerInfo &DCI) const {
10520   SelectionDAG &DAG = DCI.DAG;
10521   EVT VT = N->getValueType(0);
10522   SDLoc SL(N);
10523 
10524   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
10525     return SDValue();
10526 
10527   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10528   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10529   SDValue Op1 = N->getOperand(0);
10530   SDValue Op2 = N->getOperand(1);
10531   SDValue FMA = N->getOperand(2);
10532 
10533   if (FMA.getOpcode() != ISD::FMA ||
10534       Op1.getOpcode() != ISD::FP_EXTEND ||
10535       Op2.getOpcode() != ISD::FP_EXTEND)
10536     return SDValue();
10537 
10538   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10539   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10540   // is sufficient to allow generaing fdot2.
10541   const TargetOptions &Options = DAG.getTarget().Options;
10542   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10543       (N->getFlags().hasAllowContract() &&
10544        FMA->getFlags().hasAllowContract())) {
10545     Op1 = Op1.getOperand(0);
10546     Op2 = Op2.getOperand(0);
10547     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10548         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10549       return SDValue();
10550 
10551     SDValue Vec1 = Op1.getOperand(0);
10552     SDValue Idx1 = Op1.getOperand(1);
10553     SDValue Vec2 = Op2.getOperand(0);
10554 
10555     SDValue FMAOp1 = FMA.getOperand(0);
10556     SDValue FMAOp2 = FMA.getOperand(1);
10557     SDValue FMAAcc = FMA.getOperand(2);
10558 
10559     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10560         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10561       return SDValue();
10562 
10563     FMAOp1 = FMAOp1.getOperand(0);
10564     FMAOp2 = FMAOp2.getOperand(0);
10565     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10566         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10567       return SDValue();
10568 
10569     SDValue Vec3 = FMAOp1.getOperand(0);
10570     SDValue Vec4 = FMAOp2.getOperand(0);
10571     SDValue Idx2 = FMAOp1.getOperand(1);
10572 
10573     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10574         // Idx1 and Idx2 cannot be the same.
10575         Idx1 == Idx2)
10576       return SDValue();
10577 
10578     if (Vec1 == Vec2 || Vec3 == Vec4)
10579       return SDValue();
10580 
10581     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10582       return SDValue();
10583 
10584     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10585         (Vec1 == Vec4 && Vec2 == Vec3)) {
10586       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10587                          DAG.getTargetConstant(0, SL, MVT::i1));
10588     }
10589   }
10590   return SDValue();
10591 }
10592 
10593 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10594                                               DAGCombinerInfo &DCI) const {
10595   SelectionDAG &DAG = DCI.DAG;
10596   SDLoc SL(N);
10597 
10598   SDValue LHS = N->getOperand(0);
10599   SDValue RHS = N->getOperand(1);
10600   EVT VT = LHS.getValueType();
10601   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10602 
10603   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10604   if (!CRHS) {
10605     CRHS = dyn_cast<ConstantSDNode>(LHS);
10606     if (CRHS) {
10607       std::swap(LHS, RHS);
10608       CC = getSetCCSwappedOperands(CC);
10609     }
10610   }
10611 
10612   if (CRHS) {
10613     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10614         isBoolSGPR(LHS.getOperand(0))) {
10615       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10616       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10617       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10618       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10619       if ((CRHS->isAllOnesValue() &&
10620            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10621           (CRHS->isNullValue() &&
10622            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10623         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10624                            DAG.getConstant(-1, SL, MVT::i1));
10625       if ((CRHS->isAllOnesValue() &&
10626            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10627           (CRHS->isNullValue() &&
10628            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10629         return LHS.getOperand(0);
10630     }
10631 
10632     uint64_t CRHSVal = CRHS->getZExtValue();
10633     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10634         LHS.getOpcode() == ISD::SELECT &&
10635         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10636         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10637         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10638         isBoolSGPR(LHS.getOperand(0))) {
10639       // Given CT != FT:
10640       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10641       // setcc (select cc, CT, CF), CF, ne => cc
10642       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10643       // setcc (select cc, CT, CF), CT, eq => cc
10644       uint64_t CT = LHS.getConstantOperandVal(1);
10645       uint64_t CF = LHS.getConstantOperandVal(2);
10646 
10647       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10648           (CT == CRHSVal && CC == ISD::SETNE))
10649         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10650                            DAG.getConstant(-1, SL, MVT::i1));
10651       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10652           (CT == CRHSVal && CC == ISD::SETEQ))
10653         return LHS.getOperand(0);
10654     }
10655   }
10656 
10657   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10658                                            VT != MVT::f16))
10659     return SDValue();
10660 
10661   // Match isinf/isfinite pattern
10662   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10663   // (fcmp one (fabs x), inf) -> (fp_class x,
10664   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10665   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10666     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10667     if (!CRHS)
10668       return SDValue();
10669 
10670     const APFloat &APF = CRHS->getValueAPF();
10671     if (APF.isInfinity() && !APF.isNegative()) {
10672       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10673                                  SIInstrFlags::N_INFINITY;
10674       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10675                                     SIInstrFlags::P_ZERO |
10676                                     SIInstrFlags::N_NORMAL |
10677                                     SIInstrFlags::P_NORMAL |
10678                                     SIInstrFlags::N_SUBNORMAL |
10679                                     SIInstrFlags::P_SUBNORMAL;
10680       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10681       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10682                          DAG.getConstant(Mask, SL, MVT::i32));
10683     }
10684   }
10685 
10686   return SDValue();
10687 }
10688 
10689 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10690                                                      DAGCombinerInfo &DCI) const {
10691   SelectionDAG &DAG = DCI.DAG;
10692   SDLoc SL(N);
10693   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10694 
10695   SDValue Src = N->getOperand(0);
10696   SDValue Shift = N->getOperand(0);
10697 
10698   // TODO: Extend type shouldn't matter (assuming legal types).
10699   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10700     Shift = Shift.getOperand(0);
10701 
10702   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10703     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10704     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10705     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10706     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10707     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10708     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10709       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
10710                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10711 
10712       unsigned ShiftOffset = 8 * Offset;
10713       if (Shift.getOpcode() == ISD::SHL)
10714         ShiftOffset -= C->getZExtValue();
10715       else
10716         ShiftOffset += C->getZExtValue();
10717 
10718       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10719         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10720                            MVT::f32, Shift);
10721       }
10722     }
10723   }
10724 
10725   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10726   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10727   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10728     // We simplified Src. If this node is not dead, visit it again so it is
10729     // folded properly.
10730     if (N->getOpcode() != ISD::DELETED_NODE)
10731       DCI.AddToWorklist(N);
10732     return SDValue(N, 0);
10733   }
10734 
10735   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10736   if (SDValue DemandedSrc =
10737           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10738     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10739 
10740   return SDValue();
10741 }
10742 
10743 SDValue SITargetLowering::performClampCombine(SDNode *N,
10744                                               DAGCombinerInfo &DCI) const {
10745   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10746   if (!CSrc)
10747     return SDValue();
10748 
10749   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10750   const APFloat &F = CSrc->getValueAPF();
10751   APFloat Zero = APFloat::getZero(F.getSemantics());
10752   if (F < Zero ||
10753       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10754     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10755   }
10756 
10757   APFloat One(F.getSemantics(), "1.0");
10758   if (F > One)
10759     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10760 
10761   return SDValue(CSrc, 0);
10762 }
10763 
10764 
10765 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10766                                             DAGCombinerInfo &DCI) const {
10767   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10768     return SDValue();
10769   switch (N->getOpcode()) {
10770   case ISD::ADD:
10771     return performAddCombine(N, DCI);
10772   case ISD::SUB:
10773     return performSubCombine(N, DCI);
10774   case ISD::ADDCARRY:
10775   case ISD::SUBCARRY:
10776     return performAddCarrySubCarryCombine(N, DCI);
10777   case ISD::FADD:
10778     return performFAddCombine(N, DCI);
10779   case ISD::FSUB:
10780     return performFSubCombine(N, DCI);
10781   case ISD::SETCC:
10782     return performSetCCCombine(N, DCI);
10783   case ISD::FMAXNUM:
10784   case ISD::FMINNUM:
10785   case ISD::FMAXNUM_IEEE:
10786   case ISD::FMINNUM_IEEE:
10787   case ISD::SMAX:
10788   case ISD::SMIN:
10789   case ISD::UMAX:
10790   case ISD::UMIN:
10791   case AMDGPUISD::FMIN_LEGACY:
10792   case AMDGPUISD::FMAX_LEGACY:
10793     return performMinMaxCombine(N, DCI);
10794   case ISD::FMA:
10795     return performFMACombine(N, DCI);
10796   case ISD::AND:
10797     return performAndCombine(N, DCI);
10798   case ISD::OR:
10799     return performOrCombine(N, DCI);
10800   case ISD::XOR:
10801     return performXorCombine(N, DCI);
10802   case ISD::ZERO_EXTEND:
10803     return performZeroExtendCombine(N, DCI);
10804   case ISD::SIGN_EXTEND_INREG:
10805     return performSignExtendInRegCombine(N , DCI);
10806   case AMDGPUISD::FP_CLASS:
10807     return performClassCombine(N, DCI);
10808   case ISD::FCANONICALIZE:
10809     return performFCanonicalizeCombine(N, DCI);
10810   case AMDGPUISD::RCP:
10811     return performRcpCombine(N, DCI);
10812   case AMDGPUISD::FRACT:
10813   case AMDGPUISD::RSQ:
10814   case AMDGPUISD::RCP_LEGACY:
10815   case AMDGPUISD::RCP_IFLAG:
10816   case AMDGPUISD::RSQ_CLAMP:
10817   case AMDGPUISD::LDEXP: {
10818     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10819     SDValue Src = N->getOperand(0);
10820     if (Src.isUndef())
10821       return Src;
10822     break;
10823   }
10824   case ISD::SINT_TO_FP:
10825   case ISD::UINT_TO_FP:
10826     return performUCharToFloatCombine(N, DCI);
10827   case AMDGPUISD::CVT_F32_UBYTE0:
10828   case AMDGPUISD::CVT_F32_UBYTE1:
10829   case AMDGPUISD::CVT_F32_UBYTE2:
10830   case AMDGPUISD::CVT_F32_UBYTE3:
10831     return performCvtF32UByteNCombine(N, DCI);
10832   case AMDGPUISD::FMED3:
10833     return performFMed3Combine(N, DCI);
10834   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10835     return performCvtPkRTZCombine(N, DCI);
10836   case AMDGPUISD::CLAMP:
10837     return performClampCombine(N, DCI);
10838   case ISD::SCALAR_TO_VECTOR: {
10839     SelectionDAG &DAG = DCI.DAG;
10840     EVT VT = N->getValueType(0);
10841 
10842     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10843     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10844       SDLoc SL(N);
10845       SDValue Src = N->getOperand(0);
10846       EVT EltVT = Src.getValueType();
10847       if (EltVT == MVT::f16)
10848         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10849 
10850       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10851       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10852     }
10853 
10854     break;
10855   }
10856   case ISD::EXTRACT_VECTOR_ELT:
10857     return performExtractVectorEltCombine(N, DCI);
10858   case ISD::INSERT_VECTOR_ELT:
10859     return performInsertVectorEltCombine(N, DCI);
10860   case ISD::LOAD: {
10861     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10862       return Widended;
10863     LLVM_FALLTHROUGH;
10864   }
10865   default: {
10866     if (!DCI.isBeforeLegalize()) {
10867       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
10868         return performMemSDNodeCombine(MemNode, DCI);
10869     }
10870 
10871     break;
10872   }
10873   }
10874 
10875   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10876 }
10877 
10878 /// Helper function for adjustWritemask
10879 static unsigned SubIdx2Lane(unsigned Idx) {
10880   switch (Idx) {
10881   default: return ~0u;
10882   case AMDGPU::sub0: return 0;
10883   case AMDGPU::sub1: return 1;
10884   case AMDGPU::sub2: return 2;
10885   case AMDGPU::sub3: return 3;
10886   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10887   }
10888 }
10889 
10890 /// Adjust the writemask of MIMG instructions
10891 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10892                                           SelectionDAG &DAG) const {
10893   unsigned Opcode = Node->getMachineOpcode();
10894 
10895   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10896   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10897   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10898     return Node; // not implemented for D16
10899 
10900   SDNode *Users[5] = { nullptr };
10901   unsigned Lane = 0;
10902   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10903   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10904   unsigned NewDmask = 0;
10905   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10906   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10907   bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
10908                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10909   unsigned TFCLane = 0;
10910   bool HasChain = Node->getNumValues() > 1;
10911 
10912   if (OldDmask == 0) {
10913     // These are folded out, but on the chance it happens don't assert.
10914     return Node;
10915   }
10916 
10917   unsigned OldBitsSet = countPopulation(OldDmask);
10918   // Work out which is the TFE/LWE lane if that is enabled.
10919   if (UsesTFC) {
10920     TFCLane = OldBitsSet;
10921   }
10922 
10923   // Try to figure out the used register components
10924   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10925        I != E; ++I) {
10926 
10927     // Don't look at users of the chain.
10928     if (I.getUse().getResNo() != 0)
10929       continue;
10930 
10931     // Abort if we can't understand the usage
10932     if (!I->isMachineOpcode() ||
10933         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10934       return Node;
10935 
10936     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10937     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10938     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10939     // set, etc.
10940     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10941     if (Lane == ~0u)
10942       return Node;
10943 
10944     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10945     if (UsesTFC && Lane == TFCLane) {
10946       Users[Lane] = *I;
10947     } else {
10948       // Set which texture component corresponds to the lane.
10949       unsigned Comp;
10950       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10951         Comp = countTrailingZeros(Dmask);
10952         Dmask &= ~(1 << Comp);
10953       }
10954 
10955       // Abort if we have more than one user per component.
10956       if (Users[Lane])
10957         return Node;
10958 
10959       Users[Lane] = *I;
10960       NewDmask |= 1 << Comp;
10961     }
10962   }
10963 
10964   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10965   bool NoChannels = !NewDmask;
10966   if (NoChannels) {
10967     if (!UsesTFC) {
10968       // No uses of the result and not using TFC. Then do nothing.
10969       return Node;
10970     }
10971     // If the original dmask has one channel - then nothing to do
10972     if (OldBitsSet == 1)
10973       return Node;
10974     // Use an arbitrary dmask - required for the instruction to work
10975     NewDmask = 1;
10976   }
10977   // Abort if there's no change
10978   if (NewDmask == OldDmask)
10979     return Node;
10980 
10981   unsigned BitsSet = countPopulation(NewDmask);
10982 
10983   // Check for TFE or LWE - increase the number of channels by one to account
10984   // for the extra return value
10985   // This will need adjustment for D16 if this is also included in
10986   // adjustWriteMask (this function) but at present D16 are excluded.
10987   unsigned NewChannels = BitsSet + UsesTFC;
10988 
10989   int NewOpcode =
10990       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10991   assert(NewOpcode != -1 &&
10992          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10993          "failed to find equivalent MIMG op");
10994 
10995   // Adjust the writemask in the node
10996   SmallVector<SDValue, 12> Ops;
10997   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10998   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10999   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11000 
11001   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11002 
11003   MVT ResultVT = NewChannels == 1 ?
11004     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11005                            NewChannels == 5 ? 8 : NewChannels);
11006   SDVTList NewVTList = HasChain ?
11007     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11008 
11009 
11010   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11011                                               NewVTList, Ops);
11012 
11013   if (HasChain) {
11014     // Update chain.
11015     DAG.setNodeMemRefs(NewNode, Node->memoperands());
11016     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11017   }
11018 
11019   if (NewChannels == 1) {
11020     assert(Node->hasNUsesOfValue(1, 0));
11021     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11022                                       SDLoc(Node), Users[Lane]->getValueType(0),
11023                                       SDValue(NewNode, 0));
11024     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11025     return nullptr;
11026   }
11027 
11028   // Update the users of the node with the new indices
11029   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11030     SDNode *User = Users[i];
11031     if (!User) {
11032       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11033       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11034       if (i || !NoChannels)
11035         continue;
11036     } else {
11037       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11038       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11039     }
11040 
11041     switch (Idx) {
11042     default: break;
11043     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11044     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11045     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11046     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11047     }
11048   }
11049 
11050   DAG.RemoveDeadNode(Node);
11051   return nullptr;
11052 }
11053 
11054 static bool isFrameIndexOp(SDValue Op) {
11055   if (Op.getOpcode() == ISD::AssertZext)
11056     Op = Op.getOperand(0);
11057 
11058   return isa<FrameIndexSDNode>(Op);
11059 }
11060 
11061 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11062 /// with frame index operands.
11063 /// LLVM assumes that inputs are to these instructions are registers.
11064 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11065                                                         SelectionDAG &DAG) const {
11066   if (Node->getOpcode() == ISD::CopyToReg) {
11067     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11068     SDValue SrcVal = Node->getOperand(2);
11069 
11070     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11071     // to try understanding copies to physical registers.
11072     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11073       SDLoc SL(Node);
11074       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11075       SDValue VReg = DAG.getRegister(
11076         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11077 
11078       SDNode *Glued = Node->getGluedNode();
11079       SDValue ToVReg
11080         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11081                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11082       SDValue ToResultReg
11083         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11084                            VReg, ToVReg.getValue(1));
11085       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11086       DAG.RemoveDeadNode(Node);
11087       return ToResultReg.getNode();
11088     }
11089   }
11090 
11091   SmallVector<SDValue, 8> Ops;
11092   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11093     if (!isFrameIndexOp(Node->getOperand(i))) {
11094       Ops.push_back(Node->getOperand(i));
11095       continue;
11096     }
11097 
11098     SDLoc DL(Node);
11099     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11100                                      Node->getOperand(i).getValueType(),
11101                                      Node->getOperand(i)), 0));
11102   }
11103 
11104   return DAG.UpdateNodeOperands(Node, Ops);
11105 }
11106 
11107 /// Fold the instructions after selecting them.
11108 /// Returns null if users were already updated.
11109 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11110                                           SelectionDAG &DAG) const {
11111   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11112   unsigned Opcode = Node->getMachineOpcode();
11113 
11114   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11115       !TII->isGather4(Opcode) &&
11116       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11117     return adjustWritemask(Node, DAG);
11118   }
11119 
11120   if (Opcode == AMDGPU::INSERT_SUBREG ||
11121       Opcode == AMDGPU::REG_SEQUENCE) {
11122     legalizeTargetIndependentNode(Node, DAG);
11123     return Node;
11124   }
11125 
11126   switch (Opcode) {
11127   case AMDGPU::V_DIV_SCALE_F32_e64:
11128   case AMDGPU::V_DIV_SCALE_F64_e64: {
11129     // Satisfy the operand register constraint when one of the inputs is
11130     // undefined. Ordinarily each undef value will have its own implicit_def of
11131     // a vreg, so force these to use a single register.
11132     SDValue Src0 = Node->getOperand(1);
11133     SDValue Src1 = Node->getOperand(3);
11134     SDValue Src2 = Node->getOperand(5);
11135 
11136     if ((Src0.isMachineOpcode() &&
11137          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11138         (Src0 == Src1 || Src0 == Src2))
11139       break;
11140 
11141     MVT VT = Src0.getValueType().getSimpleVT();
11142     const TargetRegisterClass *RC =
11143         getRegClassFor(VT, Src0.getNode()->isDivergent());
11144 
11145     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11146     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11147 
11148     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11149                                       UndefReg, Src0, SDValue());
11150 
11151     // src0 must be the same register as src1 or src2, even if the value is
11152     // undefined, so make sure we don't violate this constraint.
11153     if (Src0.isMachineOpcode() &&
11154         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11155       if (Src1.isMachineOpcode() &&
11156           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11157         Src0 = Src1;
11158       else if (Src2.isMachineOpcode() &&
11159                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11160         Src0 = Src2;
11161       else {
11162         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11163         Src0 = UndefReg;
11164         Src1 = UndefReg;
11165       }
11166     } else
11167       break;
11168 
11169     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11170     Ops[1] = Src0;
11171     Ops[3] = Src1;
11172     Ops[5] = Src2;
11173     Ops.push_back(ImpDef.getValue(1));
11174     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11175   }
11176   default:
11177     break;
11178   }
11179 
11180   return Node;
11181 }
11182 
11183 /// Assign the register class depending on the number of
11184 /// bits set in the writemask
11185 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11186                                                      SDNode *Node) const {
11187   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11188 
11189   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11190 
11191   if (TII->isVOP3(MI.getOpcode())) {
11192     // Make sure constant bus requirements are respected.
11193     TII->legalizeOperandsVOP3(MRI, MI);
11194 
11195     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11196     // This saves a chain-copy of registers and better ballance register
11197     // use between vgpr and agpr as agpr tuples tend to be big.
11198     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
11199       unsigned Opc = MI.getOpcode();
11200       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11201       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11202                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11203         if (I == -1)
11204           break;
11205         MachineOperand &Op = MI.getOperand(I);
11206         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
11207              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
11208             !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg()))
11209           continue;
11210         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11211         if (!Src || !Src->isCopy() ||
11212             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11213           continue;
11214         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11215         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11216         // All uses of agpr64 and agpr32 can also accept vgpr except for
11217         // v_accvgpr_read, but we do not produce agpr reads during selection,
11218         // so no use checks are needed.
11219         MRI.setRegClass(Op.getReg(), NewRC);
11220       }
11221     }
11222 
11223     return;
11224   }
11225 
11226   // Replace unused atomics with the no return version.
11227   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11228   if (NoRetAtomicOp != -1) {
11229     if (!Node->hasAnyUseOfValue(0)) {
11230       int Glc1Idx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
11231                                                AMDGPU::OpName::glc1);
11232       if (Glc1Idx != -1)
11233         MI.RemoveOperand(Glc1Idx);
11234       MI.RemoveOperand(0);
11235       MI.setDesc(TII->get(NoRetAtomicOp));
11236       return;
11237     }
11238 
11239     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11240     // instruction, because the return type of these instructions is a vec2 of
11241     // the memory type, so it can be tied to the input operand.
11242     // This means these instructions always have a use, so we need to add a
11243     // special case to check if the atomic has only one extract_subreg use,
11244     // which itself has no uses.
11245     if ((Node->hasNUsesOfValue(1, 0) &&
11246          Node->use_begin()->isMachineOpcode() &&
11247          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11248          !Node->use_begin()->hasAnyUseOfValue(0))) {
11249       Register Def = MI.getOperand(0).getReg();
11250 
11251       // Change this into a noret atomic.
11252       MI.setDesc(TII->get(NoRetAtomicOp));
11253       MI.RemoveOperand(0);
11254 
11255       // If we only remove the def operand from the atomic instruction, the
11256       // extract_subreg will be left with a use of a vreg without a def.
11257       // So we need to insert an implicit_def to avoid machine verifier
11258       // errors.
11259       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11260               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11261     }
11262     return;
11263   }
11264 }
11265 
11266 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11267                               uint64_t Val) {
11268   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11269   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11270 }
11271 
11272 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11273                                                 const SDLoc &DL,
11274                                                 SDValue Ptr) const {
11275   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11276 
11277   // Build the half of the subregister with the constants before building the
11278   // full 128-bit register. If we are building multiple resource descriptors,
11279   // this will allow CSEing of the 2-component register.
11280   const SDValue Ops0[] = {
11281     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11282     buildSMovImm32(DAG, DL, 0),
11283     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11284     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11285     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11286   };
11287 
11288   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11289                                                 MVT::v2i32, Ops0), 0);
11290 
11291   // Combine the constants and the pointer.
11292   const SDValue Ops1[] = {
11293     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11294     Ptr,
11295     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11296     SubRegHi,
11297     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11298   };
11299 
11300   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11301 }
11302 
11303 /// Return a resource descriptor with the 'Add TID' bit enabled
11304 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11305 ///        of the resource descriptor) to create an offset, which is added to
11306 ///        the resource pointer.
11307 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11308                                            SDValue Ptr, uint32_t RsrcDword1,
11309                                            uint64_t RsrcDword2And3) const {
11310   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11311   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11312   if (RsrcDword1) {
11313     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11314                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11315                     0);
11316   }
11317 
11318   SDValue DataLo = buildSMovImm32(DAG, DL,
11319                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11320   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11321 
11322   const SDValue Ops[] = {
11323     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11324     PtrLo,
11325     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11326     PtrHi,
11327     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11328     DataLo,
11329     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11330     DataHi,
11331     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11332   };
11333 
11334   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11335 }
11336 
11337 //===----------------------------------------------------------------------===//
11338 //                         SI Inline Assembly Support
11339 //===----------------------------------------------------------------------===//
11340 
11341 std::pair<unsigned, const TargetRegisterClass *>
11342 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
11343                                                StringRef Constraint,
11344                                                MVT VT) const {
11345   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
11346 
11347   const TargetRegisterClass *RC = nullptr;
11348   if (Constraint.size() == 1) {
11349     const unsigned BitWidth = VT.getSizeInBits();
11350     switch (Constraint[0]) {
11351     default:
11352       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11353     case 's':
11354     case 'r':
11355       switch (BitWidth) {
11356       case 16:
11357         RC = &AMDGPU::SReg_32RegClass;
11358         break;
11359       case 64:
11360         RC = &AMDGPU::SGPR_64RegClass;
11361         break;
11362       default:
11363         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11364         if (!RC)
11365           return std::make_pair(0U, nullptr);
11366         break;
11367       }
11368       break;
11369     case 'v':
11370       switch (BitWidth) {
11371       case 16:
11372         RC = &AMDGPU::VGPR_32RegClass;
11373         break;
11374       default:
11375         RC = TRI->getVGPRClassForBitWidth(BitWidth);
11376         if (!RC)
11377           return std::make_pair(0U, nullptr);
11378         break;
11379       }
11380       break;
11381     case 'a':
11382       if (!Subtarget->hasMAIInsts())
11383         break;
11384       switch (BitWidth) {
11385       case 16:
11386         RC = &AMDGPU::AGPR_32RegClass;
11387         break;
11388       default:
11389         RC = TRI->getAGPRClassForBitWidth(BitWidth);
11390         if (!RC)
11391           return std::make_pair(0U, nullptr);
11392         break;
11393       }
11394       break;
11395     }
11396     // We actually support i128, i16 and f16 as inline parameters
11397     // even if they are not reported as legal
11398     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11399                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11400       return std::make_pair(0U, RC);
11401   }
11402 
11403   if (Constraint.size() > 1) {
11404     if (Constraint[1] == 'v') {
11405       RC = &AMDGPU::VGPR_32RegClass;
11406     } else if (Constraint[1] == 's') {
11407       RC = &AMDGPU::SGPR_32RegClass;
11408     } else if (Constraint[1] == 'a') {
11409       RC = &AMDGPU::AGPR_32RegClass;
11410     }
11411 
11412     if (RC) {
11413       uint32_t Idx;
11414       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
11415       if (!Failed && Idx < RC->getNumRegs())
11416         return std::make_pair(RC->getRegister(Idx), RC);
11417     }
11418   }
11419 
11420   // FIXME: Returns VS_32 for physical SGPR constraints
11421   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11422 }
11423 
11424 static bool isImmConstraint(StringRef Constraint) {
11425   if (Constraint.size() == 1) {
11426     switch (Constraint[0]) {
11427     default: break;
11428     case 'I':
11429     case 'J':
11430     case 'A':
11431     case 'B':
11432     case 'C':
11433       return true;
11434     }
11435   } else if (Constraint == "DA" ||
11436              Constraint == "DB") {
11437     return true;
11438   }
11439   return false;
11440 }
11441 
11442 SITargetLowering::ConstraintType
11443 SITargetLowering::getConstraintType(StringRef Constraint) const {
11444   if (Constraint.size() == 1) {
11445     switch (Constraint[0]) {
11446     default: break;
11447     case 's':
11448     case 'v':
11449     case 'a':
11450       return C_RegisterClass;
11451     }
11452   }
11453   if (isImmConstraint(Constraint)) {
11454     return C_Other;
11455   }
11456   return TargetLowering::getConstraintType(Constraint);
11457 }
11458 
11459 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11460   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11461     Val = Val & maskTrailingOnes<uint64_t>(Size);
11462   }
11463   return Val;
11464 }
11465 
11466 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11467                                                     std::string &Constraint,
11468                                                     std::vector<SDValue> &Ops,
11469                                                     SelectionDAG &DAG) const {
11470   if (isImmConstraint(Constraint)) {
11471     uint64_t Val;
11472     if (getAsmOperandConstVal(Op, Val) &&
11473         checkAsmConstraintVal(Op, Constraint, Val)) {
11474       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11475       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11476     }
11477   } else {
11478     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11479   }
11480 }
11481 
11482 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11483   unsigned Size = Op.getScalarValueSizeInBits();
11484   if (Size > 64)
11485     return false;
11486 
11487   if (Size == 16 && !Subtarget->has16BitInsts())
11488     return false;
11489 
11490   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11491     Val = C->getSExtValue();
11492     return true;
11493   }
11494   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11495     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11496     return true;
11497   }
11498   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11499     if (Size != 16 || Op.getNumOperands() != 2)
11500       return false;
11501     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11502       return false;
11503     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11504       Val = C->getSExtValue();
11505       return true;
11506     }
11507     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11508       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11509       return true;
11510     }
11511   }
11512 
11513   return false;
11514 }
11515 
11516 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11517                                              const std::string &Constraint,
11518                                              uint64_t Val) const {
11519   if (Constraint.size() == 1) {
11520     switch (Constraint[0]) {
11521     case 'I':
11522       return AMDGPU::isInlinableIntLiteral(Val);
11523     case 'J':
11524       return isInt<16>(Val);
11525     case 'A':
11526       return checkAsmConstraintValA(Op, Val);
11527     case 'B':
11528       return isInt<32>(Val);
11529     case 'C':
11530       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11531              AMDGPU::isInlinableIntLiteral(Val);
11532     default:
11533       break;
11534     }
11535   } else if (Constraint.size() == 2) {
11536     if (Constraint == "DA") {
11537       int64_t HiBits = static_cast<int32_t>(Val >> 32);
11538       int64_t LoBits = static_cast<int32_t>(Val);
11539       return checkAsmConstraintValA(Op, HiBits, 32) &&
11540              checkAsmConstraintValA(Op, LoBits, 32);
11541     }
11542     if (Constraint == "DB") {
11543       return true;
11544     }
11545   }
11546   llvm_unreachable("Invalid asm constraint");
11547 }
11548 
11549 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
11550                                               uint64_t Val,
11551                                               unsigned MaxSize) const {
11552   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
11553   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11554   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11555       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11556       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11557     return true;
11558   }
11559   return false;
11560 }
11561 
11562 static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
11563   switch (UnalignedClassID) {
11564   case AMDGPU::VReg_64RegClassID:
11565     return AMDGPU::VReg_64_Align2RegClassID;
11566   case AMDGPU::VReg_96RegClassID:
11567     return AMDGPU::VReg_96_Align2RegClassID;
11568   case AMDGPU::VReg_128RegClassID:
11569     return AMDGPU::VReg_128_Align2RegClassID;
11570   case AMDGPU::VReg_256RegClassID:
11571     return AMDGPU::VReg_256_Align2RegClassID;
11572   case AMDGPU::VReg_512RegClassID:
11573     return AMDGPU::VReg_512_Align2RegClassID;
11574   case AMDGPU::AReg_64RegClassID:
11575     return AMDGPU::AReg_64_Align2RegClassID;
11576   case AMDGPU::AReg_96RegClassID:
11577     return AMDGPU::AReg_96_Align2RegClassID;
11578   case AMDGPU::AReg_128RegClassID:
11579     return AMDGPU::AReg_128_Align2RegClassID;
11580   case AMDGPU::AReg_256RegClassID:
11581     return AMDGPU::AReg_256_Align2RegClassID;
11582   case AMDGPU::AReg_512RegClassID:
11583     return AMDGPU::AReg_512_Align2RegClassID;
11584   case AMDGPU::AReg_1024RegClassID:
11585     return AMDGPU::AReg_1024_Align2RegClassID;
11586   default:
11587     return -1;
11588   }
11589 }
11590 
11591 // Figure out which registers should be reserved for stack access. Only after
11592 // the function is legalized do we know all of the non-spill stack objects or if
11593 // calls are present.
11594 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
11595   MachineRegisterInfo &MRI = MF.getRegInfo();
11596   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11597   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
11598   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11599   const SIInstrInfo *TII = ST.getInstrInfo();
11600 
11601   if (Info->isEntryFunction()) {
11602     // Callable functions have fixed registers used for stack access.
11603     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
11604   }
11605 
11606   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
11607                              Info->getStackPtrOffsetReg()));
11608   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
11609     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
11610 
11611   // We need to worry about replacing the default register with itself in case
11612   // of MIR testcases missing the MFI.
11613   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
11614     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
11615 
11616   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
11617     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
11618 
11619   Info->limitOccupancy(MF);
11620 
11621   if (ST.isWave32() && !MF.empty()) {
11622     for (auto &MBB : MF) {
11623       for (auto &MI : MBB) {
11624         TII->fixImplicitOperands(MI);
11625       }
11626     }
11627   }
11628 
11629   // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
11630   // classes if required. Ideally the register class constraints would differ
11631   // per-subtarget, but there's no easy way to achieve that right now. This is
11632   // not a problem for VGPRs because the correctly aligned VGPR class is implied
11633   // from using them as the register class for legal types.
11634   if (ST.needsAlignedVGPRs()) {
11635     for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
11636       const Register Reg = Register::index2VirtReg(I);
11637       const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
11638       if (!RC)
11639         continue;
11640       int NewClassID = getAlignedAGPRClassID(RC->getID());
11641       if (NewClassID != -1)
11642         MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
11643     }
11644   }
11645 
11646   TargetLoweringBase::finalizeLowering(MF);
11647 
11648   // Allocate a VGPR for future SGPR Spill if
11649   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
11650   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
11651   if (VGPRReserveforSGPRSpill && TRI->spillSGPRToVGPR() &&
11652       !Info->VGPRReservedForSGPRSpill && !Info->isEntryFunction() &&
11653       MF.getFrameInfo().hasStackObjects())
11654     Info->reserveVGPRforSGPRSpills(MF);
11655 }
11656 
11657 void SITargetLowering::computeKnownBitsForFrameIndex(
11658   const int FI, KnownBits &Known, const MachineFunction &MF) const {
11659   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
11660 
11661   // Set the high bits to zero based on the maximum allowed scratch size per
11662   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
11663   // calculation won't overflow, so assume the sign bit is never set.
11664   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
11665 }
11666 
11667 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
11668                                    KnownBits &Known, unsigned Dim) {
11669   unsigned MaxValue =
11670       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
11671   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
11672 }
11673 
11674 void SITargetLowering::computeKnownBitsForTargetInstr(
11675     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
11676     const MachineRegisterInfo &MRI, unsigned Depth) const {
11677   const MachineInstr *MI = MRI.getVRegDef(R);
11678   switch (MI->getOpcode()) {
11679   case AMDGPU::G_INTRINSIC: {
11680     switch (MI->getIntrinsicID()) {
11681     case Intrinsic::amdgcn_workitem_id_x:
11682       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
11683       break;
11684     case Intrinsic::amdgcn_workitem_id_y:
11685       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
11686       break;
11687     case Intrinsic::amdgcn_workitem_id_z:
11688       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
11689       break;
11690     case Intrinsic::amdgcn_mbcnt_lo:
11691     case Intrinsic::amdgcn_mbcnt_hi: {
11692       // These return at most the wavefront size - 1.
11693       unsigned Size = MRI.getType(R).getSizeInBits();
11694       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
11695       break;
11696     }
11697     case Intrinsic::amdgcn_groupstaticsize: {
11698       // We can report everything over the maximum size as 0. We can't report
11699       // based on the actual size because we don't know if it's accurate or not
11700       // at any given point.
11701       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
11702       break;
11703     }
11704     }
11705     break;
11706   }
11707   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
11708     Known.Zero.setHighBits(24);
11709     break;
11710   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
11711     Known.Zero.setHighBits(16);
11712     break;
11713   }
11714 }
11715 
11716 Align SITargetLowering::computeKnownAlignForTargetInstr(
11717   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
11718   unsigned Depth) const {
11719   const MachineInstr *MI = MRI.getVRegDef(R);
11720   switch (MI->getOpcode()) {
11721   case AMDGPU::G_INTRINSIC:
11722   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
11723     // FIXME: Can this move to generic code? What about the case where the call
11724     // site specifies a lower alignment?
11725     Intrinsic::ID IID = MI->getIntrinsicID();
11726     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
11727     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
11728     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
11729       return *RetAlign;
11730     return Align(1);
11731   }
11732   default:
11733     return Align(1);
11734   }
11735 }
11736 
11737 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11738   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
11739   const Align CacheLineAlign = Align(64);
11740 
11741   // Pre-GFX10 target did not benefit from loop alignment
11742   if (!ML || DisableLoopAlignment ||
11743       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
11744       getSubtarget()->hasInstFwdPrefetchBug())
11745     return PrefAlign;
11746 
11747   // On GFX10 I$ is 4 x 64 bytes cache lines.
11748   // By default prefetcher keeps one cache line behind and reads two ahead.
11749   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
11750   // behind and one ahead.
11751   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
11752   // If loop fits 64 bytes it always spans no more than two cache lines and
11753   // does not need an alignment.
11754   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
11755   // Else if loop is less or equal 192 bytes we need two lines behind.
11756 
11757   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11758   const MachineBasicBlock *Header = ML->getHeader();
11759   if (Header->getAlignment() != PrefAlign)
11760     return Header->getAlignment(); // Already processed.
11761 
11762   unsigned LoopSize = 0;
11763   for (const MachineBasicBlock *MBB : ML->blocks()) {
11764     // If inner loop block is aligned assume in average half of the alignment
11765     // size to be added as nops.
11766     if (MBB != Header)
11767       LoopSize += MBB->getAlignment().value() / 2;
11768 
11769     for (const MachineInstr &MI : *MBB) {
11770       LoopSize += TII->getInstSizeInBytes(MI);
11771       if (LoopSize > 192)
11772         return PrefAlign;
11773     }
11774   }
11775 
11776   if (LoopSize <= 64)
11777     return PrefAlign;
11778 
11779   if (LoopSize <= 128)
11780     return CacheLineAlign;
11781 
11782   // If any of parent loops is surrounded by prefetch instructions do not
11783   // insert new for inner loop, which would reset parent's settings.
11784   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
11785     if (MachineBasicBlock *Exit = P->getExitBlock()) {
11786       auto I = Exit->getFirstNonDebugInstr();
11787       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
11788         return CacheLineAlign;
11789     }
11790   }
11791 
11792   MachineBasicBlock *Pre = ML->getLoopPreheader();
11793   MachineBasicBlock *Exit = ML->getExitBlock();
11794 
11795   if (Pre && Exit) {
11796     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
11797             TII->get(AMDGPU::S_INST_PREFETCH))
11798       .addImm(1); // prefetch 2 lines behind PC
11799 
11800     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
11801             TII->get(AMDGPU::S_INST_PREFETCH))
11802       .addImm(2); // prefetch 1 line behind PC
11803   }
11804 
11805   return CacheLineAlign;
11806 }
11807 
11808 LLVM_ATTRIBUTE_UNUSED
11809 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
11810   assert(N->getOpcode() == ISD::CopyFromReg);
11811   do {
11812     // Follow the chain until we find an INLINEASM node.
11813     N = N->getOperand(0).getNode();
11814     if (N->getOpcode() == ISD::INLINEASM ||
11815         N->getOpcode() == ISD::INLINEASM_BR)
11816       return true;
11817   } while (N->getOpcode() == ISD::CopyFromReg);
11818   return false;
11819 }
11820 
11821 bool SITargetLowering::isSDNodeSourceOfDivergence(
11822     const SDNode *N, FunctionLoweringInfo *FLI,
11823     LegacyDivergenceAnalysis *KDA) const {
11824   switch (N->getOpcode()) {
11825   case ISD::CopyFromReg: {
11826     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
11827     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
11828     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11829     Register Reg = R->getReg();
11830 
11831     // FIXME: Why does this need to consider isLiveIn?
11832     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
11833       return !TRI->isSGPRReg(MRI, Reg);
11834 
11835     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
11836       return KDA->isDivergent(V);
11837 
11838     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
11839     return !TRI->isSGPRReg(MRI, Reg);
11840   }
11841   case ISD::LOAD: {
11842     const LoadSDNode *L = cast<LoadSDNode>(N);
11843     unsigned AS = L->getAddressSpace();
11844     // A flat load may access private memory.
11845     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
11846   }
11847   case ISD::CALLSEQ_END:
11848     return true;
11849   case ISD::INTRINSIC_WO_CHAIN:
11850     return AMDGPU::isIntrinsicSourceOfDivergence(
11851         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
11852   case ISD::INTRINSIC_W_CHAIN:
11853     return AMDGPU::isIntrinsicSourceOfDivergence(
11854         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
11855   case AMDGPUISD::ATOMIC_CMP_SWAP:
11856   case AMDGPUISD::ATOMIC_INC:
11857   case AMDGPUISD::ATOMIC_DEC:
11858   case AMDGPUISD::ATOMIC_LOAD_FMIN:
11859   case AMDGPUISD::ATOMIC_LOAD_FMAX:
11860   case AMDGPUISD::BUFFER_ATOMIC_SWAP:
11861   case AMDGPUISD::BUFFER_ATOMIC_ADD:
11862   case AMDGPUISD::BUFFER_ATOMIC_SUB:
11863   case AMDGPUISD::BUFFER_ATOMIC_SMIN:
11864   case AMDGPUISD::BUFFER_ATOMIC_UMIN:
11865   case AMDGPUISD::BUFFER_ATOMIC_SMAX:
11866   case AMDGPUISD::BUFFER_ATOMIC_UMAX:
11867   case AMDGPUISD::BUFFER_ATOMIC_AND:
11868   case AMDGPUISD::BUFFER_ATOMIC_OR:
11869   case AMDGPUISD::BUFFER_ATOMIC_XOR:
11870   case AMDGPUISD::BUFFER_ATOMIC_INC:
11871   case AMDGPUISD::BUFFER_ATOMIC_DEC:
11872   case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
11873   case AMDGPUISD::BUFFER_ATOMIC_CSUB:
11874   case AMDGPUISD::BUFFER_ATOMIC_FADD:
11875   case AMDGPUISD::BUFFER_ATOMIC_FMIN:
11876   case AMDGPUISD::BUFFER_ATOMIC_FMAX:
11877     // Target-specific read-modify-write atomics are sources of divergence.
11878     return true;
11879   default:
11880     if (auto *A = dyn_cast<AtomicSDNode>(N)) {
11881       // Generic read-modify-write atomics are sources of divergence.
11882       return A->readMem() && A->writeMem();
11883     }
11884     return false;
11885   }
11886 }
11887 
11888 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
11889                                                EVT VT) const {
11890   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
11891   case MVT::f32:
11892     return hasFP32Denormals(DAG.getMachineFunction());
11893   case MVT::f64:
11894   case MVT::f16:
11895     return hasFP64FP16Denormals(DAG.getMachineFunction());
11896   default:
11897     return false;
11898   }
11899 }
11900 
11901 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
11902                                                     const SelectionDAG &DAG,
11903                                                     bool SNaN,
11904                                                     unsigned Depth) const {
11905   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
11906     const MachineFunction &MF = DAG.getMachineFunction();
11907     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11908 
11909     if (Info->getMode().DX10Clamp)
11910       return true; // Clamped to 0.
11911     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
11912   }
11913 
11914   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
11915                                                             SNaN, Depth);
11916 }
11917 
11918 // Global FP atomic instructions have a hardcoded FP mode and do not support
11919 // FP32 denormals, and only support v2f16 denormals.
11920 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
11921   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
11922   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
11923   if (&Flt == &APFloat::IEEEsingle())
11924     return DenormMode == DenormalMode::getPreserveSign();
11925   return DenormMode == DenormalMode::getIEEE();
11926 }
11927 
11928 TargetLowering::AtomicExpansionKind
11929 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
11930   switch (RMW->getOperation()) {
11931   case AtomicRMWInst::FAdd: {
11932     Type *Ty = RMW->getType();
11933 
11934     // We don't have a way to support 16-bit atomics now, so just leave them
11935     // as-is.
11936     if (Ty->isHalfTy())
11937       return AtomicExpansionKind::None;
11938 
11939     if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
11940       return AtomicExpansionKind::CmpXChg;
11941 
11942     // TODO: Do have these for flat. Older targets also had them for buffers.
11943     unsigned AS = RMW->getPointerAddressSpace();
11944 
11945     if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) &&
11946          Subtarget->hasAtomicFaddInsts()) {
11947       if (!fpModeMatchesGlobalFPAtomicMode(RMW) ||
11948           RMW->getFunction()->getFnAttribute("amdgpu-unsafe-fp-atomics")
11949               .getValueAsString() != "true")
11950         return AtomicExpansionKind::CmpXChg;
11951 
11952       if (Subtarget->hasGFX90AInsts())
11953         return (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS) ?
11954           AtomicExpansionKind::CmpXChg : AtomicExpansionKind::None;
11955 
11956       if (!Subtarget->hasGFX90AInsts() && AS != AMDGPUAS::GLOBAL_ADDRESS)
11957         return AtomicExpansionKind::CmpXChg;
11958 
11959       return RMW->use_empty() ? AtomicExpansionKind::None :
11960                                 AtomicExpansionKind::CmpXChg;
11961     }
11962 
11963     // DS FP atomics do repect the denormal mode, but the rounding mode is fixed
11964     // to round-to-nearest-even.
11965     // The only exception is DS_ADD_F64 which never flushes regardless of mode.
11966     if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) {
11967       return (Ty->isDoubleTy() && !fpModeMatchesGlobalFPAtomicMode(RMW)) ?
11968         AtomicExpansionKind::CmpXChg : AtomicExpansionKind::None;
11969     }
11970 
11971     return AtomicExpansionKind::CmpXChg;
11972   }
11973   default:
11974     break;
11975   }
11976 
11977   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
11978 }
11979 
11980 const TargetRegisterClass *
11981 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
11982   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
11983   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11984   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
11985     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
11986                                                : &AMDGPU::SReg_32RegClass;
11987   if (!TRI->isSGPRClass(RC) && !isDivergent)
11988     return TRI->getEquivalentSGPRClass(RC);
11989   else if (TRI->isSGPRClass(RC) && isDivergent)
11990     return TRI->getEquivalentVGPRClass(RC);
11991 
11992   return RC;
11993 }
11994 
11995 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
11996 // uniform values (as produced by the mask results of control flow intrinsics)
11997 // used outside of divergent blocks. The phi users need to also be treated as
11998 // always uniform.
11999 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
12000                       unsigned WaveSize) {
12001   // FIXME: We asssume we never cast the mask results of a control flow
12002   // intrinsic.
12003   // Early exit if the type won't be consistent as a compile time hack.
12004   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
12005   if (!IT || IT->getBitWidth() != WaveSize)
12006     return false;
12007 
12008   if (!isa<Instruction>(V))
12009     return false;
12010   if (!Visited.insert(V).second)
12011     return false;
12012   bool Result = false;
12013   for (auto U : V->users()) {
12014     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
12015       if (V == U->getOperand(1)) {
12016         switch (Intrinsic->getIntrinsicID()) {
12017         default:
12018           Result = false;
12019           break;
12020         case Intrinsic::amdgcn_if_break:
12021         case Intrinsic::amdgcn_if:
12022         case Intrinsic::amdgcn_else:
12023           Result = true;
12024           break;
12025         }
12026       }
12027       if (V == U->getOperand(0)) {
12028         switch (Intrinsic->getIntrinsicID()) {
12029         default:
12030           Result = false;
12031           break;
12032         case Intrinsic::amdgcn_end_cf:
12033         case Intrinsic::amdgcn_loop:
12034           Result = true;
12035           break;
12036         }
12037       }
12038     } else {
12039       Result = hasCFUser(U, Visited, WaveSize);
12040     }
12041     if (Result)
12042       break;
12043   }
12044   return Result;
12045 }
12046 
12047 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
12048                                                const Value *V) const {
12049   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
12050     if (CI->isInlineAsm()) {
12051       // FIXME: This cannot give a correct answer. This should only trigger in
12052       // the case where inline asm returns mixed SGPR and VGPR results, used
12053       // outside the defining block. We don't have a specific result to
12054       // consider, so this assumes if any value is SGPR, the overall register
12055       // also needs to be SGPR.
12056       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
12057       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
12058           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
12059       for (auto &TC : TargetConstraints) {
12060         if (TC.Type == InlineAsm::isOutput) {
12061           ComputeConstraintToUse(TC, SDValue());
12062           unsigned AssignedReg;
12063           const TargetRegisterClass *RC;
12064           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
12065               SIRI, TC.ConstraintCode, TC.ConstraintVT);
12066           if (RC) {
12067             MachineRegisterInfo &MRI = MF.getRegInfo();
12068             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
12069               return true;
12070             else if (SIRI->isSGPRClass(RC))
12071               return true;
12072           }
12073         }
12074       }
12075     }
12076   }
12077   SmallPtrSet<const Value *, 16> Visited;
12078   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
12079 }
12080 
12081 std::pair<int, MVT>
12082 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
12083                                           Type *Ty) const {
12084   auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
12085   auto Size = DL.getTypeSizeInBits(Ty);
12086   // Maximum load or store can handle 8 dwords for scalar and 4 for
12087   // vector ALU. Let's assume anything above 8 dwords is expensive
12088   // even if legal.
12089   if (Size <= 256)
12090     return Cost;
12091 
12092   Cost.first = (Size + 255) / 256;
12093   return Cost;
12094 }
12095