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/Analysis/OptimizationRemarkEmitter.h"
23 #include "llvm/BinaryFormat/ELF.h"
24 #include "llvm/CodeGen/Analysis.h"
25 #include "llvm/CodeGen/FunctionLoweringInfo.h"
26 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
27 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineLoopInfo.h"
30 #include "llvm/IR/DiagnosticInfo.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/IntrinsicsAMDGPU.h"
33 #include "llvm/IR/IntrinsicsR600.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/KnownBits.h"
36 
37 using namespace llvm;
38 
39 #define DEBUG_TYPE "si-lower"
40 
41 STATISTIC(NumTailCalls, "Number of tail calls");
42 
43 static cl::opt<bool> DisableLoopAlignment(
44   "amdgpu-disable-loop-alignment",
45   cl::desc("Do not align and prefetch loops"),
46   cl::init(false));
47 
48 static cl::opt<bool> VGPRReserveforSGPRSpill(
49     "amdgpu-reserve-vgpr-for-sgpr-spill",
50     cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true));
51 
52 static cl::opt<bool> UseDivergentRegisterIndexing(
53   "amdgpu-use-divergent-register-indexing",
54   cl::Hidden,
55   cl::desc("Use indirect register addressing for divergent indexes"),
56   cl::init(false));
57 
58 static bool hasFP32Denormals(const MachineFunction &MF) {
59   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
60   return Info->getMode().allFP32Denormals();
61 }
62 
63 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
64   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
65   return Info->getMode().allFP64FP16Denormals();
66 }
67 
68 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
69   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
70   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
71     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
72       return AMDGPU::SGPR0 + Reg;
73     }
74   }
75   llvm_unreachable("Cannot allocate sgpr");
76 }
77 
78 SITargetLowering::SITargetLowering(const TargetMachine &TM,
79                                    const GCNSubtarget &STI)
80     : AMDGPUTargetLowering(TM, STI),
81       Subtarget(&STI) {
82   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
83   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
84 
85   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
86   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
87 
88   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
89 
90   const SIRegisterInfo *TRI = STI.getRegisterInfo();
91   const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class();
92 
93   addRegisterClass(MVT::f64, V64RegClass);
94   addRegisterClass(MVT::v2f32, V64RegClass);
95 
96   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
97   addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96));
98 
99   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
100   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
101 
102   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
103   addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128));
104 
105   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
106   addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160));
107 
108   addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass);
109   addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192));
110 
111   addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass);
112   addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192));
113 
114   addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass);
115   addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224));
116 
117   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
118   addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256));
119 
120   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
121   addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256));
122 
123   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
124   addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512));
125 
126   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
127   addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512));
128 
129   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
130   addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024));
131 
132   if (Subtarget->has16BitInsts()) {
133     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
134     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
135 
136     // Unless there are also VOP3P operations, not operations are really legal.
137     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
138     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
139     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
140     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
141   }
142 
143   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
144   addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024));
145 
146   computeRegisterProperties(Subtarget->getRegisterInfo());
147 
148   // The boolean content concept here is too inflexible. Compares only ever
149   // really produce a 1-bit result. Any copy/extend from these will turn into a
150   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
151   // it's what most targets use.
152   setBooleanContents(ZeroOrOneBooleanContent);
153   setBooleanVectorContents(ZeroOrOneBooleanContent);
154 
155   // We need to custom lower vector stores from local memory
156   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
157   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
158   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
159   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
160   setOperationAction(ISD::LOAD, MVT::v6i32, Custom);
161   setOperationAction(ISD::LOAD, MVT::v7i32, Custom);
162   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
163   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
164   setOperationAction(ISD::LOAD, MVT::i1, Custom);
165   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
166 
167   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
168   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
169   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
170   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
171   setOperationAction(ISD::STORE, MVT::v6i32, Custom);
172   setOperationAction(ISD::STORE, MVT::v7i32, Custom);
173   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
174   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
175   setOperationAction(ISD::STORE, MVT::i1, Custom);
176   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
177 
178   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
179   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
180   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
181   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
182   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
183   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
184   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
185   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
186   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
187   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
188   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
189   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
190   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
191   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
192   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
193   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
194 
195   setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand);
196   setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand);
197   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
198   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
199   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
200   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
201   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
202 
203   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
204   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
205 
206   setOperationAction(ISD::SELECT, MVT::i1, Promote);
207   setOperationAction(ISD::SELECT, MVT::i64, Custom);
208   setOperationAction(ISD::SELECT, MVT::f64, Promote);
209   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
210 
211   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
212   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
213   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
214   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
215   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
216 
217   setOperationAction(ISD::SETCC, MVT::i1, Promote);
218   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
219   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
220   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
221 
222   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
223   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
224   setOperationAction(ISD::TRUNCATE, MVT::v3i32, Expand);
225   setOperationAction(ISD::FP_ROUND, MVT::v3f32, Expand);
226   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
227   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
228   setOperationAction(ISD::TRUNCATE, MVT::v5i32, Expand);
229   setOperationAction(ISD::FP_ROUND, MVT::v5f32, Expand);
230   setOperationAction(ISD::TRUNCATE, MVT::v6i32, Expand);
231   setOperationAction(ISD::FP_ROUND, MVT::v6f32, Expand);
232   setOperationAction(ISD::TRUNCATE, MVT::v7i32, Expand);
233   setOperationAction(ISD::FP_ROUND, MVT::v7f32, Expand);
234   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
235   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
236   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
237   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
238 
239   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
240   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
241   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
242   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
243   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
244   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
245   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
246   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
247 
248   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
249   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
250   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
251   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
252   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
253   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
254 
255   setOperationAction(ISD::UADDO, MVT::i32, Legal);
256   setOperationAction(ISD::USUBO, MVT::i32, Legal);
257 
258   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
259   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
260 
261   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
262   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
263   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
264 
265 #if 0
266   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
267   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
268 #endif
269 
270   // We only support LOAD/STORE and vector manipulation ops for vectors
271   // with > 4 elements.
272   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
273                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
274                   MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32,
275                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
276                   MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) {
277     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
278       switch (Op) {
279       case ISD::LOAD:
280       case ISD::STORE:
281       case ISD::BUILD_VECTOR:
282       case ISD::BITCAST:
283       case ISD::EXTRACT_VECTOR_ELT:
284       case ISD::INSERT_VECTOR_ELT:
285       case ISD::EXTRACT_SUBVECTOR:
286       case ISD::SCALAR_TO_VECTOR:
287         break;
288       case ISD::INSERT_SUBVECTOR:
289       case ISD::CONCAT_VECTORS:
290         setOperationAction(Op, VT, Custom);
291         break;
292       default:
293         setOperationAction(Op, VT, Expand);
294         break;
295       }
296     }
297   }
298 
299   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
300 
301   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
302   // is expanded to avoid having two separate loops in case the index is a VGPR.
303 
304   // Most operations are naturally 32-bit vector operations. We only support
305   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
306   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
307     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
308     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
309 
310     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
311     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
312 
313     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
314     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
315 
316     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
317     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
318   }
319 
320   for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) {
321     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
322     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32);
323 
324     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
325     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32);
326 
327     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
328     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32);
329 
330     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
331     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32);
332   }
333 
334   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
335     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
336     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
337 
338     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
339     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
340 
341     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
342     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
343 
344     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
345     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
346   }
347 
348   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
349     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
350     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
351 
352     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
353     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
354 
355     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
356     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
357 
358     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
359     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
360   }
361 
362   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
363     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
364     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
365 
366     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
367     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
368 
369     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
370     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
371 
372     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
373     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
374   }
375 
376   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
377   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
378   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
379   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
380 
381   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
382   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
383 
384   // Avoid stack access for these.
385   // TODO: Generalize to more vector types.
386   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
387   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
388   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
389   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
390 
391   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
392   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
393   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
394   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
395   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
396   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
397 
398   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
399   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
400   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
401   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
402 
403   // Deal with vec3 vector operations when widened to vec4.
404   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
405   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
406   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
407   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
408 
409   // Deal with vec5/6/7 vector operations when widened to vec8.
410   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
411   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
412   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6i32, Custom);
413   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6f32, Custom);
414   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7i32, Custom);
415   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7f32, Custom);
416   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
417   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
418 
419   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
420   // and output demarshalling
421   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
422   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
423 
424   // We can't return success/failure, only the old value,
425   // let LLVM add the comparison
426   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
427   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
428 
429   if (Subtarget->hasFlatAddressSpace()) {
430     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
431     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
432   }
433 
434   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
435   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
436 
437   // FIXME: This should be narrowed to i32, but that only happens if i64 is
438   // illegal.
439   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
440   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
441   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
442 
443   // On SI this is s_memtime and s_memrealtime on VI.
444   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
445   setOperationAction(ISD::TRAP, MVT::Other, Custom);
446   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
447 
448   if (Subtarget->has16BitInsts()) {
449     setOperationAction(ISD::FPOW, MVT::f16, Promote);
450     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
451     setOperationAction(ISD::FLOG, MVT::f16, Custom);
452     setOperationAction(ISD::FEXP, MVT::f16, Custom);
453     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
454   }
455 
456   if (Subtarget->hasMadMacF32Insts())
457     setOperationAction(ISD::FMAD, MVT::f32, Legal);
458 
459   if (!Subtarget->hasBFI()) {
460     // fcopysign can be done in a single instruction with BFI.
461     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
462     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
463   }
464 
465   if (!Subtarget->hasBCNT(32))
466     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
467 
468   if (!Subtarget->hasBCNT(64))
469     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
470 
471   if (Subtarget->hasFFBH()) {
472     setOperationAction(ISD::CTLZ, MVT::i32, Custom);
473     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
474   }
475 
476   if (Subtarget->hasFFBL()) {
477     setOperationAction(ISD::CTTZ, MVT::i32, Custom);
478     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
479   }
480 
481   // We only really have 32-bit BFE instructions (and 16-bit on VI).
482   //
483   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
484   // effort to match them now. We want this to be false for i64 cases when the
485   // extraction isn't restricted to the upper or lower half. Ideally we would
486   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
487   // span the midpoint are probably relatively rare, so don't worry about them
488   // for now.
489   if (Subtarget->hasBFE())
490     setHasExtractBitsInsn(true);
491 
492   // Clamp modifier on add/sub
493   if (Subtarget->hasIntClamp()) {
494     setOperationAction(ISD::UADDSAT, MVT::i32, Legal);
495     setOperationAction(ISD::USUBSAT, MVT::i32, Legal);
496   }
497 
498   if (Subtarget->hasAddNoCarry()) {
499     setOperationAction(ISD::SADDSAT, MVT::i16, Legal);
500     setOperationAction(ISD::SSUBSAT, MVT::i16, Legal);
501     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
502     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
503   }
504 
505   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
506   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
507   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
508   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
509 
510 
511   // These are really only legal for ieee_mode functions. We should be avoiding
512   // them for functions that don't have ieee_mode enabled, so just say they are
513   // legal.
514   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
515   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
516   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
517   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
518 
519 
520   if (Subtarget->haveRoundOpsF64()) {
521     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
522     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
523     setOperationAction(ISD::FRINT, MVT::f64, Legal);
524   } else {
525     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
526     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
527     setOperationAction(ISD::FRINT, MVT::f64, Custom);
528     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
529   }
530 
531   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
532 
533   setOperationAction(ISD::FSIN, MVT::f32, Custom);
534   setOperationAction(ISD::FCOS, MVT::f32, Custom);
535   setOperationAction(ISD::FDIV, MVT::f32, Custom);
536   setOperationAction(ISD::FDIV, MVT::f64, Custom);
537 
538   if (Subtarget->has16BitInsts()) {
539     setOperationAction(ISD::Constant, MVT::i16, Legal);
540 
541     setOperationAction(ISD::SMIN, MVT::i16, Legal);
542     setOperationAction(ISD::SMAX, MVT::i16, Legal);
543 
544     setOperationAction(ISD::UMIN, MVT::i16, Legal);
545     setOperationAction(ISD::UMAX, MVT::i16, Legal);
546 
547     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
548     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
549 
550     setOperationAction(ISD::ROTR, MVT::i16, Expand);
551     setOperationAction(ISD::ROTL, MVT::i16, Expand);
552 
553     setOperationAction(ISD::SDIV, MVT::i16, Promote);
554     setOperationAction(ISD::UDIV, MVT::i16, Promote);
555     setOperationAction(ISD::SREM, MVT::i16, Promote);
556     setOperationAction(ISD::UREM, MVT::i16, Promote);
557     setOperationAction(ISD::UADDSAT, MVT::i16, Legal);
558     setOperationAction(ISD::USUBSAT, MVT::i16, Legal);
559 
560     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
561 
562     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
563     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
564     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
565     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
566     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
567 
568     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
569 
570     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
571 
572     setOperationAction(ISD::LOAD, MVT::i16, Custom);
573 
574     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
575 
576     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
577     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
578     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
579     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
580 
581     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Custom);
582     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Custom);
583 
584     // F16 - Constant Actions.
585     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
586 
587     // F16 - Load/Store Actions.
588     setOperationAction(ISD::LOAD, MVT::f16, Promote);
589     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
590     setOperationAction(ISD::STORE, MVT::f16, Promote);
591     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
592 
593     // F16 - VOP1 Actions.
594     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
595     setOperationAction(ISD::FCOS, MVT::f16, Custom);
596     setOperationAction(ISD::FSIN, MVT::f16, Custom);
597 
598     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
599     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
600 
601     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
602     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
603     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
604     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
605     setOperationAction(ISD::FROUND, MVT::f16, Custom);
606 
607     // F16 - VOP2 Actions.
608     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
609     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
610 
611     setOperationAction(ISD::FDIV, MVT::f16, Custom);
612 
613     // F16 - VOP3 Actions.
614     setOperationAction(ISD::FMA, MVT::f16, Legal);
615     if (STI.hasMadF16())
616       setOperationAction(ISD::FMAD, MVT::f16, Legal);
617 
618     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
619       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
620         switch (Op) {
621         case ISD::LOAD:
622         case ISD::STORE:
623         case ISD::BUILD_VECTOR:
624         case ISD::BITCAST:
625         case ISD::EXTRACT_VECTOR_ELT:
626         case ISD::INSERT_VECTOR_ELT:
627         case ISD::INSERT_SUBVECTOR:
628         case ISD::EXTRACT_SUBVECTOR:
629         case ISD::SCALAR_TO_VECTOR:
630           break;
631         case ISD::CONCAT_VECTORS:
632           setOperationAction(Op, VT, Custom);
633           break;
634         default:
635           setOperationAction(Op, VT, Expand);
636           break;
637         }
638       }
639     }
640 
641     // v_perm_b32 can handle either of these.
642     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
643     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
644     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
645 
646     // XXX - Do these do anything? Vector constants turn into build_vector.
647     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
648     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
649 
650     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
651     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
652 
653     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
654     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
655     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
656     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
657 
658     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
659     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
660     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
661     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
662 
663     setOperationAction(ISD::AND, MVT::v2i16, Promote);
664     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
665     setOperationAction(ISD::OR, MVT::v2i16, Promote);
666     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
667     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
668     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
669 
670     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
671     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
672     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
673     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
674 
675     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
676     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
677     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
678     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
679 
680     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
681     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
682     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
683     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
684 
685     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
686     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
687     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
688 
689     if (!Subtarget->hasVOP3PInsts()) {
690       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
691       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
692     }
693 
694     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
695     // This isn't really legal, but this avoids the legalizer unrolling it (and
696     // allows matching fneg (fabs x) patterns)
697     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
698 
699     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
700     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
701     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
702     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
703 
704     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
705     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
706 
707     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
708     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
709   }
710 
711   if (Subtarget->hasVOP3PInsts()) {
712     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
713     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
714     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
715     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
716     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
717     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
718     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
719     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
720     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
721     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
722 
723     setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal);
724     setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal);
725     setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal);
726     setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal);
727 
728     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
729     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
730     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
731 
732     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
733     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
734 
735     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
736 
737     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
738     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
739 
740     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
741     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
742 
743     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
744     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
745     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
746     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
747     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
748     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
749 
750     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
751     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
752     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
753     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
754 
755     setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom);
756     setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom);
757     setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom);
758     setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom);
759 
760     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
761     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
762     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
763 
764     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
765     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
766 
767     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
768     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
769     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
770 
771     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
772     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
773     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
774 
775     if (Subtarget->hasPackedFP32Ops()) {
776       setOperationAction(ISD::FADD, MVT::v2f32, Legal);
777       setOperationAction(ISD::FMUL, MVT::v2f32, Legal);
778       setOperationAction(ISD::FMA,  MVT::v2f32, Legal);
779       setOperationAction(ISD::FNEG, MVT::v2f32, Legal);
780 
781       for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) {
782         setOperationAction(ISD::FADD, VT, Custom);
783         setOperationAction(ISD::FMUL, VT, Custom);
784         setOperationAction(ISD::FMA, VT, Custom);
785       }
786     }
787   }
788 
789   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
790   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
791 
792   if (Subtarget->has16BitInsts()) {
793     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
794     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
795     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
796     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
797   } else {
798     // Legalization hack.
799     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
800     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
801 
802     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
803     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
804   }
805 
806   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
807     setOperationAction(ISD::SELECT, VT, Custom);
808   }
809 
810   setOperationAction(ISD::SMULO, MVT::i64, Custom);
811   setOperationAction(ISD::UMULO, MVT::i64, Custom);
812 
813   if (Subtarget->hasMad64_32()) {
814     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
815     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
816   }
817 
818   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
819   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
820   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
821   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
822   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
823   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
824   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
825 
826   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
827   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
828   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom);
829   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom);
830   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
831   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
832   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
833   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
834   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
835   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
836   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
837 
838   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
839   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
840   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
841   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom);
842   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom);
843   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
844   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
845   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
846   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
847   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
848 
849   setTargetDAGCombine(ISD::ADD);
850   setTargetDAGCombine(ISD::ADDCARRY);
851   setTargetDAGCombine(ISD::SUB);
852   setTargetDAGCombine(ISD::SUBCARRY);
853   setTargetDAGCombine(ISD::FADD);
854   setTargetDAGCombine(ISD::FSUB);
855   setTargetDAGCombine(ISD::FMINNUM);
856   setTargetDAGCombine(ISD::FMAXNUM);
857   setTargetDAGCombine(ISD::FMINNUM_IEEE);
858   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
859   setTargetDAGCombine(ISD::FMA);
860   setTargetDAGCombine(ISD::SMIN);
861   setTargetDAGCombine(ISD::SMAX);
862   setTargetDAGCombine(ISD::UMIN);
863   setTargetDAGCombine(ISD::UMAX);
864   setTargetDAGCombine(ISD::SETCC);
865   setTargetDAGCombine(ISD::AND);
866   setTargetDAGCombine(ISD::OR);
867   setTargetDAGCombine(ISD::XOR);
868   setTargetDAGCombine(ISD::SINT_TO_FP);
869   setTargetDAGCombine(ISD::UINT_TO_FP);
870   setTargetDAGCombine(ISD::FCANONICALIZE);
871   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
872   setTargetDAGCombine(ISD::ZERO_EXTEND);
873   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
874   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
875   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
876 
877   // All memory operations. Some folding on the pointer operand is done to help
878   // matching the constant offsets in the addressing modes.
879   setTargetDAGCombine(ISD::LOAD);
880   setTargetDAGCombine(ISD::STORE);
881   setTargetDAGCombine(ISD::ATOMIC_LOAD);
882   setTargetDAGCombine(ISD::ATOMIC_STORE);
883   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
884   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
885   setTargetDAGCombine(ISD::ATOMIC_SWAP);
886   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
887   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
888   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
889   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
890   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
891   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
892   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
893   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
894   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
895   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
896   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
897   setTargetDAGCombine(ISD::INTRINSIC_VOID);
898   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
899 
900   // FIXME: In other contexts we pretend this is a per-function property.
901   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
902 
903   setSchedulingPreference(Sched::RegPressure);
904 }
905 
906 const GCNSubtarget *SITargetLowering::getSubtarget() const {
907   return Subtarget;
908 }
909 
910 //===----------------------------------------------------------------------===//
911 // TargetLowering queries
912 //===----------------------------------------------------------------------===//
913 
914 // v_mad_mix* support a conversion from f16 to f32.
915 //
916 // There is only one special case when denormals are enabled we don't currently,
917 // where this is OK to use.
918 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
919                                        EVT DestVT, EVT SrcVT) const {
920   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
921           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
922     DestVT.getScalarType() == MVT::f32 &&
923     SrcVT.getScalarType() == MVT::f16 &&
924     // TODO: This probably only requires no input flushing?
925     !hasFP32Denormals(DAG.getMachineFunction());
926 }
927 
928 bool SITargetLowering::isFPExtFoldable(const MachineInstr &MI, unsigned Opcode,
929                                        LLT DestTy, LLT SrcTy) const {
930   return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) ||
931           (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) &&
932          DestTy.getScalarSizeInBits() == 32 &&
933          SrcTy.getScalarSizeInBits() == 16 &&
934          // TODO: This probably only requires no input flushing?
935          !hasFP32Denormals(*MI.getMF());
936 }
937 
938 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
939   // SI has some legal vector types, but no legal vector operations. Say no
940   // shuffles are legal in order to prefer scalarizing some vector operations.
941   return false;
942 }
943 
944 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
945                                                     CallingConv::ID CC,
946                                                     EVT VT) const {
947   if (CC == CallingConv::AMDGPU_KERNEL)
948     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
949 
950   if (VT.isVector()) {
951     EVT ScalarVT = VT.getScalarType();
952     unsigned Size = ScalarVT.getSizeInBits();
953     if (Size == 16) {
954       if (Subtarget->has16BitInsts())
955         return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
956       return VT.isInteger() ? MVT::i32 : MVT::f32;
957     }
958 
959     if (Size < 16)
960       return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
961     return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
962   }
963 
964   if (VT.getSizeInBits() > 32)
965     return MVT::i32;
966 
967   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
968 }
969 
970 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
971                                                          CallingConv::ID CC,
972                                                          EVT VT) const {
973   if (CC == CallingConv::AMDGPU_KERNEL)
974     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
975 
976   if (VT.isVector()) {
977     unsigned NumElts = VT.getVectorNumElements();
978     EVT ScalarVT = VT.getScalarType();
979     unsigned Size = ScalarVT.getSizeInBits();
980 
981     // FIXME: Should probably promote 8-bit vectors to i16.
982     if (Size == 16 && Subtarget->has16BitInsts())
983       return (NumElts + 1) / 2;
984 
985     if (Size <= 32)
986       return NumElts;
987 
988     if (Size > 32)
989       return NumElts * ((Size + 31) / 32);
990   } else if (VT.getSizeInBits() > 32)
991     return (VT.getSizeInBits() + 31) / 32;
992 
993   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
994 }
995 
996 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
997   LLVMContext &Context, CallingConv::ID CC,
998   EVT VT, EVT &IntermediateVT,
999   unsigned &NumIntermediates, MVT &RegisterVT) const {
1000   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
1001     unsigned NumElts = VT.getVectorNumElements();
1002     EVT ScalarVT = VT.getScalarType();
1003     unsigned Size = ScalarVT.getSizeInBits();
1004     // FIXME: We should fix the ABI to be the same on targets without 16-bit
1005     // support, but unless we can properly handle 3-vectors, it will be still be
1006     // inconsistent.
1007     if (Size == 16 && Subtarget->has16BitInsts()) {
1008       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
1009       IntermediateVT = RegisterVT;
1010       NumIntermediates = (NumElts + 1) / 2;
1011       return NumIntermediates;
1012     }
1013 
1014     if (Size == 32) {
1015       RegisterVT = ScalarVT.getSimpleVT();
1016       IntermediateVT = RegisterVT;
1017       NumIntermediates = NumElts;
1018       return NumIntermediates;
1019     }
1020 
1021     if (Size < 16 && Subtarget->has16BitInsts()) {
1022       // FIXME: Should probably form v2i16 pieces
1023       RegisterVT = MVT::i16;
1024       IntermediateVT = ScalarVT;
1025       NumIntermediates = NumElts;
1026       return NumIntermediates;
1027     }
1028 
1029 
1030     if (Size != 16 && Size <= 32) {
1031       RegisterVT = MVT::i32;
1032       IntermediateVT = ScalarVT;
1033       NumIntermediates = NumElts;
1034       return NumIntermediates;
1035     }
1036 
1037     if (Size > 32) {
1038       RegisterVT = MVT::i32;
1039       IntermediateVT = RegisterVT;
1040       NumIntermediates = NumElts * ((Size + 31) / 32);
1041       return NumIntermediates;
1042     }
1043   }
1044 
1045   return TargetLowering::getVectorTypeBreakdownForCallingConv(
1046     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
1047 }
1048 
1049 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
1050   assert(DMaskLanes != 0);
1051 
1052   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1053     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
1054     return EVT::getVectorVT(Ty->getContext(),
1055                             EVT::getEVT(VT->getElementType()),
1056                             NumElts);
1057   }
1058 
1059   return EVT::getEVT(Ty);
1060 }
1061 
1062 // Peek through TFE struct returns to only use the data size.
1063 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
1064   auto *ST = dyn_cast<StructType>(Ty);
1065   if (!ST)
1066     return memVTFromImageData(Ty, DMaskLanes);
1067 
1068   // Some intrinsics return an aggregate type - special case to work out the
1069   // correct memVT.
1070   //
1071   // Only limited forms of aggregate type currently expected.
1072   if (ST->getNumContainedTypes() != 2 ||
1073       !ST->getContainedType(1)->isIntegerTy(32))
1074     return EVT();
1075   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
1076 }
1077 
1078 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1079                                           const CallInst &CI,
1080                                           MachineFunction &MF,
1081                                           unsigned IntrID) const {
1082   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1083           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1084     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1085                                                   (Intrinsic::ID)IntrID);
1086     if (Attr.hasFnAttr(Attribute::ReadNone))
1087       return false;
1088 
1089     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1090 
1091     if (RsrcIntr->IsImage) {
1092       Info.ptrVal =
1093           MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1094       Info.align.reset();
1095     } else {
1096       Info.ptrVal =
1097           MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1098     }
1099 
1100     Info.flags = MachineMemOperand::MODereferenceable;
1101     if (Attr.hasFnAttr(Attribute::ReadOnly)) {
1102       unsigned DMaskLanes = 4;
1103 
1104       if (RsrcIntr->IsImage) {
1105         const AMDGPU::ImageDimIntrinsicInfo *Intr
1106           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1107         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1108           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1109 
1110         if (!BaseOpcode->Gather4) {
1111           // If this isn't a gather, we may have excess loaded elements in the
1112           // IR type. Check the dmask for the real number of elements loaded.
1113           unsigned DMask
1114             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1115           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1116         }
1117 
1118         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1119       } else
1120         Info.memVT = EVT::getEVT(CI.getType());
1121 
1122       // FIXME: What does alignment mean for an image?
1123       Info.opc = ISD::INTRINSIC_W_CHAIN;
1124       Info.flags |= MachineMemOperand::MOLoad;
1125     } else if (Attr.hasFnAttr(Attribute::WriteOnly)) {
1126       Info.opc = ISD::INTRINSIC_VOID;
1127 
1128       Type *DataTy = CI.getArgOperand(0)->getType();
1129       if (RsrcIntr->IsImage) {
1130         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1131         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1132         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1133       } else
1134         Info.memVT = EVT::getEVT(DataTy);
1135 
1136       Info.flags |= MachineMemOperand::MOStore;
1137     } else {
1138       // Atomic
1139       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1140                                             ISD::INTRINSIC_W_CHAIN;
1141       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1142       Info.flags = MachineMemOperand::MOLoad |
1143                    MachineMemOperand::MOStore |
1144                    MachineMemOperand::MODereferenceable;
1145 
1146       // XXX - Should this be volatile without known ordering?
1147       Info.flags |= MachineMemOperand::MOVolatile;
1148     }
1149     return true;
1150   }
1151 
1152   switch (IntrID) {
1153   case Intrinsic::amdgcn_atomic_inc:
1154   case Intrinsic::amdgcn_atomic_dec:
1155   case Intrinsic::amdgcn_ds_ordered_add:
1156   case Intrinsic::amdgcn_ds_ordered_swap:
1157   case Intrinsic::amdgcn_ds_fadd:
1158   case Intrinsic::amdgcn_ds_fmin:
1159   case Intrinsic::amdgcn_ds_fmax: {
1160     Info.opc = ISD::INTRINSIC_W_CHAIN;
1161     Info.memVT = MVT::getVT(CI.getType());
1162     Info.ptrVal = CI.getOperand(0);
1163     Info.align.reset();
1164     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1165 
1166     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1167     if (!Vol->isZero())
1168       Info.flags |= MachineMemOperand::MOVolatile;
1169 
1170     return true;
1171   }
1172   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1173     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1174 
1175     Info.opc = ISD::INTRINSIC_W_CHAIN;
1176     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1177     Info.ptrVal =
1178         MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1179     Info.align.reset();
1180     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1181 
1182     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1183     if (!Vol || !Vol->isZero())
1184       Info.flags |= MachineMemOperand::MOVolatile;
1185 
1186     return true;
1187   }
1188   case Intrinsic::amdgcn_ds_append:
1189   case Intrinsic::amdgcn_ds_consume: {
1190     Info.opc = ISD::INTRINSIC_W_CHAIN;
1191     Info.memVT = MVT::getVT(CI.getType());
1192     Info.ptrVal = CI.getOperand(0);
1193     Info.align.reset();
1194     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1195 
1196     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1197     if (!Vol->isZero())
1198       Info.flags |= MachineMemOperand::MOVolatile;
1199 
1200     return true;
1201   }
1202   case Intrinsic::amdgcn_global_atomic_csub: {
1203     Info.opc = ISD::INTRINSIC_W_CHAIN;
1204     Info.memVT = MVT::getVT(CI.getType());
1205     Info.ptrVal = CI.getOperand(0);
1206     Info.align.reset();
1207     Info.flags = MachineMemOperand::MOLoad |
1208                  MachineMemOperand::MOStore |
1209                  MachineMemOperand::MOVolatile;
1210     return true;
1211   }
1212   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1213     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1214     Info.opc = ISD::INTRINSIC_W_CHAIN;
1215     Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1216     Info.ptrVal =
1217         MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1218     Info.align.reset();
1219     Info.flags = MachineMemOperand::MOLoad |
1220                  MachineMemOperand::MODereferenceable;
1221     return true;
1222   }
1223   case Intrinsic::amdgcn_global_atomic_fadd:
1224   case Intrinsic::amdgcn_global_atomic_fmin:
1225   case Intrinsic::amdgcn_global_atomic_fmax:
1226   case Intrinsic::amdgcn_flat_atomic_fadd:
1227   case Intrinsic::amdgcn_flat_atomic_fmin:
1228   case Intrinsic::amdgcn_flat_atomic_fmax: {
1229     Info.opc = ISD::INTRINSIC_W_CHAIN;
1230     Info.memVT = MVT::getVT(CI.getType());
1231     Info.ptrVal = CI.getOperand(0);
1232     Info.align.reset();
1233     Info.flags = MachineMemOperand::MOLoad |
1234                  MachineMemOperand::MOStore |
1235                  MachineMemOperand::MODereferenceable |
1236                  MachineMemOperand::MOVolatile;
1237     return true;
1238   }
1239   case Intrinsic::amdgcn_ds_gws_init:
1240   case Intrinsic::amdgcn_ds_gws_barrier:
1241   case Intrinsic::amdgcn_ds_gws_sema_v:
1242   case Intrinsic::amdgcn_ds_gws_sema_br:
1243   case Intrinsic::amdgcn_ds_gws_sema_p:
1244   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1245     Info.opc = ISD::INTRINSIC_VOID;
1246 
1247     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1248     Info.ptrVal =
1249         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1250 
1251     // This is an abstract access, but we need to specify a type and size.
1252     Info.memVT = MVT::i32;
1253     Info.size = 4;
1254     Info.align = Align(4);
1255 
1256     Info.flags = MachineMemOperand::MOStore;
1257     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1258       Info.flags = MachineMemOperand::MOLoad;
1259     return true;
1260   }
1261   default:
1262     return false;
1263   }
1264 }
1265 
1266 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1267                                             SmallVectorImpl<Value*> &Ops,
1268                                             Type *&AccessTy) const {
1269   switch (II->getIntrinsicID()) {
1270   case Intrinsic::amdgcn_atomic_inc:
1271   case Intrinsic::amdgcn_atomic_dec:
1272   case Intrinsic::amdgcn_ds_ordered_add:
1273   case Intrinsic::amdgcn_ds_ordered_swap:
1274   case Intrinsic::amdgcn_ds_append:
1275   case Intrinsic::amdgcn_ds_consume:
1276   case Intrinsic::amdgcn_ds_fadd:
1277   case Intrinsic::amdgcn_ds_fmin:
1278   case Intrinsic::amdgcn_ds_fmax:
1279   case Intrinsic::amdgcn_global_atomic_fadd:
1280   case Intrinsic::amdgcn_flat_atomic_fadd:
1281   case Intrinsic::amdgcn_flat_atomic_fmin:
1282   case Intrinsic::amdgcn_flat_atomic_fmax:
1283   case Intrinsic::amdgcn_global_atomic_csub: {
1284     Value *Ptr = II->getArgOperand(0);
1285     AccessTy = II->getType();
1286     Ops.push_back(Ptr);
1287     return true;
1288   }
1289   default:
1290     return false;
1291   }
1292 }
1293 
1294 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1295   if (!Subtarget->hasFlatInstOffsets()) {
1296     // Flat instructions do not have offsets, and only have the register
1297     // address.
1298     return AM.BaseOffs == 0 && AM.Scale == 0;
1299   }
1300 
1301   return AM.Scale == 0 &&
1302          (AM.BaseOffs == 0 ||
1303           Subtarget->getInstrInfo()->isLegalFLATOffset(
1304               AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT));
1305 }
1306 
1307 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1308   if (Subtarget->hasFlatGlobalInsts())
1309     return AM.Scale == 0 &&
1310            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1311                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1312                                     SIInstrFlags::FlatGlobal));
1313 
1314   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1315       // Assume the we will use FLAT for all global memory accesses
1316       // on VI.
1317       // FIXME: This assumption is currently wrong.  On VI we still use
1318       // MUBUF instructions for the r + i addressing mode.  As currently
1319       // implemented, the MUBUF instructions only work on buffer < 4GB.
1320       // It may be possible to support > 4GB buffers with MUBUF instructions,
1321       // by setting the stride value in the resource descriptor which would
1322       // increase the size limit to (stride * 4GB).  However, this is risky,
1323       // because it has never been validated.
1324     return isLegalFlatAddressingMode(AM);
1325   }
1326 
1327   return isLegalMUBUFAddressingMode(AM);
1328 }
1329 
1330 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1331   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1332   // additionally can do r + r + i with addr64. 32-bit has more addressing
1333   // mode options. Depending on the resource constant, it can also do
1334   // (i64 r0) + (i32 r1) * (i14 i).
1335   //
1336   // Private arrays end up using a scratch buffer most of the time, so also
1337   // assume those use MUBUF instructions. Scratch loads / stores are currently
1338   // implemented as mubuf instructions with offen bit set, so slightly
1339   // different than the normal addr64.
1340   if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1341     return false;
1342 
1343   // FIXME: Since we can split immediate into soffset and immediate offset,
1344   // would it make sense to allow any immediate?
1345 
1346   switch (AM.Scale) {
1347   case 0: // r + i or just i, depending on HasBaseReg.
1348     return true;
1349   case 1:
1350     return true; // We have r + r or r + i.
1351   case 2:
1352     if (AM.HasBaseReg) {
1353       // Reject 2 * r + r.
1354       return false;
1355     }
1356 
1357     // Allow 2 * r as r + r
1358     // Or  2 * r + i is allowed as r + r + i.
1359     return true;
1360   default: // Don't allow n * r
1361     return false;
1362   }
1363 }
1364 
1365 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1366                                              const AddrMode &AM, Type *Ty,
1367                                              unsigned AS, Instruction *I) const {
1368   // No global is ever allowed as a base.
1369   if (AM.BaseGV)
1370     return false;
1371 
1372   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1373     return isLegalGlobalAddressingMode(AM);
1374 
1375   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1376       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1377       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1378     // If the offset isn't a multiple of 4, it probably isn't going to be
1379     // correctly aligned.
1380     // FIXME: Can we get the real alignment here?
1381     if (AM.BaseOffs % 4 != 0)
1382       return isLegalMUBUFAddressingMode(AM);
1383 
1384     // There are no SMRD extloads, so if we have to do a small type access we
1385     // will use a MUBUF load.
1386     // FIXME?: We also need to do this if unaligned, but we don't know the
1387     // alignment here.
1388     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1389       return isLegalGlobalAddressingMode(AM);
1390 
1391     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1392       // SMRD instructions have an 8-bit, dword offset on SI.
1393       if (!isUInt<8>(AM.BaseOffs / 4))
1394         return false;
1395     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1396       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1397       // in 8-bits, it can use a smaller encoding.
1398       if (!isUInt<32>(AM.BaseOffs / 4))
1399         return false;
1400     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1401       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1402       if (!isUInt<20>(AM.BaseOffs))
1403         return false;
1404     } else
1405       llvm_unreachable("unhandled generation");
1406 
1407     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1408       return true;
1409 
1410     if (AM.Scale == 1 && AM.HasBaseReg)
1411       return true;
1412 
1413     return false;
1414 
1415   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1416     return isLegalMUBUFAddressingMode(AM);
1417   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1418              AS == AMDGPUAS::REGION_ADDRESS) {
1419     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1420     // field.
1421     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1422     // an 8-bit dword offset but we don't know the alignment here.
1423     if (!isUInt<16>(AM.BaseOffs))
1424       return false;
1425 
1426     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1427       return true;
1428 
1429     if (AM.Scale == 1 && AM.HasBaseReg)
1430       return true;
1431 
1432     return false;
1433   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1434              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1435     // For an unknown address space, this usually means that this is for some
1436     // reason being used for pure arithmetic, and not based on some addressing
1437     // computation. We don't have instructions that compute pointers with any
1438     // addressing modes, so treat them as having no offset like flat
1439     // instructions.
1440     return isLegalFlatAddressingMode(AM);
1441   }
1442 
1443   // Assume a user alias of global for unknown address spaces.
1444   return isLegalGlobalAddressingMode(AM);
1445 }
1446 
1447 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1448                                         const MachineFunction &MF) const {
1449   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1450     return (MemVT.getSizeInBits() <= 4 * 32);
1451   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1452     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1453     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1454   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1455     return (MemVT.getSizeInBits() <= 2 * 32);
1456   }
1457   return true;
1458 }
1459 
1460 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1461     unsigned Size, unsigned AddrSpace, Align Alignment,
1462     MachineMemOperand::Flags Flags, bool *IsFast) const {
1463   if (IsFast)
1464     *IsFast = false;
1465 
1466   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1467       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1468     // Check if alignment requirements for ds_read/write instructions are
1469     // disabled.
1470     if (Subtarget->hasUnalignedDSAccessEnabled() &&
1471         !Subtarget->hasLDSMisalignedBug()) {
1472       if (IsFast)
1473         *IsFast = Alignment != Align(2);
1474       return true;
1475     }
1476 
1477     // Either, the alignment requirements are "enabled", or there is an
1478     // unaligned LDS access related hardware bug though alignment requirements
1479     // are "disabled". In either case, we need to check for proper alignment
1480     // requirements.
1481     //
1482     if (Size == 64) {
1483       // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
1484       // can do a 4 byte aligned, 8 byte access in a single operation using
1485       // ds_read2/write2_b32 with adjacent offsets.
1486       bool AlignedBy4 = Alignment >= Align(4);
1487       if (IsFast)
1488         *IsFast = AlignedBy4;
1489 
1490       return AlignedBy4;
1491     }
1492     if (Size == 96) {
1493       // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
1494       // gfx8 and older.
1495       bool AlignedBy16 = Alignment >= Align(16);
1496       if (IsFast)
1497         *IsFast = AlignedBy16;
1498 
1499       return AlignedBy16;
1500     }
1501     if (Size == 128) {
1502       // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
1503       // gfx8 and older, but  we can do a 8 byte aligned, 16 byte access in a
1504       // single operation using ds_read2/write2_b64.
1505       bool AlignedBy8 = Alignment >= Align(8);
1506       if (IsFast)
1507         *IsFast = AlignedBy8;
1508 
1509       return AlignedBy8;
1510     }
1511   }
1512 
1513   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1514     bool AlignedBy4 = Alignment >= Align(4);
1515     if (IsFast)
1516       *IsFast = AlignedBy4;
1517 
1518     return AlignedBy4 ||
1519            Subtarget->enableFlatScratch() ||
1520            Subtarget->hasUnalignedScratchAccess();
1521   }
1522 
1523   // FIXME: We have to be conservative here and assume that flat operations
1524   // will access scratch.  If we had access to the IR function, then we
1525   // could determine if any private memory was used in the function.
1526   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1527       !Subtarget->hasUnalignedScratchAccess()) {
1528     bool AlignedBy4 = Alignment >= Align(4);
1529     if (IsFast)
1530       *IsFast = AlignedBy4;
1531 
1532     return AlignedBy4;
1533   }
1534 
1535   if (Subtarget->hasUnalignedBufferAccessEnabled() &&
1536       !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1537         AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1538     // If we have an uniform constant load, it still requires using a slow
1539     // buffer instruction if unaligned.
1540     if (IsFast) {
1541       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1542       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1543       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1544                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1545         Alignment >= Align(4) : Alignment != Align(2);
1546     }
1547 
1548     return true;
1549   }
1550 
1551   // Smaller than dword value must be aligned.
1552   if (Size < 32)
1553     return false;
1554 
1555   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1556   // byte-address are ignored, thus forcing Dword alignment.
1557   // This applies to private, global, and constant memory.
1558   if (IsFast)
1559     *IsFast = true;
1560 
1561   return Size >= 32 && Alignment >= Align(4);
1562 }
1563 
1564 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1565     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1566     bool *IsFast) const {
1567   if (IsFast)
1568     *IsFast = false;
1569 
1570   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1571   // which isn't a simple VT.
1572   // Until MVT is extended to handle this, simply check for the size and
1573   // rely on the condition below: allow accesses if the size is a multiple of 4.
1574   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1575                            VT.getStoreSize() > 16)) {
1576     return false;
1577   }
1578 
1579   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1580                                             Alignment, Flags, IsFast);
1581 }
1582 
1583 EVT SITargetLowering::getOptimalMemOpType(
1584     const MemOp &Op, const AttributeList &FuncAttributes) const {
1585   // FIXME: Should account for address space here.
1586 
1587   // The default fallback uses the private pointer size as a guess for a type to
1588   // use. Make sure we switch these to 64-bit accesses.
1589 
1590   if (Op.size() >= 16 &&
1591       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1592     return MVT::v4i32;
1593 
1594   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1595     return MVT::v2i32;
1596 
1597   // Use the default.
1598   return MVT::Other;
1599 }
1600 
1601 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1602   const MemSDNode *MemNode = cast<MemSDNode>(N);
1603   const Value *Ptr = MemNode->getMemOperand()->getValue();
1604   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1605   return I && I->getMetadata("amdgpu.noclobber");
1606 }
1607 
1608 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1609   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1610          AS == AMDGPUAS::PRIVATE_ADDRESS;
1611 }
1612 
1613 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1614                                            unsigned DestAS) const {
1615   // Flat -> private/local is a simple truncate.
1616   // Flat -> global is no-op
1617   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1618     return true;
1619 
1620   const GCNTargetMachine &TM =
1621       static_cast<const GCNTargetMachine &>(getTargetMachine());
1622   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1623 }
1624 
1625 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1626   const MemSDNode *MemNode = cast<MemSDNode>(N);
1627 
1628   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1629 }
1630 
1631 TargetLoweringBase::LegalizeTypeAction
1632 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1633   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1634       VT.getScalarType().bitsLE(MVT::i16))
1635     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1636   return TargetLoweringBase::getPreferredVectorAction(VT);
1637 }
1638 
1639 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1640                                                          Type *Ty) const {
1641   // FIXME: Could be smarter if called for vector constants.
1642   return true;
1643 }
1644 
1645 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1646   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1647     switch (Op) {
1648     case ISD::LOAD:
1649     case ISD::STORE:
1650 
1651     // These operations are done with 32-bit instructions anyway.
1652     case ISD::AND:
1653     case ISD::OR:
1654     case ISD::XOR:
1655     case ISD::SELECT:
1656       // TODO: Extensions?
1657       return true;
1658     default:
1659       return false;
1660     }
1661   }
1662 
1663   // SimplifySetCC uses this function to determine whether or not it should
1664   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1665   if (VT == MVT::i1 && Op == ISD::SETCC)
1666     return false;
1667 
1668   return TargetLowering::isTypeDesirableForOp(Op, VT);
1669 }
1670 
1671 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1672                                                    const SDLoc &SL,
1673                                                    SDValue Chain,
1674                                                    uint64_t Offset) const {
1675   const DataLayout &DL = DAG.getDataLayout();
1676   MachineFunction &MF = DAG.getMachineFunction();
1677   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1678 
1679   const ArgDescriptor *InputPtrReg;
1680   const TargetRegisterClass *RC;
1681   LLT ArgTy;
1682   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1683 
1684   std::tie(InputPtrReg, RC, ArgTy) =
1685       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1686 
1687   // We may not have the kernarg segment argument if we have no kernel
1688   // arguments.
1689   if (!InputPtrReg)
1690     return DAG.getConstant(0, SL, PtrVT);
1691 
1692   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1693   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1694     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1695 
1696   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1697 }
1698 
1699 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1700                                             const SDLoc &SL) const {
1701   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1702                                                FIRST_IMPLICIT);
1703   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1704 }
1705 
1706 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1707                                          const SDLoc &SL, SDValue Val,
1708                                          bool Signed,
1709                                          const ISD::InputArg *Arg) const {
1710   // First, if it is a widened vector, narrow it.
1711   if (VT.isVector() &&
1712       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1713     EVT NarrowedVT =
1714         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1715                          VT.getVectorNumElements());
1716     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1717                       DAG.getConstant(0, SL, MVT::i32));
1718   }
1719 
1720   // Then convert the vector elements or scalar value.
1721   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1722       VT.bitsLT(MemVT)) {
1723     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1724     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1725   }
1726 
1727   if (MemVT.isFloatingPoint())
1728     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1729   else if (Signed)
1730     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1731   else
1732     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1733 
1734   return Val;
1735 }
1736 
1737 SDValue SITargetLowering::lowerKernargMemParameter(
1738     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1739     uint64_t Offset, Align Alignment, bool Signed,
1740     const ISD::InputArg *Arg) const {
1741   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1742 
1743   // Try to avoid using an extload by loading earlier than the argument address,
1744   // and extracting the relevant bits. The load should hopefully be merged with
1745   // the previous argument.
1746   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1747     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1748     int64_t AlignDownOffset = alignDown(Offset, 4);
1749     int64_t OffsetDiff = Offset - AlignDownOffset;
1750 
1751     EVT IntVT = MemVT.changeTypeToInteger();
1752 
1753     // TODO: If we passed in the base kernel offset we could have a better
1754     // alignment than 4, but we don't really need it.
1755     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1756     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1757                                MachineMemOperand::MODereferenceable |
1758                                    MachineMemOperand::MOInvariant);
1759 
1760     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1761     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1762 
1763     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1764     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1765     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1766 
1767 
1768     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1769   }
1770 
1771   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1772   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1773                              MachineMemOperand::MODereferenceable |
1774                                  MachineMemOperand::MOInvariant);
1775 
1776   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1777   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1778 }
1779 
1780 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1781                                               const SDLoc &SL, SDValue Chain,
1782                                               const ISD::InputArg &Arg) const {
1783   MachineFunction &MF = DAG.getMachineFunction();
1784   MachineFrameInfo &MFI = MF.getFrameInfo();
1785 
1786   if (Arg.Flags.isByVal()) {
1787     unsigned Size = Arg.Flags.getByValSize();
1788     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1789     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1790   }
1791 
1792   unsigned ArgOffset = VA.getLocMemOffset();
1793   unsigned ArgSize = VA.getValVT().getStoreSize();
1794 
1795   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1796 
1797   // Create load nodes to retrieve arguments from the stack.
1798   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1799   SDValue ArgValue;
1800 
1801   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1802   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1803   MVT MemVT = VA.getValVT();
1804 
1805   switch (VA.getLocInfo()) {
1806   default:
1807     break;
1808   case CCValAssign::BCvt:
1809     MemVT = VA.getLocVT();
1810     break;
1811   case CCValAssign::SExt:
1812     ExtType = ISD::SEXTLOAD;
1813     break;
1814   case CCValAssign::ZExt:
1815     ExtType = ISD::ZEXTLOAD;
1816     break;
1817   case CCValAssign::AExt:
1818     ExtType = ISD::EXTLOAD;
1819     break;
1820   }
1821 
1822   ArgValue = DAG.getExtLoad(
1823     ExtType, SL, VA.getLocVT(), Chain, FIN,
1824     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1825     MemVT);
1826   return ArgValue;
1827 }
1828 
1829 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1830   const SIMachineFunctionInfo &MFI,
1831   EVT VT,
1832   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1833   const ArgDescriptor *Reg;
1834   const TargetRegisterClass *RC;
1835   LLT Ty;
1836 
1837   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1838   if (!Reg) {
1839     if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) {
1840       // It's possible for a kernarg intrinsic call to appear in a kernel with
1841       // no allocated segment, in which case we do not add the user sgpr
1842       // argument, so just return null.
1843       return DAG.getConstant(0, SDLoc(), VT);
1844     }
1845 
1846     // It's undefined behavior if a function marked with the amdgpu-no-*
1847     // attributes uses the corresponding intrinsic.
1848     return DAG.getUNDEF(VT);
1849   }
1850 
1851   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1852 }
1853 
1854 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1855                                CallingConv::ID CallConv,
1856                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1857                                FunctionType *FType,
1858                                SIMachineFunctionInfo *Info) {
1859   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1860     const ISD::InputArg *Arg = &Ins[I];
1861 
1862     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1863            "vector type argument should have been split");
1864 
1865     // First check if it's a PS input addr.
1866     if (CallConv == CallingConv::AMDGPU_PS &&
1867         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1868       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1869 
1870       // Inconveniently only the first part of the split is marked as isSplit,
1871       // so skip to the end. We only want to increment PSInputNum once for the
1872       // entire split argument.
1873       if (Arg->Flags.isSplit()) {
1874         while (!Arg->Flags.isSplitEnd()) {
1875           assert((!Arg->VT.isVector() ||
1876                   Arg->VT.getScalarSizeInBits() == 16) &&
1877                  "unexpected vector split in ps argument type");
1878           if (!SkipArg)
1879             Splits.push_back(*Arg);
1880           Arg = &Ins[++I];
1881         }
1882       }
1883 
1884       if (SkipArg) {
1885         // We can safely skip PS inputs.
1886         Skipped.set(Arg->getOrigArgIndex());
1887         ++PSInputNum;
1888         continue;
1889       }
1890 
1891       Info->markPSInputAllocated(PSInputNum);
1892       if (Arg->Used)
1893         Info->markPSInputEnabled(PSInputNum);
1894 
1895       ++PSInputNum;
1896     }
1897 
1898     Splits.push_back(*Arg);
1899   }
1900 }
1901 
1902 // Allocate special inputs passed in VGPRs.
1903 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1904                                                       MachineFunction &MF,
1905                                                       const SIRegisterInfo &TRI,
1906                                                       SIMachineFunctionInfo &Info) const {
1907   const LLT S32 = LLT::scalar(32);
1908   MachineRegisterInfo &MRI = MF.getRegInfo();
1909 
1910   if (Info.hasWorkItemIDX()) {
1911     Register Reg = AMDGPU::VGPR0;
1912     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1913 
1914     CCInfo.AllocateReg(Reg);
1915     unsigned Mask = (Subtarget->hasPackedTID() &&
1916                      Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
1917     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1918   }
1919 
1920   if (Info.hasWorkItemIDY()) {
1921     assert(Info.hasWorkItemIDX());
1922     if (Subtarget->hasPackedTID()) {
1923       Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1924                                                         0x3ff << 10));
1925     } else {
1926       unsigned Reg = AMDGPU::VGPR1;
1927       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1928 
1929       CCInfo.AllocateReg(Reg);
1930       Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1931     }
1932   }
1933 
1934   if (Info.hasWorkItemIDZ()) {
1935     assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
1936     if (Subtarget->hasPackedTID()) {
1937       Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1938                                                         0x3ff << 20));
1939     } else {
1940       unsigned Reg = AMDGPU::VGPR2;
1941       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1942 
1943       CCInfo.AllocateReg(Reg);
1944       Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1945     }
1946   }
1947 }
1948 
1949 // Try to allocate a VGPR at the end of the argument list, or if no argument
1950 // VGPRs are left allocating a stack slot.
1951 // If \p Mask is is given it indicates bitfield position in the register.
1952 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1953 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1954                                          ArgDescriptor Arg = ArgDescriptor()) {
1955   if (Arg.isSet())
1956     return ArgDescriptor::createArg(Arg, Mask);
1957 
1958   ArrayRef<MCPhysReg> ArgVGPRs
1959     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1960   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1961   if (RegIdx == ArgVGPRs.size()) {
1962     // Spill to stack required.
1963     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1964 
1965     return ArgDescriptor::createStack(Offset, Mask);
1966   }
1967 
1968   unsigned Reg = ArgVGPRs[RegIdx];
1969   Reg = CCInfo.AllocateReg(Reg);
1970   assert(Reg != AMDGPU::NoRegister);
1971 
1972   MachineFunction &MF = CCInfo.getMachineFunction();
1973   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1974   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1975   return ArgDescriptor::createRegister(Reg, Mask);
1976 }
1977 
1978 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1979                                              const TargetRegisterClass *RC,
1980                                              unsigned NumArgRegs) {
1981   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1982   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1983   if (RegIdx == ArgSGPRs.size())
1984     report_fatal_error("ran out of SGPRs for arguments");
1985 
1986   unsigned Reg = ArgSGPRs[RegIdx];
1987   Reg = CCInfo.AllocateReg(Reg);
1988   assert(Reg != AMDGPU::NoRegister);
1989 
1990   MachineFunction &MF = CCInfo.getMachineFunction();
1991   MF.addLiveIn(Reg, RC);
1992   return ArgDescriptor::createRegister(Reg);
1993 }
1994 
1995 // If this has a fixed position, we still should allocate the register in the
1996 // CCInfo state. Technically we could get away with this for values passed
1997 // outside of the normal argument range.
1998 static void allocateFixedSGPRInputImpl(CCState &CCInfo,
1999                                        const TargetRegisterClass *RC,
2000                                        MCRegister Reg) {
2001   Reg = CCInfo.AllocateReg(Reg);
2002   assert(Reg != AMDGPU::NoRegister);
2003   MachineFunction &MF = CCInfo.getMachineFunction();
2004   MF.addLiveIn(Reg, RC);
2005 }
2006 
2007 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
2008   if (Arg) {
2009     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
2010                                Arg.getRegister());
2011   } else
2012     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
2013 }
2014 
2015 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
2016   if (Arg) {
2017     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
2018                                Arg.getRegister());
2019   } else
2020     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
2021 }
2022 
2023 /// Allocate implicit function VGPR arguments at the end of allocated user
2024 /// arguments.
2025 void SITargetLowering::allocateSpecialInputVGPRs(
2026   CCState &CCInfo, MachineFunction &MF,
2027   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2028   const unsigned Mask = 0x3ff;
2029   ArgDescriptor Arg;
2030 
2031   if (Info.hasWorkItemIDX()) {
2032     Arg = allocateVGPR32Input(CCInfo, Mask);
2033     Info.setWorkItemIDX(Arg);
2034   }
2035 
2036   if (Info.hasWorkItemIDY()) {
2037     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
2038     Info.setWorkItemIDY(Arg);
2039   }
2040 
2041   if (Info.hasWorkItemIDZ())
2042     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
2043 }
2044 
2045 /// Allocate implicit function VGPR arguments in fixed registers.
2046 void SITargetLowering::allocateSpecialInputVGPRsFixed(
2047   CCState &CCInfo, MachineFunction &MF,
2048   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2049   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
2050   if (!Reg)
2051     report_fatal_error("failed to allocated VGPR for implicit arguments");
2052 
2053   const unsigned Mask = 0x3ff;
2054   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2055   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
2056   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
2057 }
2058 
2059 void SITargetLowering::allocateSpecialInputSGPRs(
2060   CCState &CCInfo,
2061   MachineFunction &MF,
2062   const SIRegisterInfo &TRI,
2063   SIMachineFunctionInfo &Info) const {
2064   auto &ArgInfo = Info.getArgInfo();
2065 
2066   // TODO: Unify handling with private memory pointers.
2067   if (Info.hasDispatchPtr())
2068     allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
2069 
2070   if (Info.hasQueuePtr())
2071     allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
2072 
2073   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
2074   // constant offset from the kernarg segment.
2075   if (Info.hasImplicitArgPtr())
2076     allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
2077 
2078   if (Info.hasDispatchID())
2079     allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2080 
2081   // flat_scratch_init is not applicable for non-kernel functions.
2082 
2083   if (Info.hasWorkGroupIDX())
2084     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2085 
2086   if (Info.hasWorkGroupIDY())
2087     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2088 
2089   if (Info.hasWorkGroupIDZ())
2090     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2091 }
2092 
2093 // Allocate special inputs passed in user SGPRs.
2094 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2095                                             MachineFunction &MF,
2096                                             const SIRegisterInfo &TRI,
2097                                             SIMachineFunctionInfo &Info) const {
2098   if (Info.hasImplicitBufferPtr()) {
2099     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2100     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2101     CCInfo.AllocateReg(ImplicitBufferPtrReg);
2102   }
2103 
2104   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2105   if (Info.hasPrivateSegmentBuffer()) {
2106     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2107     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2108     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2109   }
2110 
2111   if (Info.hasDispatchPtr()) {
2112     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2113     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2114     CCInfo.AllocateReg(DispatchPtrReg);
2115   }
2116 
2117   if (Info.hasQueuePtr()) {
2118     Register QueuePtrReg = Info.addQueuePtr(TRI);
2119     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2120     CCInfo.AllocateReg(QueuePtrReg);
2121   }
2122 
2123   if (Info.hasKernargSegmentPtr()) {
2124     MachineRegisterInfo &MRI = MF.getRegInfo();
2125     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2126     CCInfo.AllocateReg(InputPtrReg);
2127 
2128     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2129     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2130   }
2131 
2132   if (Info.hasDispatchID()) {
2133     Register DispatchIDReg = Info.addDispatchID(TRI);
2134     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2135     CCInfo.AllocateReg(DispatchIDReg);
2136   }
2137 
2138   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2139     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2140     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2141     CCInfo.AllocateReg(FlatScratchInitReg);
2142   }
2143 
2144   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2145   // these from the dispatch pointer.
2146 }
2147 
2148 // Allocate special input registers that are initialized per-wave.
2149 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2150                                            MachineFunction &MF,
2151                                            SIMachineFunctionInfo &Info,
2152                                            CallingConv::ID CallConv,
2153                                            bool IsShader) const {
2154   if (Info.hasWorkGroupIDX()) {
2155     Register Reg = Info.addWorkGroupIDX();
2156     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2157     CCInfo.AllocateReg(Reg);
2158   }
2159 
2160   if (Info.hasWorkGroupIDY()) {
2161     Register Reg = Info.addWorkGroupIDY();
2162     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2163     CCInfo.AllocateReg(Reg);
2164   }
2165 
2166   if (Info.hasWorkGroupIDZ()) {
2167     Register Reg = Info.addWorkGroupIDZ();
2168     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2169     CCInfo.AllocateReg(Reg);
2170   }
2171 
2172   if (Info.hasWorkGroupInfo()) {
2173     Register Reg = Info.addWorkGroupInfo();
2174     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2175     CCInfo.AllocateReg(Reg);
2176   }
2177 
2178   if (Info.hasPrivateSegmentWaveByteOffset()) {
2179     // Scratch wave offset passed in system SGPR.
2180     unsigned PrivateSegmentWaveByteOffsetReg;
2181 
2182     if (IsShader) {
2183       PrivateSegmentWaveByteOffsetReg =
2184         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2185 
2186       // This is true if the scratch wave byte offset doesn't have a fixed
2187       // location.
2188       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2189         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2190         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2191       }
2192     } else
2193       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2194 
2195     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2196     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2197   }
2198 }
2199 
2200 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2201                                      MachineFunction &MF,
2202                                      const SIRegisterInfo &TRI,
2203                                      SIMachineFunctionInfo &Info) {
2204   // Now that we've figured out where the scratch register inputs are, see if
2205   // should reserve the arguments and use them directly.
2206   MachineFrameInfo &MFI = MF.getFrameInfo();
2207   bool HasStackObjects = MFI.hasStackObjects();
2208   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2209 
2210   // Record that we know we have non-spill stack objects so we don't need to
2211   // check all stack objects later.
2212   if (HasStackObjects)
2213     Info.setHasNonSpillStackObjects(true);
2214 
2215   // Everything live out of a block is spilled with fast regalloc, so it's
2216   // almost certain that spilling will be required.
2217   if (TM.getOptLevel() == CodeGenOpt::None)
2218     HasStackObjects = true;
2219 
2220   // For now assume stack access is needed in any callee functions, so we need
2221   // the scratch registers to pass in.
2222   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2223 
2224   if (!ST.enableFlatScratch()) {
2225     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2226       // If we have stack objects, we unquestionably need the private buffer
2227       // resource. For the Code Object V2 ABI, this will be the first 4 user
2228       // SGPR inputs. We can reserve those and use them directly.
2229 
2230       Register PrivateSegmentBufferReg =
2231           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2232       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2233     } else {
2234       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2235       // We tentatively reserve the last registers (skipping the last registers
2236       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2237       // we'll replace these with the ones immediately after those which were
2238       // really allocated. In the prologue copies will be inserted from the
2239       // argument to these reserved registers.
2240 
2241       // Without HSA, relocations are used for the scratch pointer and the
2242       // buffer resource setup is always inserted in the prologue. Scratch wave
2243       // offset is still in an input SGPR.
2244       Info.setScratchRSrcReg(ReservedBufferReg);
2245     }
2246   }
2247 
2248   MachineRegisterInfo &MRI = MF.getRegInfo();
2249 
2250   // For entry functions we have to set up the stack pointer if we use it,
2251   // whereas non-entry functions get this "for free". This means there is no
2252   // intrinsic advantage to using S32 over S34 in cases where we do not have
2253   // calls but do need a frame pointer (i.e. if we are requested to have one
2254   // because frame pointer elimination is disabled). To keep things simple we
2255   // only ever use S32 as the call ABI stack pointer, and so using it does not
2256   // imply we need a separate frame pointer.
2257   //
2258   // Try to use s32 as the SP, but move it if it would interfere with input
2259   // arguments. This won't work with calls though.
2260   //
2261   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2262   // registers.
2263   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2264     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2265   } else {
2266     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2267 
2268     if (MFI.hasCalls())
2269       report_fatal_error("call in graphics shader with too many input SGPRs");
2270 
2271     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2272       if (!MRI.isLiveIn(Reg)) {
2273         Info.setStackPtrOffsetReg(Reg);
2274         break;
2275       }
2276     }
2277 
2278     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2279       report_fatal_error("failed to find register for SP");
2280   }
2281 
2282   // hasFP should be accurate for entry functions even before the frame is
2283   // finalized, because it does not rely on the known stack size, only
2284   // properties like whether variable sized objects are present.
2285   if (ST.getFrameLowering()->hasFP(MF)) {
2286     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2287   }
2288 }
2289 
2290 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2291   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2292   return !Info->isEntryFunction();
2293 }
2294 
2295 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2296 
2297 }
2298 
2299 void SITargetLowering::insertCopiesSplitCSR(
2300   MachineBasicBlock *Entry,
2301   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2302   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2303 
2304   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2305   if (!IStart)
2306     return;
2307 
2308   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2309   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2310   MachineBasicBlock::iterator MBBI = Entry->begin();
2311   for (const MCPhysReg *I = IStart; *I; ++I) {
2312     const TargetRegisterClass *RC = nullptr;
2313     if (AMDGPU::SReg_64RegClass.contains(*I))
2314       RC = &AMDGPU::SGPR_64RegClass;
2315     else if (AMDGPU::SReg_32RegClass.contains(*I))
2316       RC = &AMDGPU::SGPR_32RegClass;
2317     else
2318       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2319 
2320     Register NewVR = MRI->createVirtualRegister(RC);
2321     // Create copy from CSR to a virtual register.
2322     Entry->addLiveIn(*I);
2323     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2324       .addReg(*I);
2325 
2326     // Insert the copy-back instructions right before the terminator.
2327     for (auto *Exit : Exits)
2328       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2329               TII->get(TargetOpcode::COPY), *I)
2330         .addReg(NewVR);
2331   }
2332 }
2333 
2334 SDValue SITargetLowering::LowerFormalArguments(
2335     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2336     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2337     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2338   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2339 
2340   MachineFunction &MF = DAG.getMachineFunction();
2341   const Function &Fn = MF.getFunction();
2342   FunctionType *FType = MF.getFunction().getFunctionType();
2343   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2344 
2345   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2346     DiagnosticInfoUnsupported NoGraphicsHSA(
2347         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2348     DAG.getContext()->diagnose(NoGraphicsHSA);
2349     return DAG.getEntryNode();
2350   }
2351 
2352   Info->allocateModuleLDSGlobal(Fn.getParent());
2353 
2354   SmallVector<ISD::InputArg, 16> Splits;
2355   SmallVector<CCValAssign, 16> ArgLocs;
2356   BitVector Skipped(Ins.size());
2357   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2358                  *DAG.getContext());
2359 
2360   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2361   bool IsKernel = AMDGPU::isKernel(CallConv);
2362   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2363 
2364   if (IsGraphics) {
2365     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2366            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2367            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2368            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2369            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2370            !Info->hasWorkItemIDZ());
2371   }
2372 
2373   if (CallConv == CallingConv::AMDGPU_PS) {
2374     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2375 
2376     // At least one interpolation mode must be enabled or else the GPU will
2377     // hang.
2378     //
2379     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2380     // set PSInputAddr, the user wants to enable some bits after the compilation
2381     // based on run-time states. Since we can't know what the final PSInputEna
2382     // will look like, so we shouldn't do anything here and the user should take
2383     // responsibility for the correct programming.
2384     //
2385     // Otherwise, the following restrictions apply:
2386     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2387     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2388     //   enabled too.
2389     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2390         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2391       CCInfo.AllocateReg(AMDGPU::VGPR0);
2392       CCInfo.AllocateReg(AMDGPU::VGPR1);
2393       Info->markPSInputAllocated(0);
2394       Info->markPSInputEnabled(0);
2395     }
2396     if (Subtarget->isAmdPalOS()) {
2397       // For isAmdPalOS, the user does not enable some bits after compilation
2398       // based on run-time states; the register values being generated here are
2399       // the final ones set in hardware. Therefore we need to apply the
2400       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2401       // a bit is set in PSInputAddr but not PSInputEnable is where the
2402       // frontend set up an input arg for a particular interpolation mode, but
2403       // nothing uses that input arg. Really we should have an earlier pass
2404       // that removes such an arg.)
2405       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2406       if ((PsInputBits & 0x7F) == 0 ||
2407           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2408         Info->markPSInputEnabled(
2409             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2410     }
2411   } else if (IsKernel) {
2412     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2413   } else {
2414     Splits.append(Ins.begin(), Ins.end());
2415   }
2416 
2417   if (IsEntryFunc) {
2418     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2419     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2420   } else if (!IsGraphics) {
2421     // For the fixed ABI, pass workitem IDs in the last argument register.
2422     allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2423   }
2424 
2425   if (IsKernel) {
2426     analyzeFormalArgumentsCompute(CCInfo, Ins);
2427   } else {
2428     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2429     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2430   }
2431 
2432   SmallVector<SDValue, 16> Chains;
2433 
2434   // FIXME: This is the minimum kernel argument alignment. We should improve
2435   // this to the maximum alignment of the arguments.
2436   //
2437   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2438   // kern arg offset.
2439   const Align KernelArgBaseAlign = Align(16);
2440 
2441   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2442     const ISD::InputArg &Arg = Ins[i];
2443     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2444       InVals.push_back(DAG.getUNDEF(Arg.VT));
2445       continue;
2446     }
2447 
2448     CCValAssign &VA = ArgLocs[ArgIdx++];
2449     MVT VT = VA.getLocVT();
2450 
2451     if (IsEntryFunc && VA.isMemLoc()) {
2452       VT = Ins[i].VT;
2453       EVT MemVT = VA.getLocVT();
2454 
2455       const uint64_t Offset = VA.getLocMemOffset();
2456       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2457 
2458       if (Arg.Flags.isByRef()) {
2459         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2460 
2461         const GCNTargetMachine &TM =
2462             static_cast<const GCNTargetMachine &>(getTargetMachine());
2463         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2464                                     Arg.Flags.getPointerAddrSpace())) {
2465           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2466                                      Arg.Flags.getPointerAddrSpace());
2467         }
2468 
2469         InVals.push_back(Ptr);
2470         continue;
2471       }
2472 
2473       SDValue Arg = lowerKernargMemParameter(
2474         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2475       Chains.push_back(Arg.getValue(1));
2476 
2477       auto *ParamTy =
2478         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2479       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2480           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2481                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2482         // On SI local pointers are just offsets into LDS, so they are always
2483         // less than 16-bits.  On CI and newer they could potentially be
2484         // real pointers, so we can't guarantee their size.
2485         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2486                           DAG.getValueType(MVT::i16));
2487       }
2488 
2489       InVals.push_back(Arg);
2490       continue;
2491     } else if (!IsEntryFunc && VA.isMemLoc()) {
2492       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2493       InVals.push_back(Val);
2494       if (!Arg.Flags.isByVal())
2495         Chains.push_back(Val.getValue(1));
2496       continue;
2497     }
2498 
2499     assert(VA.isRegLoc() && "Parameter must be in a register!");
2500 
2501     Register Reg = VA.getLocReg();
2502     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2503     EVT ValVT = VA.getValVT();
2504 
2505     Reg = MF.addLiveIn(Reg, RC);
2506     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2507 
2508     if (Arg.Flags.isSRet()) {
2509       // The return object should be reasonably addressable.
2510 
2511       // FIXME: This helps when the return is a real sret. If it is a
2512       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2513       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2514       unsigned NumBits
2515         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2516       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2517         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2518     }
2519 
2520     // If this is an 8 or 16-bit value, it is really passed promoted
2521     // to 32 bits. Insert an assert[sz]ext to capture this, then
2522     // truncate to the right size.
2523     switch (VA.getLocInfo()) {
2524     case CCValAssign::Full:
2525       break;
2526     case CCValAssign::BCvt:
2527       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2528       break;
2529     case CCValAssign::SExt:
2530       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2531                         DAG.getValueType(ValVT));
2532       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2533       break;
2534     case CCValAssign::ZExt:
2535       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2536                         DAG.getValueType(ValVT));
2537       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2538       break;
2539     case CCValAssign::AExt:
2540       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2541       break;
2542     default:
2543       llvm_unreachable("Unknown loc info!");
2544     }
2545 
2546     InVals.push_back(Val);
2547   }
2548 
2549   // Start adding system SGPRs.
2550   if (IsEntryFunc) {
2551     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2552   } else {
2553     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2554     if (!IsGraphics)
2555       allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2556   }
2557 
2558   auto &ArgUsageInfo =
2559     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2560   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2561 
2562   unsigned StackArgSize = CCInfo.getNextStackOffset();
2563   Info->setBytesInStackArgArea(StackArgSize);
2564 
2565   return Chains.empty() ? Chain :
2566     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2567 }
2568 
2569 // TODO: If return values can't fit in registers, we should return as many as
2570 // possible in registers before passing on stack.
2571 bool SITargetLowering::CanLowerReturn(
2572   CallingConv::ID CallConv,
2573   MachineFunction &MF, bool IsVarArg,
2574   const SmallVectorImpl<ISD::OutputArg> &Outs,
2575   LLVMContext &Context) const {
2576   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2577   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2578   // for shaders. Vector types should be explicitly handled by CC.
2579   if (AMDGPU::isEntryFunctionCC(CallConv))
2580     return true;
2581 
2582   SmallVector<CCValAssign, 16> RVLocs;
2583   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2584   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2585 }
2586 
2587 SDValue
2588 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2589                               bool isVarArg,
2590                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2591                               const SmallVectorImpl<SDValue> &OutVals,
2592                               const SDLoc &DL, SelectionDAG &DAG) const {
2593   MachineFunction &MF = DAG.getMachineFunction();
2594   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2595 
2596   if (AMDGPU::isKernel(CallConv)) {
2597     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2598                                              OutVals, DL, DAG);
2599   }
2600 
2601   bool IsShader = AMDGPU::isShader(CallConv);
2602 
2603   Info->setIfReturnsVoid(Outs.empty());
2604   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2605 
2606   // CCValAssign - represent the assignment of the return value to a location.
2607   SmallVector<CCValAssign, 48> RVLocs;
2608   SmallVector<ISD::OutputArg, 48> Splits;
2609 
2610   // CCState - Info about the registers and stack slots.
2611   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2612                  *DAG.getContext());
2613 
2614   // Analyze outgoing return values.
2615   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2616 
2617   SDValue Flag;
2618   SmallVector<SDValue, 48> RetOps;
2619   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2620 
2621   // Add return address for callable functions.
2622   if (!Info->isEntryFunction()) {
2623     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2624     SDValue ReturnAddrReg = CreateLiveInRegister(
2625       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2626 
2627     SDValue ReturnAddrVirtualReg =
2628         DAG.getRegister(MF.getRegInfo().createVirtualRegister(
2629                             CallConv != CallingConv::AMDGPU_Gfx
2630                                 ? &AMDGPU::CCR_SGPR_64RegClass
2631                                 : &AMDGPU::Gfx_CCR_SGPR_64RegClass),
2632                         MVT::i64);
2633     Chain =
2634         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2635     Flag = Chain.getValue(1);
2636     RetOps.push_back(ReturnAddrVirtualReg);
2637   }
2638 
2639   // Copy the result values into the output registers.
2640   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2641        ++I, ++RealRVLocIdx) {
2642     CCValAssign &VA = RVLocs[I];
2643     assert(VA.isRegLoc() && "Can only return in registers!");
2644     // TODO: Partially return in registers if return values don't fit.
2645     SDValue Arg = OutVals[RealRVLocIdx];
2646 
2647     // Copied from other backends.
2648     switch (VA.getLocInfo()) {
2649     case CCValAssign::Full:
2650       break;
2651     case CCValAssign::BCvt:
2652       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2653       break;
2654     case CCValAssign::SExt:
2655       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2656       break;
2657     case CCValAssign::ZExt:
2658       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2659       break;
2660     case CCValAssign::AExt:
2661       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2662       break;
2663     default:
2664       llvm_unreachable("Unknown loc info!");
2665     }
2666 
2667     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2668     Flag = Chain.getValue(1);
2669     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2670   }
2671 
2672   // FIXME: Does sret work properly?
2673   if (!Info->isEntryFunction()) {
2674     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2675     const MCPhysReg *I =
2676       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2677     if (I) {
2678       for (; *I; ++I) {
2679         if (AMDGPU::SReg_64RegClass.contains(*I))
2680           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2681         else if (AMDGPU::SReg_32RegClass.contains(*I))
2682           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2683         else
2684           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2685       }
2686     }
2687   }
2688 
2689   // Update chain and glue.
2690   RetOps[0] = Chain;
2691   if (Flag.getNode())
2692     RetOps.push_back(Flag);
2693 
2694   unsigned Opc = AMDGPUISD::ENDPGM;
2695   if (!IsWaveEnd) {
2696     if (IsShader)
2697       Opc = AMDGPUISD::RETURN_TO_EPILOG;
2698     else if (CallConv == CallingConv::AMDGPU_Gfx)
2699       Opc = AMDGPUISD::RET_GFX_FLAG;
2700     else
2701       Opc = AMDGPUISD::RET_FLAG;
2702   }
2703 
2704   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2705 }
2706 
2707 SDValue SITargetLowering::LowerCallResult(
2708     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2709     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2710     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2711     SDValue ThisVal) const {
2712   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2713 
2714   // Assign locations to each value returned by this call.
2715   SmallVector<CCValAssign, 16> RVLocs;
2716   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2717                  *DAG.getContext());
2718   CCInfo.AnalyzeCallResult(Ins, RetCC);
2719 
2720   // Copy all of the result registers out of their specified physreg.
2721   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2722     CCValAssign VA = RVLocs[i];
2723     SDValue Val;
2724 
2725     if (VA.isRegLoc()) {
2726       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2727       Chain = Val.getValue(1);
2728       InFlag = Val.getValue(2);
2729     } else if (VA.isMemLoc()) {
2730       report_fatal_error("TODO: return values in memory");
2731     } else
2732       llvm_unreachable("unknown argument location type");
2733 
2734     switch (VA.getLocInfo()) {
2735     case CCValAssign::Full:
2736       break;
2737     case CCValAssign::BCvt:
2738       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2739       break;
2740     case CCValAssign::ZExt:
2741       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2742                         DAG.getValueType(VA.getValVT()));
2743       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2744       break;
2745     case CCValAssign::SExt:
2746       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2747                         DAG.getValueType(VA.getValVT()));
2748       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2749       break;
2750     case CCValAssign::AExt:
2751       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2752       break;
2753     default:
2754       llvm_unreachable("Unknown loc info!");
2755     }
2756 
2757     InVals.push_back(Val);
2758   }
2759 
2760   return Chain;
2761 }
2762 
2763 // Add code to pass special inputs required depending on used features separate
2764 // from the explicit user arguments present in the IR.
2765 void SITargetLowering::passSpecialInputs(
2766     CallLoweringInfo &CLI,
2767     CCState &CCInfo,
2768     const SIMachineFunctionInfo &Info,
2769     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2770     SmallVectorImpl<SDValue> &MemOpChains,
2771     SDValue Chain) const {
2772   // If we don't have a call site, this was a call inserted by
2773   // legalization. These can never use special inputs.
2774   if (!CLI.CB)
2775     return;
2776 
2777   SelectionDAG &DAG = CLI.DAG;
2778   const SDLoc &DL = CLI.DL;
2779 
2780   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2781   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2782 
2783   const AMDGPUFunctionArgInfo *CalleeArgInfo
2784     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2785   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2786     auto &ArgUsageInfo =
2787       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2788     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2789   }
2790 
2791   // TODO: Unify with private memory register handling. This is complicated by
2792   // the fact that at least in kernels, the input argument is not necessarily
2793   // in the same location as the input.
2794   static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
2795                              StringLiteral> ImplicitAttrs[] = {
2796     {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"},
2797     {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" },
2798     {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"},
2799     {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"},
2800     {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"},
2801     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"},
2802     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"}
2803   };
2804 
2805   for (auto Attr : ImplicitAttrs) {
2806     const ArgDescriptor *OutgoingArg;
2807     const TargetRegisterClass *ArgRC;
2808     LLT ArgTy;
2809 
2810     AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first;
2811 
2812     // If the callee does not use the attribute value, skip copying the value.
2813     if (CLI.CB->hasFnAttr(Attr.second))
2814       continue;
2815 
2816     std::tie(OutgoingArg, ArgRC, ArgTy) =
2817         CalleeArgInfo->getPreloadedValue(InputID);
2818     if (!OutgoingArg)
2819       continue;
2820 
2821     const ArgDescriptor *IncomingArg;
2822     const TargetRegisterClass *IncomingArgRC;
2823     LLT Ty;
2824     std::tie(IncomingArg, IncomingArgRC, Ty) =
2825         CallerArgInfo.getPreloadedValue(InputID);
2826     assert(IncomingArgRC == ArgRC);
2827 
2828     // All special arguments are ints for now.
2829     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2830     SDValue InputReg;
2831 
2832     if (IncomingArg) {
2833       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2834     } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
2835       // The implicit arg ptr is special because it doesn't have a corresponding
2836       // input for kernels, and is computed from the kernarg segment pointer.
2837       InputReg = getImplicitArgPtr(DAG, DL);
2838     } else {
2839       // We may have proven the input wasn't needed, although the ABI is
2840       // requiring it. We just need to allocate the register appropriately.
2841       InputReg = DAG.getUNDEF(ArgVT);
2842     }
2843 
2844     if (OutgoingArg->isRegister()) {
2845       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2846       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2847         report_fatal_error("failed to allocate implicit input argument");
2848     } else {
2849       unsigned SpecialArgOffset =
2850           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2851       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2852                                               SpecialArgOffset);
2853       MemOpChains.push_back(ArgStore);
2854     }
2855   }
2856 
2857   // Pack workitem IDs into a single register or pass it as is if already
2858   // packed.
2859   const ArgDescriptor *OutgoingArg;
2860   const TargetRegisterClass *ArgRC;
2861   LLT Ty;
2862 
2863   std::tie(OutgoingArg, ArgRC, Ty) =
2864       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2865   if (!OutgoingArg)
2866     std::tie(OutgoingArg, ArgRC, Ty) =
2867         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2868   if (!OutgoingArg)
2869     std::tie(OutgoingArg, ArgRC, Ty) =
2870         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2871   if (!OutgoingArg)
2872     return;
2873 
2874   const ArgDescriptor *IncomingArgX = std::get<0>(
2875       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2876   const ArgDescriptor *IncomingArgY = std::get<0>(
2877       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2878   const ArgDescriptor *IncomingArgZ = std::get<0>(
2879       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2880 
2881   SDValue InputReg;
2882   SDLoc SL;
2883 
2884   const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
2885   const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
2886   const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
2887 
2888   // If incoming ids are not packed we need to pack them.
2889   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
2890       NeedWorkItemIDX)
2891     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2892 
2893   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
2894       NeedWorkItemIDY) {
2895     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2896     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2897                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2898     InputReg = InputReg.getNode() ?
2899                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2900   }
2901 
2902   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
2903       NeedWorkItemIDZ) {
2904     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2905     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2906                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2907     InputReg = InputReg.getNode() ?
2908                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2909   }
2910 
2911   if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
2912     // Workitem ids are already packed, any of present incoming arguments
2913     // will carry all required fields.
2914     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2915       IncomingArgX ? *IncomingArgX :
2916       IncomingArgY ? *IncomingArgY :
2917                      *IncomingArgZ, ~0u);
2918     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2919   }
2920 
2921   if (OutgoingArg->isRegister()) {
2922     if (InputReg)
2923       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2924 
2925     CCInfo.AllocateReg(OutgoingArg->getRegister());
2926   } else {
2927     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2928     if (InputReg) {
2929       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2930                                               SpecialArgOffset);
2931       MemOpChains.push_back(ArgStore);
2932     }
2933   }
2934 }
2935 
2936 static bool canGuaranteeTCO(CallingConv::ID CC) {
2937   return CC == CallingConv::Fast;
2938 }
2939 
2940 /// Return true if we might ever do TCO for calls with this calling convention.
2941 static bool mayTailCallThisCC(CallingConv::ID CC) {
2942   switch (CC) {
2943   case CallingConv::C:
2944   case CallingConv::AMDGPU_Gfx:
2945     return true;
2946   default:
2947     return canGuaranteeTCO(CC);
2948   }
2949 }
2950 
2951 bool SITargetLowering::isEligibleForTailCallOptimization(
2952     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2953     const SmallVectorImpl<ISD::OutputArg> &Outs,
2954     const SmallVectorImpl<SDValue> &OutVals,
2955     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2956   if (!mayTailCallThisCC(CalleeCC))
2957     return false;
2958 
2959   // For a divergent call target, we need to do a waterfall loop over the
2960   // possible callees which precludes us from using a simple jump.
2961   if (Callee->isDivergent())
2962     return false;
2963 
2964   MachineFunction &MF = DAG.getMachineFunction();
2965   const Function &CallerF = MF.getFunction();
2966   CallingConv::ID CallerCC = CallerF.getCallingConv();
2967   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2968   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2969 
2970   // Kernels aren't callable, and don't have a live in return address so it
2971   // doesn't make sense to do a tail call with entry functions.
2972   if (!CallerPreserved)
2973     return false;
2974 
2975   bool CCMatch = CallerCC == CalleeCC;
2976 
2977   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2978     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2979       return true;
2980     return false;
2981   }
2982 
2983   // TODO: Can we handle var args?
2984   if (IsVarArg)
2985     return false;
2986 
2987   for (const Argument &Arg : CallerF.args()) {
2988     if (Arg.hasByValAttr())
2989       return false;
2990   }
2991 
2992   LLVMContext &Ctx = *DAG.getContext();
2993 
2994   // Check that the call results are passed in the same way.
2995   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2996                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2997                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2998     return false;
2999 
3000   // The callee has to preserve all registers the caller needs to preserve.
3001   if (!CCMatch) {
3002     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3003     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3004       return false;
3005   }
3006 
3007   // Nothing more to check if the callee is taking no arguments.
3008   if (Outs.empty())
3009     return true;
3010 
3011   SmallVector<CCValAssign, 16> ArgLocs;
3012   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
3013 
3014   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
3015 
3016   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
3017   // If the stack arguments for this call do not fit into our own save area then
3018   // the call cannot be made tail.
3019   // TODO: Is this really necessary?
3020   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3021     return false;
3022 
3023   const MachineRegisterInfo &MRI = MF.getRegInfo();
3024   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
3025 }
3026 
3027 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3028   if (!CI->isTailCall())
3029     return false;
3030 
3031   const Function *ParentFn = CI->getParent()->getParent();
3032   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
3033     return false;
3034   return true;
3035 }
3036 
3037 // The wave scratch offset register is used as the global base pointer.
3038 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
3039                                     SmallVectorImpl<SDValue> &InVals) const {
3040   SelectionDAG &DAG = CLI.DAG;
3041   const SDLoc &DL = CLI.DL;
3042   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3043   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3044   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3045   SDValue Chain = CLI.Chain;
3046   SDValue Callee = CLI.Callee;
3047   bool &IsTailCall = CLI.IsTailCall;
3048   CallingConv::ID CallConv = CLI.CallConv;
3049   bool IsVarArg = CLI.IsVarArg;
3050   bool IsSibCall = false;
3051   bool IsThisReturn = false;
3052   MachineFunction &MF = DAG.getMachineFunction();
3053 
3054   if (Callee.isUndef() || isNullConstant(Callee)) {
3055     if (!CLI.IsTailCall) {
3056       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
3057         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
3058     }
3059 
3060     return Chain;
3061   }
3062 
3063   if (IsVarArg) {
3064     return lowerUnhandledCall(CLI, InVals,
3065                               "unsupported call to variadic function ");
3066   }
3067 
3068   if (!CLI.CB)
3069     report_fatal_error("unsupported libcall legalization");
3070 
3071   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
3072     return lowerUnhandledCall(CLI, InVals,
3073                               "unsupported required tail call to function ");
3074   }
3075 
3076   if (AMDGPU::isShader(CallConv)) {
3077     // Note the issue is with the CC of the called function, not of the call
3078     // itself.
3079     return lowerUnhandledCall(CLI, InVals,
3080                               "unsupported call to a shader function ");
3081   }
3082 
3083   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
3084       CallConv != CallingConv::AMDGPU_Gfx) {
3085     // Only allow calls with specific calling conventions.
3086     return lowerUnhandledCall(CLI, InVals,
3087                               "unsupported calling convention for call from "
3088                               "graphics shader of function ");
3089   }
3090 
3091   if (IsTailCall) {
3092     IsTailCall = isEligibleForTailCallOptimization(
3093       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3094     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
3095       report_fatal_error("failed to perform tail call elimination on a call "
3096                          "site marked musttail");
3097     }
3098 
3099     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3100 
3101     // A sibling call is one where we're under the usual C ABI and not planning
3102     // to change that but can still do a tail call:
3103     if (!TailCallOpt && IsTailCall)
3104       IsSibCall = true;
3105 
3106     if (IsTailCall)
3107       ++NumTailCalls;
3108   }
3109 
3110   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3111   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3112   SmallVector<SDValue, 8> MemOpChains;
3113 
3114   // Analyze operands of the call, assigning locations to each operand.
3115   SmallVector<CCValAssign, 16> ArgLocs;
3116   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3117   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3118 
3119   if (CallConv != CallingConv::AMDGPU_Gfx) {
3120     // With a fixed ABI, allocate fixed registers before user arguments.
3121     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3122   }
3123 
3124   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3125 
3126   // Get a count of how many bytes are to be pushed on the stack.
3127   unsigned NumBytes = CCInfo.getNextStackOffset();
3128 
3129   if (IsSibCall) {
3130     // Since we're not changing the ABI to make this a tail call, the memory
3131     // operands are already available in the caller's incoming argument space.
3132     NumBytes = 0;
3133   }
3134 
3135   // FPDiff is the byte offset of the call's argument area from the callee's.
3136   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3137   // by this amount for a tail call. In a sibling call it must be 0 because the
3138   // caller will deallocate the entire stack and the callee still expects its
3139   // arguments to begin at SP+0. Completely unused for non-tail calls.
3140   int32_t FPDiff = 0;
3141   MachineFrameInfo &MFI = MF.getFrameInfo();
3142 
3143   // Adjust the stack pointer for the new arguments...
3144   // These operations are automatically eliminated by the prolog/epilog pass
3145   if (!IsSibCall) {
3146     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3147 
3148     if (!Subtarget->enableFlatScratch()) {
3149       SmallVector<SDValue, 4> CopyFromChains;
3150 
3151       // In the HSA case, this should be an identity copy.
3152       SDValue ScratchRSrcReg
3153         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3154       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3155       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3156       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3157     }
3158   }
3159 
3160   MVT PtrVT = MVT::i32;
3161 
3162   // Walk the register/memloc assignments, inserting copies/loads.
3163   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3164     CCValAssign &VA = ArgLocs[i];
3165     SDValue Arg = OutVals[i];
3166 
3167     // Promote the value if needed.
3168     switch (VA.getLocInfo()) {
3169     case CCValAssign::Full:
3170       break;
3171     case CCValAssign::BCvt:
3172       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3173       break;
3174     case CCValAssign::ZExt:
3175       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3176       break;
3177     case CCValAssign::SExt:
3178       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3179       break;
3180     case CCValAssign::AExt:
3181       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3182       break;
3183     case CCValAssign::FPExt:
3184       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3185       break;
3186     default:
3187       llvm_unreachable("Unknown loc info!");
3188     }
3189 
3190     if (VA.isRegLoc()) {
3191       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3192     } else {
3193       assert(VA.isMemLoc());
3194 
3195       SDValue DstAddr;
3196       MachinePointerInfo DstInfo;
3197 
3198       unsigned LocMemOffset = VA.getLocMemOffset();
3199       int32_t Offset = LocMemOffset;
3200 
3201       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3202       MaybeAlign Alignment;
3203 
3204       if (IsTailCall) {
3205         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3206         unsigned OpSize = Flags.isByVal() ?
3207           Flags.getByValSize() : VA.getValVT().getStoreSize();
3208 
3209         // FIXME: We can have better than the minimum byval required alignment.
3210         Alignment =
3211             Flags.isByVal()
3212                 ? Flags.getNonZeroByValAlign()
3213                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3214 
3215         Offset = Offset + FPDiff;
3216         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3217 
3218         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3219         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3220 
3221         // Make sure any stack arguments overlapping with where we're storing
3222         // are loaded before this eventual operation. Otherwise they'll be
3223         // clobbered.
3224 
3225         // FIXME: Why is this really necessary? This seems to just result in a
3226         // lot of code to copy the stack and write them back to the same
3227         // locations, which are supposed to be immutable?
3228         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3229       } else {
3230         // Stores to the argument stack area are relative to the stack pointer.
3231         SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3232                                         MVT::i32);
3233         DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3234         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3235         Alignment =
3236             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3237       }
3238 
3239       if (Outs[i].Flags.isByVal()) {
3240         SDValue SizeNode =
3241             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3242         SDValue Cpy =
3243             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3244                           Outs[i].Flags.getNonZeroByValAlign(),
3245                           /*isVol = */ false, /*AlwaysInline = */ true,
3246                           /*isTailCall = */ false, DstInfo,
3247                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3248 
3249         MemOpChains.push_back(Cpy);
3250       } else {
3251         SDValue Store =
3252             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3253         MemOpChains.push_back(Store);
3254       }
3255     }
3256   }
3257 
3258   if (!MemOpChains.empty())
3259     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3260 
3261   // Build a sequence of copy-to-reg nodes chained together with token chain
3262   // and flag operands which copy the outgoing args into the appropriate regs.
3263   SDValue InFlag;
3264   for (auto &RegToPass : RegsToPass) {
3265     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3266                              RegToPass.second, InFlag);
3267     InFlag = Chain.getValue(1);
3268   }
3269 
3270 
3271   SDValue PhysReturnAddrReg;
3272   if (IsTailCall) {
3273     // Since the return is being combined with the call, we need to pass on the
3274     // return address.
3275 
3276     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3277     SDValue ReturnAddrReg = CreateLiveInRegister(
3278       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3279 
3280     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3281                                         MVT::i64);
3282     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3283     InFlag = Chain.getValue(1);
3284   }
3285 
3286   // We don't usually want to end the call-sequence here because we would tidy
3287   // the frame up *after* the call, however in the ABI-changing tail-call case
3288   // we've carefully laid out the parameters so that when sp is reset they'll be
3289   // in the correct location.
3290   if (IsTailCall && !IsSibCall) {
3291     Chain = DAG.getCALLSEQ_END(Chain,
3292                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3293                                DAG.getTargetConstant(0, DL, MVT::i32),
3294                                InFlag, DL);
3295     InFlag = Chain.getValue(1);
3296   }
3297 
3298   std::vector<SDValue> Ops;
3299   Ops.push_back(Chain);
3300   Ops.push_back(Callee);
3301   // Add a redundant copy of the callee global which will not be legalized, as
3302   // we need direct access to the callee later.
3303   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3304     const GlobalValue *GV = GSD->getGlobal();
3305     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3306   } else {
3307     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3308   }
3309 
3310   if (IsTailCall) {
3311     // Each tail call may have to adjust the stack by a different amount, so
3312     // this information must travel along with the operation for eventual
3313     // consumption by emitEpilogue.
3314     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3315 
3316     Ops.push_back(PhysReturnAddrReg);
3317   }
3318 
3319   // Add argument registers to the end of the list so that they are known live
3320   // into the call.
3321   for (auto &RegToPass : RegsToPass) {
3322     Ops.push_back(DAG.getRegister(RegToPass.first,
3323                                   RegToPass.second.getValueType()));
3324   }
3325 
3326   // Add a register mask operand representing the call-preserved registers.
3327 
3328   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3329   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3330   assert(Mask && "Missing call preserved mask for calling convention");
3331   Ops.push_back(DAG.getRegisterMask(Mask));
3332 
3333   if (InFlag.getNode())
3334     Ops.push_back(InFlag);
3335 
3336   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3337 
3338   // If we're doing a tall call, use a TC_RETURN here rather than an
3339   // actual call instruction.
3340   if (IsTailCall) {
3341     MFI.setHasTailCall();
3342     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3343   }
3344 
3345   // Returns a chain and a flag for retval copy to use.
3346   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3347   Chain = Call.getValue(0);
3348   InFlag = Call.getValue(1);
3349 
3350   uint64_t CalleePopBytes = NumBytes;
3351   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3352                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3353                              InFlag, DL);
3354   if (!Ins.empty())
3355     InFlag = Chain.getValue(1);
3356 
3357   // Handle result values, copying them out of physregs into vregs that we
3358   // return.
3359   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3360                          InVals, IsThisReturn,
3361                          IsThisReturn ? OutVals[0] : SDValue());
3362 }
3363 
3364 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3365 // except for applying the wave size scale to the increment amount.
3366 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3367     SDValue Op, SelectionDAG &DAG) const {
3368   const MachineFunction &MF = DAG.getMachineFunction();
3369   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3370 
3371   SDLoc dl(Op);
3372   EVT VT = Op.getValueType();
3373   SDValue Tmp1 = Op;
3374   SDValue Tmp2 = Op.getValue(1);
3375   SDValue Tmp3 = Op.getOperand(2);
3376   SDValue Chain = Tmp1.getOperand(0);
3377 
3378   Register SPReg = Info->getStackPtrOffsetReg();
3379 
3380   // Chain the dynamic stack allocation so that it doesn't modify the stack
3381   // pointer when other instructions are using the stack.
3382   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3383 
3384   SDValue Size  = Tmp2.getOperand(1);
3385   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3386   Chain = SP.getValue(1);
3387   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3388   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3389   const TargetFrameLowering *TFL = ST.getFrameLowering();
3390   unsigned Opc =
3391     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3392     ISD::ADD : ISD::SUB;
3393 
3394   SDValue ScaledSize = DAG.getNode(
3395       ISD::SHL, dl, VT, Size,
3396       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3397 
3398   Align StackAlign = TFL->getStackAlign();
3399   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3400   if (Alignment && *Alignment > StackAlign) {
3401     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3402                        DAG.getConstant(-(uint64_t)Alignment->value()
3403                                            << ST.getWavefrontSizeLog2(),
3404                                        dl, VT));
3405   }
3406 
3407   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3408   Tmp2 = DAG.getCALLSEQ_END(
3409       Chain, DAG.getIntPtrConstant(0, dl, true),
3410       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3411 
3412   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3413 }
3414 
3415 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3416                                                   SelectionDAG &DAG) const {
3417   // We only handle constant sizes here to allow non-entry block, static sized
3418   // allocas. A truly dynamic value is more difficult to support because we
3419   // don't know if the size value is uniform or not. If the size isn't uniform,
3420   // we would need to do a wave reduction to get the maximum size to know how
3421   // much to increment the uniform stack pointer.
3422   SDValue Size = Op.getOperand(1);
3423   if (isa<ConstantSDNode>(Size))
3424       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3425 
3426   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3427 }
3428 
3429 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3430                                              const MachineFunction &MF) const {
3431   Register Reg = StringSwitch<Register>(RegName)
3432     .Case("m0", AMDGPU::M0)
3433     .Case("exec", AMDGPU::EXEC)
3434     .Case("exec_lo", AMDGPU::EXEC_LO)
3435     .Case("exec_hi", AMDGPU::EXEC_HI)
3436     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3437     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3438     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3439     .Default(Register());
3440 
3441   if (Reg == AMDGPU::NoRegister) {
3442     report_fatal_error(Twine("invalid register name \""
3443                              + StringRef(RegName)  + "\"."));
3444 
3445   }
3446 
3447   if (!Subtarget->hasFlatScrRegister() &&
3448        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3449     report_fatal_error(Twine("invalid register \""
3450                              + StringRef(RegName)  + "\" for subtarget."));
3451   }
3452 
3453   switch (Reg) {
3454   case AMDGPU::M0:
3455   case AMDGPU::EXEC_LO:
3456   case AMDGPU::EXEC_HI:
3457   case AMDGPU::FLAT_SCR_LO:
3458   case AMDGPU::FLAT_SCR_HI:
3459     if (VT.getSizeInBits() == 32)
3460       return Reg;
3461     break;
3462   case AMDGPU::EXEC:
3463   case AMDGPU::FLAT_SCR:
3464     if (VT.getSizeInBits() == 64)
3465       return Reg;
3466     break;
3467   default:
3468     llvm_unreachable("missing register type checking");
3469   }
3470 
3471   report_fatal_error(Twine("invalid type for register \""
3472                            + StringRef(RegName) + "\"."));
3473 }
3474 
3475 // If kill is not the last instruction, split the block so kill is always a
3476 // proper terminator.
3477 MachineBasicBlock *
3478 SITargetLowering::splitKillBlock(MachineInstr &MI,
3479                                  MachineBasicBlock *BB) const {
3480   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3481   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3482   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3483   return SplitBB;
3484 }
3485 
3486 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3487 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3488 // be the first instruction in the remainder block.
3489 //
3490 /// \returns { LoopBody, Remainder }
3491 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3492 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3493   MachineFunction *MF = MBB.getParent();
3494   MachineBasicBlock::iterator I(&MI);
3495 
3496   // To insert the loop we need to split the block. Move everything after this
3497   // point to a new block, and insert a new empty block between the two.
3498   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3499   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3500   MachineFunction::iterator MBBI(MBB);
3501   ++MBBI;
3502 
3503   MF->insert(MBBI, LoopBB);
3504   MF->insert(MBBI, RemainderBB);
3505 
3506   LoopBB->addSuccessor(LoopBB);
3507   LoopBB->addSuccessor(RemainderBB);
3508 
3509   // Move the rest of the block into a new block.
3510   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3511 
3512   if (InstInLoop) {
3513     auto Next = std::next(I);
3514 
3515     // Move instruction to loop body.
3516     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3517 
3518     // Move the rest of the block.
3519     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3520   } else {
3521     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3522   }
3523 
3524   MBB.addSuccessor(LoopBB);
3525 
3526   return std::make_pair(LoopBB, RemainderBB);
3527 }
3528 
3529 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3530 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3531   MachineBasicBlock *MBB = MI.getParent();
3532   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3533   auto I = MI.getIterator();
3534   auto E = std::next(I);
3535 
3536   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3537     .addImm(0);
3538 
3539   MIBundleBuilder Bundler(*MBB, I, E);
3540   finalizeBundle(*MBB, Bundler.begin());
3541 }
3542 
3543 MachineBasicBlock *
3544 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3545                                          MachineBasicBlock *BB) const {
3546   const DebugLoc &DL = MI.getDebugLoc();
3547 
3548   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3549 
3550   MachineBasicBlock *LoopBB;
3551   MachineBasicBlock *RemainderBB;
3552   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3553 
3554   // Apparently kill flags are only valid if the def is in the same block?
3555   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3556     Src->setIsKill(false);
3557 
3558   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3559 
3560   MachineBasicBlock::iterator I = LoopBB->end();
3561 
3562   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3563     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3564 
3565   // Clear TRAP_STS.MEM_VIOL
3566   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3567     .addImm(0)
3568     .addImm(EncodedReg);
3569 
3570   bundleInstWithWaitcnt(MI);
3571 
3572   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3573 
3574   // Load and check TRAP_STS.MEM_VIOL
3575   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3576     .addImm(EncodedReg);
3577 
3578   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3579   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3580     .addReg(Reg, RegState::Kill)
3581     .addImm(0);
3582   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3583     .addMBB(LoopBB);
3584 
3585   return RemainderBB;
3586 }
3587 
3588 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3589 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3590 // will only do one iteration. In the worst case, this will loop 64 times.
3591 //
3592 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3593 static MachineBasicBlock::iterator
3594 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3595                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3596                        const DebugLoc &DL, const MachineOperand &Idx,
3597                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3598                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3599                        Register &SGPRIdxReg) {
3600 
3601   MachineFunction *MF = OrigBB.getParent();
3602   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3603   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3604   MachineBasicBlock::iterator I = LoopBB.begin();
3605 
3606   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3607   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3608   Register NewExec = MRI.createVirtualRegister(BoolRC);
3609   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3610   Register CondReg = MRI.createVirtualRegister(BoolRC);
3611 
3612   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3613     .addReg(InitReg)
3614     .addMBB(&OrigBB)
3615     .addReg(ResultReg)
3616     .addMBB(&LoopBB);
3617 
3618   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3619     .addReg(InitSaveExecReg)
3620     .addMBB(&OrigBB)
3621     .addReg(NewExec)
3622     .addMBB(&LoopBB);
3623 
3624   // Read the next variant <- also loop target.
3625   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3626       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3627 
3628   // Compare the just read M0 value to all possible Idx values.
3629   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3630       .addReg(CurrentIdxReg)
3631       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3632 
3633   // Update EXEC, save the original EXEC value to VCC.
3634   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3635                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3636           NewExec)
3637     .addReg(CondReg, RegState::Kill);
3638 
3639   MRI.setSimpleHint(NewExec, CondReg);
3640 
3641   if (UseGPRIdxMode) {
3642     if (Offset == 0) {
3643       SGPRIdxReg = CurrentIdxReg;
3644     } else {
3645       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3646       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3647           .addReg(CurrentIdxReg, RegState::Kill)
3648           .addImm(Offset);
3649     }
3650   } else {
3651     // Move index from VCC into M0
3652     if (Offset == 0) {
3653       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3654         .addReg(CurrentIdxReg, RegState::Kill);
3655     } else {
3656       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3657         .addReg(CurrentIdxReg, RegState::Kill)
3658         .addImm(Offset);
3659     }
3660   }
3661 
3662   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3663   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3664   MachineInstr *InsertPt =
3665     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3666                                                   : AMDGPU::S_XOR_B64_term), Exec)
3667       .addReg(Exec)
3668       .addReg(NewExec);
3669 
3670   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3671   // s_cbranch_scc0?
3672 
3673   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3674   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3675     .addMBB(&LoopBB);
3676 
3677   return InsertPt->getIterator();
3678 }
3679 
3680 // This has slightly sub-optimal regalloc when the source vector is killed by
3681 // the read. The register allocator does not understand that the kill is
3682 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3683 // subregister from it, using 1 more VGPR than necessary. This was saved when
3684 // this was expanded after register allocation.
3685 static MachineBasicBlock::iterator
3686 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3687                unsigned InitResultReg, unsigned PhiReg, int Offset,
3688                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3689   MachineFunction *MF = MBB.getParent();
3690   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3691   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3692   MachineRegisterInfo &MRI = MF->getRegInfo();
3693   const DebugLoc &DL = MI.getDebugLoc();
3694   MachineBasicBlock::iterator I(&MI);
3695 
3696   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3697   Register DstReg = MI.getOperand(0).getReg();
3698   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3699   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3700   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3701   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3702 
3703   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3704 
3705   // Save the EXEC mask
3706   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3707     .addReg(Exec);
3708 
3709   MachineBasicBlock *LoopBB;
3710   MachineBasicBlock *RemainderBB;
3711   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3712 
3713   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3714 
3715   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3716                                       InitResultReg, DstReg, PhiReg, TmpExec,
3717                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3718 
3719   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3720   MachineFunction::iterator MBBI(LoopBB);
3721   ++MBBI;
3722   MF->insert(MBBI, LandingPad);
3723   LoopBB->removeSuccessor(RemainderBB);
3724   LandingPad->addSuccessor(RemainderBB);
3725   LoopBB->addSuccessor(LandingPad);
3726   MachineBasicBlock::iterator First = LandingPad->begin();
3727   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3728     .addReg(SaveExec);
3729 
3730   return InsPt;
3731 }
3732 
3733 // Returns subreg index, offset
3734 static std::pair<unsigned, int>
3735 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3736                             const TargetRegisterClass *SuperRC,
3737                             unsigned VecReg,
3738                             int Offset) {
3739   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3740 
3741   // Skip out of bounds offsets, or else we would end up using an undefined
3742   // register.
3743   if (Offset >= NumElts || Offset < 0)
3744     return std::make_pair(AMDGPU::sub0, Offset);
3745 
3746   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3747 }
3748 
3749 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3750                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3751                                  int Offset) {
3752   MachineBasicBlock *MBB = MI.getParent();
3753   const DebugLoc &DL = MI.getDebugLoc();
3754   MachineBasicBlock::iterator I(&MI);
3755 
3756   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3757 
3758   assert(Idx->getReg() != AMDGPU::NoRegister);
3759 
3760   if (Offset == 0) {
3761     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3762   } else {
3763     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3764         .add(*Idx)
3765         .addImm(Offset);
3766   }
3767 }
3768 
3769 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3770                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3771                                    int Offset) {
3772   MachineBasicBlock *MBB = MI.getParent();
3773   const DebugLoc &DL = MI.getDebugLoc();
3774   MachineBasicBlock::iterator I(&MI);
3775 
3776   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3777 
3778   if (Offset == 0)
3779     return Idx->getReg();
3780 
3781   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3782   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3783       .add(*Idx)
3784       .addImm(Offset);
3785   return Tmp;
3786 }
3787 
3788 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3789                                           MachineBasicBlock &MBB,
3790                                           const GCNSubtarget &ST) {
3791   const SIInstrInfo *TII = ST.getInstrInfo();
3792   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3793   MachineFunction *MF = MBB.getParent();
3794   MachineRegisterInfo &MRI = MF->getRegInfo();
3795 
3796   Register Dst = MI.getOperand(0).getReg();
3797   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3798   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3799   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3800 
3801   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3802   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3803 
3804   unsigned SubReg;
3805   std::tie(SubReg, Offset)
3806     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3807 
3808   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3809 
3810   // Check for a SGPR index.
3811   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3812     MachineBasicBlock::iterator I(&MI);
3813     const DebugLoc &DL = MI.getDebugLoc();
3814 
3815     if (UseGPRIdxMode) {
3816       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3817       // to avoid interfering with other uses, so probably requires a new
3818       // optimization pass.
3819       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3820 
3821       const MCInstrDesc &GPRIDXDesc =
3822           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3823       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3824           .addReg(SrcReg)
3825           .addReg(Idx)
3826           .addImm(SubReg);
3827     } else {
3828       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3829 
3830       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3831         .addReg(SrcReg, 0, SubReg)
3832         .addReg(SrcReg, RegState::Implicit);
3833     }
3834 
3835     MI.eraseFromParent();
3836 
3837     return &MBB;
3838   }
3839 
3840   // Control flow needs to be inserted if indexing with a VGPR.
3841   const DebugLoc &DL = MI.getDebugLoc();
3842   MachineBasicBlock::iterator I(&MI);
3843 
3844   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3845   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3846 
3847   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3848 
3849   Register SGPRIdxReg;
3850   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3851                               UseGPRIdxMode, SGPRIdxReg);
3852 
3853   MachineBasicBlock *LoopBB = InsPt->getParent();
3854 
3855   if (UseGPRIdxMode) {
3856     const MCInstrDesc &GPRIDXDesc =
3857         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3858 
3859     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3860         .addReg(SrcReg)
3861         .addReg(SGPRIdxReg)
3862         .addImm(SubReg);
3863   } else {
3864     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3865       .addReg(SrcReg, 0, SubReg)
3866       .addReg(SrcReg, RegState::Implicit);
3867   }
3868 
3869   MI.eraseFromParent();
3870 
3871   return LoopBB;
3872 }
3873 
3874 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3875                                           MachineBasicBlock &MBB,
3876                                           const GCNSubtarget &ST) {
3877   const SIInstrInfo *TII = ST.getInstrInfo();
3878   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3879   MachineFunction *MF = MBB.getParent();
3880   MachineRegisterInfo &MRI = MF->getRegInfo();
3881 
3882   Register Dst = MI.getOperand(0).getReg();
3883   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3884   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3885   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3886   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3887   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3888   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3889 
3890   // This can be an immediate, but will be folded later.
3891   assert(Val->getReg());
3892 
3893   unsigned SubReg;
3894   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3895                                                          SrcVec->getReg(),
3896                                                          Offset);
3897   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3898 
3899   if (Idx->getReg() == AMDGPU::NoRegister) {
3900     MachineBasicBlock::iterator I(&MI);
3901     const DebugLoc &DL = MI.getDebugLoc();
3902 
3903     assert(Offset == 0);
3904 
3905     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3906         .add(*SrcVec)
3907         .add(*Val)
3908         .addImm(SubReg);
3909 
3910     MI.eraseFromParent();
3911     return &MBB;
3912   }
3913 
3914   // Check for a SGPR index.
3915   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3916     MachineBasicBlock::iterator I(&MI);
3917     const DebugLoc &DL = MI.getDebugLoc();
3918 
3919     if (UseGPRIdxMode) {
3920       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3921 
3922       const MCInstrDesc &GPRIDXDesc =
3923           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3924       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3925           .addReg(SrcVec->getReg())
3926           .add(*Val)
3927           .addReg(Idx)
3928           .addImm(SubReg);
3929     } else {
3930       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3931 
3932       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3933           TRI.getRegSizeInBits(*VecRC), 32, false);
3934       BuildMI(MBB, I, DL, MovRelDesc, Dst)
3935           .addReg(SrcVec->getReg())
3936           .add(*Val)
3937           .addImm(SubReg);
3938     }
3939     MI.eraseFromParent();
3940     return &MBB;
3941   }
3942 
3943   // Control flow needs to be inserted if indexing with a VGPR.
3944   if (Val->isReg())
3945     MRI.clearKillFlags(Val->getReg());
3946 
3947   const DebugLoc &DL = MI.getDebugLoc();
3948 
3949   Register PhiReg = MRI.createVirtualRegister(VecRC);
3950 
3951   Register SGPRIdxReg;
3952   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
3953                               UseGPRIdxMode, SGPRIdxReg);
3954   MachineBasicBlock *LoopBB = InsPt->getParent();
3955 
3956   if (UseGPRIdxMode) {
3957     const MCInstrDesc &GPRIDXDesc =
3958         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3959 
3960     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3961         .addReg(PhiReg)
3962         .add(*Val)
3963         .addReg(SGPRIdxReg)
3964         .addImm(AMDGPU::sub0);
3965   } else {
3966     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3967         TRI.getRegSizeInBits(*VecRC), 32, false);
3968     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3969         .addReg(PhiReg)
3970         .add(*Val)
3971         .addImm(AMDGPU::sub0);
3972   }
3973 
3974   MI.eraseFromParent();
3975   return LoopBB;
3976 }
3977 
3978 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3979   MachineInstr &MI, MachineBasicBlock *BB) const {
3980 
3981   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3982   MachineFunction *MF = BB->getParent();
3983   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3984 
3985   switch (MI.getOpcode()) {
3986   case AMDGPU::S_UADDO_PSEUDO:
3987   case AMDGPU::S_USUBO_PSEUDO: {
3988     const DebugLoc &DL = MI.getDebugLoc();
3989     MachineOperand &Dest0 = MI.getOperand(0);
3990     MachineOperand &Dest1 = MI.getOperand(1);
3991     MachineOperand &Src0 = MI.getOperand(2);
3992     MachineOperand &Src1 = MI.getOperand(3);
3993 
3994     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3995                        ? AMDGPU::S_ADD_I32
3996                        : AMDGPU::S_SUB_I32;
3997     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3998 
3999     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
4000         .addImm(1)
4001         .addImm(0);
4002 
4003     MI.eraseFromParent();
4004     return BB;
4005   }
4006   case AMDGPU::S_ADD_U64_PSEUDO:
4007   case AMDGPU::S_SUB_U64_PSEUDO: {
4008     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4009     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4010     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4011     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
4012     const DebugLoc &DL = MI.getDebugLoc();
4013 
4014     MachineOperand &Dest = MI.getOperand(0);
4015     MachineOperand &Src0 = MI.getOperand(1);
4016     MachineOperand &Src1 = MI.getOperand(2);
4017 
4018     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4019     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4020 
4021     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
4022         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4023     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
4024         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4025 
4026     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
4027         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4028     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
4029         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4030 
4031     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
4032 
4033     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
4034     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
4035     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
4036     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
4037     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4038         .addReg(DestSub0)
4039         .addImm(AMDGPU::sub0)
4040         .addReg(DestSub1)
4041         .addImm(AMDGPU::sub1);
4042     MI.eraseFromParent();
4043     return BB;
4044   }
4045   case AMDGPU::V_ADD_U64_PSEUDO:
4046   case AMDGPU::V_SUB_U64_PSEUDO: {
4047     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4048     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4049     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4050     const DebugLoc &DL = MI.getDebugLoc();
4051 
4052     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
4053 
4054     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4055 
4056     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4057     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4058 
4059     Register CarryReg = MRI.createVirtualRegister(CarryRC);
4060     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
4061 
4062     MachineOperand &Dest = MI.getOperand(0);
4063     MachineOperand &Src0 = MI.getOperand(1);
4064     MachineOperand &Src1 = MI.getOperand(2);
4065 
4066     const TargetRegisterClass *Src0RC = Src0.isReg()
4067                                             ? MRI.getRegClass(Src0.getReg())
4068                                             : &AMDGPU::VReg_64RegClass;
4069     const TargetRegisterClass *Src1RC = Src1.isReg()
4070                                             ? MRI.getRegClass(Src1.getReg())
4071                                             : &AMDGPU::VReg_64RegClass;
4072 
4073     const TargetRegisterClass *Src0SubRC =
4074         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
4075     const TargetRegisterClass *Src1SubRC =
4076         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
4077 
4078     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
4079         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
4080     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
4081         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
4082 
4083     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
4084         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
4085     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
4086         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
4087 
4088     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
4089     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
4090                                .addReg(CarryReg, RegState::Define)
4091                                .add(SrcReg0Sub0)
4092                                .add(SrcReg1Sub0)
4093                                .addImm(0); // clamp bit
4094 
4095     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
4096     MachineInstr *HiHalf =
4097         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4098             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4099             .add(SrcReg0Sub1)
4100             .add(SrcReg1Sub1)
4101             .addReg(CarryReg, RegState::Kill)
4102             .addImm(0); // clamp bit
4103 
4104     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4105         .addReg(DestSub0)
4106         .addImm(AMDGPU::sub0)
4107         .addReg(DestSub1)
4108         .addImm(AMDGPU::sub1);
4109     TII->legalizeOperands(*LoHalf);
4110     TII->legalizeOperands(*HiHalf);
4111     MI.eraseFromParent();
4112     return BB;
4113   }
4114   case AMDGPU::S_ADD_CO_PSEUDO:
4115   case AMDGPU::S_SUB_CO_PSEUDO: {
4116     // This pseudo has a chance to be selected
4117     // only from uniform add/subcarry node. All the VGPR operands
4118     // therefore assumed to be splat vectors.
4119     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4120     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4121     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4122     MachineBasicBlock::iterator MII = MI;
4123     const DebugLoc &DL = MI.getDebugLoc();
4124     MachineOperand &Dest = MI.getOperand(0);
4125     MachineOperand &CarryDest = MI.getOperand(1);
4126     MachineOperand &Src0 = MI.getOperand(2);
4127     MachineOperand &Src1 = MI.getOperand(3);
4128     MachineOperand &Src2 = MI.getOperand(4);
4129     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4130                        ? AMDGPU::S_ADDC_U32
4131                        : AMDGPU::S_SUBB_U32;
4132     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4133       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4134       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4135           .addReg(Src0.getReg());
4136       Src0.setReg(RegOp0);
4137     }
4138     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4139       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4140       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4141           .addReg(Src1.getReg());
4142       Src1.setReg(RegOp1);
4143     }
4144     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4145     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4146       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4147           .addReg(Src2.getReg());
4148       Src2.setReg(RegOp2);
4149     }
4150 
4151     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4152     unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC);
4153     assert(WaveSize == 64 || WaveSize == 32);
4154 
4155     if (WaveSize == 64) {
4156       if (ST.hasScalarCompareEq64()) {
4157         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4158             .addReg(Src2.getReg())
4159             .addImm(0);
4160       } else {
4161         const TargetRegisterClass *SubRC =
4162             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4163         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4164             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4165         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4166             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4167         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4168 
4169         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4170             .add(Src2Sub0)
4171             .add(Src2Sub1);
4172 
4173         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4174             .addReg(Src2_32, RegState::Kill)
4175             .addImm(0);
4176       }
4177     } else {
4178       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4179           .addReg(Src2.getReg())
4180           .addImm(0);
4181     }
4182 
4183     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4184 
4185     unsigned SelOpc =
4186         (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
4187 
4188     BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg())
4189         .addImm(-1)
4190         .addImm(0);
4191 
4192     MI.eraseFromParent();
4193     return BB;
4194   }
4195   case AMDGPU::SI_INIT_M0: {
4196     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4197             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4198         .add(MI.getOperand(0));
4199     MI.eraseFromParent();
4200     return BB;
4201   }
4202   case AMDGPU::GET_GROUPSTATICSIZE: {
4203     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4204            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4205     DebugLoc DL = MI.getDebugLoc();
4206     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4207         .add(MI.getOperand(0))
4208         .addImm(MFI->getLDSSize());
4209     MI.eraseFromParent();
4210     return BB;
4211   }
4212   case AMDGPU::SI_INDIRECT_SRC_V1:
4213   case AMDGPU::SI_INDIRECT_SRC_V2:
4214   case AMDGPU::SI_INDIRECT_SRC_V4:
4215   case AMDGPU::SI_INDIRECT_SRC_V8:
4216   case AMDGPU::SI_INDIRECT_SRC_V16:
4217   case AMDGPU::SI_INDIRECT_SRC_V32:
4218     return emitIndirectSrc(MI, *BB, *getSubtarget());
4219   case AMDGPU::SI_INDIRECT_DST_V1:
4220   case AMDGPU::SI_INDIRECT_DST_V2:
4221   case AMDGPU::SI_INDIRECT_DST_V4:
4222   case AMDGPU::SI_INDIRECT_DST_V8:
4223   case AMDGPU::SI_INDIRECT_DST_V16:
4224   case AMDGPU::SI_INDIRECT_DST_V32:
4225     return emitIndirectDst(MI, *BB, *getSubtarget());
4226   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4227   case AMDGPU::SI_KILL_I1_PSEUDO:
4228     return splitKillBlock(MI, BB);
4229   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4230     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4231     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4232     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4233 
4234     Register Dst = MI.getOperand(0).getReg();
4235     Register Src0 = MI.getOperand(1).getReg();
4236     Register Src1 = MI.getOperand(2).getReg();
4237     const DebugLoc &DL = MI.getDebugLoc();
4238     Register SrcCond = MI.getOperand(3).getReg();
4239 
4240     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4241     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4242     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4243     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4244 
4245     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4246       .addReg(SrcCond);
4247     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4248       .addImm(0)
4249       .addReg(Src0, 0, AMDGPU::sub0)
4250       .addImm(0)
4251       .addReg(Src1, 0, AMDGPU::sub0)
4252       .addReg(SrcCondCopy);
4253     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4254       .addImm(0)
4255       .addReg(Src0, 0, AMDGPU::sub1)
4256       .addImm(0)
4257       .addReg(Src1, 0, AMDGPU::sub1)
4258       .addReg(SrcCondCopy);
4259 
4260     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4261       .addReg(DstLo)
4262       .addImm(AMDGPU::sub0)
4263       .addReg(DstHi)
4264       .addImm(AMDGPU::sub1);
4265     MI.eraseFromParent();
4266     return BB;
4267   }
4268   case AMDGPU::SI_BR_UNDEF: {
4269     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4270     const DebugLoc &DL = MI.getDebugLoc();
4271     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4272                            .add(MI.getOperand(0));
4273     Br->getOperand(1).setIsUndef(true); // read undef SCC
4274     MI.eraseFromParent();
4275     return BB;
4276   }
4277   case AMDGPU::ADJCALLSTACKUP:
4278   case AMDGPU::ADJCALLSTACKDOWN: {
4279     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4280     MachineInstrBuilder MIB(*MF, &MI);
4281     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4282        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4283     return BB;
4284   }
4285   case AMDGPU::SI_CALL_ISEL: {
4286     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4287     const DebugLoc &DL = MI.getDebugLoc();
4288 
4289     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4290 
4291     MachineInstrBuilder MIB;
4292     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4293 
4294     for (const MachineOperand &MO : MI.operands())
4295       MIB.add(MO);
4296 
4297     MIB.cloneMemRefs(MI);
4298     MI.eraseFromParent();
4299     return BB;
4300   }
4301   case AMDGPU::V_ADD_CO_U32_e32:
4302   case AMDGPU::V_SUB_CO_U32_e32:
4303   case AMDGPU::V_SUBREV_CO_U32_e32: {
4304     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4305     const DebugLoc &DL = MI.getDebugLoc();
4306     unsigned Opc = MI.getOpcode();
4307 
4308     bool NeedClampOperand = false;
4309     if (TII->pseudoToMCOpcode(Opc) == -1) {
4310       Opc = AMDGPU::getVOPe64(Opc);
4311       NeedClampOperand = true;
4312     }
4313 
4314     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4315     if (TII->isVOP3(*I)) {
4316       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4317       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4318       I.addReg(TRI->getVCC(), RegState::Define);
4319     }
4320     I.add(MI.getOperand(1))
4321      .add(MI.getOperand(2));
4322     if (NeedClampOperand)
4323       I.addImm(0); // clamp bit for e64 encoding
4324 
4325     TII->legalizeOperands(*I);
4326 
4327     MI.eraseFromParent();
4328     return BB;
4329   }
4330   case AMDGPU::V_ADDC_U32_e32:
4331   case AMDGPU::V_SUBB_U32_e32:
4332   case AMDGPU::V_SUBBREV_U32_e32:
4333     // These instructions have an implicit use of vcc which counts towards the
4334     // constant bus limit.
4335     TII->legalizeOperands(MI);
4336     return BB;
4337   case AMDGPU::DS_GWS_INIT:
4338   case AMDGPU::DS_GWS_SEMA_BR:
4339   case AMDGPU::DS_GWS_BARRIER:
4340     if (Subtarget->needsAlignedVGPRs()) {
4341       // Add implicit aligned super-reg to force alignment on the data operand.
4342       const DebugLoc &DL = MI.getDebugLoc();
4343       MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4344       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
4345       MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0);
4346       Register DataReg = Op->getReg();
4347       bool IsAGPR = TRI->isAGPR(MRI, DataReg);
4348       Register Undef = MRI.createVirtualRegister(
4349           IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass);
4350       BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef);
4351       Register NewVR =
4352           MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass
4353                                            : &AMDGPU::VReg_64_Align2RegClass);
4354       BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR)
4355           .addReg(DataReg, 0, Op->getSubReg())
4356           .addImm(AMDGPU::sub0)
4357           .addReg(Undef)
4358           .addImm(AMDGPU::sub1);
4359       Op->setReg(NewVR);
4360       Op->setSubReg(AMDGPU::sub0);
4361       MI.addOperand(MachineOperand::CreateReg(NewVR, false, true));
4362     }
4363     LLVM_FALLTHROUGH;
4364   case AMDGPU::DS_GWS_SEMA_V:
4365   case AMDGPU::DS_GWS_SEMA_P:
4366   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4367     // A s_waitcnt 0 is required to be the instruction immediately following.
4368     if (getSubtarget()->hasGWSAutoReplay()) {
4369       bundleInstWithWaitcnt(MI);
4370       return BB;
4371     }
4372 
4373     return emitGWSMemViolTestLoop(MI, BB);
4374   case AMDGPU::S_SETREG_B32: {
4375     // Try to optimize cases that only set the denormal mode or rounding mode.
4376     //
4377     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4378     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4379     // instead.
4380     //
4381     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4382     // allow you to have a no side effect instruction in the output of a
4383     // sideeffecting pattern.
4384     unsigned ID, Offset, Width;
4385     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4386     if (ID != AMDGPU::Hwreg::ID_MODE)
4387       return BB;
4388 
4389     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4390     const unsigned SetMask = WidthMask << Offset;
4391 
4392     if (getSubtarget()->hasDenormModeInst()) {
4393       unsigned SetDenormOp = 0;
4394       unsigned SetRoundOp = 0;
4395 
4396       // The dedicated instructions can only set the whole denorm or round mode
4397       // at once, not a subset of bits in either.
4398       if (SetMask ==
4399           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4400         // If this fully sets both the round and denorm mode, emit the two
4401         // dedicated instructions for these.
4402         SetRoundOp = AMDGPU::S_ROUND_MODE;
4403         SetDenormOp = AMDGPU::S_DENORM_MODE;
4404       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4405         SetRoundOp = AMDGPU::S_ROUND_MODE;
4406       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4407         SetDenormOp = AMDGPU::S_DENORM_MODE;
4408       }
4409 
4410       if (SetRoundOp || SetDenormOp) {
4411         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4412         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4413         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4414           unsigned ImmVal = Def->getOperand(1).getImm();
4415           if (SetRoundOp) {
4416             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4417                 .addImm(ImmVal & 0xf);
4418 
4419             // If we also have the denorm mode, get just the denorm mode bits.
4420             ImmVal >>= 4;
4421           }
4422 
4423           if (SetDenormOp) {
4424             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4425                 .addImm(ImmVal & 0xf);
4426           }
4427 
4428           MI.eraseFromParent();
4429           return BB;
4430         }
4431       }
4432     }
4433 
4434     // If only FP bits are touched, used the no side effects pseudo.
4435     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4436                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4437       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4438 
4439     return BB;
4440   }
4441   default:
4442     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4443   }
4444 }
4445 
4446 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4447   return isTypeLegal(VT.getScalarType());
4448 }
4449 
4450 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4451   // This currently forces unfolding various combinations of fsub into fma with
4452   // free fneg'd operands. As long as we have fast FMA (controlled by
4453   // isFMAFasterThanFMulAndFAdd), we should perform these.
4454 
4455   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4456   // most of these combines appear to be cycle neutral but save on instruction
4457   // count / code size.
4458   return true;
4459 }
4460 
4461 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; }
4462 
4463 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4464                                          EVT VT) const {
4465   if (!VT.isVector()) {
4466     return MVT::i1;
4467   }
4468   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4469 }
4470 
4471 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4472   // TODO: Should i16 be used always if legal? For now it would force VALU
4473   // shifts.
4474   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4475 }
4476 
4477 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4478   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4479              ? Ty.changeElementSize(16)
4480              : Ty.changeElementSize(32);
4481 }
4482 
4483 // Answering this is somewhat tricky and depends on the specific device which
4484 // have different rates for fma or all f64 operations.
4485 //
4486 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4487 // regardless of which device (although the number of cycles differs between
4488 // devices), so it is always profitable for f64.
4489 //
4490 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4491 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4492 // which we can always do even without fused FP ops since it returns the same
4493 // result as the separate operations and since it is always full
4494 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4495 // however does not support denormals, so we do report fma as faster if we have
4496 // a fast fma device and require denormals.
4497 //
4498 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4499                                                   EVT VT) const {
4500   VT = VT.getScalarType();
4501 
4502   switch (VT.getSimpleVT().SimpleTy) {
4503   case MVT::f32: {
4504     // If mad is not available this depends only on if f32 fma is full rate.
4505     if (!Subtarget->hasMadMacF32Insts())
4506       return Subtarget->hasFastFMAF32();
4507 
4508     // Otherwise f32 mad is always full rate and returns the same result as
4509     // the separate operations so should be preferred over fma.
4510     // However does not support denomals.
4511     if (hasFP32Denormals(MF))
4512       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4513 
4514     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4515     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4516   }
4517   case MVT::f64:
4518     return true;
4519   case MVT::f16:
4520     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4521   default:
4522     break;
4523   }
4524 
4525   return false;
4526 }
4527 
4528 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4529                                                   LLT Ty) const {
4530   switch (Ty.getScalarSizeInBits()) {
4531   case 16:
4532     return isFMAFasterThanFMulAndFAdd(MF, MVT::f16);
4533   case 32:
4534     return isFMAFasterThanFMulAndFAdd(MF, MVT::f32);
4535   case 64:
4536     return isFMAFasterThanFMulAndFAdd(MF, MVT::f64);
4537   default:
4538     break;
4539   }
4540 
4541   return false;
4542 }
4543 
4544 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const {
4545   if (!Ty.isScalar())
4546     return false;
4547 
4548   if (Ty.getScalarSizeInBits() == 16)
4549     return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF());
4550   if (Ty.getScalarSizeInBits() == 32)
4551     return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF());
4552 
4553   return false;
4554 }
4555 
4556 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4557                                    const SDNode *N) const {
4558   // TODO: Check future ftz flag
4559   // v_mad_f32/v_mac_f32 do not support denormals.
4560   EVT VT = N->getValueType(0);
4561   if (VT == MVT::f32)
4562     return Subtarget->hasMadMacF32Insts() &&
4563            !hasFP32Denormals(DAG.getMachineFunction());
4564   if (VT == MVT::f16) {
4565     return Subtarget->hasMadF16() &&
4566            !hasFP64FP16Denormals(DAG.getMachineFunction());
4567   }
4568 
4569   return false;
4570 }
4571 
4572 //===----------------------------------------------------------------------===//
4573 // Custom DAG Lowering Operations
4574 //===----------------------------------------------------------------------===//
4575 
4576 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4577 // wider vector type is legal.
4578 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4579                                              SelectionDAG &DAG) const {
4580   unsigned Opc = Op.getOpcode();
4581   EVT VT = Op.getValueType();
4582   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4583 
4584   SDValue Lo, Hi;
4585   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4586 
4587   SDLoc SL(Op);
4588   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4589                              Op->getFlags());
4590   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4591                              Op->getFlags());
4592 
4593   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4594 }
4595 
4596 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4597 // wider vector type is legal.
4598 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4599                                               SelectionDAG &DAG) const {
4600   unsigned Opc = Op.getOpcode();
4601   EVT VT = Op.getValueType();
4602   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4603          VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32);
4604 
4605   SDValue Lo0, Hi0;
4606   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4607   SDValue Lo1, Hi1;
4608   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4609 
4610   SDLoc SL(Op);
4611 
4612   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4613                              Op->getFlags());
4614   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4615                              Op->getFlags());
4616 
4617   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4618 }
4619 
4620 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4621                                               SelectionDAG &DAG) const {
4622   unsigned Opc = Op.getOpcode();
4623   EVT VT = Op.getValueType();
4624   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4625          VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32);
4626 
4627   SDValue Lo0, Hi0;
4628   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4629   SDValue Lo1, Hi1;
4630   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4631   SDValue Lo2, Hi2;
4632   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4633 
4634   SDLoc SL(Op);
4635 
4636   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4637                              Op->getFlags());
4638   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4639                              Op->getFlags());
4640 
4641   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4642 }
4643 
4644 
4645 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4646   switch (Op.getOpcode()) {
4647   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4648   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4649   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4650   case ISD::LOAD: {
4651     SDValue Result = LowerLOAD(Op, DAG);
4652     assert((!Result.getNode() ||
4653             Result.getNode()->getNumValues() == 2) &&
4654            "Load should return a value and a chain");
4655     return Result;
4656   }
4657 
4658   case ISD::FSIN:
4659   case ISD::FCOS:
4660     return LowerTrig(Op, DAG);
4661   case ISD::SELECT: return LowerSELECT(Op, DAG);
4662   case ISD::FDIV: return LowerFDIV(Op, DAG);
4663   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4664   case ISD::STORE: return LowerSTORE(Op, DAG);
4665   case ISD::GlobalAddress: {
4666     MachineFunction &MF = DAG.getMachineFunction();
4667     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4668     return LowerGlobalAddress(MFI, Op, DAG);
4669   }
4670   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4671   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4672   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4673   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4674   case ISD::INSERT_SUBVECTOR:
4675     return lowerINSERT_SUBVECTOR(Op, DAG);
4676   case ISD::INSERT_VECTOR_ELT:
4677     return lowerINSERT_VECTOR_ELT(Op, DAG);
4678   case ISD::EXTRACT_VECTOR_ELT:
4679     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4680   case ISD::VECTOR_SHUFFLE:
4681     return lowerVECTOR_SHUFFLE(Op, DAG);
4682   case ISD::BUILD_VECTOR:
4683     return lowerBUILD_VECTOR(Op, DAG);
4684   case ISD::FP_ROUND:
4685     return lowerFP_ROUND(Op, DAG);
4686   case ISD::TRAP:
4687     return lowerTRAP(Op, DAG);
4688   case ISD::DEBUGTRAP:
4689     return lowerDEBUGTRAP(Op, DAG);
4690   case ISD::FABS:
4691   case ISD::FNEG:
4692   case ISD::FCANONICALIZE:
4693   case ISD::BSWAP:
4694     return splitUnaryVectorOp(Op, DAG);
4695   case ISD::FMINNUM:
4696   case ISD::FMAXNUM:
4697     return lowerFMINNUM_FMAXNUM(Op, DAG);
4698   case ISD::FMA:
4699     return splitTernaryVectorOp(Op, DAG);
4700   case ISD::FP_TO_SINT:
4701   case ISD::FP_TO_UINT:
4702     return LowerFP_TO_INT(Op, DAG);
4703   case ISD::SHL:
4704   case ISD::SRA:
4705   case ISD::SRL:
4706   case ISD::ADD:
4707   case ISD::SUB:
4708   case ISD::MUL:
4709   case ISD::SMIN:
4710   case ISD::SMAX:
4711   case ISD::UMIN:
4712   case ISD::UMAX:
4713   case ISD::FADD:
4714   case ISD::FMUL:
4715   case ISD::FMINNUM_IEEE:
4716   case ISD::FMAXNUM_IEEE:
4717   case ISD::UADDSAT:
4718   case ISD::USUBSAT:
4719   case ISD::SADDSAT:
4720   case ISD::SSUBSAT:
4721     return splitBinaryVectorOp(Op, DAG);
4722   case ISD::SMULO:
4723   case ISD::UMULO:
4724     return lowerXMULO(Op, DAG);
4725   case ISD::SMUL_LOHI:
4726   case ISD::UMUL_LOHI:
4727     return lowerXMUL_LOHI(Op, DAG);
4728   case ISD::DYNAMIC_STACKALLOC:
4729     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4730   }
4731   return SDValue();
4732 }
4733 
4734 // Used for D16: Casts the result of an instruction into the right vector,
4735 // packs values if loads return unpacked values.
4736 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4737                                        const SDLoc &DL,
4738                                        SelectionDAG &DAG, bool Unpacked) {
4739   if (!LoadVT.isVector())
4740     return Result;
4741 
4742   // Cast back to the original packed type or to a larger type that is a
4743   // multiple of 32 bit for D16. Widening the return type is a required for
4744   // legalization.
4745   EVT FittingLoadVT = LoadVT;
4746   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4747     FittingLoadVT =
4748         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4749                          LoadVT.getVectorNumElements() + 1);
4750   }
4751 
4752   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4753     // Truncate to v2i16/v4i16.
4754     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4755 
4756     // Workaround legalizer not scalarizing truncate after vector op
4757     // legalization but not creating intermediate vector trunc.
4758     SmallVector<SDValue, 4> Elts;
4759     DAG.ExtractVectorElements(Result, Elts);
4760     for (SDValue &Elt : Elts)
4761       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4762 
4763     // Pad illegal v1i16/v3fi6 to v4i16
4764     if ((LoadVT.getVectorNumElements() % 2) == 1)
4765       Elts.push_back(DAG.getUNDEF(MVT::i16));
4766 
4767     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4768 
4769     // Bitcast to original type (v2f16/v4f16).
4770     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4771   }
4772 
4773   // Cast back to the original packed type.
4774   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4775 }
4776 
4777 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4778                                               MemSDNode *M,
4779                                               SelectionDAG &DAG,
4780                                               ArrayRef<SDValue> Ops,
4781                                               bool IsIntrinsic) const {
4782   SDLoc DL(M);
4783 
4784   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4785   EVT LoadVT = M->getValueType(0);
4786 
4787   EVT EquivLoadVT = LoadVT;
4788   if (LoadVT.isVector()) {
4789     if (Unpacked) {
4790       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4791                                      LoadVT.getVectorNumElements());
4792     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4793       // Widen v3f16 to legal type
4794       EquivLoadVT =
4795           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4796                            LoadVT.getVectorNumElements() + 1);
4797     }
4798   }
4799 
4800   // Change from v4f16/v2f16 to EquivLoadVT.
4801   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4802 
4803   SDValue Load
4804     = DAG.getMemIntrinsicNode(
4805       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4806       VTList, Ops, M->getMemoryVT(),
4807       M->getMemOperand());
4808 
4809   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4810 
4811   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4812 }
4813 
4814 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4815                                              SelectionDAG &DAG,
4816                                              ArrayRef<SDValue> Ops) const {
4817   SDLoc DL(M);
4818   EVT LoadVT = M->getValueType(0);
4819   EVT EltType = LoadVT.getScalarType();
4820   EVT IntVT = LoadVT.changeTypeToInteger();
4821 
4822   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4823 
4824   unsigned Opc =
4825       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4826 
4827   if (IsD16) {
4828     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4829   }
4830 
4831   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4832   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4833     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4834 
4835   if (isTypeLegal(LoadVT)) {
4836     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4837                                M->getMemOperand(), DAG);
4838   }
4839 
4840   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4841   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4842   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4843                                         M->getMemOperand(), DAG);
4844   return DAG.getMergeValues(
4845       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4846       DL);
4847 }
4848 
4849 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4850                                   SDNode *N, SelectionDAG &DAG) {
4851   EVT VT = N->getValueType(0);
4852   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4853   unsigned CondCode = CD->getZExtValue();
4854   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4855     return DAG.getUNDEF(VT);
4856 
4857   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4858 
4859   SDValue LHS = N->getOperand(1);
4860   SDValue RHS = N->getOperand(2);
4861 
4862   SDLoc DL(N);
4863 
4864   EVT CmpVT = LHS.getValueType();
4865   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4866     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4867       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4868     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4869     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4870   }
4871 
4872   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4873 
4874   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4875   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4876 
4877   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4878                               DAG.getCondCode(CCOpcode));
4879   if (VT.bitsEq(CCVT))
4880     return SetCC;
4881   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4882 }
4883 
4884 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4885                                   SDNode *N, SelectionDAG &DAG) {
4886   EVT VT = N->getValueType(0);
4887   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4888 
4889   unsigned CondCode = CD->getZExtValue();
4890   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4891     return DAG.getUNDEF(VT);
4892 
4893   SDValue Src0 = N->getOperand(1);
4894   SDValue Src1 = N->getOperand(2);
4895   EVT CmpVT = Src0.getValueType();
4896   SDLoc SL(N);
4897 
4898   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4899     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4900     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4901   }
4902 
4903   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4904   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4905   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4906   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4907   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4908                               Src1, DAG.getCondCode(CCOpcode));
4909   if (VT.bitsEq(CCVT))
4910     return SetCC;
4911   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4912 }
4913 
4914 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4915                                     SelectionDAG &DAG) {
4916   EVT VT = N->getValueType(0);
4917   SDValue Src = N->getOperand(1);
4918   SDLoc SL(N);
4919 
4920   if (Src.getOpcode() == ISD::SETCC) {
4921     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4922     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4923                        Src.getOperand(1), Src.getOperand(2));
4924   }
4925   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4926     // (ballot 0) -> 0
4927     if (Arg->isZero())
4928       return DAG.getConstant(0, SL, VT);
4929 
4930     // (ballot 1) -> EXEC/EXEC_LO
4931     if (Arg->isOne()) {
4932       Register Exec;
4933       if (VT.getScalarSizeInBits() == 32)
4934         Exec = AMDGPU::EXEC_LO;
4935       else if (VT.getScalarSizeInBits() == 64)
4936         Exec = AMDGPU::EXEC;
4937       else
4938         return SDValue();
4939 
4940       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4941     }
4942   }
4943 
4944   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4945   // ISD::SETNE)
4946   return DAG.getNode(
4947       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4948       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4949 }
4950 
4951 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4952                                           SmallVectorImpl<SDValue> &Results,
4953                                           SelectionDAG &DAG) const {
4954   switch (N->getOpcode()) {
4955   case ISD::INSERT_VECTOR_ELT: {
4956     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4957       Results.push_back(Res);
4958     return;
4959   }
4960   case ISD::EXTRACT_VECTOR_ELT: {
4961     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4962       Results.push_back(Res);
4963     return;
4964   }
4965   case ISD::INTRINSIC_WO_CHAIN: {
4966     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4967     switch (IID) {
4968     case Intrinsic::amdgcn_cvt_pkrtz: {
4969       SDValue Src0 = N->getOperand(1);
4970       SDValue Src1 = N->getOperand(2);
4971       SDLoc SL(N);
4972       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4973                                 Src0, Src1);
4974       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4975       return;
4976     }
4977     case Intrinsic::amdgcn_cvt_pknorm_i16:
4978     case Intrinsic::amdgcn_cvt_pknorm_u16:
4979     case Intrinsic::amdgcn_cvt_pk_i16:
4980     case Intrinsic::amdgcn_cvt_pk_u16: {
4981       SDValue Src0 = N->getOperand(1);
4982       SDValue Src1 = N->getOperand(2);
4983       SDLoc SL(N);
4984       unsigned Opcode;
4985 
4986       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4987         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4988       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4989         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4990       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4991         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4992       else
4993         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4994 
4995       EVT VT = N->getValueType(0);
4996       if (isTypeLegal(VT))
4997         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4998       else {
4999         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
5000         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
5001       }
5002       return;
5003     }
5004     }
5005     break;
5006   }
5007   case ISD::INTRINSIC_W_CHAIN: {
5008     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
5009       if (Res.getOpcode() == ISD::MERGE_VALUES) {
5010         // FIXME: Hacky
5011         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
5012           Results.push_back(Res.getOperand(I));
5013         }
5014       } else {
5015         Results.push_back(Res);
5016         Results.push_back(Res.getValue(1));
5017       }
5018       return;
5019     }
5020 
5021     break;
5022   }
5023   case ISD::SELECT: {
5024     SDLoc SL(N);
5025     EVT VT = N->getValueType(0);
5026     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
5027     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
5028     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
5029 
5030     EVT SelectVT = NewVT;
5031     if (NewVT.bitsLT(MVT::i32)) {
5032       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
5033       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
5034       SelectVT = MVT::i32;
5035     }
5036 
5037     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
5038                                     N->getOperand(0), LHS, RHS);
5039 
5040     if (NewVT != SelectVT)
5041       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
5042     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
5043     return;
5044   }
5045   case ISD::FNEG: {
5046     if (N->getValueType(0) != MVT::v2f16)
5047       break;
5048 
5049     SDLoc SL(N);
5050     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5051 
5052     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
5053                              BC,
5054                              DAG.getConstant(0x80008000, SL, MVT::i32));
5055     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5056     return;
5057   }
5058   case ISD::FABS: {
5059     if (N->getValueType(0) != MVT::v2f16)
5060       break;
5061 
5062     SDLoc SL(N);
5063     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5064 
5065     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
5066                              BC,
5067                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
5068     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5069     return;
5070   }
5071   default:
5072     break;
5073   }
5074 }
5075 
5076 /// Helper function for LowerBRCOND
5077 static SDNode *findUser(SDValue Value, unsigned Opcode) {
5078 
5079   SDNode *Parent = Value.getNode();
5080   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
5081        I != E; ++I) {
5082 
5083     if (I.getUse().get() != Value)
5084       continue;
5085 
5086     if (I->getOpcode() == Opcode)
5087       return *I;
5088   }
5089   return nullptr;
5090 }
5091 
5092 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
5093   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
5094     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
5095     case Intrinsic::amdgcn_if:
5096       return AMDGPUISD::IF;
5097     case Intrinsic::amdgcn_else:
5098       return AMDGPUISD::ELSE;
5099     case Intrinsic::amdgcn_loop:
5100       return AMDGPUISD::LOOP;
5101     case Intrinsic::amdgcn_end_cf:
5102       llvm_unreachable("should not occur");
5103     default:
5104       return 0;
5105     }
5106   }
5107 
5108   // break, if_break, else_break are all only used as inputs to loop, not
5109   // directly as branch conditions.
5110   return 0;
5111 }
5112 
5113 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
5114   const Triple &TT = getTargetMachine().getTargetTriple();
5115   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5116           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5117          AMDGPU::shouldEmitConstantsToTextSection(TT);
5118 }
5119 
5120 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
5121   // FIXME: Either avoid relying on address space here or change the default
5122   // address space for functions to avoid the explicit check.
5123   return (GV->getValueType()->isFunctionTy() ||
5124           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
5125          !shouldEmitFixup(GV) &&
5126          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
5127 }
5128 
5129 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
5130   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
5131 }
5132 
5133 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
5134   if (!GV->hasExternalLinkage())
5135     return true;
5136 
5137   const auto OS = getTargetMachine().getTargetTriple().getOS();
5138   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
5139 }
5140 
5141 /// This transforms the control flow intrinsics to get the branch destination as
5142 /// last parameter, also switches branch target with BR if the need arise
5143 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
5144                                       SelectionDAG &DAG) const {
5145   SDLoc DL(BRCOND);
5146 
5147   SDNode *Intr = BRCOND.getOperand(1).getNode();
5148   SDValue Target = BRCOND.getOperand(2);
5149   SDNode *BR = nullptr;
5150   SDNode *SetCC = nullptr;
5151 
5152   if (Intr->getOpcode() == ISD::SETCC) {
5153     // As long as we negate the condition everything is fine
5154     SetCC = Intr;
5155     Intr = SetCC->getOperand(0).getNode();
5156 
5157   } else {
5158     // Get the target from BR if we don't negate the condition
5159     BR = findUser(BRCOND, ISD::BR);
5160     assert(BR && "brcond missing unconditional branch user");
5161     Target = BR->getOperand(1);
5162   }
5163 
5164   unsigned CFNode = isCFIntrinsic(Intr);
5165   if (CFNode == 0) {
5166     // This is a uniform branch so we don't need to legalize.
5167     return BRCOND;
5168   }
5169 
5170   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5171                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5172 
5173   assert(!SetCC ||
5174         (SetCC->getConstantOperandVal(1) == 1 &&
5175          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5176                                                              ISD::SETNE));
5177 
5178   // operands of the new intrinsic call
5179   SmallVector<SDValue, 4> Ops;
5180   if (HaveChain)
5181     Ops.push_back(BRCOND.getOperand(0));
5182 
5183   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5184   Ops.push_back(Target);
5185 
5186   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5187 
5188   // build the new intrinsic call
5189   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5190 
5191   if (!HaveChain) {
5192     SDValue Ops[] =  {
5193       SDValue(Result, 0),
5194       BRCOND.getOperand(0)
5195     };
5196 
5197     Result = DAG.getMergeValues(Ops, DL).getNode();
5198   }
5199 
5200   if (BR) {
5201     // Give the branch instruction our target
5202     SDValue Ops[] = {
5203       BR->getOperand(0),
5204       BRCOND.getOperand(2)
5205     };
5206     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5207     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5208   }
5209 
5210   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5211 
5212   // Copy the intrinsic results to registers
5213   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5214     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5215     if (!CopyToReg)
5216       continue;
5217 
5218     Chain = DAG.getCopyToReg(
5219       Chain, DL,
5220       CopyToReg->getOperand(1),
5221       SDValue(Result, i - 1),
5222       SDValue());
5223 
5224     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5225   }
5226 
5227   // Remove the old intrinsic from the chain
5228   DAG.ReplaceAllUsesOfValueWith(
5229     SDValue(Intr, Intr->getNumValues() - 1),
5230     Intr->getOperand(0));
5231 
5232   return Chain;
5233 }
5234 
5235 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5236                                           SelectionDAG &DAG) const {
5237   MVT VT = Op.getSimpleValueType();
5238   SDLoc DL(Op);
5239   // Checking the depth
5240   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5241     return DAG.getConstant(0, DL, VT);
5242 
5243   MachineFunction &MF = DAG.getMachineFunction();
5244   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5245   // Check for kernel and shader functions
5246   if (Info->isEntryFunction())
5247     return DAG.getConstant(0, DL, VT);
5248 
5249   MachineFrameInfo &MFI = MF.getFrameInfo();
5250   // There is a call to @llvm.returnaddress in this function
5251   MFI.setReturnAddressIsTaken(true);
5252 
5253   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5254   // Get the return address reg and mark it as an implicit live-in
5255   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5256 
5257   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5258 }
5259 
5260 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5261                                             SDValue Op,
5262                                             const SDLoc &DL,
5263                                             EVT VT) const {
5264   return Op.getValueType().bitsLE(VT) ?
5265       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5266     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5267                 DAG.getTargetConstant(0, DL, MVT::i32));
5268 }
5269 
5270 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5271   assert(Op.getValueType() == MVT::f16 &&
5272          "Do not know how to custom lower FP_ROUND for non-f16 type");
5273 
5274   SDValue Src = Op.getOperand(0);
5275   EVT SrcVT = Src.getValueType();
5276   if (SrcVT != MVT::f64)
5277     return Op;
5278 
5279   SDLoc DL(Op);
5280 
5281   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5282   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5283   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5284 }
5285 
5286 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5287                                                SelectionDAG &DAG) const {
5288   EVT VT = Op.getValueType();
5289   const MachineFunction &MF = DAG.getMachineFunction();
5290   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5291   bool IsIEEEMode = Info->getMode().IEEE;
5292 
5293   // FIXME: Assert during selection that this is only selected for
5294   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5295   // mode functions, but this happens to be OK since it's only done in cases
5296   // where there is known no sNaN.
5297   if (IsIEEEMode)
5298     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5299 
5300   if (VT == MVT::v4f16)
5301     return splitBinaryVectorOp(Op, DAG);
5302   return Op;
5303 }
5304 
5305 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5306   EVT VT = Op.getValueType();
5307   SDLoc SL(Op);
5308   SDValue LHS = Op.getOperand(0);
5309   SDValue RHS = Op.getOperand(1);
5310   bool isSigned = Op.getOpcode() == ISD::SMULO;
5311 
5312   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5313     const APInt &C = RHSC->getAPIntValue();
5314     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5315     if (C.isPowerOf2()) {
5316       // smulo(x, signed_min) is same as umulo(x, signed_min).
5317       bool UseArithShift = isSigned && !C.isMinSignedValue();
5318       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5319       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5320       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5321           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5322                       SL, VT, Result, ShiftAmt),
5323           LHS, ISD::SETNE);
5324       return DAG.getMergeValues({ Result, Overflow }, SL);
5325     }
5326   }
5327 
5328   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5329   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5330                             SL, VT, LHS, RHS);
5331 
5332   SDValue Sign = isSigned
5333     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5334                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5335     : DAG.getConstant(0, SL, VT);
5336   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5337 
5338   return DAG.getMergeValues({ Result, Overflow }, SL);
5339 }
5340 
5341 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const {
5342   if (Op->isDivergent()) {
5343     // Select to V_MAD_[IU]64_[IU]32.
5344     return Op;
5345   }
5346   if (Subtarget->hasSMulHi()) {
5347     // Expand to S_MUL_I32 + S_MUL_HI_[IU]32.
5348     return SDValue();
5349   }
5350   // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to
5351   // calculate the high part, so we might as well do the whole thing with
5352   // V_MAD_[IU]64_[IU]32.
5353   return Op;
5354 }
5355 
5356 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5357   if (!Subtarget->isTrapHandlerEnabled() ||
5358       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5359     return lowerTrapEndpgm(Op, DAG);
5360 
5361   if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) {
5362     switch (*HsaAbiVer) {
5363     case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
5364     case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
5365       return lowerTrapHsaQueuePtr(Op, DAG);
5366     case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
5367       return Subtarget->supportsGetDoorbellID() ?
5368           lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG);
5369     }
5370   }
5371 
5372   llvm_unreachable("Unknown trap handler");
5373 }
5374 
5375 SDValue SITargetLowering::lowerTrapEndpgm(
5376     SDValue Op, SelectionDAG &DAG) const {
5377   SDLoc SL(Op);
5378   SDValue Chain = Op.getOperand(0);
5379   return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5380 }
5381 
5382 SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5383     SDValue Op, SelectionDAG &DAG) const {
5384   SDLoc SL(Op);
5385   SDValue Chain = Op.getOperand(0);
5386 
5387   MachineFunction &MF = DAG.getMachineFunction();
5388   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5389   Register UserSGPR = Info->getQueuePtrUserSGPR();
5390 
5391   SDValue QueuePtr;
5392   if (UserSGPR == AMDGPU::NoRegister) {
5393     // We probably are in a function incorrectly marked with
5394     // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the trap,
5395     // so just use a null pointer.
5396     QueuePtr = DAG.getConstant(0, SL, MVT::i64);
5397   } else {
5398     QueuePtr = CreateLiveInRegister(
5399       DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5400   }
5401 
5402   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5403   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5404                                    QueuePtr, SDValue());
5405 
5406   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5407   SDValue Ops[] = {
5408     ToReg,
5409     DAG.getTargetConstant(TrapID, SL, MVT::i16),
5410     SGPR01,
5411     ToReg.getValue(1)
5412   };
5413   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5414 }
5415 
5416 SDValue SITargetLowering::lowerTrapHsa(
5417     SDValue Op, SelectionDAG &DAG) const {
5418   SDLoc SL(Op);
5419   SDValue Chain = Op.getOperand(0);
5420 
5421   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5422   SDValue Ops[] = {
5423     Chain,
5424     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5425   };
5426   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5427 }
5428 
5429 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5430   SDLoc SL(Op);
5431   SDValue Chain = Op.getOperand(0);
5432   MachineFunction &MF = DAG.getMachineFunction();
5433 
5434   if (!Subtarget->isTrapHandlerEnabled() ||
5435       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5436     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5437                                      "debugtrap handler not supported",
5438                                      Op.getDebugLoc(),
5439                                      DS_Warning);
5440     LLVMContext &Ctx = MF.getFunction().getContext();
5441     Ctx.diagnose(NoTrap);
5442     return Chain;
5443   }
5444 
5445   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5446   SDValue Ops[] = {
5447     Chain,
5448     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5449   };
5450   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5451 }
5452 
5453 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5454                                              SelectionDAG &DAG) const {
5455   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5456   if (Subtarget->hasApertureRegs()) {
5457     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5458         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5459         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5460     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5461         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5462         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5463     unsigned Encoding =
5464         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5465         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5466         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5467 
5468     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5469     SDValue ApertureReg = SDValue(
5470         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5471     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5472     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5473   }
5474 
5475   MachineFunction &MF = DAG.getMachineFunction();
5476   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5477   Register UserSGPR = Info->getQueuePtrUserSGPR();
5478   if (UserSGPR == AMDGPU::NoRegister) {
5479     // We probably are in a function incorrectly marked with
5480     // amdgpu-no-queue-ptr. This is undefined.
5481     return DAG.getUNDEF(MVT::i32);
5482   }
5483 
5484   SDValue QueuePtr = CreateLiveInRegister(
5485     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5486 
5487   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5488   // private_segment_aperture_base_hi.
5489   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5490 
5491   SDValue Ptr =
5492       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5493 
5494   // TODO: Use custom target PseudoSourceValue.
5495   // TODO: We should use the value from the IR intrinsic call, but it might not
5496   // be available and how do we get it?
5497   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5498   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5499                      commonAlignment(Align(64), StructOffset),
5500                      MachineMemOperand::MODereferenceable |
5501                          MachineMemOperand::MOInvariant);
5502 }
5503 
5504 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5505                                              SelectionDAG &DAG) const {
5506   SDLoc SL(Op);
5507   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5508 
5509   SDValue Src = ASC->getOperand(0);
5510   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5511 
5512   const AMDGPUTargetMachine &TM =
5513     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5514 
5515   // flat -> local/private
5516   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5517     unsigned DestAS = ASC->getDestAddressSpace();
5518 
5519     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5520         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5521       unsigned NullVal = TM.getNullPointerValue(DestAS);
5522       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5523       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5524       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5525 
5526       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
5527                          NonNull, Ptr, SegmentNullPtr);
5528     }
5529   }
5530 
5531   // local/private -> flat
5532   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5533     unsigned SrcAS = ASC->getSrcAddressSpace();
5534 
5535     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5536         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5537       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5538       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5539 
5540       SDValue NonNull
5541         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5542 
5543       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5544       SDValue CvtPtr
5545         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5546 
5547       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5548                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5549                          FlatNullPtr);
5550     }
5551   }
5552 
5553   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5554       Src.getValueType() == MVT::i64)
5555     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5556 
5557   // global <-> flat are no-ops and never emitted.
5558 
5559   const MachineFunction &MF = DAG.getMachineFunction();
5560   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5561     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5562   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5563 
5564   return DAG.getUNDEF(ASC->getValueType(0));
5565 }
5566 
5567 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5568 // the small vector and inserting them into the big vector. That is better than
5569 // the default expansion of doing it via a stack slot. Even though the use of
5570 // the stack slot would be optimized away afterwards, the stack slot itself
5571 // remains.
5572 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5573                                                 SelectionDAG &DAG) const {
5574   SDValue Vec = Op.getOperand(0);
5575   SDValue Ins = Op.getOperand(1);
5576   SDValue Idx = Op.getOperand(2);
5577   EVT VecVT = Vec.getValueType();
5578   EVT InsVT = Ins.getValueType();
5579   EVT EltVT = VecVT.getVectorElementType();
5580   unsigned InsNumElts = InsVT.getVectorNumElements();
5581   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5582   SDLoc SL(Op);
5583 
5584   for (unsigned I = 0; I != InsNumElts; ++I) {
5585     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5586                               DAG.getConstant(I, SL, MVT::i32));
5587     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5588                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5589   }
5590   return Vec;
5591 }
5592 
5593 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5594                                                  SelectionDAG &DAG) const {
5595   SDValue Vec = Op.getOperand(0);
5596   SDValue InsVal = Op.getOperand(1);
5597   SDValue Idx = Op.getOperand(2);
5598   EVT VecVT = Vec.getValueType();
5599   EVT EltVT = VecVT.getVectorElementType();
5600   unsigned VecSize = VecVT.getSizeInBits();
5601   unsigned EltSize = EltVT.getSizeInBits();
5602 
5603 
5604   assert(VecSize <= 64);
5605 
5606   unsigned NumElts = VecVT.getVectorNumElements();
5607   SDLoc SL(Op);
5608   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5609 
5610   if (NumElts == 4 && EltSize == 16 && KIdx) {
5611     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5612 
5613     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5614                                  DAG.getConstant(0, SL, MVT::i32));
5615     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5616                                  DAG.getConstant(1, SL, MVT::i32));
5617 
5618     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5619     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5620 
5621     unsigned Idx = KIdx->getZExtValue();
5622     bool InsertLo = Idx < 2;
5623     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5624       InsertLo ? LoVec : HiVec,
5625       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5626       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5627 
5628     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5629 
5630     SDValue Concat = InsertLo ?
5631       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5632       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5633 
5634     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5635   }
5636 
5637   if (isa<ConstantSDNode>(Idx))
5638     return SDValue();
5639 
5640   MVT IntVT = MVT::getIntegerVT(VecSize);
5641 
5642   // Avoid stack access for dynamic indexing.
5643   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5644 
5645   // Create a congruent vector with the target value in each element so that
5646   // the required element can be masked and ORed into the target vector.
5647   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5648                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5649 
5650   assert(isPowerOf2_32(EltSize));
5651   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5652 
5653   // Convert vector index to bit-index.
5654   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5655 
5656   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5657   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5658                             DAG.getConstant(0xffff, SL, IntVT),
5659                             ScaledIdx);
5660 
5661   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5662   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5663                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5664 
5665   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5666   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5667 }
5668 
5669 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5670                                                   SelectionDAG &DAG) const {
5671   SDLoc SL(Op);
5672 
5673   EVT ResultVT = Op.getValueType();
5674   SDValue Vec = Op.getOperand(0);
5675   SDValue Idx = Op.getOperand(1);
5676   EVT VecVT = Vec.getValueType();
5677   unsigned VecSize = VecVT.getSizeInBits();
5678   EVT EltVT = VecVT.getVectorElementType();
5679   assert(VecSize <= 64);
5680 
5681   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5682 
5683   // Make sure we do any optimizations that will make it easier to fold
5684   // source modifiers before obscuring it with bit operations.
5685 
5686   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5687   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5688     return Combined;
5689 
5690   unsigned EltSize = EltVT.getSizeInBits();
5691   assert(isPowerOf2_32(EltSize));
5692 
5693   MVT IntVT = MVT::getIntegerVT(VecSize);
5694   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5695 
5696   // Convert vector index to bit-index (* EltSize)
5697   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5698 
5699   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5700   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5701 
5702   if (ResultVT == MVT::f16) {
5703     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5704     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5705   }
5706 
5707   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5708 }
5709 
5710 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5711   assert(Elt % 2 == 0);
5712   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5713 }
5714 
5715 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5716                                               SelectionDAG &DAG) const {
5717   SDLoc SL(Op);
5718   EVT ResultVT = Op.getValueType();
5719   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5720 
5721   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5722   EVT EltVT = PackVT.getVectorElementType();
5723   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5724 
5725   // vector_shuffle <0,1,6,7> lhs, rhs
5726   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5727   //
5728   // vector_shuffle <6,7,2,3> lhs, rhs
5729   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5730   //
5731   // vector_shuffle <6,7,0,1> lhs, rhs
5732   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5733 
5734   // Avoid scalarizing when both halves are reading from consecutive elements.
5735   SmallVector<SDValue, 4> Pieces;
5736   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5737     if (elementPairIsContiguous(SVN->getMask(), I)) {
5738       const int Idx = SVN->getMaskElt(I);
5739       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5740       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5741       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5742                                     PackVT, SVN->getOperand(VecIdx),
5743                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5744       Pieces.push_back(SubVec);
5745     } else {
5746       const int Idx0 = SVN->getMaskElt(I);
5747       const int Idx1 = SVN->getMaskElt(I + 1);
5748       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5749       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5750       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5751       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5752 
5753       SDValue Vec0 = SVN->getOperand(VecIdx0);
5754       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5755                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5756 
5757       SDValue Vec1 = SVN->getOperand(VecIdx1);
5758       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5759                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5760       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5761     }
5762   }
5763 
5764   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5765 }
5766 
5767 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5768                                             SelectionDAG &DAG) const {
5769   SDLoc SL(Op);
5770   EVT VT = Op.getValueType();
5771 
5772   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5773     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5774 
5775     // Turn into pair of packed build_vectors.
5776     // TODO: Special case for constants that can be materialized with s_mov_b64.
5777     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5778                                     { Op.getOperand(0), Op.getOperand(1) });
5779     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5780                                     { Op.getOperand(2), Op.getOperand(3) });
5781 
5782     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5783     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5784 
5785     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5786     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5787   }
5788 
5789   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5790   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5791 
5792   SDValue Lo = Op.getOperand(0);
5793   SDValue Hi = Op.getOperand(1);
5794 
5795   // Avoid adding defined bits with the zero_extend.
5796   if (Hi.isUndef()) {
5797     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5798     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5799     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5800   }
5801 
5802   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5803   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5804 
5805   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5806                               DAG.getConstant(16, SL, MVT::i32));
5807   if (Lo.isUndef())
5808     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5809 
5810   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5811   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5812 
5813   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5814   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5815 }
5816 
5817 bool
5818 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5819   // We can fold offsets for anything that doesn't require a GOT relocation.
5820   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5821           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5822           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5823          !shouldEmitGOTReloc(GA->getGlobal());
5824 }
5825 
5826 static SDValue
5827 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5828                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5829                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5830   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5831   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5832   // lowered to the following code sequence:
5833   //
5834   // For constant address space:
5835   //   s_getpc_b64 s[0:1]
5836   //   s_add_u32 s0, s0, $symbol
5837   //   s_addc_u32 s1, s1, 0
5838   //
5839   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5840   //   a fixup or relocation is emitted to replace $symbol with a literal
5841   //   constant, which is a pc-relative offset from the encoding of the $symbol
5842   //   operand to the global variable.
5843   //
5844   // For global address space:
5845   //   s_getpc_b64 s[0:1]
5846   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5847   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5848   //
5849   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5850   //   fixups or relocations are emitted to replace $symbol@*@lo and
5851   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5852   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5853   //   operand to the global variable.
5854   //
5855   // What we want here is an offset from the value returned by s_getpc
5856   // (which is the address of the s_add_u32 instruction) to the global
5857   // variable, but since the encoding of $symbol starts 4 bytes after the start
5858   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5859   // small. This requires us to add 4 to the global variable offset in order to
5860   // compute the correct address. Similarly for the s_addc_u32 instruction, the
5861   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
5862   // instruction.
5863   SDValue PtrLo =
5864       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5865   SDValue PtrHi;
5866   if (GAFlags == SIInstrInfo::MO_NONE) {
5867     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5868   } else {
5869     PtrHi =
5870         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
5871   }
5872   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5873 }
5874 
5875 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5876                                              SDValue Op,
5877                                              SelectionDAG &DAG) const {
5878   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5879   SDLoc DL(GSD);
5880   EVT PtrVT = Op.getValueType();
5881 
5882   const GlobalValue *GV = GSD->getGlobal();
5883   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5884        shouldUseLDSConstAddress(GV)) ||
5885       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5886       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
5887     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5888         GV->hasExternalLinkage()) {
5889       Type *Ty = GV->getValueType();
5890       // HIP uses an unsized array `extern __shared__ T s[]` or similar
5891       // zero-sized type in other languages to declare the dynamic shared
5892       // memory which size is not known at the compile time. They will be
5893       // allocated by the runtime and placed directly after the static
5894       // allocated ones. They all share the same offset.
5895       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
5896         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
5897         // Adjust alignment for that dynamic shared memory array.
5898         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
5899         return SDValue(
5900             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
5901       }
5902     }
5903     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5904   }
5905 
5906   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5907     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5908                                             SIInstrInfo::MO_ABS32_LO);
5909     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5910   }
5911 
5912   if (shouldEmitFixup(GV))
5913     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5914   else if (shouldEmitPCReloc(GV))
5915     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5916                                    SIInstrInfo::MO_REL32);
5917 
5918   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5919                                             SIInstrInfo::MO_GOTPCREL32);
5920 
5921   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5922   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5923   const DataLayout &DataLayout = DAG.getDataLayout();
5924   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
5925   MachinePointerInfo PtrInfo
5926     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5927 
5928   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
5929                      MachineMemOperand::MODereferenceable |
5930                          MachineMemOperand::MOInvariant);
5931 }
5932 
5933 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5934                                    const SDLoc &DL, SDValue V) const {
5935   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5936   // the destination register.
5937   //
5938   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5939   // so we will end up with redundant moves to m0.
5940   //
5941   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5942 
5943   // A Null SDValue creates a glue result.
5944   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5945                                   V, Chain);
5946   return SDValue(M0, 0);
5947 }
5948 
5949 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5950                                                  SDValue Op,
5951                                                  MVT VT,
5952                                                  unsigned Offset) const {
5953   SDLoc SL(Op);
5954   SDValue Param = lowerKernargMemParameter(
5955       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
5956   // The local size values will have the hi 16-bits as zero.
5957   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5958                      DAG.getValueType(VT));
5959 }
5960 
5961 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5962                                         EVT VT) {
5963   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5964                                       "non-hsa intrinsic with hsa target",
5965                                       DL.getDebugLoc());
5966   DAG.getContext()->diagnose(BadIntrin);
5967   return DAG.getUNDEF(VT);
5968 }
5969 
5970 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5971                                          EVT VT) {
5972   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5973                                       "intrinsic not supported on subtarget",
5974                                       DL.getDebugLoc());
5975   DAG.getContext()->diagnose(BadIntrin);
5976   return DAG.getUNDEF(VT);
5977 }
5978 
5979 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5980                                     ArrayRef<SDValue> Elts) {
5981   assert(!Elts.empty());
5982   MVT Type;
5983   unsigned NumElts = Elts.size();
5984 
5985   if (NumElts <= 8) {
5986     Type = MVT::getVectorVT(MVT::f32, NumElts);
5987   } else {
5988     assert(Elts.size() <= 16);
5989     Type = MVT::v16f32;
5990     NumElts = 16;
5991   }
5992 
5993   SmallVector<SDValue, 16> VecElts(NumElts);
5994   for (unsigned i = 0; i < Elts.size(); ++i) {
5995     SDValue Elt = Elts[i];
5996     if (Elt.getValueType() != MVT::f32)
5997       Elt = DAG.getBitcast(MVT::f32, Elt);
5998     VecElts[i] = Elt;
5999   }
6000   for (unsigned i = Elts.size(); i < NumElts; ++i)
6001     VecElts[i] = DAG.getUNDEF(MVT::f32);
6002 
6003   if (NumElts == 1)
6004     return VecElts[0];
6005   return DAG.getBuildVector(Type, DL, VecElts);
6006 }
6007 
6008 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
6009                               SDValue Src, int ExtraElts) {
6010   EVT SrcVT = Src.getValueType();
6011 
6012   SmallVector<SDValue, 8> Elts;
6013 
6014   if (SrcVT.isVector())
6015     DAG.ExtractVectorElements(Src, Elts);
6016   else
6017     Elts.push_back(Src);
6018 
6019   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
6020   while (ExtraElts--)
6021     Elts.push_back(Undef);
6022 
6023   return DAG.getBuildVector(CastVT, DL, Elts);
6024 }
6025 
6026 // Re-construct the required return value for a image load intrinsic.
6027 // This is more complicated due to the optional use TexFailCtrl which means the required
6028 // return type is an aggregate
6029 static SDValue constructRetValue(SelectionDAG &DAG,
6030                                  MachineSDNode *Result,
6031                                  ArrayRef<EVT> ResultTypes,
6032                                  bool IsTexFail, bool Unpacked, bool IsD16,
6033                                  int DMaskPop, int NumVDataDwords,
6034                                  const SDLoc &DL) {
6035   // Determine the required return type. This is the same regardless of IsTexFail flag
6036   EVT ReqRetVT = ResultTypes[0];
6037   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
6038   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6039     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
6040 
6041   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6042     DMaskPop : (DMaskPop + 1) / 2;
6043 
6044   MVT DataDwordVT = NumDataDwords == 1 ?
6045     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
6046 
6047   MVT MaskPopVT = MaskPopDwords == 1 ?
6048     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
6049 
6050   SDValue Data(Result, 0);
6051   SDValue TexFail;
6052 
6053   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
6054     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
6055     if (MaskPopVT.isVector()) {
6056       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
6057                          SDValue(Result, 0), ZeroIdx);
6058     } else {
6059       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
6060                          SDValue(Result, 0), ZeroIdx);
6061     }
6062   }
6063 
6064   if (DataDwordVT.isVector())
6065     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
6066                           NumDataDwords - MaskPopDwords);
6067 
6068   if (IsD16)
6069     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
6070 
6071   EVT LegalReqRetVT = ReqRetVT;
6072   if (!ReqRetVT.isVector()) {
6073     if (!Data.getValueType().isInteger())
6074       Data = DAG.getNode(ISD::BITCAST, DL,
6075                          Data.getValueType().changeTypeToInteger(), Data);
6076     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
6077   } else {
6078     // We need to widen the return vector to a legal type
6079     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
6080         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
6081       LegalReqRetVT =
6082           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
6083                            ReqRetVT.getVectorNumElements() + 1);
6084     }
6085   }
6086   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
6087 
6088   if (IsTexFail) {
6089     TexFail =
6090         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
6091                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
6092 
6093     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
6094   }
6095 
6096   if (Result->getNumValues() == 1)
6097     return Data;
6098 
6099   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
6100 }
6101 
6102 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
6103                          SDValue *LWE, bool &IsTexFail) {
6104   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
6105 
6106   uint64_t Value = TexFailCtrlConst->getZExtValue();
6107   if (Value) {
6108     IsTexFail = true;
6109   }
6110 
6111   SDLoc DL(TexFailCtrlConst);
6112   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
6113   Value &= ~(uint64_t)0x1;
6114   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
6115   Value &= ~(uint64_t)0x2;
6116 
6117   return Value == 0;
6118 }
6119 
6120 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
6121                                       MVT PackVectorVT,
6122                                       SmallVectorImpl<SDValue> &PackedAddrs,
6123                                       unsigned DimIdx, unsigned EndIdx,
6124                                       unsigned NumGradients) {
6125   SDLoc DL(Op);
6126   for (unsigned I = DimIdx; I < EndIdx; I++) {
6127     SDValue Addr = Op.getOperand(I);
6128 
6129     // Gradients are packed with undef for each coordinate.
6130     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
6131     // 1D: undef,dx/dh; undef,dx/dv
6132     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
6133     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
6134     if (((I + 1) >= EndIdx) ||
6135         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
6136                                          I == DimIdx + NumGradients - 1))) {
6137       if (Addr.getValueType() != MVT::i16)
6138         Addr = DAG.getBitcast(MVT::i16, Addr);
6139       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
6140     } else {
6141       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
6142       I++;
6143     }
6144     Addr = DAG.getBitcast(MVT::f32, Addr);
6145     PackedAddrs.push_back(Addr);
6146   }
6147 }
6148 
6149 SDValue SITargetLowering::lowerImage(SDValue Op,
6150                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
6151                                      SelectionDAG &DAG, bool WithChain) const {
6152   SDLoc DL(Op);
6153   MachineFunction &MF = DAG.getMachineFunction();
6154   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
6155   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
6156       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
6157   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
6158   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
6159       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
6160   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
6161       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
6162   unsigned IntrOpcode = Intr->BaseOpcode;
6163   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6164 
6165   SmallVector<EVT, 3> ResultTypes(Op->values());
6166   SmallVector<EVT, 3> OrigResultTypes(Op->values());
6167   bool IsD16 = false;
6168   bool IsG16 = false;
6169   bool IsA16 = false;
6170   SDValue VData;
6171   int NumVDataDwords;
6172   bool AdjustRetType = false;
6173 
6174   // Offset of intrinsic arguments
6175   const unsigned ArgOffset = WithChain ? 2 : 1;
6176 
6177   unsigned DMask;
6178   unsigned DMaskLanes = 0;
6179 
6180   if (BaseOpcode->Atomic) {
6181     VData = Op.getOperand(2);
6182 
6183     bool Is64Bit = VData.getValueType() == MVT::i64;
6184     if (BaseOpcode->AtomicX2) {
6185       SDValue VData2 = Op.getOperand(3);
6186       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6187                                  {VData, VData2});
6188       if (Is64Bit)
6189         VData = DAG.getBitcast(MVT::v4i32, VData);
6190 
6191       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6192       DMask = Is64Bit ? 0xf : 0x3;
6193       NumVDataDwords = Is64Bit ? 4 : 2;
6194     } else {
6195       DMask = Is64Bit ? 0x3 : 0x1;
6196       NumVDataDwords = Is64Bit ? 2 : 1;
6197     }
6198   } else {
6199     auto *DMaskConst =
6200         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6201     DMask = DMaskConst->getZExtValue();
6202     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6203 
6204     if (BaseOpcode->Store) {
6205       VData = Op.getOperand(2);
6206 
6207       MVT StoreVT = VData.getSimpleValueType();
6208       if (StoreVT.getScalarType() == MVT::f16) {
6209         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6210           return Op; // D16 is unsupported for this instruction
6211 
6212         IsD16 = true;
6213         VData = handleD16VData(VData, DAG, true);
6214       }
6215 
6216       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6217     } else {
6218       // Work out the num dwords based on the dmask popcount and underlying type
6219       // and whether packing is supported.
6220       MVT LoadVT = ResultTypes[0].getSimpleVT();
6221       if (LoadVT.getScalarType() == MVT::f16) {
6222         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6223           return Op; // D16 is unsupported for this instruction
6224 
6225         IsD16 = true;
6226       }
6227 
6228       // Confirm that the return type is large enough for the dmask specified
6229       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6230           (!LoadVT.isVector() && DMaskLanes > 1))
6231           return Op;
6232 
6233       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6234       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6235       // instructions.
6236       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6237           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6238         NumVDataDwords = (DMaskLanes + 1) / 2;
6239       else
6240         NumVDataDwords = DMaskLanes;
6241 
6242       AdjustRetType = true;
6243     }
6244   }
6245 
6246   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6247   SmallVector<SDValue, 4> VAddrs;
6248 
6249   // Optimize _L to _LZ when _L is zero
6250   if (LZMappingInfo) {
6251     if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>(
6252             Op.getOperand(ArgOffset + Intr->LodIndex))) {
6253       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
6254         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
6255         VAddrEnd--;                      // remove 'lod'
6256       }
6257     }
6258   }
6259 
6260   // Optimize _mip away, when 'lod' is zero
6261   if (MIPMappingInfo) {
6262     if (auto *ConstantLod = dyn_cast<ConstantSDNode>(
6263             Op.getOperand(ArgOffset + Intr->MipIndex))) {
6264       if (ConstantLod->isZero()) {
6265         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
6266         VAddrEnd--;                           // remove 'mip'
6267       }
6268     }
6269   }
6270 
6271   // Push back extra arguments.
6272   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++)
6273     VAddrs.push_back(Op.getOperand(ArgOffset + I));
6274 
6275   // Check for 16 bit addresses or derivatives and pack if true.
6276   MVT VAddrVT =
6277       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6278   MVT VAddrScalarVT = VAddrVT.getScalarType();
6279   MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6280   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6281 
6282   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6283   VAddrScalarVT = VAddrVT.getScalarType();
6284   MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6285   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6286 
6287   if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
6288     // 16 bit gradients are supported, but are tied to the A16 control
6289     // so both gradients and addresses must be 16 bit
6290     LLVM_DEBUG(
6291         dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6292                   "require 16 bit args for both gradients and addresses");
6293     return Op;
6294   }
6295 
6296   if (IsA16) {
6297     if (!ST->hasA16()) {
6298       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6299                            "support 16 bit addresses\n");
6300       return Op;
6301     }
6302   }
6303 
6304   // We've dealt with incorrect input so we know that if IsA16, IsG16
6305   // are set then we have to compress/pack operands (either address,
6306   // gradient or both)
6307   // In the case where a16 and gradients are tied (no G16 support) then we
6308   // have already verified that both IsA16 and IsG16 are true
6309   if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
6310     // Activate g16
6311     const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6312         AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6313     IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6314   }
6315 
6316   // Add gradients (packed or unpacked)
6317   if (IsG16) {
6318     // Pack the gradients
6319     // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6320     packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
6321                               ArgOffset + Intr->GradientStart,
6322                               ArgOffset + Intr->CoordStart, Intr->NumGradients);
6323   } else {
6324     for (unsigned I = ArgOffset + Intr->GradientStart;
6325          I < ArgOffset + Intr->CoordStart; I++)
6326       VAddrs.push_back(Op.getOperand(I));
6327   }
6328 
6329   // Add addresses (packed or unpacked)
6330   if (IsA16) {
6331     packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
6332                               ArgOffset + Intr->CoordStart, VAddrEnd,
6333                               0 /* No gradients */);
6334   } else {
6335     // Add uncompressed address
6336     for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6337       VAddrs.push_back(Op.getOperand(I));
6338   }
6339 
6340   // If the register allocator cannot place the address registers contiguously
6341   // without introducing moves, then using the non-sequential address encoding
6342   // is always preferable, since it saves VALU instructions and is usually a
6343   // wash in terms of code size or even better.
6344   //
6345   // However, we currently have no way of hinting to the register allocator that
6346   // MIMG addresses should be placed contiguously when it is possible to do so,
6347   // so force non-NSA for the common 2-address case as a heuristic.
6348   //
6349   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6350   // allocation when possible.
6351   bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) &&
6352                 VAddrs.size() >= 3 &&
6353                 VAddrs.size() <= (unsigned)ST->getNSAMaxSize();
6354   SDValue VAddr;
6355   if (!UseNSA)
6356     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6357 
6358   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6359   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6360   SDValue Unorm;
6361   if (!BaseOpcode->Sampler) {
6362     Unorm = True;
6363   } else {
6364     auto UnormConst =
6365         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6366 
6367     Unorm = UnormConst->getZExtValue() ? True : False;
6368   }
6369 
6370   SDValue TFE;
6371   SDValue LWE;
6372   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6373   bool IsTexFail = false;
6374   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6375     return Op;
6376 
6377   if (IsTexFail) {
6378     if (!DMaskLanes) {
6379       // Expecting to get an error flag since TFC is on - and dmask is 0
6380       // Force dmask to be at least 1 otherwise the instruction will fail
6381       DMask = 0x1;
6382       DMaskLanes = 1;
6383       NumVDataDwords = 1;
6384     }
6385     NumVDataDwords += 1;
6386     AdjustRetType = true;
6387   }
6388 
6389   // Has something earlier tagged that the return type needs adjusting
6390   // This happens if the instruction is a load or has set TexFailCtrl flags
6391   if (AdjustRetType) {
6392     // NumVDataDwords reflects the true number of dwords required in the return type
6393     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6394       // This is a no-op load. This can be eliminated
6395       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6396       if (isa<MemSDNode>(Op))
6397         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6398       return Undef;
6399     }
6400 
6401     EVT NewVT = NumVDataDwords > 1 ?
6402                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6403                 : MVT::i32;
6404 
6405     ResultTypes[0] = NewVT;
6406     if (ResultTypes.size() == 3) {
6407       // Original result was aggregate type used for TexFailCtrl results
6408       // The actual instruction returns as a vector type which has now been
6409       // created. Remove the aggregate result.
6410       ResultTypes.erase(&ResultTypes[1]);
6411     }
6412   }
6413 
6414   unsigned CPol = cast<ConstantSDNode>(
6415       Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6416   if (BaseOpcode->Atomic)
6417     CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6418   if (CPol & ~AMDGPU::CPol::ALL)
6419     return Op;
6420 
6421   SmallVector<SDValue, 26> Ops;
6422   if (BaseOpcode->Store || BaseOpcode->Atomic)
6423     Ops.push_back(VData); // vdata
6424   if (UseNSA)
6425     append_range(Ops, VAddrs);
6426   else
6427     Ops.push_back(VAddr);
6428   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6429   if (BaseOpcode->Sampler)
6430     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6431   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6432   if (IsGFX10Plus)
6433     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6434   Ops.push_back(Unorm);
6435   Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6436   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6437                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6438   if (IsGFX10Plus)
6439     Ops.push_back(IsA16 ? True : False);
6440   if (!Subtarget->hasGFX90AInsts()) {
6441     Ops.push_back(TFE); //tfe
6442   } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6443     report_fatal_error("TFE is not supported on this GPU");
6444   }
6445   Ops.push_back(LWE); // lwe
6446   if (!IsGFX10Plus)
6447     Ops.push_back(DimInfo->DA ? True : False);
6448   if (BaseOpcode->HasD16)
6449     Ops.push_back(IsD16 ? True : False);
6450   if (isa<MemSDNode>(Op))
6451     Ops.push_back(Op.getOperand(0)); // chain
6452 
6453   int NumVAddrDwords =
6454       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6455   int Opcode = -1;
6456 
6457   if (IsGFX10Plus) {
6458     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6459                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6460                                           : AMDGPU::MIMGEncGfx10Default,
6461                                    NumVDataDwords, NumVAddrDwords);
6462   } else {
6463     if (Subtarget->hasGFX90AInsts()) {
6464       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6465                                      NumVDataDwords, NumVAddrDwords);
6466       if (Opcode == -1)
6467         report_fatal_error(
6468             "requested image instruction is not supported on this GPU");
6469     }
6470     if (Opcode == -1 &&
6471         Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6472       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6473                                      NumVDataDwords, NumVAddrDwords);
6474     if (Opcode == -1)
6475       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6476                                      NumVDataDwords, NumVAddrDwords);
6477   }
6478   assert(Opcode != -1);
6479 
6480   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6481   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6482     MachineMemOperand *MemRef = MemOp->getMemOperand();
6483     DAG.setNodeMemRefs(NewNode, {MemRef});
6484   }
6485 
6486   if (BaseOpcode->AtomicX2) {
6487     SmallVector<SDValue, 1> Elt;
6488     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6489     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6490   }
6491   if (BaseOpcode->Store)
6492     return SDValue(NewNode, 0);
6493   return constructRetValue(DAG, NewNode,
6494                            OrigResultTypes, IsTexFail,
6495                            Subtarget->hasUnpackedD16VMem(), IsD16,
6496                            DMaskLanes, NumVDataDwords, DL);
6497 }
6498 
6499 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6500                                        SDValue Offset, SDValue CachePolicy,
6501                                        SelectionDAG &DAG) const {
6502   MachineFunction &MF = DAG.getMachineFunction();
6503 
6504   const DataLayout &DataLayout = DAG.getDataLayout();
6505   Align Alignment =
6506       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6507 
6508   MachineMemOperand *MMO = MF.getMachineMemOperand(
6509       MachinePointerInfo(),
6510       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6511           MachineMemOperand::MOInvariant,
6512       VT.getStoreSize(), Alignment);
6513 
6514   if (!Offset->isDivergent()) {
6515     SDValue Ops[] = {
6516         Rsrc,
6517         Offset, // Offset
6518         CachePolicy
6519     };
6520 
6521     // Widen vec3 load to vec4.
6522     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6523       EVT WidenedVT =
6524           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6525       auto WidenedOp = DAG.getMemIntrinsicNode(
6526           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6527           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6528       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6529                                    DAG.getVectorIdxConstant(0, DL));
6530       return Subvector;
6531     }
6532 
6533     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6534                                    DAG.getVTList(VT), Ops, VT, MMO);
6535   }
6536 
6537   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6538   // assume that the buffer is unswizzled.
6539   SmallVector<SDValue, 4> Loads;
6540   unsigned NumLoads = 1;
6541   MVT LoadVT = VT.getSimpleVT();
6542   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6543   assert((LoadVT.getScalarType() == MVT::i32 ||
6544           LoadVT.getScalarType() == MVT::f32));
6545 
6546   if (NumElts == 8 || NumElts == 16) {
6547     NumLoads = NumElts / 4;
6548     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6549   }
6550 
6551   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6552   SDValue Ops[] = {
6553       DAG.getEntryNode(),                               // Chain
6554       Rsrc,                                             // rsrc
6555       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6556       {},                                               // voffset
6557       {},                                               // soffset
6558       {},                                               // offset
6559       CachePolicy,                                      // cachepolicy
6560       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6561   };
6562 
6563   // Use the alignment to ensure that the required offsets will fit into the
6564   // immediate offsets.
6565   setBufferOffsets(Offset, DAG, &Ops[3],
6566                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6567 
6568   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6569   for (unsigned i = 0; i < NumLoads; ++i) {
6570     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6571     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6572                                         LoadVT, MMO, DAG));
6573   }
6574 
6575   if (NumElts == 8 || NumElts == 16)
6576     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6577 
6578   return Loads[0];
6579 }
6580 
6581 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6582                                                   SelectionDAG &DAG) const {
6583   MachineFunction &MF = DAG.getMachineFunction();
6584   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6585 
6586   EVT VT = Op.getValueType();
6587   SDLoc DL(Op);
6588   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6589 
6590   // TODO: Should this propagate fast-math-flags?
6591 
6592   switch (IntrinsicID) {
6593   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6594     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6595       return emitNonHSAIntrinsicError(DAG, DL, VT);
6596     return getPreloadedValue(DAG, *MFI, VT,
6597                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6598   }
6599   case Intrinsic::amdgcn_dispatch_ptr:
6600   case Intrinsic::amdgcn_queue_ptr: {
6601     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6602       DiagnosticInfoUnsupported BadIntrin(
6603           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6604           DL.getDebugLoc());
6605       DAG.getContext()->diagnose(BadIntrin);
6606       return DAG.getUNDEF(VT);
6607     }
6608 
6609     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6610       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6611     return getPreloadedValue(DAG, *MFI, VT, RegID);
6612   }
6613   case Intrinsic::amdgcn_implicitarg_ptr: {
6614     if (MFI->isEntryFunction())
6615       return getImplicitArgPtr(DAG, DL);
6616     return getPreloadedValue(DAG, *MFI, VT,
6617                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6618   }
6619   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6620     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6621       // This only makes sense to call in a kernel, so just lower to null.
6622       return DAG.getConstant(0, DL, VT);
6623     }
6624 
6625     return getPreloadedValue(DAG, *MFI, VT,
6626                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6627   }
6628   case Intrinsic::amdgcn_dispatch_id: {
6629     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6630   }
6631   case Intrinsic::amdgcn_rcp:
6632     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6633   case Intrinsic::amdgcn_rsq:
6634     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6635   case Intrinsic::amdgcn_rsq_legacy:
6636     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6637       return emitRemovedIntrinsicError(DAG, DL, VT);
6638     return SDValue();
6639   case Intrinsic::amdgcn_rcp_legacy:
6640     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6641       return emitRemovedIntrinsicError(DAG, DL, VT);
6642     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6643   case Intrinsic::amdgcn_rsq_clamp: {
6644     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6645       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6646 
6647     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6648     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6649     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6650 
6651     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6652     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6653                               DAG.getConstantFP(Max, DL, VT));
6654     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6655                        DAG.getConstantFP(Min, DL, VT));
6656   }
6657   case Intrinsic::r600_read_ngroups_x:
6658     if (Subtarget->isAmdHsaOS())
6659       return emitNonHSAIntrinsicError(DAG, DL, VT);
6660 
6661     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6662                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6663                                     false);
6664   case Intrinsic::r600_read_ngroups_y:
6665     if (Subtarget->isAmdHsaOS())
6666       return emitNonHSAIntrinsicError(DAG, DL, VT);
6667 
6668     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6669                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6670                                     false);
6671   case Intrinsic::r600_read_ngroups_z:
6672     if (Subtarget->isAmdHsaOS())
6673       return emitNonHSAIntrinsicError(DAG, DL, VT);
6674 
6675     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6676                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6677                                     false);
6678   case Intrinsic::r600_read_global_size_x:
6679     if (Subtarget->isAmdHsaOS())
6680       return emitNonHSAIntrinsicError(DAG, DL, VT);
6681 
6682     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6683                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6684                                     Align(4), false);
6685   case Intrinsic::r600_read_global_size_y:
6686     if (Subtarget->isAmdHsaOS())
6687       return emitNonHSAIntrinsicError(DAG, DL, VT);
6688 
6689     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6690                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6691                                     Align(4), false);
6692   case Intrinsic::r600_read_global_size_z:
6693     if (Subtarget->isAmdHsaOS())
6694       return emitNonHSAIntrinsicError(DAG, DL, VT);
6695 
6696     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6697                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6698                                     Align(4), false);
6699   case Intrinsic::r600_read_local_size_x:
6700     if (Subtarget->isAmdHsaOS())
6701       return emitNonHSAIntrinsicError(DAG, DL, VT);
6702 
6703     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6704                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6705   case Intrinsic::r600_read_local_size_y:
6706     if (Subtarget->isAmdHsaOS())
6707       return emitNonHSAIntrinsicError(DAG, DL, VT);
6708 
6709     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6710                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6711   case Intrinsic::r600_read_local_size_z:
6712     if (Subtarget->isAmdHsaOS())
6713       return emitNonHSAIntrinsicError(DAG, DL, VT);
6714 
6715     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6716                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6717   case Intrinsic::amdgcn_workgroup_id_x:
6718     return getPreloadedValue(DAG, *MFI, VT,
6719                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6720   case Intrinsic::amdgcn_workgroup_id_y:
6721     return getPreloadedValue(DAG, *MFI, VT,
6722                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6723   case Intrinsic::amdgcn_workgroup_id_z:
6724     return getPreloadedValue(DAG, *MFI, VT,
6725                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6726   case Intrinsic::amdgcn_workitem_id_x:
6727     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6728                           SDLoc(DAG.getEntryNode()),
6729                           MFI->getArgInfo().WorkItemIDX);
6730   case Intrinsic::amdgcn_workitem_id_y:
6731     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6732                           SDLoc(DAG.getEntryNode()),
6733                           MFI->getArgInfo().WorkItemIDY);
6734   case Intrinsic::amdgcn_workitem_id_z:
6735     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6736                           SDLoc(DAG.getEntryNode()),
6737                           MFI->getArgInfo().WorkItemIDZ);
6738   case Intrinsic::amdgcn_wavefrontsize:
6739     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6740                            SDLoc(Op), MVT::i32);
6741   case Intrinsic::amdgcn_s_buffer_load: {
6742     unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6743     if (CPol & ~AMDGPU::CPol::ALL)
6744       return Op;
6745     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6746                         DAG);
6747   }
6748   case Intrinsic::amdgcn_fdiv_fast:
6749     return lowerFDIV_FAST(Op, DAG);
6750   case Intrinsic::amdgcn_sin:
6751     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6752 
6753   case Intrinsic::amdgcn_cos:
6754     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6755 
6756   case Intrinsic::amdgcn_mul_u24:
6757     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6758   case Intrinsic::amdgcn_mul_i24:
6759     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6760 
6761   case Intrinsic::amdgcn_log_clamp: {
6762     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6763       return SDValue();
6764 
6765     return emitRemovedIntrinsicError(DAG, DL, VT);
6766   }
6767   case Intrinsic::amdgcn_ldexp:
6768     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6769                        Op.getOperand(1), Op.getOperand(2));
6770 
6771   case Intrinsic::amdgcn_fract:
6772     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6773 
6774   case Intrinsic::amdgcn_class:
6775     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6776                        Op.getOperand(1), Op.getOperand(2));
6777   case Intrinsic::amdgcn_div_fmas:
6778     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6779                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6780                        Op.getOperand(4));
6781 
6782   case Intrinsic::amdgcn_div_fixup:
6783     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6784                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6785 
6786   case Intrinsic::amdgcn_div_scale: {
6787     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6788 
6789     // Translate to the operands expected by the machine instruction. The
6790     // first parameter must be the same as the first instruction.
6791     SDValue Numerator = Op.getOperand(1);
6792     SDValue Denominator = Op.getOperand(2);
6793 
6794     // Note this order is opposite of the machine instruction's operations,
6795     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6796     // intrinsic has the numerator as the first operand to match a normal
6797     // division operation.
6798 
6799     SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator;
6800 
6801     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6802                        Denominator, Numerator);
6803   }
6804   case Intrinsic::amdgcn_icmp: {
6805     // There is a Pat that handles this variant, so return it as-is.
6806     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6807         Op.getConstantOperandVal(2) == 0 &&
6808         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6809       return Op;
6810     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6811   }
6812   case Intrinsic::amdgcn_fcmp: {
6813     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6814   }
6815   case Intrinsic::amdgcn_ballot:
6816     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6817   case Intrinsic::amdgcn_fmed3:
6818     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6819                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6820   case Intrinsic::amdgcn_fdot2:
6821     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6822                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6823                        Op.getOperand(4));
6824   case Intrinsic::amdgcn_fmul_legacy:
6825     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6826                        Op.getOperand(1), Op.getOperand(2));
6827   case Intrinsic::amdgcn_sffbh:
6828     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6829   case Intrinsic::amdgcn_sbfe:
6830     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6831                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6832   case Intrinsic::amdgcn_ubfe:
6833     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6834                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6835   case Intrinsic::amdgcn_cvt_pkrtz:
6836   case Intrinsic::amdgcn_cvt_pknorm_i16:
6837   case Intrinsic::amdgcn_cvt_pknorm_u16:
6838   case Intrinsic::amdgcn_cvt_pk_i16:
6839   case Intrinsic::amdgcn_cvt_pk_u16: {
6840     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6841     EVT VT = Op.getValueType();
6842     unsigned Opcode;
6843 
6844     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6845       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6846     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6847       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6848     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6849       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6850     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6851       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6852     else
6853       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6854 
6855     if (isTypeLegal(VT))
6856       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6857 
6858     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6859                                Op.getOperand(1), Op.getOperand(2));
6860     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6861   }
6862   case Intrinsic::amdgcn_fmad_ftz:
6863     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6864                        Op.getOperand(2), Op.getOperand(3));
6865 
6866   case Intrinsic::amdgcn_if_break:
6867     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6868                                       Op->getOperand(1), Op->getOperand(2)), 0);
6869 
6870   case Intrinsic::amdgcn_groupstaticsize: {
6871     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6872     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6873       return Op;
6874 
6875     const Module *M = MF.getFunction().getParent();
6876     const GlobalValue *GV =
6877         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6878     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6879                                             SIInstrInfo::MO_ABS32_LO);
6880     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6881   }
6882   case Intrinsic::amdgcn_is_shared:
6883   case Intrinsic::amdgcn_is_private: {
6884     SDLoc SL(Op);
6885     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6886       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6887     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6888     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6889                                  Op.getOperand(1));
6890 
6891     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6892                                 DAG.getConstant(1, SL, MVT::i32));
6893     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6894   }
6895   case Intrinsic::amdgcn_alignbit:
6896     return DAG.getNode(ISD::FSHR, DL, VT,
6897                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6898   case Intrinsic::amdgcn_perm:
6899     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
6900                        Op.getOperand(2), Op.getOperand(3));
6901   case Intrinsic::amdgcn_reloc_constant: {
6902     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6903     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6904     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6905     auto RelocSymbol = cast<GlobalVariable>(
6906         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6907     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6908                                             SIInstrInfo::MO_ABS32_LO);
6909     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6910   }
6911   default:
6912     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6913             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6914       return lowerImage(Op, ImageDimIntr, DAG, false);
6915 
6916     return Op;
6917   }
6918 }
6919 
6920 /// Update \p MMO based on the offset inputs to an intrinsic.
6921 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset,
6922                             SDValue SOffset, SDValue Offset,
6923                             SDValue VIndex = SDValue()) {
6924   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6925       !isa<ConstantSDNode>(Offset)) {
6926     // The combined offset is not known to be constant, so we cannot represent
6927     // it in the MMO. Give up.
6928     MMO->setValue((Value *)nullptr);
6929     return;
6930   }
6931 
6932   if (VIndex && (!isa<ConstantSDNode>(VIndex) ||
6933                  !cast<ConstantSDNode>(VIndex)->isZero())) {
6934     // The strided index component of the address is not known to be zero, so we
6935     // cannot represent it in the MMO. Give up.
6936     MMO->setValue((Value *)nullptr);
6937     return;
6938   }
6939 
6940   MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() +
6941                  cast<ConstantSDNode>(SOffset)->getSExtValue() +
6942                  cast<ConstantSDNode>(Offset)->getSExtValue());
6943 }
6944 
6945 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
6946                                                      SelectionDAG &DAG,
6947                                                      unsigned NewOpcode) const {
6948   SDLoc DL(Op);
6949 
6950   SDValue VData = Op.getOperand(2);
6951   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6952   SDValue Ops[] = {
6953     Op.getOperand(0), // Chain
6954     VData,            // vdata
6955     Op.getOperand(3), // rsrc
6956     DAG.getConstant(0, DL, MVT::i32), // vindex
6957     Offsets.first,    // voffset
6958     Op.getOperand(5), // soffset
6959     Offsets.second,   // offset
6960     Op.getOperand(6), // cachepolicy
6961     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6962   };
6963 
6964   auto *M = cast<MemSDNode>(Op);
6965   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
6966 
6967   EVT MemVT = VData.getValueType();
6968   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6969                                  M->getMemOperand());
6970 }
6971 
6972 // Return a value to use for the idxen operand by examining the vindex operand.
6973 static unsigned getIdxEn(SDValue VIndex) {
6974   if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex))
6975     // No need to set idxen if vindex is known to be zero.
6976     return VIndexC->getZExtValue() != 0;
6977   return 1;
6978 }
6979 
6980 SDValue
6981 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
6982                                                 unsigned NewOpcode) const {
6983   SDLoc DL(Op);
6984 
6985   SDValue VData = Op.getOperand(2);
6986   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6987   SDValue Ops[] = {
6988     Op.getOperand(0), // Chain
6989     VData,            // vdata
6990     Op.getOperand(3), // rsrc
6991     Op.getOperand(4), // vindex
6992     Offsets.first,    // voffset
6993     Op.getOperand(6), // soffset
6994     Offsets.second,   // offset
6995     Op.getOperand(7), // cachepolicy
6996     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6997   };
6998 
6999   auto *M = cast<MemSDNode>(Op);
7000   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7001 
7002   EVT MemVT = VData.getValueType();
7003   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7004                                  M->getMemOperand());
7005 }
7006 
7007 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
7008                                                  SelectionDAG &DAG) const {
7009   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7010   SDLoc DL(Op);
7011 
7012   switch (IntrID) {
7013   case Intrinsic::amdgcn_ds_ordered_add:
7014   case Intrinsic::amdgcn_ds_ordered_swap: {
7015     MemSDNode *M = cast<MemSDNode>(Op);
7016     SDValue Chain = M->getOperand(0);
7017     SDValue M0 = M->getOperand(2);
7018     SDValue Value = M->getOperand(3);
7019     unsigned IndexOperand = M->getConstantOperandVal(7);
7020     unsigned WaveRelease = M->getConstantOperandVal(8);
7021     unsigned WaveDone = M->getConstantOperandVal(9);
7022 
7023     unsigned OrderedCountIndex = IndexOperand & 0x3f;
7024     IndexOperand &= ~0x3f;
7025     unsigned CountDw = 0;
7026 
7027     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
7028       CountDw = (IndexOperand >> 24) & 0xf;
7029       IndexOperand &= ~(0xf << 24);
7030 
7031       if (CountDw < 1 || CountDw > 4) {
7032         report_fatal_error(
7033             "ds_ordered_count: dword count must be between 1 and 4");
7034       }
7035     }
7036 
7037     if (IndexOperand)
7038       report_fatal_error("ds_ordered_count: bad index operand");
7039 
7040     if (WaveDone && !WaveRelease)
7041       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
7042 
7043     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
7044     unsigned ShaderType =
7045         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
7046     unsigned Offset0 = OrderedCountIndex << 2;
7047     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
7048                        (Instruction << 4);
7049 
7050     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
7051       Offset1 |= (CountDw - 1) << 6;
7052 
7053     unsigned Offset = Offset0 | (Offset1 << 8);
7054 
7055     SDValue Ops[] = {
7056       Chain,
7057       Value,
7058       DAG.getTargetConstant(Offset, DL, MVT::i16),
7059       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
7060     };
7061     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
7062                                    M->getVTList(), Ops, M->getMemoryVT(),
7063                                    M->getMemOperand());
7064   }
7065   case Intrinsic::amdgcn_ds_fadd: {
7066     MemSDNode *M = cast<MemSDNode>(Op);
7067     unsigned Opc;
7068     switch (IntrID) {
7069     case Intrinsic::amdgcn_ds_fadd:
7070       Opc = ISD::ATOMIC_LOAD_FADD;
7071       break;
7072     }
7073 
7074     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
7075                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
7076                          M->getMemOperand());
7077   }
7078   case Intrinsic::amdgcn_atomic_inc:
7079   case Intrinsic::amdgcn_atomic_dec:
7080   case Intrinsic::amdgcn_ds_fmin:
7081   case Intrinsic::amdgcn_ds_fmax: {
7082     MemSDNode *M = cast<MemSDNode>(Op);
7083     unsigned Opc;
7084     switch (IntrID) {
7085     case Intrinsic::amdgcn_atomic_inc:
7086       Opc = AMDGPUISD::ATOMIC_INC;
7087       break;
7088     case Intrinsic::amdgcn_atomic_dec:
7089       Opc = AMDGPUISD::ATOMIC_DEC;
7090       break;
7091     case Intrinsic::amdgcn_ds_fmin:
7092       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
7093       break;
7094     case Intrinsic::amdgcn_ds_fmax:
7095       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
7096       break;
7097     default:
7098       llvm_unreachable("Unknown intrinsic!");
7099     }
7100     SDValue Ops[] = {
7101       M->getOperand(0), // Chain
7102       M->getOperand(2), // Ptr
7103       M->getOperand(3)  // Value
7104     };
7105 
7106     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
7107                                    M->getMemoryVT(), M->getMemOperand());
7108   }
7109   case Intrinsic::amdgcn_buffer_load:
7110   case Intrinsic::amdgcn_buffer_load_format: {
7111     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
7112     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7113     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7114     SDValue Ops[] = {
7115       Op.getOperand(0), // Chain
7116       Op.getOperand(2), // rsrc
7117       Op.getOperand(3), // vindex
7118       SDValue(),        // voffset -- will be set by setBufferOffsets
7119       SDValue(),        // soffset -- will be set by setBufferOffsets
7120       SDValue(),        // offset -- will be set by setBufferOffsets
7121       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7122       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7123     };
7124     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
7125 
7126     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
7127         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
7128 
7129     EVT VT = Op.getValueType();
7130     EVT IntVT = VT.changeTypeToInteger();
7131     auto *M = cast<MemSDNode>(Op);
7132     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7133     EVT LoadVT = Op.getValueType();
7134 
7135     if (LoadVT.getScalarType() == MVT::f16)
7136       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
7137                                  M, DAG, Ops);
7138 
7139     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
7140     if (LoadVT.getScalarType() == MVT::i8 ||
7141         LoadVT.getScalarType() == MVT::i16)
7142       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
7143 
7144     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
7145                                M->getMemOperand(), DAG);
7146   }
7147   case Intrinsic::amdgcn_raw_buffer_load:
7148   case Intrinsic::amdgcn_raw_buffer_load_format: {
7149     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
7150 
7151     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7152     SDValue Ops[] = {
7153       Op.getOperand(0), // Chain
7154       Op.getOperand(2), // rsrc
7155       DAG.getConstant(0, DL, MVT::i32), // vindex
7156       Offsets.first,    // voffset
7157       Op.getOperand(4), // soffset
7158       Offsets.second,   // offset
7159       Op.getOperand(5), // cachepolicy, swizzled buffer
7160       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7161     };
7162 
7163     auto *M = cast<MemSDNode>(Op);
7164     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]);
7165     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
7166   }
7167   case Intrinsic::amdgcn_struct_buffer_load:
7168   case Intrinsic::amdgcn_struct_buffer_load_format: {
7169     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
7170 
7171     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7172     SDValue Ops[] = {
7173       Op.getOperand(0), // Chain
7174       Op.getOperand(2), // rsrc
7175       Op.getOperand(3), // vindex
7176       Offsets.first,    // voffset
7177       Op.getOperand(5), // soffset
7178       Offsets.second,   // offset
7179       Op.getOperand(6), // cachepolicy, swizzled buffer
7180       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7181     };
7182 
7183     auto *M = cast<MemSDNode>(Op);
7184     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7185     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7186   }
7187   case Intrinsic::amdgcn_tbuffer_load: {
7188     MemSDNode *M = cast<MemSDNode>(Op);
7189     EVT LoadVT = Op.getValueType();
7190 
7191     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7192     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7193     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7194     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7195     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7196     SDValue Ops[] = {
7197       Op.getOperand(0),  // Chain
7198       Op.getOperand(2),  // rsrc
7199       Op.getOperand(3),  // vindex
7200       Op.getOperand(4),  // voffset
7201       Op.getOperand(5),  // soffset
7202       Op.getOperand(6),  // offset
7203       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7204       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7205       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7206     };
7207 
7208     if (LoadVT.getScalarType() == MVT::f16)
7209       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7210                                  M, DAG, Ops);
7211     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7212                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7213                                DAG);
7214   }
7215   case Intrinsic::amdgcn_raw_tbuffer_load: {
7216     MemSDNode *M = cast<MemSDNode>(Op);
7217     EVT LoadVT = Op.getValueType();
7218     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7219 
7220     SDValue Ops[] = {
7221       Op.getOperand(0),  // Chain
7222       Op.getOperand(2),  // rsrc
7223       DAG.getConstant(0, DL, MVT::i32), // vindex
7224       Offsets.first,     // voffset
7225       Op.getOperand(4),  // soffset
7226       Offsets.second,    // offset
7227       Op.getOperand(5),  // format
7228       Op.getOperand(6),  // cachepolicy, swizzled buffer
7229       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7230     };
7231 
7232     if (LoadVT.getScalarType() == MVT::f16)
7233       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7234                                  M, DAG, Ops);
7235     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7236                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7237                                DAG);
7238   }
7239   case Intrinsic::amdgcn_struct_tbuffer_load: {
7240     MemSDNode *M = cast<MemSDNode>(Op);
7241     EVT LoadVT = Op.getValueType();
7242     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7243 
7244     SDValue Ops[] = {
7245       Op.getOperand(0),  // Chain
7246       Op.getOperand(2),  // rsrc
7247       Op.getOperand(3),  // vindex
7248       Offsets.first,     // voffset
7249       Op.getOperand(5),  // soffset
7250       Offsets.second,    // offset
7251       Op.getOperand(6),  // format
7252       Op.getOperand(7),  // cachepolicy, swizzled buffer
7253       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7254     };
7255 
7256     if (LoadVT.getScalarType() == MVT::f16)
7257       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7258                                  M, DAG, Ops);
7259     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7260                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7261                                DAG);
7262   }
7263   case Intrinsic::amdgcn_buffer_atomic_swap:
7264   case Intrinsic::amdgcn_buffer_atomic_add:
7265   case Intrinsic::amdgcn_buffer_atomic_sub:
7266   case Intrinsic::amdgcn_buffer_atomic_csub:
7267   case Intrinsic::amdgcn_buffer_atomic_smin:
7268   case Intrinsic::amdgcn_buffer_atomic_umin:
7269   case Intrinsic::amdgcn_buffer_atomic_smax:
7270   case Intrinsic::amdgcn_buffer_atomic_umax:
7271   case Intrinsic::amdgcn_buffer_atomic_and:
7272   case Intrinsic::amdgcn_buffer_atomic_or:
7273   case Intrinsic::amdgcn_buffer_atomic_xor:
7274   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7275     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7276     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7277     SDValue Ops[] = {
7278       Op.getOperand(0), // Chain
7279       Op.getOperand(2), // vdata
7280       Op.getOperand(3), // rsrc
7281       Op.getOperand(4), // vindex
7282       SDValue(),        // voffset -- will be set by setBufferOffsets
7283       SDValue(),        // soffset -- will be set by setBufferOffsets
7284       SDValue(),        // offset -- will be set by setBufferOffsets
7285       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7286       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7287     };
7288     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7289 
7290     EVT VT = Op.getValueType();
7291 
7292     auto *M = cast<MemSDNode>(Op);
7293     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7294     unsigned Opcode = 0;
7295 
7296     switch (IntrID) {
7297     case Intrinsic::amdgcn_buffer_atomic_swap:
7298       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7299       break;
7300     case Intrinsic::amdgcn_buffer_atomic_add:
7301       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7302       break;
7303     case Intrinsic::amdgcn_buffer_atomic_sub:
7304       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7305       break;
7306     case Intrinsic::amdgcn_buffer_atomic_csub:
7307       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7308       break;
7309     case Intrinsic::amdgcn_buffer_atomic_smin:
7310       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7311       break;
7312     case Intrinsic::amdgcn_buffer_atomic_umin:
7313       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7314       break;
7315     case Intrinsic::amdgcn_buffer_atomic_smax:
7316       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7317       break;
7318     case Intrinsic::amdgcn_buffer_atomic_umax:
7319       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7320       break;
7321     case Intrinsic::amdgcn_buffer_atomic_and:
7322       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7323       break;
7324     case Intrinsic::amdgcn_buffer_atomic_or:
7325       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7326       break;
7327     case Intrinsic::amdgcn_buffer_atomic_xor:
7328       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7329       break;
7330     case Intrinsic::amdgcn_buffer_atomic_fadd:
7331       if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7332         DiagnosticInfoUnsupported
7333           NoFpRet(DAG.getMachineFunction().getFunction(),
7334                   "return versions of fp atomics not supported",
7335                   DL.getDebugLoc(), DS_Error);
7336         DAG.getContext()->diagnose(NoFpRet);
7337         return SDValue();
7338       }
7339       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7340       break;
7341     default:
7342       llvm_unreachable("unhandled atomic opcode");
7343     }
7344 
7345     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7346                                    M->getMemOperand());
7347   }
7348   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7349     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7350   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7351     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7352   case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7353     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7354   case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7355     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7356   case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7357     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7358   case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7359     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7360   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7361     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7362   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7363     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7364   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7365     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7366   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7367     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7368   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7369     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7370   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7371     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7372   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7373     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7374   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7375     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7376   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7377     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7378   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7379     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7380   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7381     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7382   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7383     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7384   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7385     return lowerStructBufferAtomicIntrin(Op, DAG,
7386                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7387   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7388     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7389   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7390     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7391   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7392     return lowerStructBufferAtomicIntrin(Op, DAG,
7393                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7394   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7395     return lowerStructBufferAtomicIntrin(Op, DAG,
7396                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7397   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7398     return lowerStructBufferAtomicIntrin(Op, DAG,
7399                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7400   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7401     return lowerStructBufferAtomicIntrin(Op, DAG,
7402                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7403   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7404     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7405   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7406     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7407   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7408     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7409   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7410     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7411   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7412     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7413 
7414   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7415     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7416     unsigned IdxEn = getIdxEn(Op.getOperand(5));
7417     SDValue Ops[] = {
7418       Op.getOperand(0), // Chain
7419       Op.getOperand(2), // src
7420       Op.getOperand(3), // cmp
7421       Op.getOperand(4), // rsrc
7422       Op.getOperand(5), // vindex
7423       SDValue(),        // voffset -- will be set by setBufferOffsets
7424       SDValue(),        // soffset -- will be set by setBufferOffsets
7425       SDValue(),        // offset -- will be set by setBufferOffsets
7426       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7427       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7428     };
7429     setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7430 
7431     EVT VT = Op.getValueType();
7432     auto *M = cast<MemSDNode>(Op);
7433     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7434 
7435     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7436                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7437   }
7438   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7439     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7440     SDValue Ops[] = {
7441       Op.getOperand(0), // Chain
7442       Op.getOperand(2), // src
7443       Op.getOperand(3), // cmp
7444       Op.getOperand(4), // rsrc
7445       DAG.getConstant(0, DL, MVT::i32), // vindex
7446       Offsets.first,    // voffset
7447       Op.getOperand(6), // soffset
7448       Offsets.second,   // offset
7449       Op.getOperand(7), // cachepolicy
7450       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7451     };
7452     EVT VT = Op.getValueType();
7453     auto *M = cast<MemSDNode>(Op);
7454     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]);
7455 
7456     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7457                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7458   }
7459   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7460     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7461     SDValue Ops[] = {
7462       Op.getOperand(0), // Chain
7463       Op.getOperand(2), // src
7464       Op.getOperand(3), // cmp
7465       Op.getOperand(4), // rsrc
7466       Op.getOperand(5), // vindex
7467       Offsets.first,    // voffset
7468       Op.getOperand(7), // soffset
7469       Offsets.second,   // offset
7470       Op.getOperand(8), // cachepolicy
7471       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7472     };
7473     EVT VT = Op.getValueType();
7474     auto *M = cast<MemSDNode>(Op);
7475     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7476 
7477     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7478                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7479   }
7480   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7481     MemSDNode *M = cast<MemSDNode>(Op);
7482     SDValue NodePtr = M->getOperand(2);
7483     SDValue RayExtent = M->getOperand(3);
7484     SDValue RayOrigin = M->getOperand(4);
7485     SDValue RayDir = M->getOperand(5);
7486     SDValue RayInvDir = M->getOperand(6);
7487     SDValue TDescr = M->getOperand(7);
7488 
7489     assert(NodePtr.getValueType() == MVT::i32 ||
7490            NodePtr.getValueType() == MVT::i64);
7491     assert(RayDir.getValueType() == MVT::v3f16 ||
7492            RayDir.getValueType() == MVT::v3f32);
7493 
7494     if (!Subtarget->hasGFX10_AEncoding()) {
7495       emitRemovedIntrinsicError(DAG, DL, Op.getValueType());
7496       return SDValue();
7497     }
7498 
7499     const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7500     const bool Is64 = NodePtr.getValueType() == MVT::i64;
7501     const unsigned NumVDataDwords = 4;
7502     const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
7503     const bool UseNSA = Subtarget->hasNSAEncoding() &&
7504                         NumVAddrDwords <= Subtarget->getNSAMaxSize();
7505     const unsigned BaseOpcodes[2][2] = {
7506         {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
7507         {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
7508          AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
7509     int Opcode;
7510     if (UseNSA) {
7511       Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7512                                      AMDGPU::MIMGEncGfx10NSA, NumVDataDwords,
7513                                      NumVAddrDwords);
7514     } else {
7515       Opcode = AMDGPU::getMIMGOpcode(
7516           BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords,
7517           PowerOf2Ceil(NumVAddrDwords));
7518     }
7519     assert(Opcode != -1);
7520 
7521     SmallVector<SDValue, 16> Ops;
7522 
7523     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7524       SmallVector<SDValue, 3> Lanes;
7525       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7526       if (Lanes[0].getValueSizeInBits() == 32) {
7527         for (unsigned I = 0; I < 3; ++I)
7528           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7529       } else {
7530         if (IsAligned) {
7531           Ops.push_back(
7532             DAG.getBitcast(MVT::i32,
7533                            DAG.getBuildVector(MVT::v2f16, DL,
7534                                               { Lanes[0], Lanes[1] })));
7535           Ops.push_back(Lanes[2]);
7536         } else {
7537           SDValue Elt0 = Ops.pop_back_val();
7538           Ops.push_back(
7539             DAG.getBitcast(MVT::i32,
7540                            DAG.getBuildVector(MVT::v2f16, DL,
7541                                               { Elt0, Lanes[0] })));
7542           Ops.push_back(
7543             DAG.getBitcast(MVT::i32,
7544                            DAG.getBuildVector(MVT::v2f16, DL,
7545                                               { Lanes[1], Lanes[2] })));
7546         }
7547       }
7548     };
7549 
7550     if (Is64)
7551       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7552     else
7553       Ops.push_back(NodePtr);
7554 
7555     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7556     packLanes(RayOrigin, true);
7557     packLanes(RayDir, true);
7558     packLanes(RayInvDir, false);
7559 
7560     if (!UseNSA) {
7561       // Build a single vector containing all the operands so far prepared.
7562       if (NumVAddrDwords > 8) {
7563         SDValue Undef = DAG.getUNDEF(MVT::i32);
7564         Ops.append(16 - Ops.size(), Undef);
7565       }
7566       assert(Ops.size() == 8 || Ops.size() == 16);
7567       SDValue MergedOps = DAG.getBuildVector(
7568           Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops);
7569       Ops.clear();
7570       Ops.push_back(MergedOps);
7571     }
7572 
7573     Ops.push_back(TDescr);
7574     if (IsA16)
7575       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7576     Ops.push_back(M->getChain());
7577 
7578     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7579     MachineMemOperand *MemRef = M->getMemOperand();
7580     DAG.setNodeMemRefs(NewNode, {MemRef});
7581     return SDValue(NewNode, 0);
7582   }
7583   case Intrinsic::amdgcn_global_atomic_fadd:
7584     if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7585       DiagnosticInfoUnsupported
7586         NoFpRet(DAG.getMachineFunction().getFunction(),
7587                 "return versions of fp atomics not supported",
7588                 DL.getDebugLoc(), DS_Error);
7589       DAG.getContext()->diagnose(NoFpRet);
7590       return SDValue();
7591     }
7592     LLVM_FALLTHROUGH;
7593   case Intrinsic::amdgcn_global_atomic_fmin:
7594   case Intrinsic::amdgcn_global_atomic_fmax:
7595   case Intrinsic::amdgcn_flat_atomic_fadd:
7596   case Intrinsic::amdgcn_flat_atomic_fmin:
7597   case Intrinsic::amdgcn_flat_atomic_fmax: {
7598     MemSDNode *M = cast<MemSDNode>(Op);
7599     SDValue Ops[] = {
7600       M->getOperand(0), // Chain
7601       M->getOperand(2), // Ptr
7602       M->getOperand(3)  // Value
7603     };
7604     unsigned Opcode = 0;
7605     switch (IntrID) {
7606     case Intrinsic::amdgcn_global_atomic_fadd:
7607     case Intrinsic::amdgcn_flat_atomic_fadd: {
7608       EVT VT = Op.getOperand(3).getValueType();
7609       return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7610                            DAG.getVTList(VT, MVT::Other), Ops,
7611                            M->getMemOperand());
7612     }
7613     case Intrinsic::amdgcn_global_atomic_fmin:
7614     case Intrinsic::amdgcn_flat_atomic_fmin: {
7615       Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7616       break;
7617     }
7618     case Intrinsic::amdgcn_global_atomic_fmax:
7619     case Intrinsic::amdgcn_flat_atomic_fmax: {
7620       Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7621       break;
7622     }
7623     default:
7624       llvm_unreachable("unhandled atomic opcode");
7625     }
7626     return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7627                                    M->getVTList(), Ops, M->getMemoryVT(),
7628                                    M->getMemOperand());
7629   }
7630   default:
7631 
7632     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7633             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7634       return lowerImage(Op, ImageDimIntr, DAG, true);
7635 
7636     return SDValue();
7637   }
7638 }
7639 
7640 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7641 // dwordx4 if on SI.
7642 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7643                                               SDVTList VTList,
7644                                               ArrayRef<SDValue> Ops, EVT MemVT,
7645                                               MachineMemOperand *MMO,
7646                                               SelectionDAG &DAG) const {
7647   EVT VT = VTList.VTs[0];
7648   EVT WidenedVT = VT;
7649   EVT WidenedMemVT = MemVT;
7650   if (!Subtarget->hasDwordx3LoadStores() &&
7651       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7652     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7653                                  WidenedVT.getVectorElementType(), 4);
7654     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7655                                     WidenedMemVT.getVectorElementType(), 4);
7656     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7657   }
7658 
7659   assert(VTList.NumVTs == 2);
7660   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7661 
7662   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7663                                        WidenedMemVT, MMO);
7664   if (WidenedVT != VT) {
7665     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7666                                DAG.getVectorIdxConstant(0, DL));
7667     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7668   }
7669   return NewOp;
7670 }
7671 
7672 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7673                                          bool ImageStore) const {
7674   EVT StoreVT = VData.getValueType();
7675 
7676   // No change for f16 and legal vector D16 types.
7677   if (!StoreVT.isVector())
7678     return VData;
7679 
7680   SDLoc DL(VData);
7681   unsigned NumElements = StoreVT.getVectorNumElements();
7682 
7683   if (Subtarget->hasUnpackedD16VMem()) {
7684     // We need to unpack the packed data to store.
7685     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7686     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7687 
7688     EVT EquivStoreVT =
7689         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7690     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7691     return DAG.UnrollVectorOp(ZExt.getNode());
7692   }
7693 
7694   // The sq block of gfx8.1 does not estimate register use correctly for d16
7695   // image store instructions. The data operand is computed as if it were not a
7696   // d16 image instruction.
7697   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7698     // Bitcast to i16
7699     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7700     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7701 
7702     // Decompose into scalars
7703     SmallVector<SDValue, 4> Elts;
7704     DAG.ExtractVectorElements(IntVData, Elts);
7705 
7706     // Group pairs of i16 into v2i16 and bitcast to i32
7707     SmallVector<SDValue, 4> PackedElts;
7708     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7709       SDValue Pair =
7710           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7711       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7712       PackedElts.push_back(IntPair);
7713     }
7714     if ((NumElements % 2) == 1) {
7715       // Handle v3i16
7716       unsigned I = Elts.size() / 2;
7717       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7718                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7719       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7720       PackedElts.push_back(IntPair);
7721     }
7722 
7723     // Pad using UNDEF
7724     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7725 
7726     // Build final vector
7727     EVT VecVT =
7728         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7729     return DAG.getBuildVector(VecVT, DL, PackedElts);
7730   }
7731 
7732   if (NumElements == 3) {
7733     EVT IntStoreVT =
7734         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7735     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7736 
7737     EVT WidenedStoreVT = EVT::getVectorVT(
7738         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7739     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7740                                          WidenedStoreVT.getStoreSizeInBits());
7741     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7742     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7743   }
7744 
7745   assert(isTypeLegal(StoreVT));
7746   return VData;
7747 }
7748 
7749 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7750                                               SelectionDAG &DAG) const {
7751   SDLoc DL(Op);
7752   SDValue Chain = Op.getOperand(0);
7753   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7754   MachineFunction &MF = DAG.getMachineFunction();
7755 
7756   switch (IntrinsicID) {
7757   case Intrinsic::amdgcn_exp_compr: {
7758     SDValue Src0 = Op.getOperand(4);
7759     SDValue Src1 = Op.getOperand(5);
7760     // Hack around illegal type on SI by directly selecting it.
7761     if (isTypeLegal(Src0.getValueType()))
7762       return SDValue();
7763 
7764     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7765     SDValue Undef = DAG.getUNDEF(MVT::f32);
7766     const SDValue Ops[] = {
7767       Op.getOperand(2), // tgt
7768       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7769       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7770       Undef, // src2
7771       Undef, // src3
7772       Op.getOperand(7), // vm
7773       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7774       Op.getOperand(3), // en
7775       Op.getOperand(0) // Chain
7776     };
7777 
7778     unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7779     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7780   }
7781   case Intrinsic::amdgcn_s_barrier: {
7782     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7783       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7784       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7785       if (WGSize <= ST.getWavefrontSize())
7786         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7787                                           Op.getOperand(0)), 0);
7788     }
7789     return SDValue();
7790   };
7791   case Intrinsic::amdgcn_tbuffer_store: {
7792     SDValue VData = Op.getOperand(2);
7793     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7794     if (IsD16)
7795       VData = handleD16VData(VData, DAG);
7796     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7797     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7798     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7799     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7800     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7801     SDValue Ops[] = {
7802       Chain,
7803       VData,             // vdata
7804       Op.getOperand(3),  // rsrc
7805       Op.getOperand(4),  // vindex
7806       Op.getOperand(5),  // voffset
7807       Op.getOperand(6),  // soffset
7808       Op.getOperand(7),  // offset
7809       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7810       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7811       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7812     };
7813     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7814                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7815     MemSDNode *M = cast<MemSDNode>(Op);
7816     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7817                                    M->getMemoryVT(), M->getMemOperand());
7818   }
7819 
7820   case Intrinsic::amdgcn_struct_tbuffer_store: {
7821     SDValue VData = Op.getOperand(2);
7822     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7823     if (IsD16)
7824       VData = handleD16VData(VData, DAG);
7825     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7826     SDValue Ops[] = {
7827       Chain,
7828       VData,             // vdata
7829       Op.getOperand(3),  // rsrc
7830       Op.getOperand(4),  // vindex
7831       Offsets.first,     // voffset
7832       Op.getOperand(6),  // soffset
7833       Offsets.second,    // offset
7834       Op.getOperand(7),  // format
7835       Op.getOperand(8),  // cachepolicy, swizzled buffer
7836       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7837     };
7838     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7839                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7840     MemSDNode *M = cast<MemSDNode>(Op);
7841     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7842                                    M->getMemoryVT(), M->getMemOperand());
7843   }
7844 
7845   case Intrinsic::amdgcn_raw_tbuffer_store: {
7846     SDValue VData = Op.getOperand(2);
7847     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7848     if (IsD16)
7849       VData = handleD16VData(VData, DAG);
7850     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7851     SDValue Ops[] = {
7852       Chain,
7853       VData,             // vdata
7854       Op.getOperand(3),  // rsrc
7855       DAG.getConstant(0, DL, MVT::i32), // vindex
7856       Offsets.first,     // voffset
7857       Op.getOperand(5),  // soffset
7858       Offsets.second,    // offset
7859       Op.getOperand(6),  // format
7860       Op.getOperand(7),  // cachepolicy, swizzled buffer
7861       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7862     };
7863     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7864                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7865     MemSDNode *M = cast<MemSDNode>(Op);
7866     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7867                                    M->getMemoryVT(), M->getMemOperand());
7868   }
7869 
7870   case Intrinsic::amdgcn_buffer_store:
7871   case Intrinsic::amdgcn_buffer_store_format: {
7872     SDValue VData = Op.getOperand(2);
7873     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7874     if (IsD16)
7875       VData = handleD16VData(VData, DAG);
7876     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7877     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7878     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7879     SDValue Ops[] = {
7880       Chain,
7881       VData,
7882       Op.getOperand(3), // rsrc
7883       Op.getOperand(4), // vindex
7884       SDValue(), // voffset -- will be set by setBufferOffsets
7885       SDValue(), // soffset -- will be set by setBufferOffsets
7886       SDValue(), // offset -- will be set by setBufferOffsets
7887       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7888       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7889     };
7890     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7891 
7892     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7893                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7894     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7895     MemSDNode *M = cast<MemSDNode>(Op);
7896     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7897 
7898     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7899     EVT VDataType = VData.getValueType().getScalarType();
7900     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7901       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7902 
7903     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7904                                    M->getMemoryVT(), M->getMemOperand());
7905   }
7906 
7907   case Intrinsic::amdgcn_raw_buffer_store:
7908   case Intrinsic::amdgcn_raw_buffer_store_format: {
7909     const bool IsFormat =
7910         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7911 
7912     SDValue VData = Op.getOperand(2);
7913     EVT VDataVT = VData.getValueType();
7914     EVT EltType = VDataVT.getScalarType();
7915     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7916     if (IsD16) {
7917       VData = handleD16VData(VData, DAG);
7918       VDataVT = VData.getValueType();
7919     }
7920 
7921     if (!isTypeLegal(VDataVT)) {
7922       VData =
7923           DAG.getNode(ISD::BITCAST, DL,
7924                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7925     }
7926 
7927     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7928     SDValue Ops[] = {
7929       Chain,
7930       VData,
7931       Op.getOperand(3), // rsrc
7932       DAG.getConstant(0, DL, MVT::i32), // vindex
7933       Offsets.first,    // voffset
7934       Op.getOperand(5), // soffset
7935       Offsets.second,   // offset
7936       Op.getOperand(6), // cachepolicy, swizzled buffer
7937       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7938     };
7939     unsigned Opc =
7940         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7941     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7942     MemSDNode *M = cast<MemSDNode>(Op);
7943     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
7944 
7945     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7946     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7947       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7948 
7949     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7950                                    M->getMemoryVT(), M->getMemOperand());
7951   }
7952 
7953   case Intrinsic::amdgcn_struct_buffer_store:
7954   case Intrinsic::amdgcn_struct_buffer_store_format: {
7955     const bool IsFormat =
7956         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7957 
7958     SDValue VData = Op.getOperand(2);
7959     EVT VDataVT = VData.getValueType();
7960     EVT EltType = VDataVT.getScalarType();
7961     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7962 
7963     if (IsD16) {
7964       VData = handleD16VData(VData, DAG);
7965       VDataVT = VData.getValueType();
7966     }
7967 
7968     if (!isTypeLegal(VDataVT)) {
7969       VData =
7970           DAG.getNode(ISD::BITCAST, DL,
7971                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7972     }
7973 
7974     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7975     SDValue Ops[] = {
7976       Chain,
7977       VData,
7978       Op.getOperand(3), // rsrc
7979       Op.getOperand(4), // vindex
7980       Offsets.first,    // voffset
7981       Op.getOperand(6), // soffset
7982       Offsets.second,   // offset
7983       Op.getOperand(7), // cachepolicy, swizzled buffer
7984       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7985     };
7986     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7987                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7988     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7989     MemSDNode *M = cast<MemSDNode>(Op);
7990     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7991 
7992     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7993     EVT VDataType = VData.getValueType().getScalarType();
7994     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7995       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7996 
7997     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7998                                    M->getMemoryVT(), M->getMemOperand());
7999   }
8000   case Intrinsic::amdgcn_end_cf:
8001     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
8002                                       Op->getOperand(2), Chain), 0);
8003 
8004   default: {
8005     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
8006             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
8007       return lowerImage(Op, ImageDimIntr, DAG, true);
8008 
8009     return Op;
8010   }
8011   }
8012 }
8013 
8014 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
8015 // offset (the offset that is included in bounds checking and swizzling, to be
8016 // split between the instruction's voffset and immoffset fields) and soffset
8017 // (the offset that is excluded from bounds checking and swizzling, to go in
8018 // the instruction's soffset field).  This function takes the first kind of
8019 // offset and figures out how to split it between voffset and immoffset.
8020 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
8021     SDValue Offset, SelectionDAG &DAG) const {
8022   SDLoc DL(Offset);
8023   const unsigned MaxImm = 4095;
8024   SDValue N0 = Offset;
8025   ConstantSDNode *C1 = nullptr;
8026 
8027   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
8028     N0 = SDValue();
8029   else if (DAG.isBaseWithConstantOffset(N0)) {
8030     C1 = cast<ConstantSDNode>(N0.getOperand(1));
8031     N0 = N0.getOperand(0);
8032   }
8033 
8034   if (C1) {
8035     unsigned ImmOffset = C1->getZExtValue();
8036     // If the immediate value is too big for the immoffset field, put the value
8037     // and -4096 into the immoffset field so that the value that is copied/added
8038     // for the voffset field is a multiple of 4096, and it stands more chance
8039     // of being CSEd with the copy/add for another similar load/store.
8040     // However, do not do that rounding down to a multiple of 4096 if that is a
8041     // negative number, as it appears to be illegal to have a negative offset
8042     // in the vgpr, even if adding the immediate offset makes it positive.
8043     unsigned Overflow = ImmOffset & ~MaxImm;
8044     ImmOffset -= Overflow;
8045     if ((int32_t)Overflow < 0) {
8046       Overflow += ImmOffset;
8047       ImmOffset = 0;
8048     }
8049     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
8050     if (Overflow) {
8051       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
8052       if (!N0)
8053         N0 = OverflowVal;
8054       else {
8055         SDValue Ops[] = { N0, OverflowVal };
8056         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
8057       }
8058     }
8059   }
8060   if (!N0)
8061     N0 = DAG.getConstant(0, DL, MVT::i32);
8062   if (!C1)
8063     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
8064   return {N0, SDValue(C1, 0)};
8065 }
8066 
8067 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
8068 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
8069 // pointed to by Offsets.
8070 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
8071                                         SelectionDAG &DAG, SDValue *Offsets,
8072                                         Align Alignment) const {
8073   SDLoc DL(CombinedOffset);
8074   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
8075     uint32_t Imm = C->getZExtValue();
8076     uint32_t SOffset, ImmOffset;
8077     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
8078                                  Alignment)) {
8079       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
8080       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8081       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8082       return;
8083     }
8084   }
8085   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
8086     SDValue N0 = CombinedOffset.getOperand(0);
8087     SDValue N1 = CombinedOffset.getOperand(1);
8088     uint32_t SOffset, ImmOffset;
8089     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
8090     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
8091                                                 Subtarget, Alignment)) {
8092       Offsets[0] = N0;
8093       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8094       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8095       return;
8096     }
8097   }
8098   Offsets[0] = CombinedOffset;
8099   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
8100   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
8101 }
8102 
8103 // Handle 8 bit and 16 bit buffer loads
8104 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
8105                                                      EVT LoadVT, SDLoc DL,
8106                                                      ArrayRef<SDValue> Ops,
8107                                                      MemSDNode *M) const {
8108   EVT IntVT = LoadVT.changeTypeToInteger();
8109   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
8110          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
8111 
8112   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
8113   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
8114                                                Ops, IntVT,
8115                                                M->getMemOperand());
8116   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
8117   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
8118 
8119   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
8120 }
8121 
8122 // Handle 8 bit and 16 bit buffer stores
8123 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
8124                                                       EVT VDataType, SDLoc DL,
8125                                                       SDValue Ops[],
8126                                                       MemSDNode *M) const {
8127   if (VDataType == MVT::f16)
8128     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
8129 
8130   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
8131   Ops[1] = BufferStoreExt;
8132   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
8133                                  AMDGPUISD::BUFFER_STORE_SHORT;
8134   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
8135   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
8136                                      M->getMemOperand());
8137 }
8138 
8139 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
8140                                  ISD::LoadExtType ExtType, SDValue Op,
8141                                  const SDLoc &SL, EVT VT) {
8142   if (VT.bitsLT(Op.getValueType()))
8143     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
8144 
8145   switch (ExtType) {
8146   case ISD::SEXTLOAD:
8147     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
8148   case ISD::ZEXTLOAD:
8149     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
8150   case ISD::EXTLOAD:
8151     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
8152   case ISD::NON_EXTLOAD:
8153     return Op;
8154   }
8155 
8156   llvm_unreachable("invalid ext type");
8157 }
8158 
8159 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
8160   SelectionDAG &DAG = DCI.DAG;
8161   if (Ld->getAlignment() < 4 || Ld->isDivergent())
8162     return SDValue();
8163 
8164   // FIXME: Constant loads should all be marked invariant.
8165   unsigned AS = Ld->getAddressSpace();
8166   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
8167       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
8168       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
8169     return SDValue();
8170 
8171   // Don't do this early, since it may interfere with adjacent load merging for
8172   // illegal types. We can avoid losing alignment information for exotic types
8173   // pre-legalize.
8174   EVT MemVT = Ld->getMemoryVT();
8175   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
8176       MemVT.getSizeInBits() >= 32)
8177     return SDValue();
8178 
8179   SDLoc SL(Ld);
8180 
8181   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
8182          "unexpected vector extload");
8183 
8184   // TODO: Drop only high part of range.
8185   SDValue Ptr = Ld->getBasePtr();
8186   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
8187                                 MVT::i32, SL, Ld->getChain(), Ptr,
8188                                 Ld->getOffset(),
8189                                 Ld->getPointerInfo(), MVT::i32,
8190                                 Ld->getAlignment(),
8191                                 Ld->getMemOperand()->getFlags(),
8192                                 Ld->getAAInfo(),
8193                                 nullptr); // Drop ranges
8194 
8195   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
8196   if (MemVT.isFloatingPoint()) {
8197     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
8198            "unexpected fp extload");
8199     TruncVT = MemVT.changeTypeToInteger();
8200   }
8201 
8202   SDValue Cvt = NewLoad;
8203   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
8204     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
8205                       DAG.getValueType(TruncVT));
8206   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
8207              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
8208     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
8209   } else {
8210     assert(Ld->getExtensionType() == ISD::EXTLOAD);
8211   }
8212 
8213   EVT VT = Ld->getValueType(0);
8214   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8215 
8216   DCI.AddToWorklist(Cvt.getNode());
8217 
8218   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
8219   // the appropriate extension from the 32-bit load.
8220   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
8221   DCI.AddToWorklist(Cvt.getNode());
8222 
8223   // Handle conversion back to floating point if necessary.
8224   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8225 
8226   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8227 }
8228 
8229 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8230   SDLoc DL(Op);
8231   LoadSDNode *Load = cast<LoadSDNode>(Op);
8232   ISD::LoadExtType ExtType = Load->getExtensionType();
8233   EVT MemVT = Load->getMemoryVT();
8234 
8235   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8236     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8237       return SDValue();
8238 
8239     // FIXME: Copied from PPC
8240     // First, load into 32 bits, then truncate to 1 bit.
8241 
8242     SDValue Chain = Load->getChain();
8243     SDValue BasePtr = Load->getBasePtr();
8244     MachineMemOperand *MMO = Load->getMemOperand();
8245 
8246     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8247 
8248     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8249                                    BasePtr, RealMemVT, MMO);
8250 
8251     if (!MemVT.isVector()) {
8252       SDValue Ops[] = {
8253         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8254         NewLD.getValue(1)
8255       };
8256 
8257       return DAG.getMergeValues(Ops, DL);
8258     }
8259 
8260     SmallVector<SDValue, 3> Elts;
8261     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8262       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8263                                 DAG.getConstant(I, DL, MVT::i32));
8264 
8265       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8266     }
8267 
8268     SDValue Ops[] = {
8269       DAG.getBuildVector(MemVT, DL, Elts),
8270       NewLD.getValue(1)
8271     };
8272 
8273     return DAG.getMergeValues(Ops, DL);
8274   }
8275 
8276   if (!MemVT.isVector())
8277     return SDValue();
8278 
8279   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8280          "Custom lowering for non-i32 vectors hasn't been implemented.");
8281 
8282   unsigned Alignment = Load->getAlignment();
8283   unsigned AS = Load->getAddressSpace();
8284   if (Subtarget->hasLDSMisalignedBug() &&
8285       AS == AMDGPUAS::FLAT_ADDRESS &&
8286       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8287     return SplitVectorLoad(Op, DAG);
8288   }
8289 
8290   MachineFunction &MF = DAG.getMachineFunction();
8291   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8292   // If there is a possibilty that flat instruction access scratch memory
8293   // then we need to use the same legalization rules we use for private.
8294   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8295       !Subtarget->hasMultiDwordFlatScratchAddressing())
8296     AS = MFI->hasFlatScratchInit() ?
8297          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8298 
8299   unsigned NumElements = MemVT.getVectorNumElements();
8300 
8301   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8302       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8303     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8304       if (MemVT.isPow2VectorType())
8305         return SDValue();
8306       return WidenOrSplitVectorLoad(Op, DAG);
8307     }
8308     // Non-uniform loads will be selected to MUBUF instructions, so they
8309     // have the same legalization requirements as global and private
8310     // loads.
8311     //
8312   }
8313 
8314   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8315       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8316       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8317     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8318         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8319         Alignment >= 4 && NumElements < 32) {
8320       if (MemVT.isPow2VectorType())
8321         return SDValue();
8322       return WidenOrSplitVectorLoad(Op, DAG);
8323     }
8324     // Non-uniform loads will be selected to MUBUF instructions, so they
8325     // have the same legalization requirements as global and private
8326     // loads.
8327     //
8328   }
8329   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8330       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8331       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8332       AS == AMDGPUAS::FLAT_ADDRESS) {
8333     if (NumElements > 4)
8334       return SplitVectorLoad(Op, DAG);
8335     // v3 loads not supported on SI.
8336     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8337       return WidenOrSplitVectorLoad(Op, DAG);
8338 
8339     // v3 and v4 loads are supported for private and global memory.
8340     return SDValue();
8341   }
8342   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8343     // Depending on the setting of the private_element_size field in the
8344     // resource descriptor, we can only make private accesses up to a certain
8345     // size.
8346     switch (Subtarget->getMaxPrivateElementSize()) {
8347     case 4: {
8348       SDValue Ops[2];
8349       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8350       return DAG.getMergeValues(Ops, DL);
8351     }
8352     case 8:
8353       if (NumElements > 2)
8354         return SplitVectorLoad(Op, DAG);
8355       return SDValue();
8356     case 16:
8357       // Same as global/flat
8358       if (NumElements > 4)
8359         return SplitVectorLoad(Op, DAG);
8360       // v3 loads not supported on SI.
8361       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8362         return WidenOrSplitVectorLoad(Op, DAG);
8363 
8364       return SDValue();
8365     default:
8366       llvm_unreachable("unsupported private_element_size");
8367     }
8368   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8369     // Use ds_read_b128 or ds_read_b96 when possible.
8370     if (Subtarget->hasDS96AndDS128() &&
8371         ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) ||
8372          MemVT.getStoreSize() == 12) &&
8373         allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8374                                            Load->getAlign()))
8375       return SDValue();
8376 
8377     if (NumElements > 2)
8378       return SplitVectorLoad(Op, DAG);
8379 
8380     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8381     // address is negative, then the instruction is incorrectly treated as
8382     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8383     // loads here to avoid emitting ds_read2_b32. We may re-combine the
8384     // load later in the SILoadStoreOptimizer.
8385     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
8386         NumElements == 2 && MemVT.getStoreSize() == 8 &&
8387         Load->getAlignment() < 8) {
8388       return SplitVectorLoad(Op, DAG);
8389     }
8390   }
8391 
8392   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8393                                       MemVT, *Load->getMemOperand())) {
8394     SDValue Ops[2];
8395     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8396     return DAG.getMergeValues(Ops, DL);
8397   }
8398 
8399   return SDValue();
8400 }
8401 
8402 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8403   EVT VT = Op.getValueType();
8404   assert(VT.getSizeInBits() == 64);
8405 
8406   SDLoc DL(Op);
8407   SDValue Cond = Op.getOperand(0);
8408 
8409   if (Subtarget->hasScalarCompareEq64() && Op->getOperand(0)->hasOneUse() &&
8410       !Op->isDivergent()) {
8411     if (VT == MVT::i64)
8412       return Op;
8413     SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(1));
8414     SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(2));
8415     return DAG.getNode(ISD::BITCAST, DL, VT,
8416                        DAG.getSelect(DL, MVT::i64, Cond, LHS, RHS));
8417   }
8418 
8419   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8420   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8421 
8422   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8423   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8424 
8425   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8426   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8427 
8428   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8429 
8430   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8431   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8432 
8433   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8434 
8435   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8436   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8437 }
8438 
8439 // Catch division cases where we can use shortcuts with rcp and rsq
8440 // instructions.
8441 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8442                                               SelectionDAG &DAG) const {
8443   SDLoc SL(Op);
8444   SDValue LHS = Op.getOperand(0);
8445   SDValue RHS = Op.getOperand(1);
8446   EVT VT = Op.getValueType();
8447   const SDNodeFlags Flags = Op->getFlags();
8448 
8449   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8450 
8451   // Without !fpmath accuracy information, we can't do more because we don't
8452   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8453   if (!AllowInaccurateRcp)
8454     return SDValue();
8455 
8456   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8457     if (CLHS->isExactlyValue(1.0)) {
8458       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8459       // the CI documentation has a worst case error of 1 ulp.
8460       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8461       // use it as long as we aren't trying to use denormals.
8462       //
8463       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8464 
8465       // 1.0 / sqrt(x) -> rsq(x)
8466 
8467       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8468       // error seems really high at 2^29 ULP.
8469       if (RHS.getOpcode() == ISD::FSQRT)
8470         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8471 
8472       // 1.0 / x -> rcp(x)
8473       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8474     }
8475 
8476     // Same as for 1.0, but expand the sign out of the constant.
8477     if (CLHS->isExactlyValue(-1.0)) {
8478       // -1.0 / x -> rcp (fneg x)
8479       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8480       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8481     }
8482   }
8483 
8484   // Turn into multiply by the reciprocal.
8485   // x / y -> x * (1.0 / y)
8486   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8487   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8488 }
8489 
8490 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8491                                                 SelectionDAG &DAG) const {
8492   SDLoc SL(Op);
8493   SDValue X = Op.getOperand(0);
8494   SDValue Y = Op.getOperand(1);
8495   EVT VT = Op.getValueType();
8496   const SDNodeFlags Flags = Op->getFlags();
8497 
8498   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8499                             DAG.getTarget().Options.UnsafeFPMath;
8500   if (!AllowInaccurateDiv)
8501     return SDValue();
8502 
8503   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8504   SDValue One = DAG.getConstantFP(1.0, SL, VT);
8505 
8506   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8507   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8508 
8509   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8510   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8511   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8512   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8513   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8514   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8515 }
8516 
8517 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8518                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8519                           SDNodeFlags Flags) {
8520   if (GlueChain->getNumValues() <= 1) {
8521     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8522   }
8523 
8524   assert(GlueChain->getNumValues() == 3);
8525 
8526   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8527   switch (Opcode) {
8528   default: llvm_unreachable("no chain equivalent for opcode");
8529   case ISD::FMUL:
8530     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8531     break;
8532   }
8533 
8534   return DAG.getNode(Opcode, SL, VTList,
8535                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8536                      Flags);
8537 }
8538 
8539 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8540                            EVT VT, SDValue A, SDValue B, SDValue C,
8541                            SDValue GlueChain, SDNodeFlags Flags) {
8542   if (GlueChain->getNumValues() <= 1) {
8543     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8544   }
8545 
8546   assert(GlueChain->getNumValues() == 3);
8547 
8548   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8549   switch (Opcode) {
8550   default: llvm_unreachable("no chain equivalent for opcode");
8551   case ISD::FMA:
8552     Opcode = AMDGPUISD::FMA_W_CHAIN;
8553     break;
8554   }
8555 
8556   return DAG.getNode(Opcode, SL, VTList,
8557                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8558                      Flags);
8559 }
8560 
8561 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8562   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8563     return FastLowered;
8564 
8565   SDLoc SL(Op);
8566   SDValue Src0 = Op.getOperand(0);
8567   SDValue Src1 = Op.getOperand(1);
8568 
8569   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8570   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8571 
8572   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8573   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8574 
8575   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8576   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8577 
8578   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8579 }
8580 
8581 // Faster 2.5 ULP division that does not support denormals.
8582 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8583   SDLoc SL(Op);
8584   SDValue LHS = Op.getOperand(1);
8585   SDValue RHS = Op.getOperand(2);
8586 
8587   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8588 
8589   const APFloat K0Val(BitsToFloat(0x6f800000));
8590   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8591 
8592   const APFloat K1Val(BitsToFloat(0x2f800000));
8593   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8594 
8595   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8596 
8597   EVT SetCCVT =
8598     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8599 
8600   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8601 
8602   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8603 
8604   // TODO: Should this propagate fast-math-flags?
8605   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8606 
8607   // rcp does not support denormals.
8608   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8609 
8610   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8611 
8612   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8613 }
8614 
8615 // Returns immediate value for setting the F32 denorm mode when using the
8616 // S_DENORM_MODE instruction.
8617 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8618                                     const SDLoc &SL, const GCNSubtarget *ST) {
8619   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8620   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8621                                 ? FP_DENORM_FLUSH_NONE
8622                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8623 
8624   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8625   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8626 }
8627 
8628 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8629   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8630     return FastLowered;
8631 
8632   // The selection matcher assumes anything with a chain selecting to a
8633   // mayRaiseFPException machine instruction. Since we're introducing a chain
8634   // here, we need to explicitly report nofpexcept for the regular fdiv
8635   // lowering.
8636   SDNodeFlags Flags = Op->getFlags();
8637   Flags.setNoFPExcept(true);
8638 
8639   SDLoc SL(Op);
8640   SDValue LHS = Op.getOperand(0);
8641   SDValue RHS = Op.getOperand(1);
8642 
8643   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8644 
8645   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8646 
8647   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8648                                           {RHS, RHS, LHS}, Flags);
8649   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8650                                         {LHS, RHS, LHS}, Flags);
8651 
8652   // Denominator is scaled to not be denormal, so using rcp is ok.
8653   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8654                                   DenominatorScaled, Flags);
8655   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8656                                      DenominatorScaled, Flags);
8657 
8658   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8659                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8660                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8661   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8662 
8663   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8664 
8665   if (!HasFP32Denormals) {
8666     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8667     // lowering. The chain dependence is insufficient, and we need glue. We do
8668     // not need the glue variants in a strictfp function.
8669 
8670     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8671 
8672     SDNode *EnableDenorm;
8673     if (Subtarget->hasDenormModeInst()) {
8674       const SDValue EnableDenormValue =
8675           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8676 
8677       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8678                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8679     } else {
8680       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8681                                                         SL, MVT::i32);
8682       EnableDenorm =
8683           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8684                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8685     }
8686 
8687     SDValue Ops[3] = {
8688       NegDivScale0,
8689       SDValue(EnableDenorm, 0),
8690       SDValue(EnableDenorm, 1)
8691     };
8692 
8693     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8694   }
8695 
8696   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8697                              ApproxRcp, One, NegDivScale0, Flags);
8698 
8699   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8700                              ApproxRcp, Fma0, Flags);
8701 
8702   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8703                            Fma1, Fma1, Flags);
8704 
8705   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8706                              NumeratorScaled, Mul, Flags);
8707 
8708   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8709                              Fma2, Fma1, Mul, Fma2, Flags);
8710 
8711   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8712                              NumeratorScaled, Fma3, Flags);
8713 
8714   if (!HasFP32Denormals) {
8715     SDNode *DisableDenorm;
8716     if (Subtarget->hasDenormModeInst()) {
8717       const SDValue DisableDenormValue =
8718           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8719 
8720       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8721                                   Fma4.getValue(1), DisableDenormValue,
8722                                   Fma4.getValue(2)).getNode();
8723     } else {
8724       const SDValue DisableDenormValue =
8725           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8726 
8727       DisableDenorm = DAG.getMachineNode(
8728           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8729           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8730     }
8731 
8732     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8733                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8734     DAG.setRoot(OutputChain);
8735   }
8736 
8737   SDValue Scale = NumeratorScaled.getValue(1);
8738   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8739                              {Fma4, Fma1, Fma3, Scale}, Flags);
8740 
8741   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8742 }
8743 
8744 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8745   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
8746     return FastLowered;
8747 
8748   SDLoc SL(Op);
8749   SDValue X = Op.getOperand(0);
8750   SDValue Y = Op.getOperand(1);
8751 
8752   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8753 
8754   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8755 
8756   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8757 
8758   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8759 
8760   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8761 
8762   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8763 
8764   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8765 
8766   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8767 
8768   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8769 
8770   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8771   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8772 
8773   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8774                              NegDivScale0, Mul, DivScale1);
8775 
8776   SDValue Scale;
8777 
8778   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8779     // Workaround a hardware bug on SI where the condition output from div_scale
8780     // is not usable.
8781 
8782     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8783 
8784     // Figure out if the scale to use for div_fmas.
8785     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8786     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8787     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8788     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8789 
8790     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8791     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8792 
8793     SDValue Scale0Hi
8794       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8795     SDValue Scale1Hi
8796       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8797 
8798     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8799     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8800     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8801   } else {
8802     Scale = DivScale1.getValue(1);
8803   }
8804 
8805   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8806                              Fma4, Fma3, Mul, Scale);
8807 
8808   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8809 }
8810 
8811 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8812   EVT VT = Op.getValueType();
8813 
8814   if (VT == MVT::f32)
8815     return LowerFDIV32(Op, DAG);
8816 
8817   if (VT == MVT::f64)
8818     return LowerFDIV64(Op, DAG);
8819 
8820   if (VT == MVT::f16)
8821     return LowerFDIV16(Op, DAG);
8822 
8823   llvm_unreachable("Unexpected type for fdiv");
8824 }
8825 
8826 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8827   SDLoc DL(Op);
8828   StoreSDNode *Store = cast<StoreSDNode>(Op);
8829   EVT VT = Store->getMemoryVT();
8830 
8831   if (VT == MVT::i1) {
8832     return DAG.getTruncStore(Store->getChain(), DL,
8833        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8834        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8835   }
8836 
8837   assert(VT.isVector() &&
8838          Store->getValue().getValueType().getScalarType() == MVT::i32);
8839 
8840   unsigned AS = Store->getAddressSpace();
8841   if (Subtarget->hasLDSMisalignedBug() &&
8842       AS == AMDGPUAS::FLAT_ADDRESS &&
8843       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8844     return SplitVectorStore(Op, DAG);
8845   }
8846 
8847   MachineFunction &MF = DAG.getMachineFunction();
8848   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8849   // If there is a possibilty that flat instruction access scratch memory
8850   // then we need to use the same legalization rules we use for private.
8851   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8852       !Subtarget->hasMultiDwordFlatScratchAddressing())
8853     AS = MFI->hasFlatScratchInit() ?
8854          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8855 
8856   unsigned NumElements = VT.getVectorNumElements();
8857   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8858       AS == AMDGPUAS::FLAT_ADDRESS) {
8859     if (NumElements > 4)
8860       return SplitVectorStore(Op, DAG);
8861     // v3 stores not supported on SI.
8862     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8863       return SplitVectorStore(Op, DAG);
8864 
8865     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8866                                         VT, *Store->getMemOperand()))
8867       return expandUnalignedStore(Store, DAG);
8868 
8869     return SDValue();
8870   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8871     switch (Subtarget->getMaxPrivateElementSize()) {
8872     case 4:
8873       return scalarizeVectorStore(Store, DAG);
8874     case 8:
8875       if (NumElements > 2)
8876         return SplitVectorStore(Op, DAG);
8877       return SDValue();
8878     case 16:
8879       if (NumElements > 4 ||
8880           (NumElements == 3 && !Subtarget->enableFlatScratch()))
8881         return SplitVectorStore(Op, DAG);
8882       return SDValue();
8883     default:
8884       llvm_unreachable("unsupported private_element_size");
8885     }
8886   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8887     // Use ds_write_b128 or ds_write_b96 when possible.
8888     if (Subtarget->hasDS96AndDS128() &&
8889         ((Subtarget->useDS128() && VT.getStoreSize() == 16) ||
8890          (VT.getStoreSize() == 12)) &&
8891         allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
8892                                            Store->getAlign()))
8893       return SDValue();
8894 
8895     if (NumElements > 2)
8896       return SplitVectorStore(Op, DAG);
8897 
8898     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8899     // address is negative, then the instruction is incorrectly treated as
8900     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8901     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8902     // store later in the SILoadStoreOptimizer.
8903     if (!Subtarget->hasUsableDSOffset() &&
8904         NumElements == 2 && VT.getStoreSize() == 8 &&
8905         Store->getAlignment() < 8) {
8906       return SplitVectorStore(Op, DAG);
8907     }
8908 
8909     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8910                                         VT, *Store->getMemOperand())) {
8911       if (VT.isVector())
8912         return SplitVectorStore(Op, DAG);
8913       return expandUnalignedStore(Store, DAG);
8914     }
8915 
8916     return SDValue();
8917   } else {
8918     llvm_unreachable("unhandled address space");
8919   }
8920 }
8921 
8922 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8923   SDLoc DL(Op);
8924   EVT VT = Op.getValueType();
8925   SDValue Arg = Op.getOperand(0);
8926   SDValue TrigVal;
8927 
8928   // Propagate fast-math flags so that the multiply we introduce can be folded
8929   // if Arg is already the result of a multiply by constant.
8930   auto Flags = Op->getFlags();
8931 
8932   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
8933 
8934   if (Subtarget->hasTrigReducedRange()) {
8935     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8936     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
8937   } else {
8938     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8939   }
8940 
8941   switch (Op.getOpcode()) {
8942   case ISD::FCOS:
8943     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
8944   case ISD::FSIN:
8945     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
8946   default:
8947     llvm_unreachable("Wrong trig opcode");
8948   }
8949 }
8950 
8951 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8952   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8953   assert(AtomicNode->isCompareAndSwap());
8954   unsigned AS = AtomicNode->getAddressSpace();
8955 
8956   // No custom lowering required for local address space
8957   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
8958     return Op;
8959 
8960   // Non-local address space requires custom lowering for atomic compare
8961   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8962   SDLoc DL(Op);
8963   SDValue ChainIn = Op.getOperand(0);
8964   SDValue Addr = Op.getOperand(1);
8965   SDValue Old = Op.getOperand(2);
8966   SDValue New = Op.getOperand(3);
8967   EVT VT = Op.getValueType();
8968   MVT SimpleVT = VT.getSimpleVT();
8969   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8970 
8971   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8972   SDValue Ops[] = { ChainIn, Addr, NewOld };
8973 
8974   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8975                                  Ops, VT, AtomicNode->getMemOperand());
8976 }
8977 
8978 //===----------------------------------------------------------------------===//
8979 // Custom DAG optimizations
8980 //===----------------------------------------------------------------------===//
8981 
8982 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8983                                                      DAGCombinerInfo &DCI) const {
8984   EVT VT = N->getValueType(0);
8985   EVT ScalarVT = VT.getScalarType();
8986   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8987     return SDValue();
8988 
8989   SelectionDAG &DAG = DCI.DAG;
8990   SDLoc DL(N);
8991 
8992   SDValue Src = N->getOperand(0);
8993   EVT SrcVT = Src.getValueType();
8994 
8995   // TODO: We could try to match extracting the higher bytes, which would be
8996   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8997   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8998   // about in practice.
8999   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
9000     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
9001       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
9002       DCI.AddToWorklist(Cvt.getNode());
9003 
9004       // For the f16 case, fold to a cast to f32 and then cast back to f16.
9005       if (ScalarVT != MVT::f32) {
9006         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
9007                           DAG.getTargetConstant(0, DL, MVT::i32));
9008       }
9009       return Cvt;
9010     }
9011   }
9012 
9013   return SDValue();
9014 }
9015 
9016 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
9017 
9018 // This is a variant of
9019 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
9020 //
9021 // The normal DAG combiner will do this, but only if the add has one use since
9022 // that would increase the number of instructions.
9023 //
9024 // This prevents us from seeing a constant offset that can be folded into a
9025 // memory instruction's addressing mode. If we know the resulting add offset of
9026 // a pointer can be folded into an addressing offset, we can replace the pointer
9027 // operand with the add of new constant offset. This eliminates one of the uses,
9028 // and may allow the remaining use to also be simplified.
9029 //
9030 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
9031                                                unsigned AddrSpace,
9032                                                EVT MemVT,
9033                                                DAGCombinerInfo &DCI) const {
9034   SDValue N0 = N->getOperand(0);
9035   SDValue N1 = N->getOperand(1);
9036 
9037   // We only do this to handle cases where it's profitable when there are
9038   // multiple uses of the add, so defer to the standard combine.
9039   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
9040       N0->hasOneUse())
9041     return SDValue();
9042 
9043   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
9044   if (!CN1)
9045     return SDValue();
9046 
9047   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9048   if (!CAdd)
9049     return SDValue();
9050 
9051   // If the resulting offset is too large, we can't fold it into the addressing
9052   // mode offset.
9053   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
9054   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
9055 
9056   AddrMode AM;
9057   AM.HasBaseReg = true;
9058   AM.BaseOffs = Offset.getSExtValue();
9059   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
9060     return SDValue();
9061 
9062   SelectionDAG &DAG = DCI.DAG;
9063   SDLoc SL(N);
9064   EVT VT = N->getValueType(0);
9065 
9066   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
9067   SDValue COffset = DAG.getConstant(Offset, SL, VT);
9068 
9069   SDNodeFlags Flags;
9070   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
9071                           (N0.getOpcode() == ISD::OR ||
9072                            N0->getFlags().hasNoUnsignedWrap()));
9073 
9074   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
9075 }
9076 
9077 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
9078 /// by the chain and intrinsic ID. Theoretically we would also need to check the
9079 /// specific intrinsic, but they all place the pointer operand first.
9080 static unsigned getBasePtrIndex(const MemSDNode *N) {
9081   switch (N->getOpcode()) {
9082   case ISD::STORE:
9083   case ISD::INTRINSIC_W_CHAIN:
9084   case ISD::INTRINSIC_VOID:
9085     return 2;
9086   default:
9087     return 1;
9088   }
9089 }
9090 
9091 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
9092                                                   DAGCombinerInfo &DCI) const {
9093   SelectionDAG &DAG = DCI.DAG;
9094   SDLoc SL(N);
9095 
9096   unsigned PtrIdx = getBasePtrIndex(N);
9097   SDValue Ptr = N->getOperand(PtrIdx);
9098 
9099   // TODO: We could also do this for multiplies.
9100   if (Ptr.getOpcode() == ISD::SHL) {
9101     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
9102                                           N->getMemoryVT(), DCI);
9103     if (NewPtr) {
9104       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
9105 
9106       NewOps[PtrIdx] = NewPtr;
9107       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
9108     }
9109   }
9110 
9111   return SDValue();
9112 }
9113 
9114 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
9115   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
9116          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
9117          (Opc == ISD::XOR && Val == 0);
9118 }
9119 
9120 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
9121 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
9122 // integer combine opportunities since most 64-bit operations are decomposed
9123 // this way.  TODO: We won't want this for SALU especially if it is an inline
9124 // immediate.
9125 SDValue SITargetLowering::splitBinaryBitConstantOp(
9126   DAGCombinerInfo &DCI,
9127   const SDLoc &SL,
9128   unsigned Opc, SDValue LHS,
9129   const ConstantSDNode *CRHS) const {
9130   uint64_t Val = CRHS->getZExtValue();
9131   uint32_t ValLo = Lo_32(Val);
9132   uint32_t ValHi = Hi_32(Val);
9133   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9134 
9135     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
9136          bitOpWithConstantIsReducible(Opc, ValHi)) ||
9137         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
9138     // If we need to materialize a 64-bit immediate, it will be split up later
9139     // anyway. Avoid creating the harder to understand 64-bit immediate
9140     // materialization.
9141     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
9142   }
9143 
9144   return SDValue();
9145 }
9146 
9147 // Returns true if argument is a boolean value which is not serialized into
9148 // memory or argument and does not require v_cndmask_b32 to be deserialized.
9149 static bool isBoolSGPR(SDValue V) {
9150   if (V.getValueType() != MVT::i1)
9151     return false;
9152   switch (V.getOpcode()) {
9153   default:
9154     break;
9155   case ISD::SETCC:
9156   case AMDGPUISD::FP_CLASS:
9157     return true;
9158   case ISD::AND:
9159   case ISD::OR:
9160   case ISD::XOR:
9161     return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
9162   }
9163   return false;
9164 }
9165 
9166 // If a constant has all zeroes or all ones within each byte return it.
9167 // Otherwise return 0.
9168 static uint32_t getConstantPermuteMask(uint32_t C) {
9169   // 0xff for any zero byte in the mask
9170   uint32_t ZeroByteMask = 0;
9171   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
9172   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
9173   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
9174   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
9175   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
9176   if ((NonZeroByteMask & C) != NonZeroByteMask)
9177     return 0; // Partial bytes selected.
9178   return C;
9179 }
9180 
9181 // Check if a node selects whole bytes from its operand 0 starting at a byte
9182 // boundary while masking the rest. Returns select mask as in the v_perm_b32
9183 // or -1 if not succeeded.
9184 // Note byte select encoding:
9185 // value 0-3 selects corresponding source byte;
9186 // value 0xc selects zero;
9187 // value 0xff selects 0xff.
9188 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
9189   assert(V.getValueSizeInBits() == 32);
9190 
9191   if (V.getNumOperands() != 2)
9192     return ~0;
9193 
9194   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
9195   if (!N1)
9196     return ~0;
9197 
9198   uint32_t C = N1->getZExtValue();
9199 
9200   switch (V.getOpcode()) {
9201   default:
9202     break;
9203   case ISD::AND:
9204     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9205       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
9206     }
9207     break;
9208 
9209   case ISD::OR:
9210     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9211       return (0x03020100 & ~ConstMask) | ConstMask;
9212     }
9213     break;
9214 
9215   case ISD::SHL:
9216     if (C % 8)
9217       return ~0;
9218 
9219     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
9220 
9221   case ISD::SRL:
9222     if (C % 8)
9223       return ~0;
9224 
9225     return uint32_t(0x0c0c0c0c03020100ull >> C);
9226   }
9227 
9228   return ~0;
9229 }
9230 
9231 SDValue SITargetLowering::performAndCombine(SDNode *N,
9232                                             DAGCombinerInfo &DCI) const {
9233   if (DCI.isBeforeLegalize())
9234     return SDValue();
9235 
9236   SelectionDAG &DAG = DCI.DAG;
9237   EVT VT = N->getValueType(0);
9238   SDValue LHS = N->getOperand(0);
9239   SDValue RHS = N->getOperand(1);
9240 
9241 
9242   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9243   if (VT == MVT::i64 && CRHS) {
9244     if (SDValue Split
9245         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9246       return Split;
9247   }
9248 
9249   if (CRHS && VT == MVT::i32) {
9250     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9251     // nb = number of trailing zeroes in mask
9252     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9253     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9254     uint64_t Mask = CRHS->getZExtValue();
9255     unsigned Bits = countPopulation(Mask);
9256     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9257         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9258       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9259         unsigned Shift = CShift->getZExtValue();
9260         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9261         unsigned Offset = NB + Shift;
9262         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9263           SDLoc SL(N);
9264           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9265                                     LHS->getOperand(0),
9266                                     DAG.getConstant(Offset, SL, MVT::i32),
9267                                     DAG.getConstant(Bits, SL, MVT::i32));
9268           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9269           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9270                                     DAG.getValueType(NarrowVT));
9271           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9272                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9273           return Shl;
9274         }
9275       }
9276     }
9277 
9278     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9279     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9280         isa<ConstantSDNode>(LHS.getOperand(2))) {
9281       uint32_t Sel = getConstantPermuteMask(Mask);
9282       if (!Sel)
9283         return SDValue();
9284 
9285       // Select 0xc for all zero bytes
9286       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9287       SDLoc DL(N);
9288       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9289                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9290     }
9291   }
9292 
9293   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9294   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9295   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9296     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9297     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9298 
9299     SDValue X = LHS.getOperand(0);
9300     SDValue Y = RHS.getOperand(0);
9301     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9302       return SDValue();
9303 
9304     if (LCC == ISD::SETO) {
9305       if (X != LHS.getOperand(1))
9306         return SDValue();
9307 
9308       if (RCC == ISD::SETUNE) {
9309         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9310         if (!C1 || !C1->isInfinity() || C1->isNegative())
9311           return SDValue();
9312 
9313         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9314                               SIInstrFlags::N_SUBNORMAL |
9315                               SIInstrFlags::N_ZERO |
9316                               SIInstrFlags::P_ZERO |
9317                               SIInstrFlags::P_SUBNORMAL |
9318                               SIInstrFlags::P_NORMAL;
9319 
9320         static_assert(((~(SIInstrFlags::S_NAN |
9321                           SIInstrFlags::Q_NAN |
9322                           SIInstrFlags::N_INFINITY |
9323                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9324                       "mask not equal");
9325 
9326         SDLoc DL(N);
9327         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9328                            X, DAG.getConstant(Mask, DL, MVT::i32));
9329       }
9330     }
9331   }
9332 
9333   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9334     std::swap(LHS, RHS);
9335 
9336   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9337       RHS.hasOneUse()) {
9338     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9339     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9340     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9341     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9342     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9343         (RHS.getOperand(0) == LHS.getOperand(0) &&
9344          LHS.getOperand(0) == LHS.getOperand(1))) {
9345       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9346       unsigned NewMask = LCC == ISD::SETO ?
9347         Mask->getZExtValue() & ~OrdMask :
9348         Mask->getZExtValue() & OrdMask;
9349 
9350       SDLoc DL(N);
9351       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9352                          DAG.getConstant(NewMask, DL, MVT::i32));
9353     }
9354   }
9355 
9356   if (VT == MVT::i32 &&
9357       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9358     // and x, (sext cc from i1) => select cc, x, 0
9359     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9360       std::swap(LHS, RHS);
9361     if (isBoolSGPR(RHS.getOperand(0)))
9362       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9363                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9364   }
9365 
9366   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9367   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9368   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9369       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9370     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9371     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9372     if (LHSMask != ~0u && RHSMask != ~0u) {
9373       // Canonicalize the expression in an attempt to have fewer unique masks
9374       // and therefore fewer registers used to hold the masks.
9375       if (LHSMask > RHSMask) {
9376         std::swap(LHSMask, RHSMask);
9377         std::swap(LHS, RHS);
9378       }
9379 
9380       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9381       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9382       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9383       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9384 
9385       // Check of we need to combine values from two sources within a byte.
9386       if (!(LHSUsedLanes & RHSUsedLanes) &&
9387           // If we select high and lower word keep it for SDWA.
9388           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9389           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9390         // Each byte in each mask is either selector mask 0-3, or has higher
9391         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9392         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9393         // mask which is not 0xff wins. By anding both masks we have a correct
9394         // result except that 0x0c shall be corrected to give 0x0c only.
9395         uint32_t Mask = LHSMask & RHSMask;
9396         for (unsigned I = 0; I < 32; I += 8) {
9397           uint32_t ByteSel = 0xff << I;
9398           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9399             Mask &= (0x0c << I) & 0xffffffff;
9400         }
9401 
9402         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9403         // or 0x0c.
9404         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9405         SDLoc DL(N);
9406 
9407         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9408                            LHS.getOperand(0), RHS.getOperand(0),
9409                            DAG.getConstant(Sel, DL, MVT::i32));
9410       }
9411     }
9412   }
9413 
9414   return SDValue();
9415 }
9416 
9417 SDValue SITargetLowering::performOrCombine(SDNode *N,
9418                                            DAGCombinerInfo &DCI) const {
9419   SelectionDAG &DAG = DCI.DAG;
9420   SDValue LHS = N->getOperand(0);
9421   SDValue RHS = N->getOperand(1);
9422 
9423   EVT VT = N->getValueType(0);
9424   if (VT == MVT::i1) {
9425     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9426     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9427         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9428       SDValue Src = LHS.getOperand(0);
9429       if (Src != RHS.getOperand(0))
9430         return SDValue();
9431 
9432       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9433       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9434       if (!CLHS || !CRHS)
9435         return SDValue();
9436 
9437       // Only 10 bits are used.
9438       static const uint32_t MaxMask = 0x3ff;
9439 
9440       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9441       SDLoc DL(N);
9442       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9443                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9444     }
9445 
9446     return SDValue();
9447   }
9448 
9449   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9450   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9451       LHS.getOpcode() == AMDGPUISD::PERM &&
9452       isa<ConstantSDNode>(LHS.getOperand(2))) {
9453     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9454     if (!Sel)
9455       return SDValue();
9456 
9457     Sel |= LHS.getConstantOperandVal(2);
9458     SDLoc DL(N);
9459     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9460                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9461   }
9462 
9463   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9464   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9465   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9466       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9467     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9468     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9469     if (LHSMask != ~0u && RHSMask != ~0u) {
9470       // Canonicalize the expression in an attempt to have fewer unique masks
9471       // and therefore fewer registers used to hold the masks.
9472       if (LHSMask > RHSMask) {
9473         std::swap(LHSMask, RHSMask);
9474         std::swap(LHS, RHS);
9475       }
9476 
9477       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9478       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9479       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9480       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9481 
9482       // Check of we need to combine values from two sources within a byte.
9483       if (!(LHSUsedLanes & RHSUsedLanes) &&
9484           // If we select high and lower word keep it for SDWA.
9485           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9486           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9487         // Kill zero bytes selected by other mask. Zero value is 0xc.
9488         LHSMask &= ~RHSUsedLanes;
9489         RHSMask &= ~LHSUsedLanes;
9490         // Add 4 to each active LHS lane
9491         LHSMask |= LHSUsedLanes & 0x04040404;
9492         // Combine masks
9493         uint32_t Sel = LHSMask | RHSMask;
9494         SDLoc DL(N);
9495 
9496         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9497                            LHS.getOperand(0), RHS.getOperand(0),
9498                            DAG.getConstant(Sel, DL, MVT::i32));
9499       }
9500     }
9501   }
9502 
9503   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9504     return SDValue();
9505 
9506   // TODO: This could be a generic combine with a predicate for extracting the
9507   // high half of an integer being free.
9508 
9509   // (or i64:x, (zero_extend i32:y)) ->
9510   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9511   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9512       RHS.getOpcode() != ISD::ZERO_EXTEND)
9513     std::swap(LHS, RHS);
9514 
9515   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9516     SDValue ExtSrc = RHS.getOperand(0);
9517     EVT SrcVT = ExtSrc.getValueType();
9518     if (SrcVT == MVT::i32) {
9519       SDLoc SL(N);
9520       SDValue LowLHS, HiBits;
9521       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9522       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9523 
9524       DCI.AddToWorklist(LowOr.getNode());
9525       DCI.AddToWorklist(HiBits.getNode());
9526 
9527       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9528                                 LowOr, HiBits);
9529       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9530     }
9531   }
9532 
9533   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9534   if (CRHS) {
9535     if (SDValue Split
9536           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR,
9537                                      N->getOperand(0), CRHS))
9538       return Split;
9539   }
9540 
9541   return SDValue();
9542 }
9543 
9544 SDValue SITargetLowering::performXorCombine(SDNode *N,
9545                                             DAGCombinerInfo &DCI) const {
9546   EVT VT = N->getValueType(0);
9547   if (VT != MVT::i64)
9548     return SDValue();
9549 
9550   SDValue LHS = N->getOperand(0);
9551   SDValue RHS = N->getOperand(1);
9552 
9553   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9554   if (CRHS) {
9555     if (SDValue Split
9556           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9557       return Split;
9558   }
9559 
9560   return SDValue();
9561 }
9562 
9563 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9564                                                    DAGCombinerInfo &DCI) const {
9565   if (!Subtarget->has16BitInsts() ||
9566       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9567     return SDValue();
9568 
9569   EVT VT = N->getValueType(0);
9570   if (VT != MVT::i32)
9571     return SDValue();
9572 
9573   SDValue Src = N->getOperand(0);
9574   if (Src.getValueType() != MVT::i16)
9575     return SDValue();
9576 
9577   return SDValue();
9578 }
9579 
9580 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9581                                                         DAGCombinerInfo &DCI)
9582                                                         const {
9583   SDValue Src = N->getOperand(0);
9584   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9585 
9586   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9587       VTSign->getVT() == MVT::i8) ||
9588       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9589       VTSign->getVT() == MVT::i16)) &&
9590       Src.hasOneUse()) {
9591     auto *M = cast<MemSDNode>(Src);
9592     SDValue Ops[] = {
9593       Src.getOperand(0), // Chain
9594       Src.getOperand(1), // rsrc
9595       Src.getOperand(2), // vindex
9596       Src.getOperand(3), // voffset
9597       Src.getOperand(4), // soffset
9598       Src.getOperand(5), // offset
9599       Src.getOperand(6),
9600       Src.getOperand(7)
9601     };
9602     // replace with BUFFER_LOAD_BYTE/SHORT
9603     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9604                                          Src.getOperand(0).getValueType());
9605     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9606                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9607     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9608                                                           ResList,
9609                                                           Ops, M->getMemoryVT(),
9610                                                           M->getMemOperand());
9611     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9612                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9613   }
9614   return SDValue();
9615 }
9616 
9617 SDValue SITargetLowering::performClassCombine(SDNode *N,
9618                                               DAGCombinerInfo &DCI) const {
9619   SelectionDAG &DAG = DCI.DAG;
9620   SDValue Mask = N->getOperand(1);
9621 
9622   // fp_class x, 0 -> false
9623   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9624     if (CMask->isZero())
9625       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9626   }
9627 
9628   if (N->getOperand(0).isUndef())
9629     return DAG.getUNDEF(MVT::i1);
9630 
9631   return SDValue();
9632 }
9633 
9634 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9635                                             DAGCombinerInfo &DCI) const {
9636   EVT VT = N->getValueType(0);
9637   SDValue N0 = N->getOperand(0);
9638 
9639   if (N0.isUndef())
9640     return N0;
9641 
9642   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9643                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9644     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9645                            N->getFlags());
9646   }
9647 
9648   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9649     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9650                            N0.getOperand(0), N->getFlags());
9651   }
9652 
9653   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9654 }
9655 
9656 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9657                                        unsigned MaxDepth) const {
9658   unsigned Opcode = Op.getOpcode();
9659   if (Opcode == ISD::FCANONICALIZE)
9660     return true;
9661 
9662   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9663     auto F = CFP->getValueAPF();
9664     if (F.isNaN() && F.isSignaling())
9665       return false;
9666     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9667   }
9668 
9669   // If source is a result of another standard FP operation it is already in
9670   // canonical form.
9671   if (MaxDepth == 0)
9672     return false;
9673 
9674   switch (Opcode) {
9675   // These will flush denorms if required.
9676   case ISD::FADD:
9677   case ISD::FSUB:
9678   case ISD::FMUL:
9679   case ISD::FCEIL:
9680   case ISD::FFLOOR:
9681   case ISD::FMA:
9682   case ISD::FMAD:
9683   case ISD::FSQRT:
9684   case ISD::FDIV:
9685   case ISD::FREM:
9686   case ISD::FP_ROUND:
9687   case ISD::FP_EXTEND:
9688   case AMDGPUISD::FMUL_LEGACY:
9689   case AMDGPUISD::FMAD_FTZ:
9690   case AMDGPUISD::RCP:
9691   case AMDGPUISD::RSQ:
9692   case AMDGPUISD::RSQ_CLAMP:
9693   case AMDGPUISD::RCP_LEGACY:
9694   case AMDGPUISD::RCP_IFLAG:
9695   case AMDGPUISD::DIV_SCALE:
9696   case AMDGPUISD::DIV_FMAS:
9697   case AMDGPUISD::DIV_FIXUP:
9698   case AMDGPUISD::FRACT:
9699   case AMDGPUISD::LDEXP:
9700   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9701   case AMDGPUISD::CVT_F32_UBYTE0:
9702   case AMDGPUISD::CVT_F32_UBYTE1:
9703   case AMDGPUISD::CVT_F32_UBYTE2:
9704   case AMDGPUISD::CVT_F32_UBYTE3:
9705     return true;
9706 
9707   // It can/will be lowered or combined as a bit operation.
9708   // Need to check their input recursively to handle.
9709   case ISD::FNEG:
9710   case ISD::FABS:
9711   case ISD::FCOPYSIGN:
9712     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9713 
9714   case ISD::FSIN:
9715   case ISD::FCOS:
9716   case ISD::FSINCOS:
9717     return Op.getValueType().getScalarType() != MVT::f16;
9718 
9719   case ISD::FMINNUM:
9720   case ISD::FMAXNUM:
9721   case ISD::FMINNUM_IEEE:
9722   case ISD::FMAXNUM_IEEE:
9723   case AMDGPUISD::CLAMP:
9724   case AMDGPUISD::FMED3:
9725   case AMDGPUISD::FMAX3:
9726   case AMDGPUISD::FMIN3: {
9727     // FIXME: Shouldn't treat the generic operations different based these.
9728     // However, we aren't really required to flush the result from
9729     // minnum/maxnum..
9730 
9731     // snans will be quieted, so we only need to worry about denormals.
9732     if (Subtarget->supportsMinMaxDenormModes() ||
9733         denormalsEnabledForType(DAG, Op.getValueType()))
9734       return true;
9735 
9736     // Flushing may be required.
9737     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9738     // targets need to check their input recursively.
9739 
9740     // FIXME: Does this apply with clamp? It's implemented with max.
9741     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9742       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9743         return false;
9744     }
9745 
9746     return true;
9747   }
9748   case ISD::SELECT: {
9749     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9750            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9751   }
9752   case ISD::BUILD_VECTOR: {
9753     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9754       SDValue SrcOp = Op.getOperand(i);
9755       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9756         return false;
9757     }
9758 
9759     return true;
9760   }
9761   case ISD::EXTRACT_VECTOR_ELT:
9762   case ISD::EXTRACT_SUBVECTOR: {
9763     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9764   }
9765   case ISD::INSERT_VECTOR_ELT: {
9766     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9767            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9768   }
9769   case ISD::UNDEF:
9770     // Could be anything.
9771     return false;
9772 
9773   case ISD::BITCAST:
9774     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9775   case ISD::TRUNCATE: {
9776     // Hack round the mess we make when legalizing extract_vector_elt
9777     if (Op.getValueType() == MVT::i16) {
9778       SDValue TruncSrc = Op.getOperand(0);
9779       if (TruncSrc.getValueType() == MVT::i32 &&
9780           TruncSrc.getOpcode() == ISD::BITCAST &&
9781           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9782         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9783       }
9784     }
9785     return false;
9786   }
9787   case ISD::INTRINSIC_WO_CHAIN: {
9788     unsigned IntrinsicID
9789       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9790     // TODO: Handle more intrinsics
9791     switch (IntrinsicID) {
9792     case Intrinsic::amdgcn_cvt_pkrtz:
9793     case Intrinsic::amdgcn_cubeid:
9794     case Intrinsic::amdgcn_frexp_mant:
9795     case Intrinsic::amdgcn_fdot2:
9796     case Intrinsic::amdgcn_rcp:
9797     case Intrinsic::amdgcn_rsq:
9798     case Intrinsic::amdgcn_rsq_clamp:
9799     case Intrinsic::amdgcn_rcp_legacy:
9800     case Intrinsic::amdgcn_rsq_legacy:
9801     case Intrinsic::amdgcn_trig_preop:
9802       return true;
9803     default:
9804       break;
9805     }
9806 
9807     LLVM_FALLTHROUGH;
9808   }
9809   default:
9810     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9811            DAG.isKnownNeverSNaN(Op);
9812   }
9813 
9814   llvm_unreachable("invalid operation");
9815 }
9816 
9817 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
9818                                        unsigned MaxDepth) const {
9819   MachineRegisterInfo &MRI = MF.getRegInfo();
9820   MachineInstr *MI = MRI.getVRegDef(Reg);
9821   unsigned Opcode = MI->getOpcode();
9822 
9823   if (Opcode == AMDGPU::G_FCANONICALIZE)
9824     return true;
9825 
9826   Optional<FPValueAndVReg> FCR;
9827   // Constant splat (can be padded with undef) or scalar constant.
9828   if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) {
9829     if (FCR->Value.isSignaling())
9830       return false;
9831     return !FCR->Value.isDenormal() ||
9832            denormalsEnabledForType(MRI.getType(FCR->VReg), MF);
9833   }
9834 
9835   if (MaxDepth == 0)
9836     return false;
9837 
9838   switch (Opcode) {
9839   case AMDGPU::G_FMINNUM_IEEE:
9840   case AMDGPU::G_FMAXNUM_IEEE: {
9841     if (Subtarget->supportsMinMaxDenormModes() ||
9842         denormalsEnabledForType(MRI.getType(Reg), MF))
9843       return true;
9844     for (const MachineOperand &MO : llvm::drop_begin(MI->operands()))
9845       if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1))
9846         return false;
9847     return true;
9848   }
9849   default:
9850     return denormalsEnabledForType(MRI.getType(Reg), MF) &&
9851            isKnownNeverSNaN(Reg, MRI);
9852   }
9853 
9854   llvm_unreachable("invalid operation");
9855 }
9856 
9857 // Constant fold canonicalize.
9858 SDValue SITargetLowering::getCanonicalConstantFP(
9859   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9860   // Flush denormals to 0 if not enabled.
9861   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9862     return DAG.getConstantFP(0.0, SL, VT);
9863 
9864   if (C.isNaN()) {
9865     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9866     if (C.isSignaling()) {
9867       // Quiet a signaling NaN.
9868       // FIXME: Is this supposed to preserve payload bits?
9869       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9870     }
9871 
9872     // Make sure it is the canonical NaN bitpattern.
9873     //
9874     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9875     // immediate?
9876     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9877       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9878   }
9879 
9880   // Already canonical.
9881   return DAG.getConstantFP(C, SL, VT);
9882 }
9883 
9884 static bool vectorEltWillFoldAway(SDValue Op) {
9885   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9886 }
9887 
9888 SDValue SITargetLowering::performFCanonicalizeCombine(
9889   SDNode *N,
9890   DAGCombinerInfo &DCI) const {
9891   SelectionDAG &DAG = DCI.DAG;
9892   SDValue N0 = N->getOperand(0);
9893   EVT VT = N->getValueType(0);
9894 
9895   // fcanonicalize undef -> qnan
9896   if (N0.isUndef()) {
9897     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9898     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9899   }
9900 
9901   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9902     EVT VT = N->getValueType(0);
9903     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9904   }
9905 
9906   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9907   //                                                   (fcanonicalize k)
9908   //
9909   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9910 
9911   // TODO: This could be better with wider vectors that will be split to v2f16,
9912   // and to consider uses since there aren't that many packed operations.
9913   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9914       isTypeLegal(MVT::v2f16)) {
9915     SDLoc SL(N);
9916     SDValue NewElts[2];
9917     SDValue Lo = N0.getOperand(0);
9918     SDValue Hi = N0.getOperand(1);
9919     EVT EltVT = Lo.getValueType();
9920 
9921     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9922       for (unsigned I = 0; I != 2; ++I) {
9923         SDValue Op = N0.getOperand(I);
9924         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9925           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9926                                               CFP->getValueAPF());
9927         } else if (Op.isUndef()) {
9928           // Handled below based on what the other operand is.
9929           NewElts[I] = Op;
9930         } else {
9931           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9932         }
9933       }
9934 
9935       // If one half is undef, and one is constant, perfer a splat vector rather
9936       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9937       // cheaper to use and may be free with a packed operation.
9938       if (NewElts[0].isUndef()) {
9939         if (isa<ConstantFPSDNode>(NewElts[1]))
9940           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9941             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9942       }
9943 
9944       if (NewElts[1].isUndef()) {
9945         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9946           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9947       }
9948 
9949       return DAG.getBuildVector(VT, SL, NewElts);
9950     }
9951   }
9952 
9953   unsigned SrcOpc = N0.getOpcode();
9954 
9955   // If it's free to do so, push canonicalizes further up the source, which may
9956   // find a canonical source.
9957   //
9958   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9959   // sNaNs.
9960   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9961     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9962     if (CRHS && N0.hasOneUse()) {
9963       SDLoc SL(N);
9964       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9965                                    N0.getOperand(0));
9966       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9967       DCI.AddToWorklist(Canon0.getNode());
9968 
9969       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9970     }
9971   }
9972 
9973   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9974 }
9975 
9976 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9977   switch (Opc) {
9978   case ISD::FMAXNUM:
9979   case ISD::FMAXNUM_IEEE:
9980     return AMDGPUISD::FMAX3;
9981   case ISD::SMAX:
9982     return AMDGPUISD::SMAX3;
9983   case ISD::UMAX:
9984     return AMDGPUISD::UMAX3;
9985   case ISD::FMINNUM:
9986   case ISD::FMINNUM_IEEE:
9987     return AMDGPUISD::FMIN3;
9988   case ISD::SMIN:
9989     return AMDGPUISD::SMIN3;
9990   case ISD::UMIN:
9991     return AMDGPUISD::UMIN3;
9992   default:
9993     llvm_unreachable("Not a min/max opcode");
9994   }
9995 }
9996 
9997 SDValue SITargetLowering::performIntMed3ImmCombine(
9998   SelectionDAG &DAG, const SDLoc &SL,
9999   SDValue Op0, SDValue Op1, bool Signed) const {
10000   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
10001   if (!K1)
10002     return SDValue();
10003 
10004   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
10005   if (!K0)
10006     return SDValue();
10007 
10008   if (Signed) {
10009     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
10010       return SDValue();
10011   } else {
10012     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
10013       return SDValue();
10014   }
10015 
10016   EVT VT = K0->getValueType(0);
10017   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
10018   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
10019     return DAG.getNode(Med3Opc, SL, VT,
10020                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
10021   }
10022 
10023   // If there isn't a 16-bit med3 operation, convert to 32-bit.
10024   if (VT == MVT::i16) {
10025     MVT NVT = MVT::i32;
10026     unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
10027 
10028     SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
10029     SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
10030     SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
10031 
10032     SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
10033     return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
10034   }
10035 
10036   return SDValue();
10037 }
10038 
10039 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
10040   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
10041     return C;
10042 
10043   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
10044     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
10045       return C;
10046   }
10047 
10048   return nullptr;
10049 }
10050 
10051 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
10052                                                   const SDLoc &SL,
10053                                                   SDValue Op0,
10054                                                   SDValue Op1) const {
10055   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
10056   if (!K1)
10057     return SDValue();
10058 
10059   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
10060   if (!K0)
10061     return SDValue();
10062 
10063   // Ordered >= (although NaN inputs should have folded away by now).
10064   if (K0->getValueAPF() > K1->getValueAPF())
10065     return SDValue();
10066 
10067   const MachineFunction &MF = DAG.getMachineFunction();
10068   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10069 
10070   // TODO: Check IEEE bit enabled?
10071   EVT VT = Op0.getValueType();
10072   if (Info->getMode().DX10Clamp) {
10073     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
10074     // hardware fmed3 behavior converting to a min.
10075     // FIXME: Should this be allowing -0.0?
10076     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
10077       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
10078   }
10079 
10080   // med3 for f16 is only available on gfx9+, and not available for v2f16.
10081   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
10082     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
10083     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
10084     // then give the other result, which is different from med3 with a NaN
10085     // input.
10086     SDValue Var = Op0.getOperand(0);
10087     if (!DAG.isKnownNeverSNaN(Var))
10088       return SDValue();
10089 
10090     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10091 
10092     if ((!K0->hasOneUse() ||
10093          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
10094         (!K1->hasOneUse() ||
10095          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
10096       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
10097                          Var, SDValue(K0, 0), SDValue(K1, 0));
10098     }
10099   }
10100 
10101   return SDValue();
10102 }
10103 
10104 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
10105                                                DAGCombinerInfo &DCI) const {
10106   SelectionDAG &DAG = DCI.DAG;
10107 
10108   EVT VT = N->getValueType(0);
10109   unsigned Opc = N->getOpcode();
10110   SDValue Op0 = N->getOperand(0);
10111   SDValue Op1 = N->getOperand(1);
10112 
10113   // Only do this if the inner op has one use since this will just increases
10114   // register pressure for no benefit.
10115 
10116   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
10117       !VT.isVector() &&
10118       (VT == MVT::i32 || VT == MVT::f32 ||
10119        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
10120     // max(max(a, b), c) -> max3(a, b, c)
10121     // min(min(a, b), c) -> min3(a, b, c)
10122     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
10123       SDLoc DL(N);
10124       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10125                          DL,
10126                          N->getValueType(0),
10127                          Op0.getOperand(0),
10128                          Op0.getOperand(1),
10129                          Op1);
10130     }
10131 
10132     // Try commuted.
10133     // max(a, max(b, c)) -> max3(a, b, c)
10134     // min(a, min(b, c)) -> min3(a, b, c)
10135     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
10136       SDLoc DL(N);
10137       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10138                          DL,
10139                          N->getValueType(0),
10140                          Op0,
10141                          Op1.getOperand(0),
10142                          Op1.getOperand(1));
10143     }
10144   }
10145 
10146   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
10147   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
10148     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
10149       return Med3;
10150   }
10151 
10152   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
10153     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
10154       return Med3;
10155   }
10156 
10157   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
10158   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
10159        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
10160        (Opc == AMDGPUISD::FMIN_LEGACY &&
10161         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
10162       (VT == MVT::f32 || VT == MVT::f64 ||
10163        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
10164        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
10165       Op0.hasOneUse()) {
10166     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
10167       return Res;
10168   }
10169 
10170   return SDValue();
10171 }
10172 
10173 static bool isClampZeroToOne(SDValue A, SDValue B) {
10174   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
10175     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
10176       // FIXME: Should this be allowing -0.0?
10177       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
10178              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
10179     }
10180   }
10181 
10182   return false;
10183 }
10184 
10185 // FIXME: Should only worry about snans for version with chain.
10186 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
10187                                               DAGCombinerInfo &DCI) const {
10188   EVT VT = N->getValueType(0);
10189   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
10190   // NaNs. With a NaN input, the order of the operands may change the result.
10191 
10192   SelectionDAG &DAG = DCI.DAG;
10193   SDLoc SL(N);
10194 
10195   SDValue Src0 = N->getOperand(0);
10196   SDValue Src1 = N->getOperand(1);
10197   SDValue Src2 = N->getOperand(2);
10198 
10199   if (isClampZeroToOne(Src0, Src1)) {
10200     // const_a, const_b, x -> clamp is safe in all cases including signaling
10201     // nans.
10202     // FIXME: Should this be allowing -0.0?
10203     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
10204   }
10205 
10206   const MachineFunction &MF = DAG.getMachineFunction();
10207   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10208 
10209   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
10210   // handling no dx10-clamp?
10211   if (Info->getMode().DX10Clamp) {
10212     // If NaNs is clamped to 0, we are free to reorder the inputs.
10213 
10214     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10215       std::swap(Src0, Src1);
10216 
10217     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10218       std::swap(Src1, Src2);
10219 
10220     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10221       std::swap(Src0, Src1);
10222 
10223     if (isClampZeroToOne(Src1, Src2))
10224       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10225   }
10226 
10227   return SDValue();
10228 }
10229 
10230 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10231                                                  DAGCombinerInfo &DCI) const {
10232   SDValue Src0 = N->getOperand(0);
10233   SDValue Src1 = N->getOperand(1);
10234   if (Src0.isUndef() && Src1.isUndef())
10235     return DCI.DAG.getUNDEF(N->getValueType(0));
10236   return SDValue();
10237 }
10238 
10239 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10240 // expanded into a set of cmp/select instructions.
10241 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10242                                                 unsigned NumElem,
10243                                                 bool IsDivergentIdx) {
10244   if (UseDivergentRegisterIndexing)
10245     return false;
10246 
10247   unsigned VecSize = EltSize * NumElem;
10248 
10249   // Sub-dword vectors of size 2 dword or less have better implementation.
10250   if (VecSize <= 64 && EltSize < 32)
10251     return false;
10252 
10253   // Always expand the rest of sub-dword instructions, otherwise it will be
10254   // lowered via memory.
10255   if (EltSize < 32)
10256     return true;
10257 
10258   // Always do this if var-idx is divergent, otherwise it will become a loop.
10259   if (IsDivergentIdx)
10260     return true;
10261 
10262   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10263   unsigned NumInsts = NumElem /* Number of compares */ +
10264                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10265   return NumInsts <= 16;
10266 }
10267 
10268 static bool shouldExpandVectorDynExt(SDNode *N) {
10269   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10270   if (isa<ConstantSDNode>(Idx))
10271     return false;
10272 
10273   SDValue Vec = N->getOperand(0);
10274   EVT VecVT = Vec.getValueType();
10275   EVT EltVT = VecVT.getVectorElementType();
10276   unsigned EltSize = EltVT.getSizeInBits();
10277   unsigned NumElem = VecVT.getVectorNumElements();
10278 
10279   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
10280                                                     Idx->isDivergent());
10281 }
10282 
10283 SDValue SITargetLowering::performExtractVectorEltCombine(
10284   SDNode *N, DAGCombinerInfo &DCI) const {
10285   SDValue Vec = N->getOperand(0);
10286   SelectionDAG &DAG = DCI.DAG;
10287 
10288   EVT VecVT = Vec.getValueType();
10289   EVT EltVT = VecVT.getVectorElementType();
10290 
10291   if ((Vec.getOpcode() == ISD::FNEG ||
10292        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10293     SDLoc SL(N);
10294     EVT EltVT = N->getValueType(0);
10295     SDValue Idx = N->getOperand(1);
10296     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10297                               Vec.getOperand(0), Idx);
10298     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10299   }
10300 
10301   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10302   //    =>
10303   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10304   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10305   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10306   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10307     SDLoc SL(N);
10308     EVT EltVT = N->getValueType(0);
10309     SDValue Idx = N->getOperand(1);
10310     unsigned Opc = Vec.getOpcode();
10311 
10312     switch(Opc) {
10313     default:
10314       break;
10315       // TODO: Support other binary operations.
10316     case ISD::FADD:
10317     case ISD::FSUB:
10318     case ISD::FMUL:
10319     case ISD::ADD:
10320     case ISD::UMIN:
10321     case ISD::UMAX:
10322     case ISD::SMIN:
10323     case ISD::SMAX:
10324     case ISD::FMAXNUM:
10325     case ISD::FMINNUM:
10326     case ISD::FMAXNUM_IEEE:
10327     case ISD::FMINNUM_IEEE: {
10328       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10329                                  Vec.getOperand(0), Idx);
10330       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10331                                  Vec.getOperand(1), Idx);
10332 
10333       DCI.AddToWorklist(Elt0.getNode());
10334       DCI.AddToWorklist(Elt1.getNode());
10335       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10336     }
10337     }
10338   }
10339 
10340   unsigned VecSize = VecVT.getSizeInBits();
10341   unsigned EltSize = EltVT.getSizeInBits();
10342 
10343   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10344   if (::shouldExpandVectorDynExt(N)) {
10345     SDLoc SL(N);
10346     SDValue Idx = N->getOperand(1);
10347     SDValue V;
10348     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10349       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10350       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10351       if (I == 0)
10352         V = Elt;
10353       else
10354         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10355     }
10356     return V;
10357   }
10358 
10359   if (!DCI.isBeforeLegalize())
10360     return SDValue();
10361 
10362   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10363   // elements. This exposes more load reduction opportunities by replacing
10364   // multiple small extract_vector_elements with a single 32-bit extract.
10365   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10366   if (isa<MemSDNode>(Vec) &&
10367       EltSize <= 16 &&
10368       EltVT.isByteSized() &&
10369       VecSize > 32 &&
10370       VecSize % 32 == 0 &&
10371       Idx) {
10372     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10373 
10374     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10375     unsigned EltIdx = BitIndex / 32;
10376     unsigned LeftoverBitIdx = BitIndex % 32;
10377     SDLoc SL(N);
10378 
10379     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10380     DCI.AddToWorklist(Cast.getNode());
10381 
10382     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10383                               DAG.getConstant(EltIdx, SL, MVT::i32));
10384     DCI.AddToWorklist(Elt.getNode());
10385     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10386                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10387     DCI.AddToWorklist(Srl.getNode());
10388 
10389     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10390     DCI.AddToWorklist(Trunc.getNode());
10391     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10392   }
10393 
10394   return SDValue();
10395 }
10396 
10397 SDValue
10398 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10399                                                 DAGCombinerInfo &DCI) const {
10400   SDValue Vec = N->getOperand(0);
10401   SDValue Idx = N->getOperand(2);
10402   EVT VecVT = Vec.getValueType();
10403   EVT EltVT = VecVT.getVectorElementType();
10404 
10405   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10406   // => BUILD_VECTOR n x select (e, const-idx)
10407   if (!::shouldExpandVectorDynExt(N))
10408     return SDValue();
10409 
10410   SelectionDAG &DAG = DCI.DAG;
10411   SDLoc SL(N);
10412   SDValue Ins = N->getOperand(1);
10413   EVT IdxVT = Idx.getValueType();
10414 
10415   SmallVector<SDValue, 16> Ops;
10416   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10417     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10418     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10419     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10420     Ops.push_back(V);
10421   }
10422 
10423   return DAG.getBuildVector(VecVT, SL, Ops);
10424 }
10425 
10426 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10427                                           const SDNode *N0,
10428                                           const SDNode *N1) const {
10429   EVT VT = N0->getValueType(0);
10430 
10431   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10432   // support denormals ever.
10433   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10434        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10435         getSubtarget()->hasMadF16())) &&
10436        isOperationLegal(ISD::FMAD, VT))
10437     return ISD::FMAD;
10438 
10439   const TargetOptions &Options = DAG.getTarget().Options;
10440   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10441        (N0->getFlags().hasAllowContract() &&
10442         N1->getFlags().hasAllowContract())) &&
10443       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10444     return ISD::FMA;
10445   }
10446 
10447   return 0;
10448 }
10449 
10450 // For a reassociatable opcode perform:
10451 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10452 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10453                                                SelectionDAG &DAG) const {
10454   EVT VT = N->getValueType(0);
10455   if (VT != MVT::i32 && VT != MVT::i64)
10456     return SDValue();
10457 
10458   unsigned Opc = N->getOpcode();
10459   SDValue Op0 = N->getOperand(0);
10460   SDValue Op1 = N->getOperand(1);
10461 
10462   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10463     return SDValue();
10464 
10465   if (Op0->isDivergent())
10466     std::swap(Op0, Op1);
10467 
10468   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10469     return SDValue();
10470 
10471   SDValue Op2 = Op1.getOperand(1);
10472   Op1 = Op1.getOperand(0);
10473   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10474     return SDValue();
10475 
10476   if (Op1->isDivergent())
10477     std::swap(Op1, Op2);
10478 
10479   // If either operand is constant this will conflict with
10480   // DAGCombiner::ReassociateOps().
10481   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
10482       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
10483     return SDValue();
10484 
10485   SDLoc SL(N);
10486   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10487   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10488 }
10489 
10490 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10491                            EVT VT,
10492                            SDValue N0, SDValue N1, SDValue N2,
10493                            bool Signed) {
10494   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10495   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10496   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10497   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10498 }
10499 
10500 SDValue SITargetLowering::performAddCombine(SDNode *N,
10501                                             DAGCombinerInfo &DCI) const {
10502   SelectionDAG &DAG = DCI.DAG;
10503   EVT VT = N->getValueType(0);
10504   SDLoc SL(N);
10505   SDValue LHS = N->getOperand(0);
10506   SDValue RHS = N->getOperand(1);
10507 
10508   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10509       && Subtarget->hasMad64_32() &&
10510       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10511       VT.getScalarSizeInBits() <= 64) {
10512     if (LHS.getOpcode() != ISD::MUL)
10513       std::swap(LHS, RHS);
10514 
10515     SDValue MulLHS = LHS.getOperand(0);
10516     SDValue MulRHS = LHS.getOperand(1);
10517     SDValue AddRHS = RHS;
10518 
10519     // TODO: Maybe restrict if SGPR inputs.
10520     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10521         numBitsUnsigned(MulRHS, DAG) <= 32) {
10522       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10523       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10524       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10525       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10526     }
10527 
10528     if (numBitsSigned(MulLHS, DAG) <= 32 && numBitsSigned(MulRHS, DAG) <= 32) {
10529       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10530       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10531       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10532       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10533     }
10534 
10535     return SDValue();
10536   }
10537 
10538   if (SDValue V = reassociateScalarOps(N, DAG)) {
10539     return V;
10540   }
10541 
10542   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10543     return SDValue();
10544 
10545   // add x, zext (setcc) => addcarry x, 0, setcc
10546   // add x, sext (setcc) => subcarry x, 0, setcc
10547   unsigned Opc = LHS.getOpcode();
10548   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10549       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10550     std::swap(RHS, LHS);
10551 
10552   Opc = RHS.getOpcode();
10553   switch (Opc) {
10554   default: break;
10555   case ISD::ZERO_EXTEND:
10556   case ISD::SIGN_EXTEND:
10557   case ISD::ANY_EXTEND: {
10558     auto Cond = RHS.getOperand(0);
10559     // If this won't be a real VOPC output, we would still need to insert an
10560     // extra instruction anyway.
10561     if (!isBoolSGPR(Cond))
10562       break;
10563     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10564     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10565     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10566     return DAG.getNode(Opc, SL, VTList, Args);
10567   }
10568   case ISD::ADDCARRY: {
10569     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10570     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10571     if (!C || C->getZExtValue() != 0) break;
10572     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10573     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10574   }
10575   }
10576   return SDValue();
10577 }
10578 
10579 SDValue SITargetLowering::performSubCombine(SDNode *N,
10580                                             DAGCombinerInfo &DCI) const {
10581   SelectionDAG &DAG = DCI.DAG;
10582   EVT VT = N->getValueType(0);
10583 
10584   if (VT != MVT::i32)
10585     return SDValue();
10586 
10587   SDLoc SL(N);
10588   SDValue LHS = N->getOperand(0);
10589   SDValue RHS = N->getOperand(1);
10590 
10591   // sub x, zext (setcc) => subcarry x, 0, setcc
10592   // sub x, sext (setcc) => addcarry x, 0, setcc
10593   unsigned Opc = RHS.getOpcode();
10594   switch (Opc) {
10595   default: break;
10596   case ISD::ZERO_EXTEND:
10597   case ISD::SIGN_EXTEND:
10598   case ISD::ANY_EXTEND: {
10599     auto Cond = RHS.getOperand(0);
10600     // If this won't be a real VOPC output, we would still need to insert an
10601     // extra instruction anyway.
10602     if (!isBoolSGPR(Cond))
10603       break;
10604     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10605     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10606     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10607     return DAG.getNode(Opc, SL, VTList, Args);
10608   }
10609   }
10610 
10611   if (LHS.getOpcode() == ISD::SUBCARRY) {
10612     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10613     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10614     if (!C || !C->isZero())
10615       return SDValue();
10616     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10617     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10618   }
10619   return SDValue();
10620 }
10621 
10622 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10623   DAGCombinerInfo &DCI) const {
10624 
10625   if (N->getValueType(0) != MVT::i32)
10626     return SDValue();
10627 
10628   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10629   if (!C || C->getZExtValue() != 0)
10630     return SDValue();
10631 
10632   SelectionDAG &DAG = DCI.DAG;
10633   SDValue LHS = N->getOperand(0);
10634 
10635   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10636   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10637   unsigned LHSOpc = LHS.getOpcode();
10638   unsigned Opc = N->getOpcode();
10639   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10640       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10641     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10642     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10643   }
10644   return SDValue();
10645 }
10646 
10647 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10648                                              DAGCombinerInfo &DCI) const {
10649   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10650     return SDValue();
10651 
10652   SelectionDAG &DAG = DCI.DAG;
10653   EVT VT = N->getValueType(0);
10654 
10655   SDLoc SL(N);
10656   SDValue LHS = N->getOperand(0);
10657   SDValue RHS = N->getOperand(1);
10658 
10659   // These should really be instruction patterns, but writing patterns with
10660   // source modiifiers is a pain.
10661 
10662   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10663   if (LHS.getOpcode() == ISD::FADD) {
10664     SDValue A = LHS.getOperand(0);
10665     if (A == LHS.getOperand(1)) {
10666       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10667       if (FusedOp != 0) {
10668         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10669         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10670       }
10671     }
10672   }
10673 
10674   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10675   if (RHS.getOpcode() == ISD::FADD) {
10676     SDValue A = RHS.getOperand(0);
10677     if (A == RHS.getOperand(1)) {
10678       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10679       if (FusedOp != 0) {
10680         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10681         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10682       }
10683     }
10684   }
10685 
10686   return SDValue();
10687 }
10688 
10689 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10690                                              DAGCombinerInfo &DCI) const {
10691   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10692     return SDValue();
10693 
10694   SelectionDAG &DAG = DCI.DAG;
10695   SDLoc SL(N);
10696   EVT VT = N->getValueType(0);
10697   assert(!VT.isVector());
10698 
10699   // Try to get the fneg to fold into the source modifier. This undoes generic
10700   // DAG combines and folds them into the mad.
10701   //
10702   // Only do this if we are not trying to support denormals. v_mad_f32 does
10703   // not support denormals ever.
10704   SDValue LHS = N->getOperand(0);
10705   SDValue RHS = N->getOperand(1);
10706   if (LHS.getOpcode() == ISD::FADD) {
10707     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10708     SDValue A = LHS.getOperand(0);
10709     if (A == LHS.getOperand(1)) {
10710       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10711       if (FusedOp != 0){
10712         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10713         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10714 
10715         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10716       }
10717     }
10718   }
10719 
10720   if (RHS.getOpcode() == ISD::FADD) {
10721     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10722 
10723     SDValue A = RHS.getOperand(0);
10724     if (A == RHS.getOperand(1)) {
10725       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10726       if (FusedOp != 0){
10727         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10728         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10729       }
10730     }
10731   }
10732 
10733   return SDValue();
10734 }
10735 
10736 SDValue SITargetLowering::performFMACombine(SDNode *N,
10737                                             DAGCombinerInfo &DCI) const {
10738   SelectionDAG &DAG = DCI.DAG;
10739   EVT VT = N->getValueType(0);
10740   SDLoc SL(N);
10741 
10742   if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
10743     return SDValue();
10744 
10745   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10746   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10747   SDValue Op1 = N->getOperand(0);
10748   SDValue Op2 = N->getOperand(1);
10749   SDValue FMA = N->getOperand(2);
10750 
10751   if (FMA.getOpcode() != ISD::FMA ||
10752       Op1.getOpcode() != ISD::FP_EXTEND ||
10753       Op2.getOpcode() != ISD::FP_EXTEND)
10754     return SDValue();
10755 
10756   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10757   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10758   // is sufficient to allow generaing fdot2.
10759   const TargetOptions &Options = DAG.getTarget().Options;
10760   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10761       (N->getFlags().hasAllowContract() &&
10762        FMA->getFlags().hasAllowContract())) {
10763     Op1 = Op1.getOperand(0);
10764     Op2 = Op2.getOperand(0);
10765     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10766         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10767       return SDValue();
10768 
10769     SDValue Vec1 = Op1.getOperand(0);
10770     SDValue Idx1 = Op1.getOperand(1);
10771     SDValue Vec2 = Op2.getOperand(0);
10772 
10773     SDValue FMAOp1 = FMA.getOperand(0);
10774     SDValue FMAOp2 = FMA.getOperand(1);
10775     SDValue FMAAcc = FMA.getOperand(2);
10776 
10777     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10778         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10779       return SDValue();
10780 
10781     FMAOp1 = FMAOp1.getOperand(0);
10782     FMAOp2 = FMAOp2.getOperand(0);
10783     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10784         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10785       return SDValue();
10786 
10787     SDValue Vec3 = FMAOp1.getOperand(0);
10788     SDValue Vec4 = FMAOp2.getOperand(0);
10789     SDValue Idx2 = FMAOp1.getOperand(1);
10790 
10791     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10792         // Idx1 and Idx2 cannot be the same.
10793         Idx1 == Idx2)
10794       return SDValue();
10795 
10796     if (Vec1 == Vec2 || Vec3 == Vec4)
10797       return SDValue();
10798 
10799     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10800       return SDValue();
10801 
10802     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10803         (Vec1 == Vec4 && Vec2 == Vec3)) {
10804       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10805                          DAG.getTargetConstant(0, SL, MVT::i1));
10806     }
10807   }
10808   return SDValue();
10809 }
10810 
10811 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10812                                               DAGCombinerInfo &DCI) const {
10813   SelectionDAG &DAG = DCI.DAG;
10814   SDLoc SL(N);
10815 
10816   SDValue LHS = N->getOperand(0);
10817   SDValue RHS = N->getOperand(1);
10818   EVT VT = LHS.getValueType();
10819   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10820 
10821   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10822   if (!CRHS) {
10823     CRHS = dyn_cast<ConstantSDNode>(LHS);
10824     if (CRHS) {
10825       std::swap(LHS, RHS);
10826       CC = getSetCCSwappedOperands(CC);
10827     }
10828   }
10829 
10830   if (CRHS) {
10831     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10832         isBoolSGPR(LHS.getOperand(0))) {
10833       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10834       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10835       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10836       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10837       if ((CRHS->isAllOnes() &&
10838            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10839           (CRHS->isZero() &&
10840            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10841         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10842                            DAG.getConstant(-1, SL, MVT::i1));
10843       if ((CRHS->isAllOnes() &&
10844            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10845           (CRHS->isZero() &&
10846            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10847         return LHS.getOperand(0);
10848     }
10849 
10850     const APInt &CRHSVal = CRHS->getAPIntValue();
10851     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10852         LHS.getOpcode() == ISD::SELECT &&
10853         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10854         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10855         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10856         isBoolSGPR(LHS.getOperand(0))) {
10857       // Given CT != FT:
10858       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10859       // setcc (select cc, CT, CF), CF, ne => cc
10860       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10861       // setcc (select cc, CT, CF), CT, eq => cc
10862       const APInt &CT = LHS.getConstantOperandAPInt(1);
10863       const APInt &CF = LHS.getConstantOperandAPInt(2);
10864 
10865       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10866           (CT == CRHSVal && CC == ISD::SETNE))
10867         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10868                            DAG.getConstant(-1, SL, MVT::i1));
10869       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10870           (CT == CRHSVal && CC == ISD::SETEQ))
10871         return LHS.getOperand(0);
10872     }
10873   }
10874 
10875   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10876                                            VT != MVT::f16))
10877     return SDValue();
10878 
10879   // Match isinf/isfinite pattern
10880   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10881   // (fcmp one (fabs x), inf) -> (fp_class x,
10882   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10883   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10884     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10885     if (!CRHS)
10886       return SDValue();
10887 
10888     const APFloat &APF = CRHS->getValueAPF();
10889     if (APF.isInfinity() && !APF.isNegative()) {
10890       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10891                                  SIInstrFlags::N_INFINITY;
10892       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10893                                     SIInstrFlags::P_ZERO |
10894                                     SIInstrFlags::N_NORMAL |
10895                                     SIInstrFlags::P_NORMAL |
10896                                     SIInstrFlags::N_SUBNORMAL |
10897                                     SIInstrFlags::P_SUBNORMAL;
10898       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10899       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10900                          DAG.getConstant(Mask, SL, MVT::i32));
10901     }
10902   }
10903 
10904   return SDValue();
10905 }
10906 
10907 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10908                                                      DAGCombinerInfo &DCI) const {
10909   SelectionDAG &DAG = DCI.DAG;
10910   SDLoc SL(N);
10911   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10912 
10913   SDValue Src = N->getOperand(0);
10914   SDValue Shift = N->getOperand(0);
10915 
10916   // TODO: Extend type shouldn't matter (assuming legal types).
10917   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10918     Shift = Shift.getOperand(0);
10919 
10920   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10921     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10922     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10923     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10924     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10925     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10926     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10927       SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0),
10928                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10929 
10930       unsigned ShiftOffset = 8 * Offset;
10931       if (Shift.getOpcode() == ISD::SHL)
10932         ShiftOffset -= C->getZExtValue();
10933       else
10934         ShiftOffset += C->getZExtValue();
10935 
10936       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10937         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10938                            MVT::f32, Shifted);
10939       }
10940     }
10941   }
10942 
10943   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10944   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10945   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10946     // We simplified Src. If this node is not dead, visit it again so it is
10947     // folded properly.
10948     if (N->getOpcode() != ISD::DELETED_NODE)
10949       DCI.AddToWorklist(N);
10950     return SDValue(N, 0);
10951   }
10952 
10953   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10954   if (SDValue DemandedSrc =
10955           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10956     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10957 
10958   return SDValue();
10959 }
10960 
10961 SDValue SITargetLowering::performClampCombine(SDNode *N,
10962                                               DAGCombinerInfo &DCI) const {
10963   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10964   if (!CSrc)
10965     return SDValue();
10966 
10967   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10968   const APFloat &F = CSrc->getValueAPF();
10969   APFloat Zero = APFloat::getZero(F.getSemantics());
10970   if (F < Zero ||
10971       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10972     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10973   }
10974 
10975   APFloat One(F.getSemantics(), "1.0");
10976   if (F > One)
10977     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10978 
10979   return SDValue(CSrc, 0);
10980 }
10981 
10982 
10983 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10984                                             DAGCombinerInfo &DCI) const {
10985   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10986     return SDValue();
10987   switch (N->getOpcode()) {
10988   case ISD::ADD:
10989     return performAddCombine(N, DCI);
10990   case ISD::SUB:
10991     return performSubCombine(N, DCI);
10992   case ISD::ADDCARRY:
10993   case ISD::SUBCARRY:
10994     return performAddCarrySubCarryCombine(N, DCI);
10995   case ISD::FADD:
10996     return performFAddCombine(N, DCI);
10997   case ISD::FSUB:
10998     return performFSubCombine(N, DCI);
10999   case ISD::SETCC:
11000     return performSetCCCombine(N, DCI);
11001   case ISD::FMAXNUM:
11002   case ISD::FMINNUM:
11003   case ISD::FMAXNUM_IEEE:
11004   case ISD::FMINNUM_IEEE:
11005   case ISD::SMAX:
11006   case ISD::SMIN:
11007   case ISD::UMAX:
11008   case ISD::UMIN:
11009   case AMDGPUISD::FMIN_LEGACY:
11010   case AMDGPUISD::FMAX_LEGACY:
11011     return performMinMaxCombine(N, DCI);
11012   case ISD::FMA:
11013     return performFMACombine(N, DCI);
11014   case ISD::AND:
11015     return performAndCombine(N, DCI);
11016   case ISD::OR:
11017     return performOrCombine(N, DCI);
11018   case ISD::XOR:
11019     return performXorCombine(N, DCI);
11020   case ISD::ZERO_EXTEND:
11021     return performZeroExtendCombine(N, DCI);
11022   case ISD::SIGN_EXTEND_INREG:
11023     return performSignExtendInRegCombine(N , DCI);
11024   case AMDGPUISD::FP_CLASS:
11025     return performClassCombine(N, DCI);
11026   case ISD::FCANONICALIZE:
11027     return performFCanonicalizeCombine(N, DCI);
11028   case AMDGPUISD::RCP:
11029     return performRcpCombine(N, DCI);
11030   case AMDGPUISD::FRACT:
11031   case AMDGPUISD::RSQ:
11032   case AMDGPUISD::RCP_LEGACY:
11033   case AMDGPUISD::RCP_IFLAG:
11034   case AMDGPUISD::RSQ_CLAMP:
11035   case AMDGPUISD::LDEXP: {
11036     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
11037     SDValue Src = N->getOperand(0);
11038     if (Src.isUndef())
11039       return Src;
11040     break;
11041   }
11042   case ISD::SINT_TO_FP:
11043   case ISD::UINT_TO_FP:
11044     return performUCharToFloatCombine(N, DCI);
11045   case AMDGPUISD::CVT_F32_UBYTE0:
11046   case AMDGPUISD::CVT_F32_UBYTE1:
11047   case AMDGPUISD::CVT_F32_UBYTE2:
11048   case AMDGPUISD::CVT_F32_UBYTE3:
11049     return performCvtF32UByteNCombine(N, DCI);
11050   case AMDGPUISD::FMED3:
11051     return performFMed3Combine(N, DCI);
11052   case AMDGPUISD::CVT_PKRTZ_F16_F32:
11053     return performCvtPkRTZCombine(N, DCI);
11054   case AMDGPUISD::CLAMP:
11055     return performClampCombine(N, DCI);
11056   case ISD::SCALAR_TO_VECTOR: {
11057     SelectionDAG &DAG = DCI.DAG;
11058     EVT VT = N->getValueType(0);
11059 
11060     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
11061     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
11062       SDLoc SL(N);
11063       SDValue Src = N->getOperand(0);
11064       EVT EltVT = Src.getValueType();
11065       if (EltVT == MVT::f16)
11066         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
11067 
11068       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
11069       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
11070     }
11071 
11072     break;
11073   }
11074   case ISD::EXTRACT_VECTOR_ELT:
11075     return performExtractVectorEltCombine(N, DCI);
11076   case ISD::INSERT_VECTOR_ELT:
11077     return performInsertVectorEltCombine(N, DCI);
11078   case ISD::LOAD: {
11079     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
11080       return Widended;
11081     LLVM_FALLTHROUGH;
11082   }
11083   default: {
11084     if (!DCI.isBeforeLegalize()) {
11085       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
11086         return performMemSDNodeCombine(MemNode, DCI);
11087     }
11088 
11089     break;
11090   }
11091   }
11092 
11093   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
11094 }
11095 
11096 /// Helper function for adjustWritemask
11097 static unsigned SubIdx2Lane(unsigned Idx) {
11098   switch (Idx) {
11099   default: return ~0u;
11100   case AMDGPU::sub0: return 0;
11101   case AMDGPU::sub1: return 1;
11102   case AMDGPU::sub2: return 2;
11103   case AMDGPU::sub3: return 3;
11104   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
11105   }
11106 }
11107 
11108 /// Adjust the writemask of MIMG instructions
11109 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
11110                                           SelectionDAG &DAG) const {
11111   unsigned Opcode = Node->getMachineOpcode();
11112 
11113   // Subtract 1 because the vdata output is not a MachineSDNode operand.
11114   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
11115   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
11116     return Node; // not implemented for D16
11117 
11118   SDNode *Users[5] = { nullptr };
11119   unsigned Lane = 0;
11120   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
11121   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
11122   unsigned NewDmask = 0;
11123   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
11124   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
11125   bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
11126                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
11127   unsigned TFCLane = 0;
11128   bool HasChain = Node->getNumValues() > 1;
11129 
11130   if (OldDmask == 0) {
11131     // These are folded out, but on the chance it happens don't assert.
11132     return Node;
11133   }
11134 
11135   unsigned OldBitsSet = countPopulation(OldDmask);
11136   // Work out which is the TFE/LWE lane if that is enabled.
11137   if (UsesTFC) {
11138     TFCLane = OldBitsSet;
11139   }
11140 
11141   // Try to figure out the used register components
11142   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
11143        I != E; ++I) {
11144 
11145     // Don't look at users of the chain.
11146     if (I.getUse().getResNo() != 0)
11147       continue;
11148 
11149     // Abort if we can't understand the usage
11150     if (!I->isMachineOpcode() ||
11151         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
11152       return Node;
11153 
11154     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
11155     // Note that subregs are packed, i.e. Lane==0 is the first bit set
11156     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
11157     // set, etc.
11158     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
11159     if (Lane == ~0u)
11160       return Node;
11161 
11162     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
11163     if (UsesTFC && Lane == TFCLane) {
11164       Users[Lane] = *I;
11165     } else {
11166       // Set which texture component corresponds to the lane.
11167       unsigned Comp;
11168       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
11169         Comp = countTrailingZeros(Dmask);
11170         Dmask &= ~(1 << Comp);
11171       }
11172 
11173       // Abort if we have more than one user per component.
11174       if (Users[Lane])
11175         return Node;
11176 
11177       Users[Lane] = *I;
11178       NewDmask |= 1 << Comp;
11179     }
11180   }
11181 
11182   // Don't allow 0 dmask, as hardware assumes one channel enabled.
11183   bool NoChannels = !NewDmask;
11184   if (NoChannels) {
11185     if (!UsesTFC) {
11186       // No uses of the result and not using TFC. Then do nothing.
11187       return Node;
11188     }
11189     // If the original dmask has one channel - then nothing to do
11190     if (OldBitsSet == 1)
11191       return Node;
11192     // Use an arbitrary dmask - required for the instruction to work
11193     NewDmask = 1;
11194   }
11195   // Abort if there's no change
11196   if (NewDmask == OldDmask)
11197     return Node;
11198 
11199   unsigned BitsSet = countPopulation(NewDmask);
11200 
11201   // Check for TFE or LWE - increase the number of channels by one to account
11202   // for the extra return value
11203   // This will need adjustment for D16 if this is also included in
11204   // adjustWriteMask (this function) but at present D16 are excluded.
11205   unsigned NewChannels = BitsSet + UsesTFC;
11206 
11207   int NewOpcode =
11208       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
11209   assert(NewOpcode != -1 &&
11210          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
11211          "failed to find equivalent MIMG op");
11212 
11213   // Adjust the writemask in the node
11214   SmallVector<SDValue, 12> Ops;
11215   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
11216   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
11217   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11218 
11219   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11220 
11221   MVT ResultVT = NewChannels == 1 ?
11222     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11223                            NewChannels == 5 ? 8 : NewChannels);
11224   SDVTList NewVTList = HasChain ?
11225     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11226 
11227 
11228   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11229                                               NewVTList, Ops);
11230 
11231   if (HasChain) {
11232     // Update chain.
11233     DAG.setNodeMemRefs(NewNode, Node->memoperands());
11234     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11235   }
11236 
11237   if (NewChannels == 1) {
11238     assert(Node->hasNUsesOfValue(1, 0));
11239     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11240                                       SDLoc(Node), Users[Lane]->getValueType(0),
11241                                       SDValue(NewNode, 0));
11242     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11243     return nullptr;
11244   }
11245 
11246   // Update the users of the node with the new indices
11247   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11248     SDNode *User = Users[i];
11249     if (!User) {
11250       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11251       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11252       if (i || !NoChannels)
11253         continue;
11254     } else {
11255       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11256       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11257     }
11258 
11259     switch (Idx) {
11260     default: break;
11261     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11262     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11263     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11264     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11265     }
11266   }
11267 
11268   DAG.RemoveDeadNode(Node);
11269   return nullptr;
11270 }
11271 
11272 static bool isFrameIndexOp(SDValue Op) {
11273   if (Op.getOpcode() == ISD::AssertZext)
11274     Op = Op.getOperand(0);
11275 
11276   return isa<FrameIndexSDNode>(Op);
11277 }
11278 
11279 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11280 /// with frame index operands.
11281 /// LLVM assumes that inputs are to these instructions are registers.
11282 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11283                                                         SelectionDAG &DAG) const {
11284   if (Node->getOpcode() == ISD::CopyToReg) {
11285     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11286     SDValue SrcVal = Node->getOperand(2);
11287 
11288     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11289     // to try understanding copies to physical registers.
11290     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11291       SDLoc SL(Node);
11292       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11293       SDValue VReg = DAG.getRegister(
11294         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11295 
11296       SDNode *Glued = Node->getGluedNode();
11297       SDValue ToVReg
11298         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11299                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11300       SDValue ToResultReg
11301         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11302                            VReg, ToVReg.getValue(1));
11303       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11304       DAG.RemoveDeadNode(Node);
11305       return ToResultReg.getNode();
11306     }
11307   }
11308 
11309   SmallVector<SDValue, 8> Ops;
11310   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11311     if (!isFrameIndexOp(Node->getOperand(i))) {
11312       Ops.push_back(Node->getOperand(i));
11313       continue;
11314     }
11315 
11316     SDLoc DL(Node);
11317     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11318                                      Node->getOperand(i).getValueType(),
11319                                      Node->getOperand(i)), 0));
11320   }
11321 
11322   return DAG.UpdateNodeOperands(Node, Ops);
11323 }
11324 
11325 /// Fold the instructions after selecting them.
11326 /// Returns null if users were already updated.
11327 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11328                                           SelectionDAG &DAG) const {
11329   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11330   unsigned Opcode = Node->getMachineOpcode();
11331 
11332   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11333       !TII->isGather4(Opcode) &&
11334       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11335     return adjustWritemask(Node, DAG);
11336   }
11337 
11338   if (Opcode == AMDGPU::INSERT_SUBREG ||
11339       Opcode == AMDGPU::REG_SEQUENCE) {
11340     legalizeTargetIndependentNode(Node, DAG);
11341     return Node;
11342   }
11343 
11344   switch (Opcode) {
11345   case AMDGPU::V_DIV_SCALE_F32_e64:
11346   case AMDGPU::V_DIV_SCALE_F64_e64: {
11347     // Satisfy the operand register constraint when one of the inputs is
11348     // undefined. Ordinarily each undef value will have its own implicit_def of
11349     // a vreg, so force these to use a single register.
11350     SDValue Src0 = Node->getOperand(1);
11351     SDValue Src1 = Node->getOperand(3);
11352     SDValue Src2 = Node->getOperand(5);
11353 
11354     if ((Src0.isMachineOpcode() &&
11355          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11356         (Src0 == Src1 || Src0 == Src2))
11357       break;
11358 
11359     MVT VT = Src0.getValueType().getSimpleVT();
11360     const TargetRegisterClass *RC =
11361         getRegClassFor(VT, Src0.getNode()->isDivergent());
11362 
11363     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11364     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11365 
11366     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11367                                       UndefReg, Src0, SDValue());
11368 
11369     // src0 must be the same register as src1 or src2, even if the value is
11370     // undefined, so make sure we don't violate this constraint.
11371     if (Src0.isMachineOpcode() &&
11372         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11373       if (Src1.isMachineOpcode() &&
11374           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11375         Src0 = Src1;
11376       else if (Src2.isMachineOpcode() &&
11377                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11378         Src0 = Src2;
11379       else {
11380         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11381         Src0 = UndefReg;
11382         Src1 = UndefReg;
11383       }
11384     } else
11385       break;
11386 
11387     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11388     Ops[1] = Src0;
11389     Ops[3] = Src1;
11390     Ops[5] = Src2;
11391     Ops.push_back(ImpDef.getValue(1));
11392     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11393   }
11394   default:
11395     break;
11396   }
11397 
11398   return Node;
11399 }
11400 
11401 // Any MIMG instructions that use tfe or lwe require an initialization of the
11402 // result register that will be written in the case of a memory access failure.
11403 // The required code is also added to tie this init code to the result of the
11404 // img instruction.
11405 void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
11406   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11407   const SIRegisterInfo &TRI = TII->getRegisterInfo();
11408   MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11409   MachineBasicBlock &MBB = *MI.getParent();
11410 
11411   MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
11412   MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
11413   MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
11414 
11415   if (!TFE && !LWE) // intersect_ray
11416     return;
11417 
11418   unsigned TFEVal = TFE ? TFE->getImm() : 0;
11419   unsigned LWEVal = LWE->getImm();
11420   unsigned D16Val = D16 ? D16->getImm() : 0;
11421 
11422   if (!TFEVal && !LWEVal)
11423     return;
11424 
11425   // At least one of TFE or LWE are non-zero
11426   // We have to insert a suitable initialization of the result value and
11427   // tie this to the dest of the image instruction.
11428 
11429   const DebugLoc &DL = MI.getDebugLoc();
11430 
11431   int DstIdx =
11432       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
11433 
11434   // Calculate which dword we have to initialize to 0.
11435   MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
11436 
11437   // check that dmask operand is found.
11438   assert(MO_Dmask && "Expected dmask operand in instruction");
11439 
11440   unsigned dmask = MO_Dmask->getImm();
11441   // Determine the number of active lanes taking into account the
11442   // Gather4 special case
11443   unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask);
11444 
11445   bool Packed = !Subtarget->hasUnpackedD16VMem();
11446 
11447   unsigned InitIdx =
11448       D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
11449 
11450   // Abandon attempt if the dst size isn't large enough
11451   // - this is in fact an error but this is picked up elsewhere and
11452   // reported correctly.
11453   uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
11454   if (DstSize < InitIdx)
11455     return;
11456 
11457   // Create a register for the intialization value.
11458   Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11459   unsigned NewDst = 0; // Final initialized value will be in here
11460 
11461   // If PRTStrictNull feature is enabled (the default) then initialize
11462   // all the result registers to 0, otherwise just the error indication
11463   // register (VGPRn+1)
11464   unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
11465   unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
11466 
11467   BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
11468   for (; SizeLeft; SizeLeft--, CurrIdx++) {
11469     NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11470     // Initialize dword
11471     Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
11472     BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
11473       .addImm(0);
11474     // Insert into the super-reg
11475     BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
11476       .addReg(PrevDst)
11477       .addReg(SubReg)
11478       .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
11479 
11480     PrevDst = NewDst;
11481   }
11482 
11483   // Add as an implicit operand
11484   MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
11485 
11486   // Tie the just added implicit operand to the dst
11487   MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
11488 }
11489 
11490 /// Assign the register class depending on the number of
11491 /// bits set in the writemask
11492 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11493                                                      SDNode *Node) const {
11494   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11495 
11496   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11497 
11498   if (TII->isVOP3(MI.getOpcode())) {
11499     // Make sure constant bus requirements are respected.
11500     TII->legalizeOperandsVOP3(MRI, MI);
11501 
11502     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11503     // This saves a chain-copy of registers and better ballance register
11504     // use between vgpr and agpr as agpr tuples tend to be big.
11505     if (MI.getDesc().OpInfo) {
11506       unsigned Opc = MI.getOpcode();
11507       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11508       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11509                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11510         if (I == -1)
11511           break;
11512         MachineOperand &Op = MI.getOperand(I);
11513         if (!Op.isReg() || !Op.getReg().isVirtual())
11514           continue;
11515         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11516         if (!TRI->hasAGPRs(RC))
11517           continue;
11518         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11519         if (!Src || !Src->isCopy() ||
11520             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11521           continue;
11522         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11523         // All uses of agpr64 and agpr32 can also accept vgpr except for
11524         // v_accvgpr_read, but we do not produce agpr reads during selection,
11525         // so no use checks are needed.
11526         MRI.setRegClass(Op.getReg(), NewRC);
11527       }
11528     }
11529 
11530     return;
11531   }
11532 
11533   // Replace unused atomics with the no return version.
11534   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11535   if (NoRetAtomicOp != -1) {
11536     if (!Node->hasAnyUseOfValue(0)) {
11537       int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
11538                                                AMDGPU::OpName::cpol);
11539       if (CPolIdx != -1) {
11540         MachineOperand &CPol = MI.getOperand(CPolIdx);
11541         CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC);
11542       }
11543       MI.RemoveOperand(0);
11544       MI.setDesc(TII->get(NoRetAtomicOp));
11545       return;
11546     }
11547 
11548     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11549     // instruction, because the return type of these instructions is a vec2 of
11550     // the memory type, so it can be tied to the input operand.
11551     // This means these instructions always have a use, so we need to add a
11552     // special case to check if the atomic has only one extract_subreg use,
11553     // which itself has no uses.
11554     if ((Node->hasNUsesOfValue(1, 0) &&
11555          Node->use_begin()->isMachineOpcode() &&
11556          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11557          !Node->use_begin()->hasAnyUseOfValue(0))) {
11558       Register Def = MI.getOperand(0).getReg();
11559 
11560       // Change this into a noret atomic.
11561       MI.setDesc(TII->get(NoRetAtomicOp));
11562       MI.RemoveOperand(0);
11563 
11564       // If we only remove the def operand from the atomic instruction, the
11565       // extract_subreg will be left with a use of a vreg without a def.
11566       // So we need to insert an implicit_def to avoid machine verifier
11567       // errors.
11568       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11569               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11570     }
11571     return;
11572   }
11573 
11574   if (TII->isMIMG(MI) && !MI.mayStore())
11575     AddIMGInit(MI);
11576 }
11577 
11578 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11579                               uint64_t Val) {
11580   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11581   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11582 }
11583 
11584 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11585                                                 const SDLoc &DL,
11586                                                 SDValue Ptr) const {
11587   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11588 
11589   // Build the half of the subregister with the constants before building the
11590   // full 128-bit register. If we are building multiple resource descriptors,
11591   // this will allow CSEing of the 2-component register.
11592   const SDValue Ops0[] = {
11593     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11594     buildSMovImm32(DAG, DL, 0),
11595     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11596     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11597     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11598   };
11599 
11600   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11601                                                 MVT::v2i32, Ops0), 0);
11602 
11603   // Combine the constants and the pointer.
11604   const SDValue Ops1[] = {
11605     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11606     Ptr,
11607     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11608     SubRegHi,
11609     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11610   };
11611 
11612   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11613 }
11614 
11615 /// Return a resource descriptor with the 'Add TID' bit enabled
11616 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11617 ///        of the resource descriptor) to create an offset, which is added to
11618 ///        the resource pointer.
11619 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11620                                            SDValue Ptr, uint32_t RsrcDword1,
11621                                            uint64_t RsrcDword2And3) const {
11622   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11623   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11624   if (RsrcDword1) {
11625     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11626                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11627                     0);
11628   }
11629 
11630   SDValue DataLo = buildSMovImm32(DAG, DL,
11631                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11632   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11633 
11634   const SDValue Ops[] = {
11635     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11636     PtrLo,
11637     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11638     PtrHi,
11639     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11640     DataLo,
11641     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11642     DataHi,
11643     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11644   };
11645 
11646   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11647 }
11648 
11649 //===----------------------------------------------------------------------===//
11650 //                         SI Inline Assembly Support
11651 //===----------------------------------------------------------------------===//
11652 
11653 std::pair<unsigned, const TargetRegisterClass *>
11654 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
11655                                                StringRef Constraint,
11656                                                MVT VT) const {
11657   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
11658 
11659   const TargetRegisterClass *RC = nullptr;
11660   if (Constraint.size() == 1) {
11661     const unsigned BitWidth = VT.getSizeInBits();
11662     switch (Constraint[0]) {
11663     default:
11664       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11665     case 's':
11666     case 'r':
11667       switch (BitWidth) {
11668       case 16:
11669         RC = &AMDGPU::SReg_32RegClass;
11670         break;
11671       case 64:
11672         RC = &AMDGPU::SGPR_64RegClass;
11673         break;
11674       default:
11675         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11676         if (!RC)
11677           return std::make_pair(0U, nullptr);
11678         break;
11679       }
11680       break;
11681     case 'v':
11682       switch (BitWidth) {
11683       case 16:
11684         RC = &AMDGPU::VGPR_32RegClass;
11685         break;
11686       default:
11687         RC = TRI->getVGPRClassForBitWidth(BitWidth);
11688         if (!RC)
11689           return std::make_pair(0U, nullptr);
11690         break;
11691       }
11692       break;
11693     case 'a':
11694       if (!Subtarget->hasMAIInsts())
11695         break;
11696       switch (BitWidth) {
11697       case 16:
11698         RC = &AMDGPU::AGPR_32RegClass;
11699         break;
11700       default:
11701         RC = TRI->getAGPRClassForBitWidth(BitWidth);
11702         if (!RC)
11703           return std::make_pair(0U, nullptr);
11704         break;
11705       }
11706       break;
11707     }
11708     // We actually support i128, i16 and f16 as inline parameters
11709     // even if they are not reported as legal
11710     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11711                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11712       return std::make_pair(0U, RC);
11713   }
11714 
11715   if (Constraint.size() > 1) {
11716     if (Constraint[1] == 'v') {
11717       RC = &AMDGPU::VGPR_32RegClass;
11718     } else if (Constraint[1] == 's') {
11719       RC = &AMDGPU::SGPR_32RegClass;
11720     } else if (Constraint[1] == 'a') {
11721       RC = &AMDGPU::AGPR_32RegClass;
11722     }
11723 
11724     if (RC) {
11725       uint32_t Idx;
11726       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
11727       if (!Failed && Idx < RC->getNumRegs())
11728         return std::make_pair(RC->getRegister(Idx), RC);
11729     }
11730   }
11731 
11732   // FIXME: Returns VS_32 for physical SGPR constraints
11733   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11734 }
11735 
11736 static bool isImmConstraint(StringRef Constraint) {
11737   if (Constraint.size() == 1) {
11738     switch (Constraint[0]) {
11739     default: break;
11740     case 'I':
11741     case 'J':
11742     case 'A':
11743     case 'B':
11744     case 'C':
11745       return true;
11746     }
11747   } else if (Constraint == "DA" ||
11748              Constraint == "DB") {
11749     return true;
11750   }
11751   return false;
11752 }
11753 
11754 SITargetLowering::ConstraintType
11755 SITargetLowering::getConstraintType(StringRef Constraint) const {
11756   if (Constraint.size() == 1) {
11757     switch (Constraint[0]) {
11758     default: break;
11759     case 's':
11760     case 'v':
11761     case 'a':
11762       return C_RegisterClass;
11763     }
11764   }
11765   if (isImmConstraint(Constraint)) {
11766     return C_Other;
11767   }
11768   return TargetLowering::getConstraintType(Constraint);
11769 }
11770 
11771 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11772   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11773     Val = Val & maskTrailingOnes<uint64_t>(Size);
11774   }
11775   return Val;
11776 }
11777 
11778 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11779                                                     std::string &Constraint,
11780                                                     std::vector<SDValue> &Ops,
11781                                                     SelectionDAG &DAG) const {
11782   if (isImmConstraint(Constraint)) {
11783     uint64_t Val;
11784     if (getAsmOperandConstVal(Op, Val) &&
11785         checkAsmConstraintVal(Op, Constraint, Val)) {
11786       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11787       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11788     }
11789   } else {
11790     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11791   }
11792 }
11793 
11794 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11795   unsigned Size = Op.getScalarValueSizeInBits();
11796   if (Size > 64)
11797     return false;
11798 
11799   if (Size == 16 && !Subtarget->has16BitInsts())
11800     return false;
11801 
11802   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11803     Val = C->getSExtValue();
11804     return true;
11805   }
11806   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11807     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11808     return true;
11809   }
11810   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11811     if (Size != 16 || Op.getNumOperands() != 2)
11812       return false;
11813     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11814       return false;
11815     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11816       Val = C->getSExtValue();
11817       return true;
11818     }
11819     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11820       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11821       return true;
11822     }
11823   }
11824 
11825   return false;
11826 }
11827 
11828 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11829                                              const std::string &Constraint,
11830                                              uint64_t Val) const {
11831   if (Constraint.size() == 1) {
11832     switch (Constraint[0]) {
11833     case 'I':
11834       return AMDGPU::isInlinableIntLiteral(Val);
11835     case 'J':
11836       return isInt<16>(Val);
11837     case 'A':
11838       return checkAsmConstraintValA(Op, Val);
11839     case 'B':
11840       return isInt<32>(Val);
11841     case 'C':
11842       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11843              AMDGPU::isInlinableIntLiteral(Val);
11844     default:
11845       break;
11846     }
11847   } else if (Constraint.size() == 2) {
11848     if (Constraint == "DA") {
11849       int64_t HiBits = static_cast<int32_t>(Val >> 32);
11850       int64_t LoBits = static_cast<int32_t>(Val);
11851       return checkAsmConstraintValA(Op, HiBits, 32) &&
11852              checkAsmConstraintValA(Op, LoBits, 32);
11853     }
11854     if (Constraint == "DB") {
11855       return true;
11856     }
11857   }
11858   llvm_unreachable("Invalid asm constraint");
11859 }
11860 
11861 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
11862                                               uint64_t Val,
11863                                               unsigned MaxSize) const {
11864   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
11865   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11866   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11867       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11868       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11869     return true;
11870   }
11871   return false;
11872 }
11873 
11874 static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
11875   switch (UnalignedClassID) {
11876   case AMDGPU::VReg_64RegClassID:
11877     return AMDGPU::VReg_64_Align2RegClassID;
11878   case AMDGPU::VReg_96RegClassID:
11879     return AMDGPU::VReg_96_Align2RegClassID;
11880   case AMDGPU::VReg_128RegClassID:
11881     return AMDGPU::VReg_128_Align2RegClassID;
11882   case AMDGPU::VReg_160RegClassID:
11883     return AMDGPU::VReg_160_Align2RegClassID;
11884   case AMDGPU::VReg_192RegClassID:
11885     return AMDGPU::VReg_192_Align2RegClassID;
11886   case AMDGPU::VReg_224RegClassID:
11887     return AMDGPU::VReg_224_Align2RegClassID;
11888   case AMDGPU::VReg_256RegClassID:
11889     return AMDGPU::VReg_256_Align2RegClassID;
11890   case AMDGPU::VReg_512RegClassID:
11891     return AMDGPU::VReg_512_Align2RegClassID;
11892   case AMDGPU::VReg_1024RegClassID:
11893     return AMDGPU::VReg_1024_Align2RegClassID;
11894   case AMDGPU::AReg_64RegClassID:
11895     return AMDGPU::AReg_64_Align2RegClassID;
11896   case AMDGPU::AReg_96RegClassID:
11897     return AMDGPU::AReg_96_Align2RegClassID;
11898   case AMDGPU::AReg_128RegClassID:
11899     return AMDGPU::AReg_128_Align2RegClassID;
11900   case AMDGPU::AReg_160RegClassID:
11901     return AMDGPU::AReg_160_Align2RegClassID;
11902   case AMDGPU::AReg_192RegClassID:
11903     return AMDGPU::AReg_192_Align2RegClassID;
11904   case AMDGPU::AReg_256RegClassID:
11905     return AMDGPU::AReg_256_Align2RegClassID;
11906   case AMDGPU::AReg_512RegClassID:
11907     return AMDGPU::AReg_512_Align2RegClassID;
11908   case AMDGPU::AReg_1024RegClassID:
11909     return AMDGPU::AReg_1024_Align2RegClassID;
11910   default:
11911     return -1;
11912   }
11913 }
11914 
11915 // Figure out which registers should be reserved for stack access. Only after
11916 // the function is legalized do we know all of the non-spill stack objects or if
11917 // calls are present.
11918 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
11919   MachineRegisterInfo &MRI = MF.getRegInfo();
11920   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11921   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
11922   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11923   const SIInstrInfo *TII = ST.getInstrInfo();
11924 
11925   if (Info->isEntryFunction()) {
11926     // Callable functions have fixed registers used for stack access.
11927     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
11928   }
11929 
11930   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
11931                              Info->getStackPtrOffsetReg()));
11932   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
11933     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
11934 
11935   // We need to worry about replacing the default register with itself in case
11936   // of MIR testcases missing the MFI.
11937   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
11938     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
11939 
11940   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
11941     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
11942 
11943   Info->limitOccupancy(MF);
11944 
11945   if (ST.isWave32() && !MF.empty()) {
11946     for (auto &MBB : MF) {
11947       for (auto &MI : MBB) {
11948         TII->fixImplicitOperands(MI);
11949       }
11950     }
11951   }
11952 
11953   // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
11954   // classes if required. Ideally the register class constraints would differ
11955   // per-subtarget, but there's no easy way to achieve that right now. This is
11956   // not a problem for VGPRs because the correctly aligned VGPR class is implied
11957   // from using them as the register class for legal types.
11958   if (ST.needsAlignedVGPRs()) {
11959     for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
11960       const Register Reg = Register::index2VirtReg(I);
11961       const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
11962       if (!RC)
11963         continue;
11964       int NewClassID = getAlignedAGPRClassID(RC->getID());
11965       if (NewClassID != -1)
11966         MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
11967     }
11968   }
11969 
11970   TargetLoweringBase::finalizeLowering(MF);
11971 
11972   // Allocate a VGPR for future SGPR Spill if
11973   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
11974   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
11975   if (VGPRReserveforSGPRSpill && TRI->spillSGPRToVGPR() &&
11976       !Info->VGPRReservedForSGPRSpill && !Info->isEntryFunction())
11977     Info->reserveVGPRforSGPRSpills(MF);
11978 }
11979 
11980 void SITargetLowering::computeKnownBitsForFrameIndex(
11981   const int FI, KnownBits &Known, const MachineFunction &MF) const {
11982   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
11983 
11984   // Set the high bits to zero based on the maximum allowed scratch size per
11985   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
11986   // calculation won't overflow, so assume the sign bit is never set.
11987   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
11988 }
11989 
11990 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
11991                                    KnownBits &Known, unsigned Dim) {
11992   unsigned MaxValue =
11993       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
11994   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
11995 }
11996 
11997 void SITargetLowering::computeKnownBitsForTargetInstr(
11998     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
11999     const MachineRegisterInfo &MRI, unsigned Depth) const {
12000   const MachineInstr *MI = MRI.getVRegDef(R);
12001   switch (MI->getOpcode()) {
12002   case AMDGPU::G_INTRINSIC: {
12003     switch (MI->getIntrinsicID()) {
12004     case Intrinsic::amdgcn_workitem_id_x:
12005       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
12006       break;
12007     case Intrinsic::amdgcn_workitem_id_y:
12008       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
12009       break;
12010     case Intrinsic::amdgcn_workitem_id_z:
12011       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
12012       break;
12013     case Intrinsic::amdgcn_mbcnt_lo:
12014     case Intrinsic::amdgcn_mbcnt_hi: {
12015       // These return at most the wavefront size - 1.
12016       unsigned Size = MRI.getType(R).getSizeInBits();
12017       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
12018       break;
12019     }
12020     case Intrinsic::amdgcn_groupstaticsize: {
12021       // We can report everything over the maximum size as 0. We can't report
12022       // based on the actual size because we don't know if it's accurate or not
12023       // at any given point.
12024       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
12025       break;
12026     }
12027     }
12028     break;
12029   }
12030   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
12031     Known.Zero.setHighBits(24);
12032     break;
12033   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
12034     Known.Zero.setHighBits(16);
12035     break;
12036   }
12037 }
12038 
12039 Align SITargetLowering::computeKnownAlignForTargetInstr(
12040   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
12041   unsigned Depth) const {
12042   const MachineInstr *MI = MRI.getVRegDef(R);
12043   switch (MI->getOpcode()) {
12044   case AMDGPU::G_INTRINSIC:
12045   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
12046     // FIXME: Can this move to generic code? What about the case where the call
12047     // site specifies a lower alignment?
12048     Intrinsic::ID IID = MI->getIntrinsicID();
12049     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
12050     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
12051     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
12052       return *RetAlign;
12053     return Align(1);
12054   }
12055   default:
12056     return Align(1);
12057   }
12058 }
12059 
12060 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12061   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
12062   const Align CacheLineAlign = Align(64);
12063 
12064   // Pre-GFX10 target did not benefit from loop alignment
12065   if (!ML || DisableLoopAlignment ||
12066       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
12067       getSubtarget()->hasInstFwdPrefetchBug())
12068     return PrefAlign;
12069 
12070   // On GFX10 I$ is 4 x 64 bytes cache lines.
12071   // By default prefetcher keeps one cache line behind and reads two ahead.
12072   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
12073   // behind and one ahead.
12074   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
12075   // If loop fits 64 bytes it always spans no more than two cache lines and
12076   // does not need an alignment.
12077   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
12078   // Else if loop is less or equal 192 bytes we need two lines behind.
12079 
12080   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12081   const MachineBasicBlock *Header = ML->getHeader();
12082   if (Header->getAlignment() != PrefAlign)
12083     return Header->getAlignment(); // Already processed.
12084 
12085   unsigned LoopSize = 0;
12086   for (const MachineBasicBlock *MBB : ML->blocks()) {
12087     // If inner loop block is aligned assume in average half of the alignment
12088     // size to be added as nops.
12089     if (MBB != Header)
12090       LoopSize += MBB->getAlignment().value() / 2;
12091 
12092     for (const MachineInstr &MI : *MBB) {
12093       LoopSize += TII->getInstSizeInBytes(MI);
12094       if (LoopSize > 192)
12095         return PrefAlign;
12096     }
12097   }
12098 
12099   if (LoopSize <= 64)
12100     return PrefAlign;
12101 
12102   if (LoopSize <= 128)
12103     return CacheLineAlign;
12104 
12105   // If any of parent loops is surrounded by prefetch instructions do not
12106   // insert new for inner loop, which would reset parent's settings.
12107   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
12108     if (MachineBasicBlock *Exit = P->getExitBlock()) {
12109       auto I = Exit->getFirstNonDebugInstr();
12110       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
12111         return CacheLineAlign;
12112     }
12113   }
12114 
12115   MachineBasicBlock *Pre = ML->getLoopPreheader();
12116   MachineBasicBlock *Exit = ML->getExitBlock();
12117 
12118   if (Pre && Exit) {
12119     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
12120             TII->get(AMDGPU::S_INST_PREFETCH))
12121       .addImm(1); // prefetch 2 lines behind PC
12122 
12123     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
12124             TII->get(AMDGPU::S_INST_PREFETCH))
12125       .addImm(2); // prefetch 1 line behind PC
12126   }
12127 
12128   return CacheLineAlign;
12129 }
12130 
12131 LLVM_ATTRIBUTE_UNUSED
12132 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
12133   assert(N->getOpcode() == ISD::CopyFromReg);
12134   do {
12135     // Follow the chain until we find an INLINEASM node.
12136     N = N->getOperand(0).getNode();
12137     if (N->getOpcode() == ISD::INLINEASM ||
12138         N->getOpcode() == ISD::INLINEASM_BR)
12139       return true;
12140   } while (N->getOpcode() == ISD::CopyFromReg);
12141   return false;
12142 }
12143 
12144 bool SITargetLowering::isSDNodeSourceOfDivergence(
12145     const SDNode *N, FunctionLoweringInfo *FLI,
12146     LegacyDivergenceAnalysis *KDA) const {
12147   switch (N->getOpcode()) {
12148   case ISD::CopyFromReg: {
12149     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
12150     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
12151     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12152     Register Reg = R->getReg();
12153 
12154     // FIXME: Why does this need to consider isLiveIn?
12155     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
12156       return !TRI->isSGPRReg(MRI, Reg);
12157 
12158     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
12159       return KDA->isDivergent(V);
12160 
12161     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
12162     return !TRI->isSGPRReg(MRI, Reg);
12163   }
12164   case ISD::LOAD: {
12165     const LoadSDNode *L = cast<LoadSDNode>(N);
12166     unsigned AS = L->getAddressSpace();
12167     // A flat load may access private memory.
12168     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
12169   }
12170   case ISD::CALLSEQ_END:
12171     return true;
12172   case ISD::INTRINSIC_WO_CHAIN:
12173     return AMDGPU::isIntrinsicSourceOfDivergence(
12174         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
12175   case ISD::INTRINSIC_W_CHAIN:
12176     return AMDGPU::isIntrinsicSourceOfDivergence(
12177         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
12178   case AMDGPUISD::ATOMIC_CMP_SWAP:
12179   case AMDGPUISD::ATOMIC_INC:
12180   case AMDGPUISD::ATOMIC_DEC:
12181   case AMDGPUISD::ATOMIC_LOAD_FMIN:
12182   case AMDGPUISD::ATOMIC_LOAD_FMAX:
12183   case AMDGPUISD::BUFFER_ATOMIC_SWAP:
12184   case AMDGPUISD::BUFFER_ATOMIC_ADD:
12185   case AMDGPUISD::BUFFER_ATOMIC_SUB:
12186   case AMDGPUISD::BUFFER_ATOMIC_SMIN:
12187   case AMDGPUISD::BUFFER_ATOMIC_UMIN:
12188   case AMDGPUISD::BUFFER_ATOMIC_SMAX:
12189   case AMDGPUISD::BUFFER_ATOMIC_UMAX:
12190   case AMDGPUISD::BUFFER_ATOMIC_AND:
12191   case AMDGPUISD::BUFFER_ATOMIC_OR:
12192   case AMDGPUISD::BUFFER_ATOMIC_XOR:
12193   case AMDGPUISD::BUFFER_ATOMIC_INC:
12194   case AMDGPUISD::BUFFER_ATOMIC_DEC:
12195   case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
12196   case AMDGPUISD::BUFFER_ATOMIC_CSUB:
12197   case AMDGPUISD::BUFFER_ATOMIC_FADD:
12198   case AMDGPUISD::BUFFER_ATOMIC_FMIN:
12199   case AMDGPUISD::BUFFER_ATOMIC_FMAX:
12200     // Target-specific read-modify-write atomics are sources of divergence.
12201     return true;
12202   default:
12203     if (auto *A = dyn_cast<AtomicSDNode>(N)) {
12204       // Generic read-modify-write atomics are sources of divergence.
12205       return A->readMem() && A->writeMem();
12206     }
12207     return false;
12208   }
12209 }
12210 
12211 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
12212                                                EVT VT) const {
12213   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
12214   case MVT::f32:
12215     return hasFP32Denormals(DAG.getMachineFunction());
12216   case MVT::f64:
12217   case MVT::f16:
12218     return hasFP64FP16Denormals(DAG.getMachineFunction());
12219   default:
12220     return false;
12221   }
12222 }
12223 
12224 bool SITargetLowering::denormalsEnabledForType(LLT Ty,
12225                                                MachineFunction &MF) const {
12226   switch (Ty.getScalarSizeInBits()) {
12227   case 32:
12228     return hasFP32Denormals(MF);
12229   case 64:
12230   case 16:
12231     return hasFP64FP16Denormals(MF);
12232   default:
12233     return false;
12234   }
12235 }
12236 
12237 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
12238                                                     const SelectionDAG &DAG,
12239                                                     bool SNaN,
12240                                                     unsigned Depth) const {
12241   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
12242     const MachineFunction &MF = DAG.getMachineFunction();
12243     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12244 
12245     if (Info->getMode().DX10Clamp)
12246       return true; // Clamped to 0.
12247     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
12248   }
12249 
12250   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
12251                                                             SNaN, Depth);
12252 }
12253 
12254 // Global FP atomic instructions have a hardcoded FP mode and do not support
12255 // FP32 denormals, and only support v2f16 denormals.
12256 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
12257   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
12258   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
12259   if (&Flt == &APFloat::IEEEsingle())
12260     return DenormMode == DenormalMode::getPreserveSign();
12261   return DenormMode == DenormalMode::getIEEE();
12262 }
12263 
12264 TargetLowering::AtomicExpansionKind
12265 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
12266 
12267   auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) {
12268     OptimizationRemarkEmitter ORE(RMW->getFunction());
12269     LLVMContext &Ctx = RMW->getFunction()->getContext();
12270     SmallVector<StringRef> SSNs;
12271     Ctx.getSyncScopeNames(SSNs);
12272     auto MemScope = SSNs[RMW->getSyncScopeID()].empty()
12273                         ? "system"
12274                         : SSNs[RMW->getSyncScopeID()];
12275     ORE.emit([&]() {
12276       return OptimizationRemark(DEBUG_TYPE, "Passed", RMW)
12277              << "Hardware instruction generated for atomic "
12278              << RMW->getOperationName(RMW->getOperation())
12279              << " operation at memory scope " << MemScope
12280              << " due to an unsafe request.";
12281     });
12282     return Kind;
12283   };
12284 
12285   switch (RMW->getOperation()) {
12286   case AtomicRMWInst::FAdd: {
12287     Type *Ty = RMW->getType();
12288 
12289     // We don't have a way to support 16-bit atomics now, so just leave them
12290     // as-is.
12291     if (Ty->isHalfTy())
12292       return AtomicExpansionKind::None;
12293 
12294     if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
12295       return AtomicExpansionKind::CmpXChg;
12296 
12297     unsigned AS = RMW->getPointerAddressSpace();
12298 
12299     if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) &&
12300          Subtarget->hasAtomicFaddInsts()) {
12301       // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
12302       // floating point atomic instructions. May generate more efficient code,
12303       // but may not respect rounding and denormal modes, and may give incorrect
12304       // results for certain memory destinations.
12305       if (RMW->getFunction()
12306               ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12307               .getValueAsString() != "true")
12308         return AtomicExpansionKind::CmpXChg;
12309 
12310       if (Subtarget->hasGFX90AInsts()) {
12311         if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS)
12312           return AtomicExpansionKind::CmpXChg;
12313 
12314         auto SSID = RMW->getSyncScopeID();
12315         if (SSID == SyncScope::System ||
12316             SSID == RMW->getContext().getOrInsertSyncScopeID("one-as"))
12317           return AtomicExpansionKind::CmpXChg;
12318 
12319         return ReportUnsafeHWInst(AtomicExpansionKind::None);
12320       }
12321 
12322       if (AS == AMDGPUAS::FLAT_ADDRESS)
12323         return AtomicExpansionKind::CmpXChg;
12324 
12325       return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12326                               : AtomicExpansionKind::CmpXChg;
12327     }
12328 
12329     // DS FP atomics do repect the denormal mode, but the rounding mode is fixed
12330     // to round-to-nearest-even.
12331     // The only exception is DS_ADD_F64 which never flushes regardless of mode.
12332     if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) {
12333       if (!Ty->isDoubleTy())
12334         return AtomicExpansionKind::None;
12335 
12336       if (fpModeMatchesGlobalFPAtomicMode(RMW))
12337         return AtomicExpansionKind::None;
12338 
12339       return RMW->getFunction()
12340                          ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12341                          .getValueAsString() == "true"
12342                  ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12343                  : AtomicExpansionKind::CmpXChg;
12344     }
12345 
12346     return AtomicExpansionKind::CmpXChg;
12347   }
12348   default:
12349     break;
12350   }
12351 
12352   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
12353 }
12354 
12355 const TargetRegisterClass *
12356 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
12357   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
12358   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12359   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
12360     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
12361                                                : &AMDGPU::SReg_32RegClass;
12362   if (!TRI->isSGPRClass(RC) && !isDivergent)
12363     return TRI->getEquivalentSGPRClass(RC);
12364   else if (TRI->isSGPRClass(RC) && isDivergent)
12365     return TRI->getEquivalentVGPRClass(RC);
12366 
12367   return RC;
12368 }
12369 
12370 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
12371 // uniform values (as produced by the mask results of control flow intrinsics)
12372 // used outside of divergent blocks. The phi users need to also be treated as
12373 // always uniform.
12374 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
12375                       unsigned WaveSize) {
12376   // FIXME: We asssume we never cast the mask results of a control flow
12377   // intrinsic.
12378   // Early exit if the type won't be consistent as a compile time hack.
12379   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
12380   if (!IT || IT->getBitWidth() != WaveSize)
12381     return false;
12382 
12383   if (!isa<Instruction>(V))
12384     return false;
12385   if (!Visited.insert(V).second)
12386     return false;
12387   bool Result = false;
12388   for (auto U : V->users()) {
12389     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
12390       if (V == U->getOperand(1)) {
12391         switch (Intrinsic->getIntrinsicID()) {
12392         default:
12393           Result = false;
12394           break;
12395         case Intrinsic::amdgcn_if_break:
12396         case Intrinsic::amdgcn_if:
12397         case Intrinsic::amdgcn_else:
12398           Result = true;
12399           break;
12400         }
12401       }
12402       if (V == U->getOperand(0)) {
12403         switch (Intrinsic->getIntrinsicID()) {
12404         default:
12405           Result = false;
12406           break;
12407         case Intrinsic::amdgcn_end_cf:
12408         case Intrinsic::amdgcn_loop:
12409           Result = true;
12410           break;
12411         }
12412       }
12413     } else {
12414       Result = hasCFUser(U, Visited, WaveSize);
12415     }
12416     if (Result)
12417       break;
12418   }
12419   return Result;
12420 }
12421 
12422 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
12423                                                const Value *V) const {
12424   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
12425     if (CI->isInlineAsm()) {
12426       // FIXME: This cannot give a correct answer. This should only trigger in
12427       // the case where inline asm returns mixed SGPR and VGPR results, used
12428       // outside the defining block. We don't have a specific result to
12429       // consider, so this assumes if any value is SGPR, the overall register
12430       // also needs to be SGPR.
12431       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
12432       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
12433           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
12434       for (auto &TC : TargetConstraints) {
12435         if (TC.Type == InlineAsm::isOutput) {
12436           ComputeConstraintToUse(TC, SDValue());
12437           unsigned AssignedReg;
12438           const TargetRegisterClass *RC;
12439           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
12440               SIRI, TC.ConstraintCode, TC.ConstraintVT);
12441           if (RC) {
12442             MachineRegisterInfo &MRI = MF.getRegInfo();
12443             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
12444               return true;
12445             else if (SIRI->isSGPRClass(RC))
12446               return true;
12447           }
12448         }
12449       }
12450     }
12451   }
12452   SmallPtrSet<const Value *, 16> Visited;
12453   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
12454 }
12455 
12456 std::pair<InstructionCost, MVT>
12457 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
12458                                           Type *Ty) const {
12459   std::pair<InstructionCost, MVT> Cost =
12460       TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
12461   auto Size = DL.getTypeSizeInBits(Ty);
12462   // Maximum load or store can handle 8 dwords for scalar and 4 for
12463   // vector ALU. Let's assume anything above 8 dwords is expensive
12464   // even if legal.
12465   if (Size <= 256)
12466     return Cost;
12467 
12468   Cost.first += (Size + 255) / 256;
12469   return Cost;
12470 }
12471