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/MachineFunction.h"
28 #include "llvm/CodeGen/MachineLoopInfo.h"
29 #include "llvm/IR/DiagnosticInfo.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/IntrinsicsAMDGPU.h"
32 #include "llvm/IR/IntrinsicsR600.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/KnownBits.h"
35 
36 using namespace llvm;
37 
38 #define DEBUG_TYPE "si-lower"
39 
40 STATISTIC(NumTailCalls, "Number of tail calls");
41 
42 static cl::opt<bool> DisableLoopAlignment(
43   "amdgpu-disable-loop-alignment",
44   cl::desc("Do not align and prefetch loops"),
45   cl::init(false));
46 
47 static cl::opt<bool> VGPRReserveforSGPRSpill(
48     "amdgpu-reserve-vgpr-for-sgpr-spill",
49     cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true));
50 
51 static cl::opt<bool> UseDivergentRegisterIndexing(
52   "amdgpu-use-divergent-register-indexing",
53   cl::Hidden,
54   cl::desc("Use indirect register addressing for divergent indexes"),
55   cl::init(false));
56 
57 static bool hasFP32Denormals(const MachineFunction &MF) {
58   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
59   return Info->getMode().allFP32Denormals();
60 }
61 
62 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
63   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
64   return Info->getMode().allFP64FP16Denormals();
65 }
66 
67 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
68   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
69   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
70     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
71       return AMDGPU::SGPR0 + Reg;
72     }
73   }
74   llvm_unreachable("Cannot allocate sgpr");
75 }
76 
77 SITargetLowering::SITargetLowering(const TargetMachine &TM,
78                                    const GCNSubtarget &STI)
79     : AMDGPUTargetLowering(TM, STI),
80       Subtarget(&STI) {
81   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
82   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
83 
84   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
85   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
86 
87   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
88 
89   const SIRegisterInfo *TRI = STI.getRegisterInfo();
90   const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class();
91 
92   addRegisterClass(MVT::f64, V64RegClass);
93   addRegisterClass(MVT::v2f32, V64RegClass);
94 
95   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
96   addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96));
97 
98   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
99   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
100 
101   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
102   addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128));
103 
104   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
105   addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160));
106 
107   addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass);
108   addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192));
109 
110   addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass);
111   addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192));
112 
113   addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass);
114   addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224));
115 
116   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
117   addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256));
118 
119   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
120   addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256));
121 
122   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
123   addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512));
124 
125   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
126   addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512));
127 
128   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
129   addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024));
130 
131   if (Subtarget->has16BitInsts()) {
132     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
133     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
134 
135     // Unless there are also VOP3P operations, not operations are really legal.
136     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
137     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
138     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
139     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
140   }
141 
142   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
143   addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024));
144 
145   computeRegisterProperties(Subtarget->getRegisterInfo());
146 
147   // The boolean content concept here is too inflexible. Compares only ever
148   // really produce a 1-bit result. Any copy/extend from these will turn into a
149   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
150   // it's what most targets use.
151   setBooleanContents(ZeroOrOneBooleanContent);
152   setBooleanVectorContents(ZeroOrOneBooleanContent);
153 
154   // We need to custom lower vector stores from local memory
155   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
156   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
157   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
158   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
159   setOperationAction(ISD::LOAD, MVT::v6i32, Custom);
160   setOperationAction(ISD::LOAD, MVT::v7i32, Custom);
161   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
162   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
163   setOperationAction(ISD::LOAD, MVT::i1, Custom);
164   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
165 
166   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
167   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
168   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
169   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
170   setOperationAction(ISD::STORE, MVT::v6i32, Custom);
171   setOperationAction(ISD::STORE, MVT::v7i32, Custom);
172   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
173   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
174   setOperationAction(ISD::STORE, MVT::i1, Custom);
175   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
176 
177   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
178   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
179   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
180   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
181   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
182   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
183   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
184   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
185   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
186   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
187   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
188   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
189   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
190   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
191   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
192   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
193 
194   setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand);
195   setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand);
196   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
197   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
198   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
199   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
200   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
201 
202   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
203   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
204 
205   setOperationAction(ISD::SELECT, MVT::i1, Promote);
206   setOperationAction(ISD::SELECT, MVT::i64, Custom);
207   setOperationAction(ISD::SELECT, MVT::f64, Promote);
208   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
209 
210   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
211   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
212   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
213   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
214   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
215 
216   setOperationAction(ISD::SETCC, MVT::i1, Promote);
217   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
218   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
219   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
220 
221   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
222   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
223   setOperationAction(ISD::TRUNCATE, MVT::v3i32, Expand);
224   setOperationAction(ISD::FP_ROUND, MVT::v3f32, Expand);
225   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
226   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
227   setOperationAction(ISD::TRUNCATE, MVT::v5i32, Expand);
228   setOperationAction(ISD::FP_ROUND, MVT::v5f32, Expand);
229   setOperationAction(ISD::TRUNCATE, MVT::v6i32, Expand);
230   setOperationAction(ISD::FP_ROUND, MVT::v6f32, Expand);
231   setOperationAction(ISD::TRUNCATE, MVT::v7i32, Expand);
232   setOperationAction(ISD::FP_ROUND, MVT::v7f32, Expand);
233   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
234   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
235   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
236   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
237 
238   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
239   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
240   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
241   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
242   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
243   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
244   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
245   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
246 
247   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
248   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
249   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
250   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
251   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
252   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
253 
254   setOperationAction(ISD::UADDO, MVT::i32, Legal);
255   setOperationAction(ISD::USUBO, MVT::i32, Legal);
256 
257   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
258   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
259 
260   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
261   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
262   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
263 
264 #if 0
265   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
266   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
267 #endif
268 
269   // We only support LOAD/STORE and vector manipulation ops for vectors
270   // with > 4 elements.
271   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
272                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
273                   MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32,
274                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
275                   MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) {
276     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
277       switch (Op) {
278       case ISD::LOAD:
279       case ISD::STORE:
280       case ISD::BUILD_VECTOR:
281       case ISD::BITCAST:
282       case ISD::EXTRACT_VECTOR_ELT:
283       case ISD::INSERT_VECTOR_ELT:
284       case ISD::EXTRACT_SUBVECTOR:
285       case ISD::SCALAR_TO_VECTOR:
286         break;
287       case ISD::INSERT_SUBVECTOR:
288       case ISD::CONCAT_VECTORS:
289         setOperationAction(Op, VT, Custom);
290         break;
291       default:
292         setOperationAction(Op, VT, Expand);
293         break;
294       }
295     }
296   }
297 
298   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
299 
300   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
301   // is expanded to avoid having two separate loops in case the index is a VGPR.
302 
303   // Most operations are naturally 32-bit vector operations. We only support
304   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
305   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
306     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
307     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
308 
309     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
310     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
311 
312     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
313     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
314 
315     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
316     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
317   }
318 
319   for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) {
320     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
321     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32);
322 
323     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
324     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32);
325 
326     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
327     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32);
328 
329     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
330     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32);
331   }
332 
333   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
334     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
335     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
336 
337     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
338     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
339 
340     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
341     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
342 
343     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
344     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
345   }
346 
347   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
348     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
349     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
350 
351     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
352     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
353 
354     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
355     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
356 
357     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
358     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
359   }
360 
361   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
362     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
363     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
364 
365     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
366     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
367 
368     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
369     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
370 
371     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
372     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
373   }
374 
375   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
376   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
377   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
378   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
379 
380   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
381   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
382 
383   // Avoid stack access for these.
384   // TODO: Generalize to more vector types.
385   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
386   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
387   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
388   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
389 
390   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
391   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
392   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
393   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
394   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
395   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
396 
397   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
398   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
399   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
400   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
401 
402   // Deal with vec3 vector operations when widened to vec4.
403   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
404   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
405   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
406   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
407 
408   // Deal with vec5/6/7 vector operations when widened to vec8.
409   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
410   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
411   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6i32, Custom);
412   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6f32, Custom);
413   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7i32, Custom);
414   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7f32, Custom);
415   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
416   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
417 
418   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
419   // and output demarshalling
420   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
421   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
422 
423   // We can't return success/failure, only the old value,
424   // let LLVM add the comparison
425   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
426   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
427 
428   if (Subtarget->hasFlatAddressSpace()) {
429     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
430     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
431   }
432 
433   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
434   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
435 
436   // FIXME: This should be narrowed to i32, but that only happens if i64 is
437   // illegal.
438   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
439   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
440   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
441 
442   // On SI this is s_memtime and s_memrealtime on VI.
443   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
444   setOperationAction(ISD::TRAP, MVT::Other, Custom);
445   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
446 
447   if (Subtarget->has16BitInsts()) {
448     setOperationAction(ISD::FPOW, MVT::f16, Promote);
449     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
450     setOperationAction(ISD::FLOG, MVT::f16, Custom);
451     setOperationAction(ISD::FEXP, MVT::f16, Custom);
452     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
453   }
454 
455   if (Subtarget->hasMadMacF32Insts())
456     setOperationAction(ISD::FMAD, MVT::f32, Legal);
457 
458   if (!Subtarget->hasBFI()) {
459     // fcopysign can be done in a single instruction with BFI.
460     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
461     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
462   }
463 
464   if (!Subtarget->hasBCNT(32))
465     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
466 
467   if (!Subtarget->hasBCNT(64))
468     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
469 
470   if (Subtarget->hasFFBH()) {
471     setOperationAction(ISD::CTLZ, MVT::i32, Custom);
472     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
473   }
474 
475   if (Subtarget->hasFFBL()) {
476     setOperationAction(ISD::CTTZ, MVT::i32, Custom);
477     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
478   }
479 
480   // We only really have 32-bit BFE instructions (and 16-bit on VI).
481   //
482   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
483   // effort to match them now. We want this to be false for i64 cases when the
484   // extraction isn't restricted to the upper or lower half. Ideally we would
485   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
486   // span the midpoint are probably relatively rare, so don't worry about them
487   // for now.
488   if (Subtarget->hasBFE())
489     setHasExtractBitsInsn(true);
490 
491   // Clamp modifier on add/sub
492   if (Subtarget->hasIntClamp()) {
493     setOperationAction(ISD::UADDSAT, MVT::i32, Legal);
494     setOperationAction(ISD::USUBSAT, MVT::i32, Legal);
495   }
496 
497   if (Subtarget->hasAddNoCarry()) {
498     setOperationAction(ISD::SADDSAT, MVT::i16, Legal);
499     setOperationAction(ISD::SSUBSAT, MVT::i16, Legal);
500     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
501     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
502   }
503 
504   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
505   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
506   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
507   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
508 
509 
510   // These are really only legal for ieee_mode functions. We should be avoiding
511   // them for functions that don't have ieee_mode enabled, so just say they are
512   // legal.
513   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
514   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
515   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
516   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
517 
518 
519   if (Subtarget->haveRoundOpsF64()) {
520     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
521     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
522     setOperationAction(ISD::FRINT, MVT::f64, Legal);
523   } else {
524     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
525     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
526     setOperationAction(ISD::FRINT, MVT::f64, Custom);
527     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
528   }
529 
530   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
531 
532   setOperationAction(ISD::FSIN, MVT::f32, Custom);
533   setOperationAction(ISD::FCOS, MVT::f32, Custom);
534   setOperationAction(ISD::FDIV, MVT::f32, Custom);
535   setOperationAction(ISD::FDIV, MVT::f64, Custom);
536 
537   if (Subtarget->has16BitInsts()) {
538     setOperationAction(ISD::Constant, MVT::i16, Legal);
539 
540     setOperationAction(ISD::SMIN, MVT::i16, Legal);
541     setOperationAction(ISD::SMAX, MVT::i16, Legal);
542 
543     setOperationAction(ISD::UMIN, MVT::i16, Legal);
544     setOperationAction(ISD::UMAX, MVT::i16, Legal);
545 
546     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
547     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
548 
549     setOperationAction(ISD::ROTR, MVT::i16, Expand);
550     setOperationAction(ISD::ROTL, MVT::i16, Expand);
551 
552     setOperationAction(ISD::SDIV, MVT::i16, Promote);
553     setOperationAction(ISD::UDIV, MVT::i16, Promote);
554     setOperationAction(ISD::SREM, MVT::i16, Promote);
555     setOperationAction(ISD::UREM, MVT::i16, Promote);
556     setOperationAction(ISD::UADDSAT, MVT::i16, Legal);
557     setOperationAction(ISD::USUBSAT, MVT::i16, Legal);
558 
559     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
560 
561     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
562     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
563     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
564     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
565     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
566 
567     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
568 
569     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
570 
571     setOperationAction(ISD::LOAD, MVT::i16, Custom);
572 
573     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
574 
575     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
576     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
577     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
578     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
579 
580     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Custom);
581     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Custom);
582 
583     // F16 - Constant Actions.
584     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
585 
586     // F16 - Load/Store Actions.
587     setOperationAction(ISD::LOAD, MVT::f16, Promote);
588     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
589     setOperationAction(ISD::STORE, MVT::f16, Promote);
590     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
591 
592     // F16 - VOP1 Actions.
593     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
594     setOperationAction(ISD::FCOS, MVT::f16, Custom);
595     setOperationAction(ISD::FSIN, MVT::f16, Custom);
596 
597     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
598     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
599 
600     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
601     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
602     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
603     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
604     setOperationAction(ISD::FROUND, MVT::f16, Custom);
605 
606     // F16 - VOP2 Actions.
607     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
608     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
609 
610     setOperationAction(ISD::FDIV, MVT::f16, Custom);
611 
612     // F16 - VOP3 Actions.
613     setOperationAction(ISD::FMA, MVT::f16, Legal);
614     if (STI.hasMadF16())
615       setOperationAction(ISD::FMAD, MVT::f16, Legal);
616 
617     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
618       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
619         switch (Op) {
620         case ISD::LOAD:
621         case ISD::STORE:
622         case ISD::BUILD_VECTOR:
623         case ISD::BITCAST:
624         case ISD::EXTRACT_VECTOR_ELT:
625         case ISD::INSERT_VECTOR_ELT:
626         case ISD::INSERT_SUBVECTOR:
627         case ISD::EXTRACT_SUBVECTOR:
628         case ISD::SCALAR_TO_VECTOR:
629           break;
630         case ISD::CONCAT_VECTORS:
631           setOperationAction(Op, VT, Custom);
632           break;
633         default:
634           setOperationAction(Op, VT, Expand);
635           break;
636         }
637       }
638     }
639 
640     // v_perm_b32 can handle either of these.
641     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
642     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
643     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
644 
645     // XXX - Do these do anything? Vector constants turn into build_vector.
646     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
647     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
648 
649     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
650     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
651 
652     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
653     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
654     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
655     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
656 
657     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
658     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
659     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
660     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
661 
662     setOperationAction(ISD::AND, MVT::v2i16, Promote);
663     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
664     setOperationAction(ISD::OR, MVT::v2i16, Promote);
665     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
666     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
667     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
668 
669     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
670     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
671     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
672     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
673 
674     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
675     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
676     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
677     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
678 
679     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
680     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
681     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
682     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
683 
684     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
685     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
686     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
687 
688     if (!Subtarget->hasVOP3PInsts()) {
689       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
690       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
691     }
692 
693     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
694     // This isn't really legal, but this avoids the legalizer unrolling it (and
695     // allows matching fneg (fabs x) patterns)
696     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
697 
698     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
699     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
700     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
701     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
702 
703     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
704     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
705 
706     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
707     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
708   }
709 
710   if (Subtarget->hasVOP3PInsts()) {
711     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
712     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
713     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
714     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
715     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
716     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
717     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
718     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
719     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
720     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
721 
722     setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal);
723     setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal);
724     setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal);
725     setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal);
726 
727     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
728     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
729     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
730 
731     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
732     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
733 
734     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
735 
736     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
737     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
738 
739     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
740     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
741 
742     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
743     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
744     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
745     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
746     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
747     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
748 
749     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
750     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
751     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
752     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
753 
754     setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom);
755     setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom);
756     setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom);
757     setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom);
758 
759     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
760     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
761     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
762 
763     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
764     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
765 
766     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
767     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
768     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
769 
770     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
771     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
772     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
773 
774     if (Subtarget->hasPackedFP32Ops()) {
775       setOperationAction(ISD::FADD, MVT::v2f32, Legal);
776       setOperationAction(ISD::FMUL, MVT::v2f32, Legal);
777       setOperationAction(ISD::FMA,  MVT::v2f32, Legal);
778       setOperationAction(ISD::FNEG, MVT::v2f32, Legal);
779 
780       for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) {
781         setOperationAction(ISD::FADD, VT, Custom);
782         setOperationAction(ISD::FMUL, VT, Custom);
783         setOperationAction(ISD::FMA, VT, Custom);
784       }
785     }
786   }
787 
788   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
789   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
790 
791   if (Subtarget->has16BitInsts()) {
792     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
793     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
794     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
795     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
796   } else {
797     // Legalization hack.
798     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
799     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
800 
801     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
802     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
803   }
804 
805   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
806     setOperationAction(ISD::SELECT, VT, Custom);
807   }
808 
809   setOperationAction(ISD::SMULO, MVT::i64, Custom);
810   setOperationAction(ISD::UMULO, MVT::i64, Custom);
811 
812   if (Subtarget->hasMad64_32()) {
813     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
814     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
815   }
816 
817   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
818   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
819   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
820   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
821   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
822   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
823   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
824 
825   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
826   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
827   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom);
828   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom);
829   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
830   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
831   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
832   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
833   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
834   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
835   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
836 
837   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
838   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
839   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
840   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom);
841   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom);
842   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
843   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
844   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
845   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
846   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
847 
848   setTargetDAGCombine(ISD::ADD);
849   setTargetDAGCombine(ISD::ADDCARRY);
850   setTargetDAGCombine(ISD::SUB);
851   setTargetDAGCombine(ISD::SUBCARRY);
852   setTargetDAGCombine(ISD::FADD);
853   setTargetDAGCombine(ISD::FSUB);
854   setTargetDAGCombine(ISD::FMINNUM);
855   setTargetDAGCombine(ISD::FMAXNUM);
856   setTargetDAGCombine(ISD::FMINNUM_IEEE);
857   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
858   setTargetDAGCombine(ISD::FMA);
859   setTargetDAGCombine(ISD::SMIN);
860   setTargetDAGCombine(ISD::SMAX);
861   setTargetDAGCombine(ISD::UMIN);
862   setTargetDAGCombine(ISD::UMAX);
863   setTargetDAGCombine(ISD::SETCC);
864   setTargetDAGCombine(ISD::AND);
865   setTargetDAGCombine(ISD::OR);
866   setTargetDAGCombine(ISD::XOR);
867   setTargetDAGCombine(ISD::SINT_TO_FP);
868   setTargetDAGCombine(ISD::UINT_TO_FP);
869   setTargetDAGCombine(ISD::FCANONICALIZE);
870   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
871   setTargetDAGCombine(ISD::ZERO_EXTEND);
872   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
873   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
874   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
875 
876   // All memory operations. Some folding on the pointer operand is done to help
877   // matching the constant offsets in the addressing modes.
878   setTargetDAGCombine(ISD::LOAD);
879   setTargetDAGCombine(ISD::STORE);
880   setTargetDAGCombine(ISD::ATOMIC_LOAD);
881   setTargetDAGCombine(ISD::ATOMIC_STORE);
882   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
883   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
884   setTargetDAGCombine(ISD::ATOMIC_SWAP);
885   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
886   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
887   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
888   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
889   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
890   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
891   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
892   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
893   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
894   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
895   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
896   setTargetDAGCombine(ISD::INTRINSIC_VOID);
897   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
898 
899   // FIXME: In other contexts we pretend this is a per-function property.
900   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
901 
902   setSchedulingPreference(Sched::RegPressure);
903 }
904 
905 const GCNSubtarget *SITargetLowering::getSubtarget() const {
906   return Subtarget;
907 }
908 
909 //===----------------------------------------------------------------------===//
910 // TargetLowering queries
911 //===----------------------------------------------------------------------===//
912 
913 // v_mad_mix* support a conversion from f16 to f32.
914 //
915 // There is only one special case when denormals are enabled we don't currently,
916 // where this is OK to use.
917 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
918                                        EVT DestVT, EVT SrcVT) const {
919   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
920           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
921     DestVT.getScalarType() == MVT::f32 &&
922     SrcVT.getScalarType() == MVT::f16 &&
923     // TODO: This probably only requires no input flushing?
924     !hasFP32Denormals(DAG.getMachineFunction());
925 }
926 
927 bool SITargetLowering::isFPExtFoldable(const MachineInstr &MI, unsigned Opcode,
928                                        LLT DestTy, LLT SrcTy) const {
929   return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) ||
930           (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) &&
931          DestTy.getScalarSizeInBits() == 32 &&
932          SrcTy.getScalarSizeInBits() == 16 &&
933          // TODO: This probably only requires no input flushing?
934          !hasFP32Denormals(*MI.getMF());
935 }
936 
937 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
938   // SI has some legal vector types, but no legal vector operations. Say no
939   // shuffles are legal in order to prefer scalarizing some vector operations.
940   return false;
941 }
942 
943 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
944                                                     CallingConv::ID CC,
945                                                     EVT VT) const {
946   if (CC == CallingConv::AMDGPU_KERNEL)
947     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
948 
949   if (VT.isVector()) {
950     EVT ScalarVT = VT.getScalarType();
951     unsigned Size = ScalarVT.getSizeInBits();
952     if (Size == 16) {
953       if (Subtarget->has16BitInsts())
954         return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
955       return VT.isInteger() ? MVT::i32 : MVT::f32;
956     }
957 
958     if (Size < 16)
959       return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
960     return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
961   }
962 
963   if (VT.getSizeInBits() > 32)
964     return MVT::i32;
965 
966   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
967 }
968 
969 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
970                                                          CallingConv::ID CC,
971                                                          EVT VT) const {
972   if (CC == CallingConv::AMDGPU_KERNEL)
973     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
974 
975   if (VT.isVector()) {
976     unsigned NumElts = VT.getVectorNumElements();
977     EVT ScalarVT = VT.getScalarType();
978     unsigned Size = ScalarVT.getSizeInBits();
979 
980     // FIXME: Should probably promote 8-bit vectors to i16.
981     if (Size == 16 && Subtarget->has16BitInsts())
982       return (NumElts + 1) / 2;
983 
984     if (Size <= 32)
985       return NumElts;
986 
987     if (Size > 32)
988       return NumElts * ((Size + 31) / 32);
989   } else if (VT.getSizeInBits() > 32)
990     return (VT.getSizeInBits() + 31) / 32;
991 
992   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
993 }
994 
995 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
996   LLVMContext &Context, CallingConv::ID CC,
997   EVT VT, EVT &IntermediateVT,
998   unsigned &NumIntermediates, MVT &RegisterVT) const {
999   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
1000     unsigned NumElts = VT.getVectorNumElements();
1001     EVT ScalarVT = VT.getScalarType();
1002     unsigned Size = ScalarVT.getSizeInBits();
1003     // FIXME: We should fix the ABI to be the same on targets without 16-bit
1004     // support, but unless we can properly handle 3-vectors, it will be still be
1005     // inconsistent.
1006     if (Size == 16 && Subtarget->has16BitInsts()) {
1007       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
1008       IntermediateVT = RegisterVT;
1009       NumIntermediates = (NumElts + 1) / 2;
1010       return NumIntermediates;
1011     }
1012 
1013     if (Size == 32) {
1014       RegisterVT = ScalarVT.getSimpleVT();
1015       IntermediateVT = RegisterVT;
1016       NumIntermediates = NumElts;
1017       return NumIntermediates;
1018     }
1019 
1020     if (Size < 16 && Subtarget->has16BitInsts()) {
1021       // FIXME: Should probably form v2i16 pieces
1022       RegisterVT = MVT::i16;
1023       IntermediateVT = ScalarVT;
1024       NumIntermediates = NumElts;
1025       return NumIntermediates;
1026     }
1027 
1028 
1029     if (Size != 16 && Size <= 32) {
1030       RegisterVT = MVT::i32;
1031       IntermediateVT = ScalarVT;
1032       NumIntermediates = NumElts;
1033       return NumIntermediates;
1034     }
1035 
1036     if (Size > 32) {
1037       RegisterVT = MVT::i32;
1038       IntermediateVT = RegisterVT;
1039       NumIntermediates = NumElts * ((Size + 31) / 32);
1040       return NumIntermediates;
1041     }
1042   }
1043 
1044   return TargetLowering::getVectorTypeBreakdownForCallingConv(
1045     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
1046 }
1047 
1048 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
1049   assert(DMaskLanes != 0);
1050 
1051   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1052     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
1053     return EVT::getVectorVT(Ty->getContext(),
1054                             EVT::getEVT(VT->getElementType()),
1055                             NumElts);
1056   }
1057 
1058   return EVT::getEVT(Ty);
1059 }
1060 
1061 // Peek through TFE struct returns to only use the data size.
1062 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
1063   auto *ST = dyn_cast<StructType>(Ty);
1064   if (!ST)
1065     return memVTFromImageData(Ty, DMaskLanes);
1066 
1067   // Some intrinsics return an aggregate type - special case to work out the
1068   // correct memVT.
1069   //
1070   // Only limited forms of aggregate type currently expected.
1071   if (ST->getNumContainedTypes() != 2 ||
1072       !ST->getContainedType(1)->isIntegerTy(32))
1073     return EVT();
1074   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
1075 }
1076 
1077 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1078                                           const CallInst &CI,
1079                                           MachineFunction &MF,
1080                                           unsigned IntrID) const {
1081   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1082           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1083     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1084                                                   (Intrinsic::ID)IntrID);
1085     if (Attr.hasFnAttr(Attribute::ReadNone))
1086       return false;
1087 
1088     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1089 
1090     if (RsrcIntr->IsImage) {
1091       Info.ptrVal =
1092           MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1093       Info.align.reset();
1094     } else {
1095       Info.ptrVal =
1096           MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1097     }
1098 
1099     Info.flags = MachineMemOperand::MODereferenceable;
1100     if (Attr.hasFnAttr(Attribute::ReadOnly)) {
1101       unsigned DMaskLanes = 4;
1102 
1103       if (RsrcIntr->IsImage) {
1104         const AMDGPU::ImageDimIntrinsicInfo *Intr
1105           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1106         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1107           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1108 
1109         if (!BaseOpcode->Gather4) {
1110           // If this isn't a gather, we may have excess loaded elements in the
1111           // IR type. Check the dmask for the real number of elements loaded.
1112           unsigned DMask
1113             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1114           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1115         }
1116 
1117         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1118       } else
1119         Info.memVT = EVT::getEVT(CI.getType());
1120 
1121       // FIXME: What does alignment mean for an image?
1122       Info.opc = ISD::INTRINSIC_W_CHAIN;
1123       Info.flags |= MachineMemOperand::MOLoad;
1124     } else if (Attr.hasFnAttr(Attribute::WriteOnly)) {
1125       Info.opc = ISD::INTRINSIC_VOID;
1126 
1127       Type *DataTy = CI.getArgOperand(0)->getType();
1128       if (RsrcIntr->IsImage) {
1129         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1130         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1131         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1132       } else
1133         Info.memVT = EVT::getEVT(DataTy);
1134 
1135       Info.flags |= MachineMemOperand::MOStore;
1136     } else {
1137       // Atomic
1138       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1139                                             ISD::INTRINSIC_W_CHAIN;
1140       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1141       Info.flags = MachineMemOperand::MOLoad |
1142                    MachineMemOperand::MOStore |
1143                    MachineMemOperand::MODereferenceable;
1144 
1145       // XXX - Should this be volatile without known ordering?
1146       Info.flags |= MachineMemOperand::MOVolatile;
1147     }
1148     return true;
1149   }
1150 
1151   switch (IntrID) {
1152   case Intrinsic::amdgcn_atomic_inc:
1153   case Intrinsic::amdgcn_atomic_dec:
1154   case Intrinsic::amdgcn_ds_ordered_add:
1155   case Intrinsic::amdgcn_ds_ordered_swap:
1156   case Intrinsic::amdgcn_ds_fadd:
1157   case Intrinsic::amdgcn_ds_fmin:
1158   case Intrinsic::amdgcn_ds_fmax: {
1159     Info.opc = ISD::INTRINSIC_W_CHAIN;
1160     Info.memVT = MVT::getVT(CI.getType());
1161     Info.ptrVal = CI.getOperand(0);
1162     Info.align.reset();
1163     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1164 
1165     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1166     if (!Vol->isZero())
1167       Info.flags |= MachineMemOperand::MOVolatile;
1168 
1169     return true;
1170   }
1171   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1172     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1173 
1174     Info.opc = ISD::INTRINSIC_W_CHAIN;
1175     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1176     Info.ptrVal =
1177         MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1178     Info.align.reset();
1179     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1180 
1181     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1182     if (!Vol || !Vol->isZero())
1183       Info.flags |= MachineMemOperand::MOVolatile;
1184 
1185     return true;
1186   }
1187   case Intrinsic::amdgcn_ds_append:
1188   case Intrinsic::amdgcn_ds_consume: {
1189     Info.opc = ISD::INTRINSIC_W_CHAIN;
1190     Info.memVT = MVT::getVT(CI.getType());
1191     Info.ptrVal = CI.getOperand(0);
1192     Info.align.reset();
1193     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1194 
1195     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1196     if (!Vol->isZero())
1197       Info.flags |= MachineMemOperand::MOVolatile;
1198 
1199     return true;
1200   }
1201   case Intrinsic::amdgcn_global_atomic_csub: {
1202     Info.opc = ISD::INTRINSIC_W_CHAIN;
1203     Info.memVT = MVT::getVT(CI.getType());
1204     Info.ptrVal = CI.getOperand(0);
1205     Info.align.reset();
1206     Info.flags = MachineMemOperand::MOLoad |
1207                  MachineMemOperand::MOStore |
1208                  MachineMemOperand::MOVolatile;
1209     return true;
1210   }
1211   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1212     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1213     Info.opc = ISD::INTRINSIC_W_CHAIN;
1214     Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1215     Info.ptrVal =
1216         MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1217     Info.align.reset();
1218     Info.flags = MachineMemOperand::MOLoad |
1219                  MachineMemOperand::MODereferenceable;
1220     return true;
1221   }
1222   case Intrinsic::amdgcn_global_atomic_fadd:
1223   case Intrinsic::amdgcn_global_atomic_fmin:
1224   case Intrinsic::amdgcn_global_atomic_fmax:
1225   case Intrinsic::amdgcn_flat_atomic_fadd:
1226   case Intrinsic::amdgcn_flat_atomic_fmin:
1227   case Intrinsic::amdgcn_flat_atomic_fmax: {
1228     Info.opc = ISD::INTRINSIC_W_CHAIN;
1229     Info.memVT = MVT::getVT(CI.getType());
1230     Info.ptrVal = CI.getOperand(0);
1231     Info.align.reset();
1232     Info.flags = MachineMemOperand::MOLoad |
1233                  MachineMemOperand::MOStore |
1234                  MachineMemOperand::MODereferenceable |
1235                  MachineMemOperand::MOVolatile;
1236     return true;
1237   }
1238   case Intrinsic::amdgcn_ds_gws_init:
1239   case Intrinsic::amdgcn_ds_gws_barrier:
1240   case Intrinsic::amdgcn_ds_gws_sema_v:
1241   case Intrinsic::amdgcn_ds_gws_sema_br:
1242   case Intrinsic::amdgcn_ds_gws_sema_p:
1243   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1244     Info.opc = ISD::INTRINSIC_VOID;
1245 
1246     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1247     Info.ptrVal =
1248         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1249 
1250     // This is an abstract access, but we need to specify a type and size.
1251     Info.memVT = MVT::i32;
1252     Info.size = 4;
1253     Info.align = Align(4);
1254 
1255     Info.flags = MachineMemOperand::MOStore;
1256     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1257       Info.flags = MachineMemOperand::MOLoad;
1258     return true;
1259   }
1260   default:
1261     return false;
1262   }
1263 }
1264 
1265 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1266                                             SmallVectorImpl<Value*> &Ops,
1267                                             Type *&AccessTy) const {
1268   switch (II->getIntrinsicID()) {
1269   case Intrinsic::amdgcn_atomic_inc:
1270   case Intrinsic::amdgcn_atomic_dec:
1271   case Intrinsic::amdgcn_ds_ordered_add:
1272   case Intrinsic::amdgcn_ds_ordered_swap:
1273   case Intrinsic::amdgcn_ds_append:
1274   case Intrinsic::amdgcn_ds_consume:
1275   case Intrinsic::amdgcn_ds_fadd:
1276   case Intrinsic::amdgcn_ds_fmin:
1277   case Intrinsic::amdgcn_ds_fmax:
1278   case Intrinsic::amdgcn_global_atomic_fadd:
1279   case Intrinsic::amdgcn_flat_atomic_fadd:
1280   case Intrinsic::amdgcn_flat_atomic_fmin:
1281   case Intrinsic::amdgcn_flat_atomic_fmax:
1282   case Intrinsic::amdgcn_global_atomic_csub: {
1283     Value *Ptr = II->getArgOperand(0);
1284     AccessTy = II->getType();
1285     Ops.push_back(Ptr);
1286     return true;
1287   }
1288   default:
1289     return false;
1290   }
1291 }
1292 
1293 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1294   if (!Subtarget->hasFlatInstOffsets()) {
1295     // Flat instructions do not have offsets, and only have the register
1296     // address.
1297     return AM.BaseOffs == 0 && AM.Scale == 0;
1298   }
1299 
1300   return AM.Scale == 0 &&
1301          (AM.BaseOffs == 0 ||
1302           Subtarget->getInstrInfo()->isLegalFLATOffset(
1303               AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT));
1304 }
1305 
1306 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1307   if (Subtarget->hasFlatGlobalInsts())
1308     return AM.Scale == 0 &&
1309            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1310                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1311                                     SIInstrFlags::FlatGlobal));
1312 
1313   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1314       // Assume the we will use FLAT for all global memory accesses
1315       // on VI.
1316       // FIXME: This assumption is currently wrong.  On VI we still use
1317       // MUBUF instructions for the r + i addressing mode.  As currently
1318       // implemented, the MUBUF instructions only work on buffer < 4GB.
1319       // It may be possible to support > 4GB buffers with MUBUF instructions,
1320       // by setting the stride value in the resource descriptor which would
1321       // increase the size limit to (stride * 4GB).  However, this is risky,
1322       // because it has never been validated.
1323     return isLegalFlatAddressingMode(AM);
1324   }
1325 
1326   return isLegalMUBUFAddressingMode(AM);
1327 }
1328 
1329 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1330   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1331   // additionally can do r + r + i with addr64. 32-bit has more addressing
1332   // mode options. Depending on the resource constant, it can also do
1333   // (i64 r0) + (i32 r1) * (i14 i).
1334   //
1335   // Private arrays end up using a scratch buffer most of the time, so also
1336   // assume those use MUBUF instructions. Scratch loads / stores are currently
1337   // implemented as mubuf instructions with offen bit set, so slightly
1338   // different than the normal addr64.
1339   if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1340     return false;
1341 
1342   // FIXME: Since we can split immediate into soffset and immediate offset,
1343   // would it make sense to allow any immediate?
1344 
1345   switch (AM.Scale) {
1346   case 0: // r + i or just i, depending on HasBaseReg.
1347     return true;
1348   case 1:
1349     return true; // We have r + r or r + i.
1350   case 2:
1351     if (AM.HasBaseReg) {
1352       // Reject 2 * r + r.
1353       return false;
1354     }
1355 
1356     // Allow 2 * r as r + r
1357     // Or  2 * r + i is allowed as r + r + i.
1358     return true;
1359   default: // Don't allow n * r
1360     return false;
1361   }
1362 }
1363 
1364 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1365                                              const AddrMode &AM, Type *Ty,
1366                                              unsigned AS, Instruction *I) const {
1367   // No global is ever allowed as a base.
1368   if (AM.BaseGV)
1369     return false;
1370 
1371   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1372     return isLegalGlobalAddressingMode(AM);
1373 
1374   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1375       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1376       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1377     // If the offset isn't a multiple of 4, it probably isn't going to be
1378     // correctly aligned.
1379     // FIXME: Can we get the real alignment here?
1380     if (AM.BaseOffs % 4 != 0)
1381       return isLegalMUBUFAddressingMode(AM);
1382 
1383     // There are no SMRD extloads, so if we have to do a small type access we
1384     // will use a MUBUF load.
1385     // FIXME?: We also need to do this if unaligned, but we don't know the
1386     // alignment here.
1387     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1388       return isLegalGlobalAddressingMode(AM);
1389 
1390     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1391       // SMRD instructions have an 8-bit, dword offset on SI.
1392       if (!isUInt<8>(AM.BaseOffs / 4))
1393         return false;
1394     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1395       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1396       // in 8-bits, it can use a smaller encoding.
1397       if (!isUInt<32>(AM.BaseOffs / 4))
1398         return false;
1399     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1400       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1401       if (!isUInt<20>(AM.BaseOffs))
1402         return false;
1403     } else
1404       llvm_unreachable("unhandled generation");
1405 
1406     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1407       return true;
1408 
1409     if (AM.Scale == 1 && AM.HasBaseReg)
1410       return true;
1411 
1412     return false;
1413 
1414   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1415     return isLegalMUBUFAddressingMode(AM);
1416   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1417              AS == AMDGPUAS::REGION_ADDRESS) {
1418     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1419     // field.
1420     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1421     // an 8-bit dword offset but we don't know the alignment here.
1422     if (!isUInt<16>(AM.BaseOffs))
1423       return false;
1424 
1425     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1426       return true;
1427 
1428     if (AM.Scale == 1 && AM.HasBaseReg)
1429       return true;
1430 
1431     return false;
1432   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1433              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1434     // For an unknown address space, this usually means that this is for some
1435     // reason being used for pure arithmetic, and not based on some addressing
1436     // computation. We don't have instructions that compute pointers with any
1437     // addressing modes, so treat them as having no offset like flat
1438     // instructions.
1439     return isLegalFlatAddressingMode(AM);
1440   }
1441 
1442   // Assume a user alias of global for unknown address spaces.
1443   return isLegalGlobalAddressingMode(AM);
1444 }
1445 
1446 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1447                                         const MachineFunction &MF) const {
1448   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1449     return (MemVT.getSizeInBits() <= 4 * 32);
1450   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1451     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1452     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1453   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1454     return (MemVT.getSizeInBits() <= 2 * 32);
1455   }
1456   return true;
1457 }
1458 
1459 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1460     unsigned Size, unsigned AddrSpace, Align Alignment,
1461     MachineMemOperand::Flags Flags, bool *IsFast) const {
1462   if (IsFast)
1463     *IsFast = false;
1464 
1465   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1466       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1467     // Check if alignment requirements for ds_read/write instructions are
1468     // disabled.
1469     if (Subtarget->hasUnalignedDSAccessEnabled() &&
1470         !Subtarget->hasLDSMisalignedBug()) {
1471       if (IsFast)
1472         *IsFast = Alignment != Align(2);
1473       return true;
1474     }
1475 
1476     // Either, the alignment requirements are "enabled", or there is an
1477     // unaligned LDS access related hardware bug though alignment requirements
1478     // are "disabled". In either case, we need to check for proper alignment
1479     // requirements.
1480     //
1481     if (Size == 64) {
1482       // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
1483       // can do a 4 byte aligned, 8 byte access in a single operation using
1484       // ds_read2/write2_b32 with adjacent offsets.
1485       bool AlignedBy4 = Alignment >= Align(4);
1486       if (IsFast)
1487         *IsFast = AlignedBy4;
1488 
1489       return AlignedBy4;
1490     }
1491     if (Size == 96) {
1492       // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
1493       // gfx8 and older.
1494       bool AlignedBy16 = Alignment >= Align(16);
1495       if (IsFast)
1496         *IsFast = AlignedBy16;
1497 
1498       return AlignedBy16;
1499     }
1500     if (Size == 128) {
1501       // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
1502       // gfx8 and older, but  we can do a 8 byte aligned, 16 byte access in a
1503       // single operation using ds_read2/write2_b64.
1504       bool AlignedBy8 = Alignment >= Align(8);
1505       if (IsFast)
1506         *IsFast = AlignedBy8;
1507 
1508       return AlignedBy8;
1509     }
1510   }
1511 
1512   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1513     bool AlignedBy4 = Alignment >= Align(4);
1514     if (IsFast)
1515       *IsFast = AlignedBy4;
1516 
1517     return AlignedBy4 ||
1518            Subtarget->enableFlatScratch() ||
1519            Subtarget->hasUnalignedScratchAccess();
1520   }
1521 
1522   // FIXME: We have to be conservative here and assume that flat operations
1523   // will access scratch.  If we had access to the IR function, then we
1524   // could determine if any private memory was used in the function.
1525   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1526       !Subtarget->hasUnalignedScratchAccess()) {
1527     bool AlignedBy4 = Alignment >= Align(4);
1528     if (IsFast)
1529       *IsFast = AlignedBy4;
1530 
1531     return AlignedBy4;
1532   }
1533 
1534   if (Subtarget->hasUnalignedBufferAccessEnabled() &&
1535       !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1536         AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1537     // If we have an uniform constant load, it still requires using a slow
1538     // buffer instruction if unaligned.
1539     if (IsFast) {
1540       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1541       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1542       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1543                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1544         Alignment >= Align(4) : Alignment != Align(2);
1545     }
1546 
1547     return true;
1548   }
1549 
1550   // Smaller than dword value must be aligned.
1551   if (Size < 32)
1552     return false;
1553 
1554   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1555   // byte-address are ignored, thus forcing Dword alignment.
1556   // This applies to private, global, and constant memory.
1557   if (IsFast)
1558     *IsFast = true;
1559 
1560   return Size >= 32 && Alignment >= Align(4);
1561 }
1562 
1563 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1564     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1565     bool *IsFast) const {
1566   if (IsFast)
1567     *IsFast = false;
1568 
1569   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1570   // which isn't a simple VT.
1571   // Until MVT is extended to handle this, simply check for the size and
1572   // rely on the condition below: allow accesses if the size is a multiple of 4.
1573   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1574                            VT.getStoreSize() > 16)) {
1575     return false;
1576   }
1577 
1578   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1579                                             Alignment, Flags, IsFast);
1580 }
1581 
1582 EVT SITargetLowering::getOptimalMemOpType(
1583     const MemOp &Op, const AttributeList &FuncAttributes) const {
1584   // FIXME: Should account for address space here.
1585 
1586   // The default fallback uses the private pointer size as a guess for a type to
1587   // use. Make sure we switch these to 64-bit accesses.
1588 
1589   if (Op.size() >= 16 &&
1590       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1591     return MVT::v4i32;
1592 
1593   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1594     return MVT::v2i32;
1595 
1596   // Use the default.
1597   return MVT::Other;
1598 }
1599 
1600 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1601   const MemSDNode *MemNode = cast<MemSDNode>(N);
1602   const Value *Ptr = MemNode->getMemOperand()->getValue();
1603   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1604   return I && I->getMetadata("amdgpu.noclobber");
1605 }
1606 
1607 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1608   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1609          AS == AMDGPUAS::PRIVATE_ADDRESS;
1610 }
1611 
1612 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1613                                            unsigned DestAS) const {
1614   // Flat -> private/local is a simple truncate.
1615   // Flat -> global is no-op
1616   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1617     return true;
1618 
1619   const GCNTargetMachine &TM =
1620       static_cast<const GCNTargetMachine &>(getTargetMachine());
1621   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1622 }
1623 
1624 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1625   const MemSDNode *MemNode = cast<MemSDNode>(N);
1626 
1627   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1628 }
1629 
1630 TargetLoweringBase::LegalizeTypeAction
1631 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1632   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1633       VT.getScalarType().bitsLE(MVT::i16))
1634     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1635   return TargetLoweringBase::getPreferredVectorAction(VT);
1636 }
1637 
1638 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1639                                                          Type *Ty) const {
1640   // FIXME: Could be smarter if called for vector constants.
1641   return true;
1642 }
1643 
1644 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1645   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1646     switch (Op) {
1647     case ISD::LOAD:
1648     case ISD::STORE:
1649 
1650     // These operations are done with 32-bit instructions anyway.
1651     case ISD::AND:
1652     case ISD::OR:
1653     case ISD::XOR:
1654     case ISD::SELECT:
1655       // TODO: Extensions?
1656       return true;
1657     default:
1658       return false;
1659     }
1660   }
1661 
1662   // SimplifySetCC uses this function to determine whether or not it should
1663   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1664   if (VT == MVT::i1 && Op == ISD::SETCC)
1665     return false;
1666 
1667   return TargetLowering::isTypeDesirableForOp(Op, VT);
1668 }
1669 
1670 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1671                                                    const SDLoc &SL,
1672                                                    SDValue Chain,
1673                                                    uint64_t Offset) const {
1674   const DataLayout &DL = DAG.getDataLayout();
1675   MachineFunction &MF = DAG.getMachineFunction();
1676   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1677 
1678   const ArgDescriptor *InputPtrReg;
1679   const TargetRegisterClass *RC;
1680   LLT ArgTy;
1681   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1682 
1683   std::tie(InputPtrReg, RC, ArgTy) =
1684       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1685 
1686   // We may not have the kernarg segment argument if we have no kernel
1687   // arguments.
1688   if (!InputPtrReg)
1689     return DAG.getConstant(0, SL, PtrVT);
1690 
1691   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1692   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1693     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1694 
1695   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1696 }
1697 
1698 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1699                                             const SDLoc &SL) const {
1700   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1701                                                FIRST_IMPLICIT);
1702   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1703 }
1704 
1705 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1706                                          const SDLoc &SL, SDValue Val,
1707                                          bool Signed,
1708                                          const ISD::InputArg *Arg) const {
1709   // First, if it is a widened vector, narrow it.
1710   if (VT.isVector() &&
1711       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1712     EVT NarrowedVT =
1713         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1714                          VT.getVectorNumElements());
1715     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1716                       DAG.getConstant(0, SL, MVT::i32));
1717   }
1718 
1719   // Then convert the vector elements or scalar value.
1720   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1721       VT.bitsLT(MemVT)) {
1722     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1723     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1724   }
1725 
1726   if (MemVT.isFloatingPoint())
1727     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1728   else if (Signed)
1729     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1730   else
1731     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1732 
1733   return Val;
1734 }
1735 
1736 SDValue SITargetLowering::lowerKernargMemParameter(
1737     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1738     uint64_t Offset, Align Alignment, bool Signed,
1739     const ISD::InputArg *Arg) const {
1740   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1741 
1742   // Try to avoid using an extload by loading earlier than the argument address,
1743   // and extracting the relevant bits. The load should hopefully be merged with
1744   // the previous argument.
1745   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1746     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1747     int64_t AlignDownOffset = alignDown(Offset, 4);
1748     int64_t OffsetDiff = Offset - AlignDownOffset;
1749 
1750     EVT IntVT = MemVT.changeTypeToInteger();
1751 
1752     // TODO: If we passed in the base kernel offset we could have a better
1753     // alignment than 4, but we don't really need it.
1754     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1755     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1756                                MachineMemOperand::MODereferenceable |
1757                                    MachineMemOperand::MOInvariant);
1758 
1759     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1760     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1761 
1762     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1763     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1764     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1765 
1766 
1767     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1768   }
1769 
1770   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1771   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1772                              MachineMemOperand::MODereferenceable |
1773                                  MachineMemOperand::MOInvariant);
1774 
1775   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1776   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1777 }
1778 
1779 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1780                                               const SDLoc &SL, SDValue Chain,
1781                                               const ISD::InputArg &Arg) const {
1782   MachineFunction &MF = DAG.getMachineFunction();
1783   MachineFrameInfo &MFI = MF.getFrameInfo();
1784 
1785   if (Arg.Flags.isByVal()) {
1786     unsigned Size = Arg.Flags.getByValSize();
1787     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1788     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1789   }
1790 
1791   unsigned ArgOffset = VA.getLocMemOffset();
1792   unsigned ArgSize = VA.getValVT().getStoreSize();
1793 
1794   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1795 
1796   // Create load nodes to retrieve arguments from the stack.
1797   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1798   SDValue ArgValue;
1799 
1800   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1801   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1802   MVT MemVT = VA.getValVT();
1803 
1804   switch (VA.getLocInfo()) {
1805   default:
1806     break;
1807   case CCValAssign::BCvt:
1808     MemVT = VA.getLocVT();
1809     break;
1810   case CCValAssign::SExt:
1811     ExtType = ISD::SEXTLOAD;
1812     break;
1813   case CCValAssign::ZExt:
1814     ExtType = ISD::ZEXTLOAD;
1815     break;
1816   case CCValAssign::AExt:
1817     ExtType = ISD::EXTLOAD;
1818     break;
1819   }
1820 
1821   ArgValue = DAG.getExtLoad(
1822     ExtType, SL, VA.getLocVT(), Chain, FIN,
1823     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1824     MemVT);
1825   return ArgValue;
1826 }
1827 
1828 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1829   const SIMachineFunctionInfo &MFI,
1830   EVT VT,
1831   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1832   const ArgDescriptor *Reg;
1833   const TargetRegisterClass *RC;
1834   LLT Ty;
1835 
1836   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1837   if (!Reg) {
1838     if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) {
1839       // It's possible for a kernarg intrinsic call to appear in a kernel with
1840       // no allocated segment, in which case we do not add the user sgpr
1841       // argument, so just return null.
1842       return DAG.getConstant(0, SDLoc(), VT);
1843     }
1844 
1845     // It's undefined behavior if a function marked with the amdgpu-no-*
1846     // attributes uses the corresponding intrinsic.
1847     return DAG.getUNDEF(VT);
1848   }
1849 
1850   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1851 }
1852 
1853 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1854                                CallingConv::ID CallConv,
1855                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1856                                FunctionType *FType,
1857                                SIMachineFunctionInfo *Info) {
1858   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1859     const ISD::InputArg *Arg = &Ins[I];
1860 
1861     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1862            "vector type argument should have been split");
1863 
1864     // First check if it's a PS input addr.
1865     if (CallConv == CallingConv::AMDGPU_PS &&
1866         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1867       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1868 
1869       // Inconveniently only the first part of the split is marked as isSplit,
1870       // so skip to the end. We only want to increment PSInputNum once for the
1871       // entire split argument.
1872       if (Arg->Flags.isSplit()) {
1873         while (!Arg->Flags.isSplitEnd()) {
1874           assert((!Arg->VT.isVector() ||
1875                   Arg->VT.getScalarSizeInBits() == 16) &&
1876                  "unexpected vector split in ps argument type");
1877           if (!SkipArg)
1878             Splits.push_back(*Arg);
1879           Arg = &Ins[++I];
1880         }
1881       }
1882 
1883       if (SkipArg) {
1884         // We can safely skip PS inputs.
1885         Skipped.set(Arg->getOrigArgIndex());
1886         ++PSInputNum;
1887         continue;
1888       }
1889 
1890       Info->markPSInputAllocated(PSInputNum);
1891       if (Arg->Used)
1892         Info->markPSInputEnabled(PSInputNum);
1893 
1894       ++PSInputNum;
1895     }
1896 
1897     Splits.push_back(*Arg);
1898   }
1899 }
1900 
1901 // Allocate special inputs passed in VGPRs.
1902 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1903                                                       MachineFunction &MF,
1904                                                       const SIRegisterInfo &TRI,
1905                                                       SIMachineFunctionInfo &Info) const {
1906   const LLT S32 = LLT::scalar(32);
1907   MachineRegisterInfo &MRI = MF.getRegInfo();
1908 
1909   if (Info.hasWorkItemIDX()) {
1910     Register Reg = AMDGPU::VGPR0;
1911     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1912 
1913     CCInfo.AllocateReg(Reg);
1914     unsigned Mask = (Subtarget->hasPackedTID() &&
1915                      Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
1916     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1917   }
1918 
1919   if (Info.hasWorkItemIDY()) {
1920     assert(Info.hasWorkItemIDX());
1921     if (Subtarget->hasPackedTID()) {
1922       Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1923                                                         0x3ff << 10));
1924     } else {
1925       unsigned Reg = AMDGPU::VGPR1;
1926       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1927 
1928       CCInfo.AllocateReg(Reg);
1929       Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1930     }
1931   }
1932 
1933   if (Info.hasWorkItemIDZ()) {
1934     assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
1935     if (Subtarget->hasPackedTID()) {
1936       Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1937                                                         0x3ff << 20));
1938     } else {
1939       unsigned Reg = AMDGPU::VGPR2;
1940       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1941 
1942       CCInfo.AllocateReg(Reg);
1943       Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1944     }
1945   }
1946 }
1947 
1948 // Try to allocate a VGPR at the end of the argument list, or if no argument
1949 // VGPRs are left allocating a stack slot.
1950 // If \p Mask is is given it indicates bitfield position in the register.
1951 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1952 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1953                                          ArgDescriptor Arg = ArgDescriptor()) {
1954   if (Arg.isSet())
1955     return ArgDescriptor::createArg(Arg, Mask);
1956 
1957   ArrayRef<MCPhysReg> ArgVGPRs
1958     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1959   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1960   if (RegIdx == ArgVGPRs.size()) {
1961     // Spill to stack required.
1962     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1963 
1964     return ArgDescriptor::createStack(Offset, Mask);
1965   }
1966 
1967   unsigned Reg = ArgVGPRs[RegIdx];
1968   Reg = CCInfo.AllocateReg(Reg);
1969   assert(Reg != AMDGPU::NoRegister);
1970 
1971   MachineFunction &MF = CCInfo.getMachineFunction();
1972   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1973   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1974   return ArgDescriptor::createRegister(Reg, Mask);
1975 }
1976 
1977 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1978                                              const TargetRegisterClass *RC,
1979                                              unsigned NumArgRegs) {
1980   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1981   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1982   if (RegIdx == ArgSGPRs.size())
1983     report_fatal_error("ran out of SGPRs for arguments");
1984 
1985   unsigned Reg = ArgSGPRs[RegIdx];
1986   Reg = CCInfo.AllocateReg(Reg);
1987   assert(Reg != AMDGPU::NoRegister);
1988 
1989   MachineFunction &MF = CCInfo.getMachineFunction();
1990   MF.addLiveIn(Reg, RC);
1991   return ArgDescriptor::createRegister(Reg);
1992 }
1993 
1994 // If this has a fixed position, we still should allocate the register in the
1995 // CCInfo state. Technically we could get away with this for values passed
1996 // outside of the normal argument range.
1997 static void allocateFixedSGPRInputImpl(CCState &CCInfo,
1998                                        const TargetRegisterClass *RC,
1999                                        MCRegister Reg) {
2000   Reg = CCInfo.AllocateReg(Reg);
2001   assert(Reg != AMDGPU::NoRegister);
2002   MachineFunction &MF = CCInfo.getMachineFunction();
2003   MF.addLiveIn(Reg, RC);
2004 }
2005 
2006 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
2007   if (Arg) {
2008     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
2009                                Arg.getRegister());
2010   } else
2011     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
2012 }
2013 
2014 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
2015   if (Arg) {
2016     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
2017                                Arg.getRegister());
2018   } else
2019     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
2020 }
2021 
2022 /// Allocate implicit function VGPR arguments at the end of allocated user
2023 /// arguments.
2024 void SITargetLowering::allocateSpecialInputVGPRs(
2025   CCState &CCInfo, MachineFunction &MF,
2026   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2027   const unsigned Mask = 0x3ff;
2028   ArgDescriptor Arg;
2029 
2030   if (Info.hasWorkItemIDX()) {
2031     Arg = allocateVGPR32Input(CCInfo, Mask);
2032     Info.setWorkItemIDX(Arg);
2033   }
2034 
2035   if (Info.hasWorkItemIDY()) {
2036     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
2037     Info.setWorkItemIDY(Arg);
2038   }
2039 
2040   if (Info.hasWorkItemIDZ())
2041     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
2042 }
2043 
2044 /// Allocate implicit function VGPR arguments in fixed registers.
2045 void SITargetLowering::allocateSpecialInputVGPRsFixed(
2046   CCState &CCInfo, MachineFunction &MF,
2047   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2048   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
2049   if (!Reg)
2050     report_fatal_error("failed to allocated VGPR for implicit arguments");
2051 
2052   const unsigned Mask = 0x3ff;
2053   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2054   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
2055   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
2056 }
2057 
2058 void SITargetLowering::allocateSpecialInputSGPRs(
2059   CCState &CCInfo,
2060   MachineFunction &MF,
2061   const SIRegisterInfo &TRI,
2062   SIMachineFunctionInfo &Info) const {
2063   auto &ArgInfo = Info.getArgInfo();
2064 
2065   // We need to allocate these in place regardless of their use.
2066   const bool IsFixed = AMDGPUTargetMachine::EnableFixedFunctionABI;
2067 
2068   // TODO: Unify handling with private memory pointers.
2069   if (IsFixed || Info.hasDispatchPtr())
2070     allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
2071 
2072   if (IsFixed || Info.hasQueuePtr())
2073     allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
2074 
2075   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
2076   // constant offset from the kernarg segment.
2077   if (IsFixed || Info.hasImplicitArgPtr())
2078     allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
2079 
2080   if (IsFixed || Info.hasDispatchID())
2081     allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2082 
2083   // flat_scratch_init is not applicable for non-kernel functions.
2084 
2085   if (IsFixed || Info.hasWorkGroupIDX())
2086     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2087 
2088   if (IsFixed || Info.hasWorkGroupIDY())
2089     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2090 
2091   if (IsFixed || Info.hasWorkGroupIDZ())
2092     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2093 }
2094 
2095 // Allocate special inputs passed in user SGPRs.
2096 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2097                                             MachineFunction &MF,
2098                                             const SIRegisterInfo &TRI,
2099                                             SIMachineFunctionInfo &Info) const {
2100   if (Info.hasImplicitBufferPtr()) {
2101     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2102     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2103     CCInfo.AllocateReg(ImplicitBufferPtrReg);
2104   }
2105 
2106   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2107   if (Info.hasPrivateSegmentBuffer()) {
2108     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2109     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2110     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2111   }
2112 
2113   if (Info.hasDispatchPtr()) {
2114     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2115     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2116     CCInfo.AllocateReg(DispatchPtrReg);
2117   }
2118 
2119   if (Info.hasQueuePtr()) {
2120     Register QueuePtrReg = Info.addQueuePtr(TRI);
2121     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2122     CCInfo.AllocateReg(QueuePtrReg);
2123   }
2124 
2125   if (Info.hasKernargSegmentPtr()) {
2126     MachineRegisterInfo &MRI = MF.getRegInfo();
2127     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2128     CCInfo.AllocateReg(InputPtrReg);
2129 
2130     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2131     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2132   }
2133 
2134   if (Info.hasDispatchID()) {
2135     Register DispatchIDReg = Info.addDispatchID(TRI);
2136     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2137     CCInfo.AllocateReg(DispatchIDReg);
2138   }
2139 
2140   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2141     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2142     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2143     CCInfo.AllocateReg(FlatScratchInitReg);
2144   }
2145 
2146   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2147   // these from the dispatch pointer.
2148 }
2149 
2150 // Allocate special input registers that are initialized per-wave.
2151 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2152                                            MachineFunction &MF,
2153                                            SIMachineFunctionInfo &Info,
2154                                            CallingConv::ID CallConv,
2155                                            bool IsShader) const {
2156   if (Info.hasWorkGroupIDX()) {
2157     Register Reg = Info.addWorkGroupIDX();
2158     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2159     CCInfo.AllocateReg(Reg);
2160   }
2161 
2162   if (Info.hasWorkGroupIDY()) {
2163     Register Reg = Info.addWorkGroupIDY();
2164     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2165     CCInfo.AllocateReg(Reg);
2166   }
2167 
2168   if (Info.hasWorkGroupIDZ()) {
2169     Register Reg = Info.addWorkGroupIDZ();
2170     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2171     CCInfo.AllocateReg(Reg);
2172   }
2173 
2174   if (Info.hasWorkGroupInfo()) {
2175     Register Reg = Info.addWorkGroupInfo();
2176     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2177     CCInfo.AllocateReg(Reg);
2178   }
2179 
2180   if (Info.hasPrivateSegmentWaveByteOffset()) {
2181     // Scratch wave offset passed in system SGPR.
2182     unsigned PrivateSegmentWaveByteOffsetReg;
2183 
2184     if (IsShader) {
2185       PrivateSegmentWaveByteOffsetReg =
2186         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2187 
2188       // This is true if the scratch wave byte offset doesn't have a fixed
2189       // location.
2190       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2191         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2192         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2193       }
2194     } else
2195       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2196 
2197     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2198     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2199   }
2200 }
2201 
2202 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2203                                      MachineFunction &MF,
2204                                      const SIRegisterInfo &TRI,
2205                                      SIMachineFunctionInfo &Info) {
2206   // Now that we've figured out where the scratch register inputs are, see if
2207   // should reserve the arguments and use them directly.
2208   MachineFrameInfo &MFI = MF.getFrameInfo();
2209   bool HasStackObjects = MFI.hasStackObjects();
2210   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2211 
2212   // Record that we know we have non-spill stack objects so we don't need to
2213   // check all stack objects later.
2214   if (HasStackObjects)
2215     Info.setHasNonSpillStackObjects(true);
2216 
2217   // Everything live out of a block is spilled with fast regalloc, so it's
2218   // almost certain that spilling will be required.
2219   if (TM.getOptLevel() == CodeGenOpt::None)
2220     HasStackObjects = true;
2221 
2222   // For now assume stack access is needed in any callee functions, so we need
2223   // the scratch registers to pass in.
2224   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2225 
2226   if (!ST.enableFlatScratch()) {
2227     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2228       // If we have stack objects, we unquestionably need the private buffer
2229       // resource. For the Code Object V2 ABI, this will be the first 4 user
2230       // SGPR inputs. We can reserve those and use them directly.
2231 
2232       Register PrivateSegmentBufferReg =
2233           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2234       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2235     } else {
2236       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2237       // We tentatively reserve the last registers (skipping the last registers
2238       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2239       // we'll replace these with the ones immediately after those which were
2240       // really allocated. In the prologue copies will be inserted from the
2241       // argument to these reserved registers.
2242 
2243       // Without HSA, relocations are used for the scratch pointer and the
2244       // buffer resource setup is always inserted in the prologue. Scratch wave
2245       // offset is still in an input SGPR.
2246       Info.setScratchRSrcReg(ReservedBufferReg);
2247     }
2248   }
2249 
2250   MachineRegisterInfo &MRI = MF.getRegInfo();
2251 
2252   // For entry functions we have to set up the stack pointer if we use it,
2253   // whereas non-entry functions get this "for free". This means there is no
2254   // intrinsic advantage to using S32 over S34 in cases where we do not have
2255   // calls but do need a frame pointer (i.e. if we are requested to have one
2256   // because frame pointer elimination is disabled). To keep things simple we
2257   // only ever use S32 as the call ABI stack pointer, and so using it does not
2258   // imply we need a separate frame pointer.
2259   //
2260   // Try to use s32 as the SP, but move it if it would interfere with input
2261   // arguments. This won't work with calls though.
2262   //
2263   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2264   // registers.
2265   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2266     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2267   } else {
2268     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2269 
2270     if (MFI.hasCalls())
2271       report_fatal_error("call in graphics shader with too many input SGPRs");
2272 
2273     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2274       if (!MRI.isLiveIn(Reg)) {
2275         Info.setStackPtrOffsetReg(Reg);
2276         break;
2277       }
2278     }
2279 
2280     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2281       report_fatal_error("failed to find register for SP");
2282   }
2283 
2284   // hasFP should be accurate for entry functions even before the frame is
2285   // finalized, because it does not rely on the known stack size, only
2286   // properties like whether variable sized objects are present.
2287   if (ST.getFrameLowering()->hasFP(MF)) {
2288     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2289   }
2290 }
2291 
2292 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2293   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2294   return !Info->isEntryFunction();
2295 }
2296 
2297 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2298 
2299 }
2300 
2301 void SITargetLowering::insertCopiesSplitCSR(
2302   MachineBasicBlock *Entry,
2303   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2304   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2305 
2306   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2307   if (!IStart)
2308     return;
2309 
2310   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2311   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2312   MachineBasicBlock::iterator MBBI = Entry->begin();
2313   for (const MCPhysReg *I = IStart; *I; ++I) {
2314     const TargetRegisterClass *RC = nullptr;
2315     if (AMDGPU::SReg_64RegClass.contains(*I))
2316       RC = &AMDGPU::SGPR_64RegClass;
2317     else if (AMDGPU::SReg_32RegClass.contains(*I))
2318       RC = &AMDGPU::SGPR_32RegClass;
2319     else
2320       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2321 
2322     Register NewVR = MRI->createVirtualRegister(RC);
2323     // Create copy from CSR to a virtual register.
2324     Entry->addLiveIn(*I);
2325     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2326       .addReg(*I);
2327 
2328     // Insert the copy-back instructions right before the terminator.
2329     for (auto *Exit : Exits)
2330       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2331               TII->get(TargetOpcode::COPY), *I)
2332         .addReg(NewVR);
2333   }
2334 }
2335 
2336 SDValue SITargetLowering::LowerFormalArguments(
2337     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2338     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2339     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2340   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2341 
2342   MachineFunction &MF = DAG.getMachineFunction();
2343   const Function &Fn = MF.getFunction();
2344   FunctionType *FType = MF.getFunction().getFunctionType();
2345   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2346 
2347   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2348     DiagnosticInfoUnsupported NoGraphicsHSA(
2349         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2350     DAG.getContext()->diagnose(NoGraphicsHSA);
2351     return DAG.getEntryNode();
2352   }
2353 
2354   Info->allocateModuleLDSGlobal(Fn.getParent());
2355 
2356   SmallVector<ISD::InputArg, 16> Splits;
2357   SmallVector<CCValAssign, 16> ArgLocs;
2358   BitVector Skipped(Ins.size());
2359   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2360                  *DAG.getContext());
2361 
2362   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2363   bool IsKernel = AMDGPU::isKernel(CallConv);
2364   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2365 
2366   if (IsGraphics) {
2367     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2368            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2369            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2370            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2371            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2372            !Info->hasWorkItemIDZ());
2373   }
2374 
2375   if (CallConv == CallingConv::AMDGPU_PS) {
2376     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2377 
2378     // At least one interpolation mode must be enabled or else the GPU will
2379     // hang.
2380     //
2381     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2382     // set PSInputAddr, the user wants to enable some bits after the compilation
2383     // based on run-time states. Since we can't know what the final PSInputEna
2384     // will look like, so we shouldn't do anything here and the user should take
2385     // responsibility for the correct programming.
2386     //
2387     // Otherwise, the following restrictions apply:
2388     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2389     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2390     //   enabled too.
2391     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2392         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2393       CCInfo.AllocateReg(AMDGPU::VGPR0);
2394       CCInfo.AllocateReg(AMDGPU::VGPR1);
2395       Info->markPSInputAllocated(0);
2396       Info->markPSInputEnabled(0);
2397     }
2398     if (Subtarget->isAmdPalOS()) {
2399       // For isAmdPalOS, the user does not enable some bits after compilation
2400       // based on run-time states; the register values being generated here are
2401       // the final ones set in hardware. Therefore we need to apply the
2402       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2403       // a bit is set in PSInputAddr but not PSInputEnable is where the
2404       // frontend set up an input arg for a particular interpolation mode, but
2405       // nothing uses that input arg. Really we should have an earlier pass
2406       // that removes such an arg.)
2407       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2408       if ((PsInputBits & 0x7F) == 0 ||
2409           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2410         Info->markPSInputEnabled(
2411             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2412     }
2413   } else if (IsKernel) {
2414     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2415   } else {
2416     Splits.append(Ins.begin(), Ins.end());
2417   }
2418 
2419   if (IsEntryFunc) {
2420     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2421     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2422   } else {
2423     // For the fixed ABI, pass workitem IDs in the last argument register.
2424     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2425       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2426   }
2427 
2428   if (IsKernel) {
2429     analyzeFormalArgumentsCompute(CCInfo, Ins);
2430   } else {
2431     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2432     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2433   }
2434 
2435   SmallVector<SDValue, 16> Chains;
2436 
2437   // FIXME: This is the minimum kernel argument alignment. We should improve
2438   // this to the maximum alignment of the arguments.
2439   //
2440   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2441   // kern arg offset.
2442   const Align KernelArgBaseAlign = Align(16);
2443 
2444   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2445     const ISD::InputArg &Arg = Ins[i];
2446     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2447       InVals.push_back(DAG.getUNDEF(Arg.VT));
2448       continue;
2449     }
2450 
2451     CCValAssign &VA = ArgLocs[ArgIdx++];
2452     MVT VT = VA.getLocVT();
2453 
2454     if (IsEntryFunc && VA.isMemLoc()) {
2455       VT = Ins[i].VT;
2456       EVT MemVT = VA.getLocVT();
2457 
2458       const uint64_t Offset = VA.getLocMemOffset();
2459       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2460 
2461       if (Arg.Flags.isByRef()) {
2462         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2463 
2464         const GCNTargetMachine &TM =
2465             static_cast<const GCNTargetMachine &>(getTargetMachine());
2466         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2467                                     Arg.Flags.getPointerAddrSpace())) {
2468           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2469                                      Arg.Flags.getPointerAddrSpace());
2470         }
2471 
2472         InVals.push_back(Ptr);
2473         continue;
2474       }
2475 
2476       SDValue Arg = lowerKernargMemParameter(
2477         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2478       Chains.push_back(Arg.getValue(1));
2479 
2480       auto *ParamTy =
2481         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2482       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2483           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2484                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2485         // On SI local pointers are just offsets into LDS, so they are always
2486         // less than 16-bits.  On CI and newer they could potentially be
2487         // real pointers, so we can't guarantee their size.
2488         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2489                           DAG.getValueType(MVT::i16));
2490       }
2491 
2492       InVals.push_back(Arg);
2493       continue;
2494     } else if (!IsEntryFunc && VA.isMemLoc()) {
2495       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2496       InVals.push_back(Val);
2497       if (!Arg.Flags.isByVal())
2498         Chains.push_back(Val.getValue(1));
2499       continue;
2500     }
2501 
2502     assert(VA.isRegLoc() && "Parameter must be in a register!");
2503 
2504     Register Reg = VA.getLocReg();
2505     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2506     EVT ValVT = VA.getValVT();
2507 
2508     Reg = MF.addLiveIn(Reg, RC);
2509     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2510 
2511     if (Arg.Flags.isSRet()) {
2512       // The return object should be reasonably addressable.
2513 
2514       // FIXME: This helps when the return is a real sret. If it is a
2515       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2516       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2517       unsigned NumBits
2518         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2519       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2520         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2521     }
2522 
2523     // If this is an 8 or 16-bit value, it is really passed promoted
2524     // to 32 bits. Insert an assert[sz]ext to capture this, then
2525     // truncate to the right size.
2526     switch (VA.getLocInfo()) {
2527     case CCValAssign::Full:
2528       break;
2529     case CCValAssign::BCvt:
2530       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2531       break;
2532     case CCValAssign::SExt:
2533       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2534                         DAG.getValueType(ValVT));
2535       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2536       break;
2537     case CCValAssign::ZExt:
2538       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2539                         DAG.getValueType(ValVT));
2540       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2541       break;
2542     case CCValAssign::AExt:
2543       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2544       break;
2545     default:
2546       llvm_unreachable("Unknown loc info!");
2547     }
2548 
2549     InVals.push_back(Val);
2550   }
2551 
2552   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2553     // Special inputs come after user arguments.
2554     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2555   }
2556 
2557   // Start adding system SGPRs.
2558   if (IsEntryFunc) {
2559     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2560   } else {
2561     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2562     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2563   }
2564 
2565   auto &ArgUsageInfo =
2566     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2567   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2568 
2569   unsigned StackArgSize = CCInfo.getNextStackOffset();
2570   Info->setBytesInStackArgArea(StackArgSize);
2571 
2572   return Chains.empty() ? Chain :
2573     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2574 }
2575 
2576 // TODO: If return values can't fit in registers, we should return as many as
2577 // possible in registers before passing on stack.
2578 bool SITargetLowering::CanLowerReturn(
2579   CallingConv::ID CallConv,
2580   MachineFunction &MF, bool IsVarArg,
2581   const SmallVectorImpl<ISD::OutputArg> &Outs,
2582   LLVMContext &Context) const {
2583   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2584   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2585   // for shaders. Vector types should be explicitly handled by CC.
2586   if (AMDGPU::isEntryFunctionCC(CallConv))
2587     return true;
2588 
2589   SmallVector<CCValAssign, 16> RVLocs;
2590   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2591   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2592 }
2593 
2594 SDValue
2595 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2596                               bool isVarArg,
2597                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2598                               const SmallVectorImpl<SDValue> &OutVals,
2599                               const SDLoc &DL, SelectionDAG &DAG) const {
2600   MachineFunction &MF = DAG.getMachineFunction();
2601   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2602 
2603   if (AMDGPU::isKernel(CallConv)) {
2604     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2605                                              OutVals, DL, DAG);
2606   }
2607 
2608   bool IsShader = AMDGPU::isShader(CallConv);
2609 
2610   Info->setIfReturnsVoid(Outs.empty());
2611   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2612 
2613   // CCValAssign - represent the assignment of the return value to a location.
2614   SmallVector<CCValAssign, 48> RVLocs;
2615   SmallVector<ISD::OutputArg, 48> Splits;
2616 
2617   // CCState - Info about the registers and stack slots.
2618   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2619                  *DAG.getContext());
2620 
2621   // Analyze outgoing return values.
2622   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2623 
2624   SDValue Flag;
2625   SmallVector<SDValue, 48> RetOps;
2626   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2627 
2628   // Add return address for callable functions.
2629   if (!Info->isEntryFunction()) {
2630     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2631     SDValue ReturnAddrReg = CreateLiveInRegister(
2632       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2633 
2634     SDValue ReturnAddrVirtualReg =
2635         DAG.getRegister(MF.getRegInfo().createVirtualRegister(
2636                             CallConv != CallingConv::AMDGPU_Gfx
2637                                 ? &AMDGPU::CCR_SGPR_64RegClass
2638                                 : &AMDGPU::Gfx_CCR_SGPR_64RegClass),
2639                         MVT::i64);
2640     Chain =
2641         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2642     Flag = Chain.getValue(1);
2643     RetOps.push_back(ReturnAddrVirtualReg);
2644   }
2645 
2646   // Copy the result values into the output registers.
2647   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2648        ++I, ++RealRVLocIdx) {
2649     CCValAssign &VA = RVLocs[I];
2650     assert(VA.isRegLoc() && "Can only return in registers!");
2651     // TODO: Partially return in registers if return values don't fit.
2652     SDValue Arg = OutVals[RealRVLocIdx];
2653 
2654     // Copied from other backends.
2655     switch (VA.getLocInfo()) {
2656     case CCValAssign::Full:
2657       break;
2658     case CCValAssign::BCvt:
2659       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2660       break;
2661     case CCValAssign::SExt:
2662       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2663       break;
2664     case CCValAssign::ZExt:
2665       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2666       break;
2667     case CCValAssign::AExt:
2668       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2669       break;
2670     default:
2671       llvm_unreachable("Unknown loc info!");
2672     }
2673 
2674     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2675     Flag = Chain.getValue(1);
2676     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2677   }
2678 
2679   // FIXME: Does sret work properly?
2680   if (!Info->isEntryFunction()) {
2681     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2682     const MCPhysReg *I =
2683       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2684     if (I) {
2685       for (; *I; ++I) {
2686         if (AMDGPU::SReg_64RegClass.contains(*I))
2687           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2688         else if (AMDGPU::SReg_32RegClass.contains(*I))
2689           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2690         else
2691           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2692       }
2693     }
2694   }
2695 
2696   // Update chain and glue.
2697   RetOps[0] = Chain;
2698   if (Flag.getNode())
2699     RetOps.push_back(Flag);
2700 
2701   unsigned Opc = AMDGPUISD::ENDPGM;
2702   if (!IsWaveEnd) {
2703     if (IsShader)
2704       Opc = AMDGPUISD::RETURN_TO_EPILOG;
2705     else if (CallConv == CallingConv::AMDGPU_Gfx)
2706       Opc = AMDGPUISD::RET_GFX_FLAG;
2707     else
2708       Opc = AMDGPUISD::RET_FLAG;
2709   }
2710 
2711   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2712 }
2713 
2714 SDValue SITargetLowering::LowerCallResult(
2715     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2716     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2717     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2718     SDValue ThisVal) const {
2719   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2720 
2721   // Assign locations to each value returned by this call.
2722   SmallVector<CCValAssign, 16> RVLocs;
2723   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2724                  *DAG.getContext());
2725   CCInfo.AnalyzeCallResult(Ins, RetCC);
2726 
2727   // Copy all of the result registers out of their specified physreg.
2728   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2729     CCValAssign VA = RVLocs[i];
2730     SDValue Val;
2731 
2732     if (VA.isRegLoc()) {
2733       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2734       Chain = Val.getValue(1);
2735       InFlag = Val.getValue(2);
2736     } else if (VA.isMemLoc()) {
2737       report_fatal_error("TODO: return values in memory");
2738     } else
2739       llvm_unreachable("unknown argument location type");
2740 
2741     switch (VA.getLocInfo()) {
2742     case CCValAssign::Full:
2743       break;
2744     case CCValAssign::BCvt:
2745       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2746       break;
2747     case CCValAssign::ZExt:
2748       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2749                         DAG.getValueType(VA.getValVT()));
2750       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2751       break;
2752     case CCValAssign::SExt:
2753       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2754                         DAG.getValueType(VA.getValVT()));
2755       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2756       break;
2757     case CCValAssign::AExt:
2758       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2759       break;
2760     default:
2761       llvm_unreachable("Unknown loc info!");
2762     }
2763 
2764     InVals.push_back(Val);
2765   }
2766 
2767   return Chain;
2768 }
2769 
2770 // Add code to pass special inputs required depending on used features separate
2771 // from the explicit user arguments present in the IR.
2772 void SITargetLowering::passSpecialInputs(
2773     CallLoweringInfo &CLI,
2774     CCState &CCInfo,
2775     const SIMachineFunctionInfo &Info,
2776     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2777     SmallVectorImpl<SDValue> &MemOpChains,
2778     SDValue Chain) const {
2779   // If we don't have a call site, this was a call inserted by
2780   // legalization. These can never use special inputs.
2781   if (!CLI.CB)
2782     return;
2783 
2784   SelectionDAG &DAG = CLI.DAG;
2785   const SDLoc &DL = CLI.DL;
2786 
2787   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2788   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2789 
2790   const AMDGPUFunctionArgInfo *CalleeArgInfo
2791     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2792   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2793     auto &ArgUsageInfo =
2794       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2795     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2796   }
2797 
2798   // TODO: Unify with private memory register handling. This is complicated by
2799   // the fact that at least in kernels, the input argument is not necessarily
2800   // in the same location as the input.
2801   static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
2802                              StringLiteral> ImplicitAttrs[] = {
2803     {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"},
2804     {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" },
2805     {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"},
2806     {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"},
2807     {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"},
2808     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"},
2809     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"}
2810   };
2811 
2812   for (auto Attr : ImplicitAttrs) {
2813     const ArgDescriptor *OutgoingArg;
2814     const TargetRegisterClass *ArgRC;
2815     LLT ArgTy;
2816 
2817     AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first;
2818 
2819     // If the callee does not use the attribute value, skip copying the value.
2820     if (CLI.CB->hasFnAttr(Attr.second))
2821       continue;
2822 
2823     std::tie(OutgoingArg, ArgRC, ArgTy) =
2824         CalleeArgInfo->getPreloadedValue(InputID);
2825     if (!OutgoingArg)
2826       continue;
2827 
2828     const ArgDescriptor *IncomingArg;
2829     const TargetRegisterClass *IncomingArgRC;
2830     LLT Ty;
2831     std::tie(IncomingArg, IncomingArgRC, Ty) =
2832         CallerArgInfo.getPreloadedValue(InputID);
2833     assert(IncomingArgRC == ArgRC);
2834 
2835     // All special arguments are ints for now.
2836     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2837     SDValue InputReg;
2838 
2839     if (IncomingArg) {
2840       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2841     } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
2842       // The implicit arg ptr is special because it doesn't have a corresponding
2843       // input for kernels, and is computed from the kernarg segment pointer.
2844       InputReg = getImplicitArgPtr(DAG, DL);
2845     } else {
2846       // We may have proven the input wasn't needed, although the ABI is
2847       // requiring it. We just need to allocate the register appropriately.
2848       InputReg = DAG.getUNDEF(ArgVT);
2849     }
2850 
2851     if (OutgoingArg->isRegister()) {
2852       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2853       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2854         report_fatal_error("failed to allocate implicit input argument");
2855     } else {
2856       unsigned SpecialArgOffset =
2857           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2858       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2859                                               SpecialArgOffset);
2860       MemOpChains.push_back(ArgStore);
2861     }
2862   }
2863 
2864   // Pack workitem IDs into a single register or pass it as is if already
2865   // packed.
2866   const ArgDescriptor *OutgoingArg;
2867   const TargetRegisterClass *ArgRC;
2868   LLT Ty;
2869 
2870   std::tie(OutgoingArg, ArgRC, Ty) =
2871       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2872   if (!OutgoingArg)
2873     std::tie(OutgoingArg, ArgRC, Ty) =
2874         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2875   if (!OutgoingArg)
2876     std::tie(OutgoingArg, ArgRC, Ty) =
2877         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2878   if (!OutgoingArg)
2879     return;
2880 
2881   const ArgDescriptor *IncomingArgX = std::get<0>(
2882       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2883   const ArgDescriptor *IncomingArgY = std::get<0>(
2884       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2885   const ArgDescriptor *IncomingArgZ = std::get<0>(
2886       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2887 
2888   SDValue InputReg;
2889   SDLoc SL;
2890 
2891   const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
2892   const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
2893   const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
2894 
2895   // If incoming ids are not packed we need to pack them.
2896   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
2897       NeedWorkItemIDX)
2898     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2899 
2900   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
2901       NeedWorkItemIDY) {
2902     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2903     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2904                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2905     InputReg = InputReg.getNode() ?
2906                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2907   }
2908 
2909   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
2910       NeedWorkItemIDZ) {
2911     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2912     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2913                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2914     InputReg = InputReg.getNode() ?
2915                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2916   }
2917 
2918   if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
2919     // Workitem ids are already packed, any of present incoming arguments
2920     // will carry all required fields.
2921     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2922       IncomingArgX ? *IncomingArgX :
2923       IncomingArgY ? *IncomingArgY :
2924                      *IncomingArgZ, ~0u);
2925     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2926   }
2927 
2928   if (OutgoingArg->isRegister()) {
2929     if (InputReg)
2930       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2931 
2932     CCInfo.AllocateReg(OutgoingArg->getRegister());
2933   } else {
2934     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2935     if (InputReg) {
2936       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2937                                               SpecialArgOffset);
2938       MemOpChains.push_back(ArgStore);
2939     }
2940   }
2941 }
2942 
2943 static bool canGuaranteeTCO(CallingConv::ID CC) {
2944   return CC == CallingConv::Fast;
2945 }
2946 
2947 /// Return true if we might ever do TCO for calls with this calling convention.
2948 static bool mayTailCallThisCC(CallingConv::ID CC) {
2949   switch (CC) {
2950   case CallingConv::C:
2951   case CallingConv::AMDGPU_Gfx:
2952     return true;
2953   default:
2954     return canGuaranteeTCO(CC);
2955   }
2956 }
2957 
2958 bool SITargetLowering::isEligibleForTailCallOptimization(
2959     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2960     const SmallVectorImpl<ISD::OutputArg> &Outs,
2961     const SmallVectorImpl<SDValue> &OutVals,
2962     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2963   if (!mayTailCallThisCC(CalleeCC))
2964     return false;
2965 
2966   // For a divergent call target, we need to do a waterfall loop over the
2967   // possible callees which precludes us from using a simple jump.
2968   if (Callee->isDivergent())
2969     return false;
2970 
2971   MachineFunction &MF = DAG.getMachineFunction();
2972   const Function &CallerF = MF.getFunction();
2973   CallingConv::ID CallerCC = CallerF.getCallingConv();
2974   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2975   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2976 
2977   // Kernels aren't callable, and don't have a live in return address so it
2978   // doesn't make sense to do a tail call with entry functions.
2979   if (!CallerPreserved)
2980     return false;
2981 
2982   bool CCMatch = CallerCC == CalleeCC;
2983 
2984   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2985     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2986       return true;
2987     return false;
2988   }
2989 
2990   // TODO: Can we handle var args?
2991   if (IsVarArg)
2992     return false;
2993 
2994   for (const Argument &Arg : CallerF.args()) {
2995     if (Arg.hasByValAttr())
2996       return false;
2997   }
2998 
2999   LLVMContext &Ctx = *DAG.getContext();
3000 
3001   // Check that the call results are passed in the same way.
3002   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
3003                                   CCAssignFnForCall(CalleeCC, IsVarArg),
3004                                   CCAssignFnForCall(CallerCC, IsVarArg)))
3005     return false;
3006 
3007   // The callee has to preserve all registers the caller needs to preserve.
3008   if (!CCMatch) {
3009     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3010     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3011       return false;
3012   }
3013 
3014   // Nothing more to check if the callee is taking no arguments.
3015   if (Outs.empty())
3016     return true;
3017 
3018   SmallVector<CCValAssign, 16> ArgLocs;
3019   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
3020 
3021   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
3022 
3023   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
3024   // If the stack arguments for this call do not fit into our own save area then
3025   // the call cannot be made tail.
3026   // TODO: Is this really necessary?
3027   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3028     return false;
3029 
3030   const MachineRegisterInfo &MRI = MF.getRegInfo();
3031   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
3032 }
3033 
3034 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3035   if (!CI->isTailCall())
3036     return false;
3037 
3038   const Function *ParentFn = CI->getParent()->getParent();
3039   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
3040     return false;
3041   return true;
3042 }
3043 
3044 // The wave scratch offset register is used as the global base pointer.
3045 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
3046                                     SmallVectorImpl<SDValue> &InVals) const {
3047   SelectionDAG &DAG = CLI.DAG;
3048   const SDLoc &DL = CLI.DL;
3049   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3050   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3051   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3052   SDValue Chain = CLI.Chain;
3053   SDValue Callee = CLI.Callee;
3054   bool &IsTailCall = CLI.IsTailCall;
3055   CallingConv::ID CallConv = CLI.CallConv;
3056   bool IsVarArg = CLI.IsVarArg;
3057   bool IsSibCall = false;
3058   bool IsThisReturn = false;
3059   MachineFunction &MF = DAG.getMachineFunction();
3060 
3061   if (Callee.isUndef() || isNullConstant(Callee)) {
3062     if (!CLI.IsTailCall) {
3063       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
3064         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
3065     }
3066 
3067     return Chain;
3068   }
3069 
3070   if (IsVarArg) {
3071     return lowerUnhandledCall(CLI, InVals,
3072                               "unsupported call to variadic function ");
3073   }
3074 
3075   if (!CLI.CB)
3076     report_fatal_error("unsupported libcall legalization");
3077 
3078   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
3079     return lowerUnhandledCall(CLI, InVals,
3080                               "unsupported required tail call to function ");
3081   }
3082 
3083   if (AMDGPU::isShader(CallConv)) {
3084     // Note the issue is with the CC of the called function, not of the call
3085     // itself.
3086     return lowerUnhandledCall(CLI, InVals,
3087                               "unsupported call to a shader function ");
3088   }
3089 
3090   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
3091       CallConv != CallingConv::AMDGPU_Gfx) {
3092     // Only allow calls with specific calling conventions.
3093     return lowerUnhandledCall(CLI, InVals,
3094                               "unsupported calling convention for call from "
3095                               "graphics shader of function ");
3096   }
3097 
3098   if (IsTailCall) {
3099     IsTailCall = isEligibleForTailCallOptimization(
3100       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3101     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
3102       report_fatal_error("failed to perform tail call elimination on a call "
3103                          "site marked musttail");
3104     }
3105 
3106     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3107 
3108     // A sibling call is one where we're under the usual C ABI and not planning
3109     // to change that but can still do a tail call:
3110     if (!TailCallOpt && IsTailCall)
3111       IsSibCall = true;
3112 
3113     if (IsTailCall)
3114       ++NumTailCalls;
3115   }
3116 
3117   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3118   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3119   SmallVector<SDValue, 8> MemOpChains;
3120 
3121   // Analyze operands of the call, assigning locations to each operand.
3122   SmallVector<CCValAssign, 16> ArgLocs;
3123   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3124   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3125 
3126   if (AMDGPUTargetMachine::EnableFixedFunctionABI &&
3127       CallConv != CallingConv::AMDGPU_Gfx) {
3128     // With a fixed ABI, allocate fixed registers before user arguments.
3129     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3130   }
3131 
3132   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3133 
3134   // Get a count of how many bytes are to be pushed on the stack.
3135   unsigned NumBytes = CCInfo.getNextStackOffset();
3136 
3137   if (IsSibCall) {
3138     // Since we're not changing the ABI to make this a tail call, the memory
3139     // operands are already available in the caller's incoming argument space.
3140     NumBytes = 0;
3141   }
3142 
3143   // FPDiff is the byte offset of the call's argument area from the callee's.
3144   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3145   // by this amount for a tail call. In a sibling call it must be 0 because the
3146   // caller will deallocate the entire stack and the callee still expects its
3147   // arguments to begin at SP+0. Completely unused for non-tail calls.
3148   int32_t FPDiff = 0;
3149   MachineFrameInfo &MFI = MF.getFrameInfo();
3150 
3151   // Adjust the stack pointer for the new arguments...
3152   // These operations are automatically eliminated by the prolog/epilog pass
3153   if (!IsSibCall) {
3154     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3155 
3156     if (!Subtarget->enableFlatScratch()) {
3157       SmallVector<SDValue, 4> CopyFromChains;
3158 
3159       // In the HSA case, this should be an identity copy.
3160       SDValue ScratchRSrcReg
3161         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3162       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3163       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3164       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3165     }
3166   }
3167 
3168   MVT PtrVT = MVT::i32;
3169 
3170   // Walk the register/memloc assignments, inserting copies/loads.
3171   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3172     CCValAssign &VA = ArgLocs[i];
3173     SDValue Arg = OutVals[i];
3174 
3175     // Promote the value if needed.
3176     switch (VA.getLocInfo()) {
3177     case CCValAssign::Full:
3178       break;
3179     case CCValAssign::BCvt:
3180       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3181       break;
3182     case CCValAssign::ZExt:
3183       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3184       break;
3185     case CCValAssign::SExt:
3186       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3187       break;
3188     case CCValAssign::AExt:
3189       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3190       break;
3191     case CCValAssign::FPExt:
3192       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3193       break;
3194     default:
3195       llvm_unreachable("Unknown loc info!");
3196     }
3197 
3198     if (VA.isRegLoc()) {
3199       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3200     } else {
3201       assert(VA.isMemLoc());
3202 
3203       SDValue DstAddr;
3204       MachinePointerInfo DstInfo;
3205 
3206       unsigned LocMemOffset = VA.getLocMemOffset();
3207       int32_t Offset = LocMemOffset;
3208 
3209       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3210       MaybeAlign Alignment;
3211 
3212       if (IsTailCall) {
3213         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3214         unsigned OpSize = Flags.isByVal() ?
3215           Flags.getByValSize() : VA.getValVT().getStoreSize();
3216 
3217         // FIXME: We can have better than the minimum byval required alignment.
3218         Alignment =
3219             Flags.isByVal()
3220                 ? Flags.getNonZeroByValAlign()
3221                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3222 
3223         Offset = Offset + FPDiff;
3224         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3225 
3226         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3227         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3228 
3229         // Make sure any stack arguments overlapping with where we're storing
3230         // are loaded before this eventual operation. Otherwise they'll be
3231         // clobbered.
3232 
3233         // FIXME: Why is this really necessary? This seems to just result in a
3234         // lot of code to copy the stack and write them back to the same
3235         // locations, which are supposed to be immutable?
3236         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3237       } else {
3238         // Stores to the argument stack area are relative to the stack pointer.
3239         SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3240                                         MVT::i32);
3241         DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3242         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3243         Alignment =
3244             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3245       }
3246 
3247       if (Outs[i].Flags.isByVal()) {
3248         SDValue SizeNode =
3249             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3250         SDValue Cpy =
3251             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3252                           Outs[i].Flags.getNonZeroByValAlign(),
3253                           /*isVol = */ false, /*AlwaysInline = */ true,
3254                           /*isTailCall = */ false, DstInfo,
3255                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3256 
3257         MemOpChains.push_back(Cpy);
3258       } else {
3259         SDValue Store =
3260             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3261         MemOpChains.push_back(Store);
3262       }
3263     }
3264   }
3265 
3266   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
3267       CallConv != CallingConv::AMDGPU_Gfx) {
3268     // Copy special input registers after user input arguments.
3269     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3270   }
3271 
3272   if (!MemOpChains.empty())
3273     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3274 
3275   // Build a sequence of copy-to-reg nodes chained together with token chain
3276   // and flag operands which copy the outgoing args into the appropriate regs.
3277   SDValue InFlag;
3278   for (auto &RegToPass : RegsToPass) {
3279     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3280                              RegToPass.second, InFlag);
3281     InFlag = Chain.getValue(1);
3282   }
3283 
3284 
3285   SDValue PhysReturnAddrReg;
3286   if (IsTailCall) {
3287     // Since the return is being combined with the call, we need to pass on the
3288     // return address.
3289 
3290     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3291     SDValue ReturnAddrReg = CreateLiveInRegister(
3292       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3293 
3294     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3295                                         MVT::i64);
3296     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3297     InFlag = Chain.getValue(1);
3298   }
3299 
3300   // We don't usually want to end the call-sequence here because we would tidy
3301   // the frame up *after* the call, however in the ABI-changing tail-call case
3302   // we've carefully laid out the parameters so that when sp is reset they'll be
3303   // in the correct location.
3304   if (IsTailCall && !IsSibCall) {
3305     Chain = DAG.getCALLSEQ_END(Chain,
3306                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3307                                DAG.getTargetConstant(0, DL, MVT::i32),
3308                                InFlag, DL);
3309     InFlag = Chain.getValue(1);
3310   }
3311 
3312   std::vector<SDValue> Ops;
3313   Ops.push_back(Chain);
3314   Ops.push_back(Callee);
3315   // Add a redundant copy of the callee global which will not be legalized, as
3316   // we need direct access to the callee later.
3317   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3318     const GlobalValue *GV = GSD->getGlobal();
3319     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3320   } else {
3321     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3322   }
3323 
3324   if (IsTailCall) {
3325     // Each tail call may have to adjust the stack by a different amount, so
3326     // this information must travel along with the operation for eventual
3327     // consumption by emitEpilogue.
3328     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3329 
3330     Ops.push_back(PhysReturnAddrReg);
3331   }
3332 
3333   // Add argument registers to the end of the list so that they are known live
3334   // into the call.
3335   for (auto &RegToPass : RegsToPass) {
3336     Ops.push_back(DAG.getRegister(RegToPass.first,
3337                                   RegToPass.second.getValueType()));
3338   }
3339 
3340   // Add a register mask operand representing the call-preserved registers.
3341 
3342   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3343   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3344   assert(Mask && "Missing call preserved mask for calling convention");
3345   Ops.push_back(DAG.getRegisterMask(Mask));
3346 
3347   if (InFlag.getNode())
3348     Ops.push_back(InFlag);
3349 
3350   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3351 
3352   // If we're doing a tall call, use a TC_RETURN here rather than an
3353   // actual call instruction.
3354   if (IsTailCall) {
3355     MFI.setHasTailCall();
3356     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3357   }
3358 
3359   // Returns a chain and a flag for retval copy to use.
3360   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3361   Chain = Call.getValue(0);
3362   InFlag = Call.getValue(1);
3363 
3364   uint64_t CalleePopBytes = NumBytes;
3365   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3366                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3367                              InFlag, DL);
3368   if (!Ins.empty())
3369     InFlag = Chain.getValue(1);
3370 
3371   // Handle result values, copying them out of physregs into vregs that we
3372   // return.
3373   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3374                          InVals, IsThisReturn,
3375                          IsThisReturn ? OutVals[0] : SDValue());
3376 }
3377 
3378 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3379 // except for applying the wave size scale to the increment amount.
3380 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3381     SDValue Op, SelectionDAG &DAG) const {
3382   const MachineFunction &MF = DAG.getMachineFunction();
3383   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3384 
3385   SDLoc dl(Op);
3386   EVT VT = Op.getValueType();
3387   SDValue Tmp1 = Op;
3388   SDValue Tmp2 = Op.getValue(1);
3389   SDValue Tmp3 = Op.getOperand(2);
3390   SDValue Chain = Tmp1.getOperand(0);
3391 
3392   Register SPReg = Info->getStackPtrOffsetReg();
3393 
3394   // Chain the dynamic stack allocation so that it doesn't modify the stack
3395   // pointer when other instructions are using the stack.
3396   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3397 
3398   SDValue Size  = Tmp2.getOperand(1);
3399   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3400   Chain = SP.getValue(1);
3401   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3402   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3403   const TargetFrameLowering *TFL = ST.getFrameLowering();
3404   unsigned Opc =
3405     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3406     ISD::ADD : ISD::SUB;
3407 
3408   SDValue ScaledSize = DAG.getNode(
3409       ISD::SHL, dl, VT, Size,
3410       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3411 
3412   Align StackAlign = TFL->getStackAlign();
3413   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3414   if (Alignment && *Alignment > StackAlign) {
3415     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3416                        DAG.getConstant(-(uint64_t)Alignment->value()
3417                                            << ST.getWavefrontSizeLog2(),
3418                                        dl, VT));
3419   }
3420 
3421   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3422   Tmp2 = DAG.getCALLSEQ_END(
3423       Chain, DAG.getIntPtrConstant(0, dl, true),
3424       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3425 
3426   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3427 }
3428 
3429 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3430                                                   SelectionDAG &DAG) const {
3431   // We only handle constant sizes here to allow non-entry block, static sized
3432   // allocas. A truly dynamic value is more difficult to support because we
3433   // don't know if the size value is uniform or not. If the size isn't uniform,
3434   // we would need to do a wave reduction to get the maximum size to know how
3435   // much to increment the uniform stack pointer.
3436   SDValue Size = Op.getOperand(1);
3437   if (isa<ConstantSDNode>(Size))
3438       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3439 
3440   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3441 }
3442 
3443 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3444                                              const MachineFunction &MF) const {
3445   Register Reg = StringSwitch<Register>(RegName)
3446     .Case("m0", AMDGPU::M0)
3447     .Case("exec", AMDGPU::EXEC)
3448     .Case("exec_lo", AMDGPU::EXEC_LO)
3449     .Case("exec_hi", AMDGPU::EXEC_HI)
3450     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3451     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3452     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3453     .Default(Register());
3454 
3455   if (Reg == AMDGPU::NoRegister) {
3456     report_fatal_error(Twine("invalid register name \""
3457                              + StringRef(RegName)  + "\"."));
3458 
3459   }
3460 
3461   if (!Subtarget->hasFlatScrRegister() &&
3462        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3463     report_fatal_error(Twine("invalid register \""
3464                              + StringRef(RegName)  + "\" for subtarget."));
3465   }
3466 
3467   switch (Reg) {
3468   case AMDGPU::M0:
3469   case AMDGPU::EXEC_LO:
3470   case AMDGPU::EXEC_HI:
3471   case AMDGPU::FLAT_SCR_LO:
3472   case AMDGPU::FLAT_SCR_HI:
3473     if (VT.getSizeInBits() == 32)
3474       return Reg;
3475     break;
3476   case AMDGPU::EXEC:
3477   case AMDGPU::FLAT_SCR:
3478     if (VT.getSizeInBits() == 64)
3479       return Reg;
3480     break;
3481   default:
3482     llvm_unreachable("missing register type checking");
3483   }
3484 
3485   report_fatal_error(Twine("invalid type for register \""
3486                            + StringRef(RegName) + "\"."));
3487 }
3488 
3489 // If kill is not the last instruction, split the block so kill is always a
3490 // proper terminator.
3491 MachineBasicBlock *
3492 SITargetLowering::splitKillBlock(MachineInstr &MI,
3493                                  MachineBasicBlock *BB) const {
3494   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3495   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3496   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3497   return SplitBB;
3498 }
3499 
3500 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3501 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3502 // be the first instruction in the remainder block.
3503 //
3504 /// \returns { LoopBody, Remainder }
3505 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3506 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3507   MachineFunction *MF = MBB.getParent();
3508   MachineBasicBlock::iterator I(&MI);
3509 
3510   // To insert the loop we need to split the block. Move everything after this
3511   // point to a new block, and insert a new empty block between the two.
3512   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3513   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3514   MachineFunction::iterator MBBI(MBB);
3515   ++MBBI;
3516 
3517   MF->insert(MBBI, LoopBB);
3518   MF->insert(MBBI, RemainderBB);
3519 
3520   LoopBB->addSuccessor(LoopBB);
3521   LoopBB->addSuccessor(RemainderBB);
3522 
3523   // Move the rest of the block into a new block.
3524   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3525 
3526   if (InstInLoop) {
3527     auto Next = std::next(I);
3528 
3529     // Move instruction to loop body.
3530     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3531 
3532     // Move the rest of the block.
3533     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3534   } else {
3535     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3536   }
3537 
3538   MBB.addSuccessor(LoopBB);
3539 
3540   return std::make_pair(LoopBB, RemainderBB);
3541 }
3542 
3543 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3544 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3545   MachineBasicBlock *MBB = MI.getParent();
3546   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3547   auto I = MI.getIterator();
3548   auto E = std::next(I);
3549 
3550   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3551     .addImm(0);
3552 
3553   MIBundleBuilder Bundler(*MBB, I, E);
3554   finalizeBundle(*MBB, Bundler.begin());
3555 }
3556 
3557 MachineBasicBlock *
3558 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3559                                          MachineBasicBlock *BB) const {
3560   const DebugLoc &DL = MI.getDebugLoc();
3561 
3562   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3563 
3564   MachineBasicBlock *LoopBB;
3565   MachineBasicBlock *RemainderBB;
3566   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3567 
3568   // Apparently kill flags are only valid if the def is in the same block?
3569   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3570     Src->setIsKill(false);
3571 
3572   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3573 
3574   MachineBasicBlock::iterator I = LoopBB->end();
3575 
3576   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3577     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3578 
3579   // Clear TRAP_STS.MEM_VIOL
3580   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3581     .addImm(0)
3582     .addImm(EncodedReg);
3583 
3584   bundleInstWithWaitcnt(MI);
3585 
3586   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3587 
3588   // Load and check TRAP_STS.MEM_VIOL
3589   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3590     .addImm(EncodedReg);
3591 
3592   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3593   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3594     .addReg(Reg, RegState::Kill)
3595     .addImm(0);
3596   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3597     .addMBB(LoopBB);
3598 
3599   return RemainderBB;
3600 }
3601 
3602 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3603 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3604 // will only do one iteration. In the worst case, this will loop 64 times.
3605 //
3606 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3607 static MachineBasicBlock::iterator
3608 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3609                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3610                        const DebugLoc &DL, const MachineOperand &Idx,
3611                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3612                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3613                        Register &SGPRIdxReg) {
3614 
3615   MachineFunction *MF = OrigBB.getParent();
3616   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3617   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3618   MachineBasicBlock::iterator I = LoopBB.begin();
3619 
3620   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3621   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3622   Register NewExec = MRI.createVirtualRegister(BoolRC);
3623   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3624   Register CondReg = MRI.createVirtualRegister(BoolRC);
3625 
3626   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3627     .addReg(InitReg)
3628     .addMBB(&OrigBB)
3629     .addReg(ResultReg)
3630     .addMBB(&LoopBB);
3631 
3632   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3633     .addReg(InitSaveExecReg)
3634     .addMBB(&OrigBB)
3635     .addReg(NewExec)
3636     .addMBB(&LoopBB);
3637 
3638   // Read the next variant <- also loop target.
3639   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3640       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3641 
3642   // Compare the just read M0 value to all possible Idx values.
3643   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3644       .addReg(CurrentIdxReg)
3645       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3646 
3647   // Update EXEC, save the original EXEC value to VCC.
3648   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3649                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3650           NewExec)
3651     .addReg(CondReg, RegState::Kill);
3652 
3653   MRI.setSimpleHint(NewExec, CondReg);
3654 
3655   if (UseGPRIdxMode) {
3656     if (Offset == 0) {
3657       SGPRIdxReg = CurrentIdxReg;
3658     } else {
3659       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3660       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3661           .addReg(CurrentIdxReg, RegState::Kill)
3662           .addImm(Offset);
3663     }
3664   } else {
3665     // Move index from VCC into M0
3666     if (Offset == 0) {
3667       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3668         .addReg(CurrentIdxReg, RegState::Kill);
3669     } else {
3670       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3671         .addReg(CurrentIdxReg, RegState::Kill)
3672         .addImm(Offset);
3673     }
3674   }
3675 
3676   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3677   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3678   MachineInstr *InsertPt =
3679     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3680                                                   : AMDGPU::S_XOR_B64_term), Exec)
3681       .addReg(Exec)
3682       .addReg(NewExec);
3683 
3684   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3685   // s_cbranch_scc0?
3686 
3687   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3688   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3689     .addMBB(&LoopBB);
3690 
3691   return InsertPt->getIterator();
3692 }
3693 
3694 // This has slightly sub-optimal regalloc when the source vector is killed by
3695 // the read. The register allocator does not understand that the kill is
3696 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3697 // subregister from it, using 1 more VGPR than necessary. This was saved when
3698 // this was expanded after register allocation.
3699 static MachineBasicBlock::iterator
3700 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3701                unsigned InitResultReg, unsigned PhiReg, int Offset,
3702                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3703   MachineFunction *MF = MBB.getParent();
3704   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3705   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3706   MachineRegisterInfo &MRI = MF->getRegInfo();
3707   const DebugLoc &DL = MI.getDebugLoc();
3708   MachineBasicBlock::iterator I(&MI);
3709 
3710   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3711   Register DstReg = MI.getOperand(0).getReg();
3712   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3713   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3714   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3715   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3716 
3717   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3718 
3719   // Save the EXEC mask
3720   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3721     .addReg(Exec);
3722 
3723   MachineBasicBlock *LoopBB;
3724   MachineBasicBlock *RemainderBB;
3725   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3726 
3727   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3728 
3729   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3730                                       InitResultReg, DstReg, PhiReg, TmpExec,
3731                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3732 
3733   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3734   MachineFunction::iterator MBBI(LoopBB);
3735   ++MBBI;
3736   MF->insert(MBBI, LandingPad);
3737   LoopBB->removeSuccessor(RemainderBB);
3738   LandingPad->addSuccessor(RemainderBB);
3739   LoopBB->addSuccessor(LandingPad);
3740   MachineBasicBlock::iterator First = LandingPad->begin();
3741   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3742     .addReg(SaveExec);
3743 
3744   return InsPt;
3745 }
3746 
3747 // Returns subreg index, offset
3748 static std::pair<unsigned, int>
3749 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3750                             const TargetRegisterClass *SuperRC,
3751                             unsigned VecReg,
3752                             int Offset) {
3753   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3754 
3755   // Skip out of bounds offsets, or else we would end up using an undefined
3756   // register.
3757   if (Offset >= NumElts || Offset < 0)
3758     return std::make_pair(AMDGPU::sub0, Offset);
3759 
3760   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3761 }
3762 
3763 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3764                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3765                                  int Offset) {
3766   MachineBasicBlock *MBB = MI.getParent();
3767   const DebugLoc &DL = MI.getDebugLoc();
3768   MachineBasicBlock::iterator I(&MI);
3769 
3770   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3771 
3772   assert(Idx->getReg() != AMDGPU::NoRegister);
3773 
3774   if (Offset == 0) {
3775     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3776   } else {
3777     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3778         .add(*Idx)
3779         .addImm(Offset);
3780   }
3781 }
3782 
3783 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3784                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3785                                    int Offset) {
3786   MachineBasicBlock *MBB = MI.getParent();
3787   const DebugLoc &DL = MI.getDebugLoc();
3788   MachineBasicBlock::iterator I(&MI);
3789 
3790   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3791 
3792   if (Offset == 0)
3793     return Idx->getReg();
3794 
3795   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3796   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3797       .add(*Idx)
3798       .addImm(Offset);
3799   return Tmp;
3800 }
3801 
3802 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3803                                           MachineBasicBlock &MBB,
3804                                           const GCNSubtarget &ST) {
3805   const SIInstrInfo *TII = ST.getInstrInfo();
3806   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3807   MachineFunction *MF = MBB.getParent();
3808   MachineRegisterInfo &MRI = MF->getRegInfo();
3809 
3810   Register Dst = MI.getOperand(0).getReg();
3811   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3812   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3813   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3814 
3815   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3816   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3817 
3818   unsigned SubReg;
3819   std::tie(SubReg, Offset)
3820     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3821 
3822   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3823 
3824   // Check for a SGPR index.
3825   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3826     MachineBasicBlock::iterator I(&MI);
3827     const DebugLoc &DL = MI.getDebugLoc();
3828 
3829     if (UseGPRIdxMode) {
3830       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3831       // to avoid interfering with other uses, so probably requires a new
3832       // optimization pass.
3833       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3834 
3835       const MCInstrDesc &GPRIDXDesc =
3836           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3837       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3838           .addReg(SrcReg)
3839           .addReg(Idx)
3840           .addImm(SubReg);
3841     } else {
3842       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3843 
3844       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3845         .addReg(SrcReg, 0, SubReg)
3846         .addReg(SrcReg, RegState::Implicit);
3847     }
3848 
3849     MI.eraseFromParent();
3850 
3851     return &MBB;
3852   }
3853 
3854   // Control flow needs to be inserted if indexing with a VGPR.
3855   const DebugLoc &DL = MI.getDebugLoc();
3856   MachineBasicBlock::iterator I(&MI);
3857 
3858   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3859   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3860 
3861   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3862 
3863   Register SGPRIdxReg;
3864   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3865                               UseGPRIdxMode, SGPRIdxReg);
3866 
3867   MachineBasicBlock *LoopBB = InsPt->getParent();
3868 
3869   if (UseGPRIdxMode) {
3870     const MCInstrDesc &GPRIDXDesc =
3871         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3872 
3873     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3874         .addReg(SrcReg)
3875         .addReg(SGPRIdxReg)
3876         .addImm(SubReg);
3877   } else {
3878     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3879       .addReg(SrcReg, 0, SubReg)
3880       .addReg(SrcReg, RegState::Implicit);
3881   }
3882 
3883   MI.eraseFromParent();
3884 
3885   return LoopBB;
3886 }
3887 
3888 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3889                                           MachineBasicBlock &MBB,
3890                                           const GCNSubtarget &ST) {
3891   const SIInstrInfo *TII = ST.getInstrInfo();
3892   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3893   MachineFunction *MF = MBB.getParent();
3894   MachineRegisterInfo &MRI = MF->getRegInfo();
3895 
3896   Register Dst = MI.getOperand(0).getReg();
3897   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3898   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3899   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3900   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3901   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3902   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3903 
3904   // This can be an immediate, but will be folded later.
3905   assert(Val->getReg());
3906 
3907   unsigned SubReg;
3908   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3909                                                          SrcVec->getReg(),
3910                                                          Offset);
3911   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3912 
3913   if (Idx->getReg() == AMDGPU::NoRegister) {
3914     MachineBasicBlock::iterator I(&MI);
3915     const DebugLoc &DL = MI.getDebugLoc();
3916 
3917     assert(Offset == 0);
3918 
3919     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3920         .add(*SrcVec)
3921         .add(*Val)
3922         .addImm(SubReg);
3923 
3924     MI.eraseFromParent();
3925     return &MBB;
3926   }
3927 
3928   // Check for a SGPR index.
3929   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3930     MachineBasicBlock::iterator I(&MI);
3931     const DebugLoc &DL = MI.getDebugLoc();
3932 
3933     if (UseGPRIdxMode) {
3934       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3935 
3936       const MCInstrDesc &GPRIDXDesc =
3937           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3938       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3939           .addReg(SrcVec->getReg())
3940           .add(*Val)
3941           .addReg(Idx)
3942           .addImm(SubReg);
3943     } else {
3944       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3945 
3946       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3947           TRI.getRegSizeInBits(*VecRC), 32, false);
3948       BuildMI(MBB, I, DL, MovRelDesc, Dst)
3949           .addReg(SrcVec->getReg())
3950           .add(*Val)
3951           .addImm(SubReg);
3952     }
3953     MI.eraseFromParent();
3954     return &MBB;
3955   }
3956 
3957   // Control flow needs to be inserted if indexing with a VGPR.
3958   if (Val->isReg())
3959     MRI.clearKillFlags(Val->getReg());
3960 
3961   const DebugLoc &DL = MI.getDebugLoc();
3962 
3963   Register PhiReg = MRI.createVirtualRegister(VecRC);
3964 
3965   Register SGPRIdxReg;
3966   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
3967                               UseGPRIdxMode, SGPRIdxReg);
3968   MachineBasicBlock *LoopBB = InsPt->getParent();
3969 
3970   if (UseGPRIdxMode) {
3971     const MCInstrDesc &GPRIDXDesc =
3972         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3973 
3974     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3975         .addReg(PhiReg)
3976         .add(*Val)
3977         .addReg(SGPRIdxReg)
3978         .addImm(AMDGPU::sub0);
3979   } else {
3980     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3981         TRI.getRegSizeInBits(*VecRC), 32, false);
3982     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3983         .addReg(PhiReg)
3984         .add(*Val)
3985         .addImm(AMDGPU::sub0);
3986   }
3987 
3988   MI.eraseFromParent();
3989   return LoopBB;
3990 }
3991 
3992 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3993   MachineInstr &MI, MachineBasicBlock *BB) const {
3994 
3995   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3996   MachineFunction *MF = BB->getParent();
3997   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3998 
3999   switch (MI.getOpcode()) {
4000   case AMDGPU::S_UADDO_PSEUDO:
4001   case AMDGPU::S_USUBO_PSEUDO: {
4002     const DebugLoc &DL = MI.getDebugLoc();
4003     MachineOperand &Dest0 = MI.getOperand(0);
4004     MachineOperand &Dest1 = MI.getOperand(1);
4005     MachineOperand &Src0 = MI.getOperand(2);
4006     MachineOperand &Src1 = MI.getOperand(3);
4007 
4008     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
4009                        ? AMDGPU::S_ADD_I32
4010                        : AMDGPU::S_SUB_I32;
4011     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
4012 
4013     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
4014         .addImm(1)
4015         .addImm(0);
4016 
4017     MI.eraseFromParent();
4018     return BB;
4019   }
4020   case AMDGPU::S_ADD_U64_PSEUDO:
4021   case AMDGPU::S_SUB_U64_PSEUDO: {
4022     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4023     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4024     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4025     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
4026     const DebugLoc &DL = MI.getDebugLoc();
4027 
4028     MachineOperand &Dest = MI.getOperand(0);
4029     MachineOperand &Src0 = MI.getOperand(1);
4030     MachineOperand &Src1 = MI.getOperand(2);
4031 
4032     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4033     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4034 
4035     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
4036         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4037     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
4038         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4039 
4040     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
4041         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4042     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
4043         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4044 
4045     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
4046 
4047     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
4048     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
4049     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
4050     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
4051     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4052         .addReg(DestSub0)
4053         .addImm(AMDGPU::sub0)
4054         .addReg(DestSub1)
4055         .addImm(AMDGPU::sub1);
4056     MI.eraseFromParent();
4057     return BB;
4058   }
4059   case AMDGPU::V_ADD_U64_PSEUDO:
4060   case AMDGPU::V_SUB_U64_PSEUDO: {
4061     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4062     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4063     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4064     const DebugLoc &DL = MI.getDebugLoc();
4065 
4066     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
4067 
4068     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4069 
4070     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4071     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4072 
4073     Register CarryReg = MRI.createVirtualRegister(CarryRC);
4074     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
4075 
4076     MachineOperand &Dest = MI.getOperand(0);
4077     MachineOperand &Src0 = MI.getOperand(1);
4078     MachineOperand &Src1 = MI.getOperand(2);
4079 
4080     const TargetRegisterClass *Src0RC = Src0.isReg()
4081                                             ? MRI.getRegClass(Src0.getReg())
4082                                             : &AMDGPU::VReg_64RegClass;
4083     const TargetRegisterClass *Src1RC = Src1.isReg()
4084                                             ? MRI.getRegClass(Src1.getReg())
4085                                             : &AMDGPU::VReg_64RegClass;
4086 
4087     const TargetRegisterClass *Src0SubRC =
4088         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
4089     const TargetRegisterClass *Src1SubRC =
4090         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
4091 
4092     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
4093         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
4094     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
4095         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
4096 
4097     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
4098         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
4099     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
4100         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
4101 
4102     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
4103     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
4104                                .addReg(CarryReg, RegState::Define)
4105                                .add(SrcReg0Sub0)
4106                                .add(SrcReg1Sub0)
4107                                .addImm(0); // clamp bit
4108 
4109     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
4110     MachineInstr *HiHalf =
4111         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4112             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4113             .add(SrcReg0Sub1)
4114             .add(SrcReg1Sub1)
4115             .addReg(CarryReg, RegState::Kill)
4116             .addImm(0); // clamp bit
4117 
4118     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4119         .addReg(DestSub0)
4120         .addImm(AMDGPU::sub0)
4121         .addReg(DestSub1)
4122         .addImm(AMDGPU::sub1);
4123     TII->legalizeOperands(*LoHalf);
4124     TII->legalizeOperands(*HiHalf);
4125     MI.eraseFromParent();
4126     return BB;
4127   }
4128   case AMDGPU::S_ADD_CO_PSEUDO:
4129   case AMDGPU::S_SUB_CO_PSEUDO: {
4130     // This pseudo has a chance to be selected
4131     // only from uniform add/subcarry node. All the VGPR operands
4132     // therefore assumed to be splat vectors.
4133     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4134     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4135     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4136     MachineBasicBlock::iterator MII = MI;
4137     const DebugLoc &DL = MI.getDebugLoc();
4138     MachineOperand &Dest = MI.getOperand(0);
4139     MachineOperand &CarryDest = MI.getOperand(1);
4140     MachineOperand &Src0 = MI.getOperand(2);
4141     MachineOperand &Src1 = MI.getOperand(3);
4142     MachineOperand &Src2 = MI.getOperand(4);
4143     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4144                        ? AMDGPU::S_ADDC_U32
4145                        : AMDGPU::S_SUBB_U32;
4146     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4147       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4148       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4149           .addReg(Src0.getReg());
4150       Src0.setReg(RegOp0);
4151     }
4152     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4153       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4154       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4155           .addReg(Src1.getReg());
4156       Src1.setReg(RegOp1);
4157     }
4158     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4159     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4160       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4161           .addReg(Src2.getReg());
4162       Src2.setReg(RegOp2);
4163     }
4164 
4165     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4166     unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC);
4167     assert(WaveSize == 64 || WaveSize == 32);
4168 
4169     if (WaveSize == 64) {
4170       if (ST.hasScalarCompareEq64()) {
4171         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4172             .addReg(Src2.getReg())
4173             .addImm(0);
4174       } else {
4175         const TargetRegisterClass *SubRC =
4176             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4177         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4178             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4179         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4180             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4181         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4182 
4183         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4184             .add(Src2Sub0)
4185             .add(Src2Sub1);
4186 
4187         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4188             .addReg(Src2_32, RegState::Kill)
4189             .addImm(0);
4190       }
4191     } else {
4192       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4193           .addReg(Src2.getReg())
4194           .addImm(0);
4195     }
4196 
4197     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4198 
4199     unsigned SelOpc =
4200         (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
4201 
4202     BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg())
4203         .addImm(-1)
4204         .addImm(0);
4205 
4206     MI.eraseFromParent();
4207     return BB;
4208   }
4209   case AMDGPU::SI_INIT_M0: {
4210     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4211             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4212         .add(MI.getOperand(0));
4213     MI.eraseFromParent();
4214     return BB;
4215   }
4216   case AMDGPU::GET_GROUPSTATICSIZE: {
4217     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4218            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4219     DebugLoc DL = MI.getDebugLoc();
4220     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4221         .add(MI.getOperand(0))
4222         .addImm(MFI->getLDSSize());
4223     MI.eraseFromParent();
4224     return BB;
4225   }
4226   case AMDGPU::SI_INDIRECT_SRC_V1:
4227   case AMDGPU::SI_INDIRECT_SRC_V2:
4228   case AMDGPU::SI_INDIRECT_SRC_V4:
4229   case AMDGPU::SI_INDIRECT_SRC_V8:
4230   case AMDGPU::SI_INDIRECT_SRC_V16:
4231   case AMDGPU::SI_INDIRECT_SRC_V32:
4232     return emitIndirectSrc(MI, *BB, *getSubtarget());
4233   case AMDGPU::SI_INDIRECT_DST_V1:
4234   case AMDGPU::SI_INDIRECT_DST_V2:
4235   case AMDGPU::SI_INDIRECT_DST_V4:
4236   case AMDGPU::SI_INDIRECT_DST_V8:
4237   case AMDGPU::SI_INDIRECT_DST_V16:
4238   case AMDGPU::SI_INDIRECT_DST_V32:
4239     return emitIndirectDst(MI, *BB, *getSubtarget());
4240   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4241   case AMDGPU::SI_KILL_I1_PSEUDO:
4242     return splitKillBlock(MI, BB);
4243   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4244     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4245     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4246     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4247 
4248     Register Dst = MI.getOperand(0).getReg();
4249     Register Src0 = MI.getOperand(1).getReg();
4250     Register Src1 = MI.getOperand(2).getReg();
4251     const DebugLoc &DL = MI.getDebugLoc();
4252     Register SrcCond = MI.getOperand(3).getReg();
4253 
4254     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4255     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4256     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4257     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4258 
4259     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4260       .addReg(SrcCond);
4261     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4262       .addImm(0)
4263       .addReg(Src0, 0, AMDGPU::sub0)
4264       .addImm(0)
4265       .addReg(Src1, 0, AMDGPU::sub0)
4266       .addReg(SrcCondCopy);
4267     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4268       .addImm(0)
4269       .addReg(Src0, 0, AMDGPU::sub1)
4270       .addImm(0)
4271       .addReg(Src1, 0, AMDGPU::sub1)
4272       .addReg(SrcCondCopy);
4273 
4274     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4275       .addReg(DstLo)
4276       .addImm(AMDGPU::sub0)
4277       .addReg(DstHi)
4278       .addImm(AMDGPU::sub1);
4279     MI.eraseFromParent();
4280     return BB;
4281   }
4282   case AMDGPU::SI_BR_UNDEF: {
4283     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4284     const DebugLoc &DL = MI.getDebugLoc();
4285     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4286                            .add(MI.getOperand(0));
4287     Br->getOperand(1).setIsUndef(true); // read undef SCC
4288     MI.eraseFromParent();
4289     return BB;
4290   }
4291   case AMDGPU::ADJCALLSTACKUP:
4292   case AMDGPU::ADJCALLSTACKDOWN: {
4293     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4294     MachineInstrBuilder MIB(*MF, &MI);
4295     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4296        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4297     return BB;
4298   }
4299   case AMDGPU::SI_CALL_ISEL: {
4300     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4301     const DebugLoc &DL = MI.getDebugLoc();
4302 
4303     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4304 
4305     MachineInstrBuilder MIB;
4306     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4307 
4308     for (const MachineOperand &MO : MI.operands())
4309       MIB.add(MO);
4310 
4311     MIB.cloneMemRefs(MI);
4312     MI.eraseFromParent();
4313     return BB;
4314   }
4315   case AMDGPU::V_ADD_CO_U32_e32:
4316   case AMDGPU::V_SUB_CO_U32_e32:
4317   case AMDGPU::V_SUBREV_CO_U32_e32: {
4318     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4319     const DebugLoc &DL = MI.getDebugLoc();
4320     unsigned Opc = MI.getOpcode();
4321 
4322     bool NeedClampOperand = false;
4323     if (TII->pseudoToMCOpcode(Opc) == -1) {
4324       Opc = AMDGPU::getVOPe64(Opc);
4325       NeedClampOperand = true;
4326     }
4327 
4328     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4329     if (TII->isVOP3(*I)) {
4330       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4331       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4332       I.addReg(TRI->getVCC(), RegState::Define);
4333     }
4334     I.add(MI.getOperand(1))
4335      .add(MI.getOperand(2));
4336     if (NeedClampOperand)
4337       I.addImm(0); // clamp bit for e64 encoding
4338 
4339     TII->legalizeOperands(*I);
4340 
4341     MI.eraseFromParent();
4342     return BB;
4343   }
4344   case AMDGPU::V_ADDC_U32_e32:
4345   case AMDGPU::V_SUBB_U32_e32:
4346   case AMDGPU::V_SUBBREV_U32_e32:
4347     // These instructions have an implicit use of vcc which counts towards the
4348     // constant bus limit.
4349     TII->legalizeOperands(MI);
4350     return BB;
4351   case AMDGPU::DS_GWS_INIT:
4352   case AMDGPU::DS_GWS_SEMA_BR:
4353   case AMDGPU::DS_GWS_BARRIER:
4354     if (Subtarget->needsAlignedVGPRs()) {
4355       // Add implicit aligned super-reg to force alignment on the data operand.
4356       const DebugLoc &DL = MI.getDebugLoc();
4357       MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4358       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
4359       MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0);
4360       Register DataReg = Op->getReg();
4361       bool IsAGPR = TRI->isAGPR(MRI, DataReg);
4362       Register Undef = MRI.createVirtualRegister(
4363           IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass);
4364       BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef);
4365       Register NewVR =
4366           MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass
4367                                            : &AMDGPU::VReg_64_Align2RegClass);
4368       BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR)
4369           .addReg(DataReg, 0, Op->getSubReg())
4370           .addImm(AMDGPU::sub0)
4371           .addReg(Undef)
4372           .addImm(AMDGPU::sub1);
4373       Op->setReg(NewVR);
4374       Op->setSubReg(AMDGPU::sub0);
4375       MI.addOperand(MachineOperand::CreateReg(NewVR, false, true));
4376     }
4377     LLVM_FALLTHROUGH;
4378   case AMDGPU::DS_GWS_SEMA_V:
4379   case AMDGPU::DS_GWS_SEMA_P:
4380   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4381     // A s_waitcnt 0 is required to be the instruction immediately following.
4382     if (getSubtarget()->hasGWSAutoReplay()) {
4383       bundleInstWithWaitcnt(MI);
4384       return BB;
4385     }
4386 
4387     return emitGWSMemViolTestLoop(MI, BB);
4388   case AMDGPU::S_SETREG_B32: {
4389     // Try to optimize cases that only set the denormal mode or rounding mode.
4390     //
4391     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4392     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4393     // instead.
4394     //
4395     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4396     // allow you to have a no side effect instruction in the output of a
4397     // sideeffecting pattern.
4398     unsigned ID, Offset, Width;
4399     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4400     if (ID != AMDGPU::Hwreg::ID_MODE)
4401       return BB;
4402 
4403     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4404     const unsigned SetMask = WidthMask << Offset;
4405 
4406     if (getSubtarget()->hasDenormModeInst()) {
4407       unsigned SetDenormOp = 0;
4408       unsigned SetRoundOp = 0;
4409 
4410       // The dedicated instructions can only set the whole denorm or round mode
4411       // at once, not a subset of bits in either.
4412       if (SetMask ==
4413           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4414         // If this fully sets both the round and denorm mode, emit the two
4415         // dedicated instructions for these.
4416         SetRoundOp = AMDGPU::S_ROUND_MODE;
4417         SetDenormOp = AMDGPU::S_DENORM_MODE;
4418       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4419         SetRoundOp = AMDGPU::S_ROUND_MODE;
4420       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4421         SetDenormOp = AMDGPU::S_DENORM_MODE;
4422       }
4423 
4424       if (SetRoundOp || SetDenormOp) {
4425         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4426         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4427         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4428           unsigned ImmVal = Def->getOperand(1).getImm();
4429           if (SetRoundOp) {
4430             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4431                 .addImm(ImmVal & 0xf);
4432 
4433             // If we also have the denorm mode, get just the denorm mode bits.
4434             ImmVal >>= 4;
4435           }
4436 
4437           if (SetDenormOp) {
4438             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4439                 .addImm(ImmVal & 0xf);
4440           }
4441 
4442           MI.eraseFromParent();
4443           return BB;
4444         }
4445       }
4446     }
4447 
4448     // If only FP bits are touched, used the no side effects pseudo.
4449     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4450                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4451       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4452 
4453     return BB;
4454   }
4455   default:
4456     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4457   }
4458 }
4459 
4460 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4461   return isTypeLegal(VT.getScalarType());
4462 }
4463 
4464 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4465   // This currently forces unfolding various combinations of fsub into fma with
4466   // free fneg'd operands. As long as we have fast FMA (controlled by
4467   // isFMAFasterThanFMulAndFAdd), we should perform these.
4468 
4469   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4470   // most of these combines appear to be cycle neutral but save on instruction
4471   // count / code size.
4472   return true;
4473 }
4474 
4475 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; }
4476 
4477 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4478                                          EVT VT) const {
4479   if (!VT.isVector()) {
4480     return MVT::i1;
4481   }
4482   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4483 }
4484 
4485 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4486   // TODO: Should i16 be used always if legal? For now it would force VALU
4487   // shifts.
4488   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4489 }
4490 
4491 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4492   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4493              ? Ty.changeElementSize(16)
4494              : Ty.changeElementSize(32);
4495 }
4496 
4497 // Answering this is somewhat tricky and depends on the specific device which
4498 // have different rates for fma or all f64 operations.
4499 //
4500 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4501 // regardless of which device (although the number of cycles differs between
4502 // devices), so it is always profitable for f64.
4503 //
4504 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4505 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4506 // which we can always do even without fused FP ops since it returns the same
4507 // result as the separate operations and since it is always full
4508 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4509 // however does not support denormals, so we do report fma as faster if we have
4510 // a fast fma device and require denormals.
4511 //
4512 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4513                                                   EVT VT) const {
4514   VT = VT.getScalarType();
4515 
4516   switch (VT.getSimpleVT().SimpleTy) {
4517   case MVT::f32: {
4518     // If mad is not available this depends only on if f32 fma is full rate.
4519     if (!Subtarget->hasMadMacF32Insts())
4520       return Subtarget->hasFastFMAF32();
4521 
4522     // Otherwise f32 mad is always full rate and returns the same result as
4523     // the separate operations so should be preferred over fma.
4524     // However does not support denomals.
4525     if (hasFP32Denormals(MF))
4526       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4527 
4528     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4529     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4530   }
4531   case MVT::f64:
4532     return true;
4533   case MVT::f16:
4534     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4535   default:
4536     break;
4537   }
4538 
4539   return false;
4540 }
4541 
4542 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4543                                                   LLT Ty) const {
4544   switch (Ty.getScalarSizeInBits()) {
4545   case 16:
4546     return isFMAFasterThanFMulAndFAdd(MF, MVT::f16);
4547   case 32:
4548     return isFMAFasterThanFMulAndFAdd(MF, MVT::f32);
4549   case 64:
4550     return isFMAFasterThanFMulAndFAdd(MF, MVT::f64);
4551   default:
4552     break;
4553   }
4554 
4555   return false;
4556 }
4557 
4558 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const {
4559   if (!Ty.isScalar())
4560     return false;
4561 
4562   if (Ty.getScalarSizeInBits() == 16)
4563     return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF());
4564   if (Ty.getScalarSizeInBits() == 32)
4565     return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF());
4566 
4567   return false;
4568 }
4569 
4570 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4571                                    const SDNode *N) const {
4572   // TODO: Check future ftz flag
4573   // v_mad_f32/v_mac_f32 do not support denormals.
4574   EVT VT = N->getValueType(0);
4575   if (VT == MVT::f32)
4576     return Subtarget->hasMadMacF32Insts() &&
4577            !hasFP32Denormals(DAG.getMachineFunction());
4578   if (VT == MVT::f16) {
4579     return Subtarget->hasMadF16() &&
4580            !hasFP64FP16Denormals(DAG.getMachineFunction());
4581   }
4582 
4583   return false;
4584 }
4585 
4586 //===----------------------------------------------------------------------===//
4587 // Custom DAG Lowering Operations
4588 //===----------------------------------------------------------------------===//
4589 
4590 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4591 // wider vector type is legal.
4592 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4593                                              SelectionDAG &DAG) const {
4594   unsigned Opc = Op.getOpcode();
4595   EVT VT = Op.getValueType();
4596   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4597 
4598   SDValue Lo, Hi;
4599   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4600 
4601   SDLoc SL(Op);
4602   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4603                              Op->getFlags());
4604   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4605                              Op->getFlags());
4606 
4607   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4608 }
4609 
4610 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4611 // wider vector type is legal.
4612 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4613                                               SelectionDAG &DAG) const {
4614   unsigned Opc = Op.getOpcode();
4615   EVT VT = Op.getValueType();
4616   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4617          VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32);
4618 
4619   SDValue Lo0, Hi0;
4620   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4621   SDValue Lo1, Hi1;
4622   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4623 
4624   SDLoc SL(Op);
4625 
4626   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4627                              Op->getFlags());
4628   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4629                              Op->getFlags());
4630 
4631   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4632 }
4633 
4634 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4635                                               SelectionDAG &DAG) const {
4636   unsigned Opc = Op.getOpcode();
4637   EVT VT = Op.getValueType();
4638   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4639          VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32);
4640 
4641   SDValue Lo0, Hi0;
4642   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4643   SDValue Lo1, Hi1;
4644   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4645   SDValue Lo2, Hi2;
4646   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4647 
4648   SDLoc SL(Op);
4649 
4650   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4651                              Op->getFlags());
4652   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4653                              Op->getFlags());
4654 
4655   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4656 }
4657 
4658 
4659 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4660   switch (Op.getOpcode()) {
4661   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4662   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4663   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4664   case ISD::LOAD: {
4665     SDValue Result = LowerLOAD(Op, DAG);
4666     assert((!Result.getNode() ||
4667             Result.getNode()->getNumValues() == 2) &&
4668            "Load should return a value and a chain");
4669     return Result;
4670   }
4671 
4672   case ISD::FSIN:
4673   case ISD::FCOS:
4674     return LowerTrig(Op, DAG);
4675   case ISD::SELECT: return LowerSELECT(Op, DAG);
4676   case ISD::FDIV: return LowerFDIV(Op, DAG);
4677   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4678   case ISD::STORE: return LowerSTORE(Op, DAG);
4679   case ISD::GlobalAddress: {
4680     MachineFunction &MF = DAG.getMachineFunction();
4681     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4682     return LowerGlobalAddress(MFI, Op, DAG);
4683   }
4684   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4685   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4686   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4687   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4688   case ISD::INSERT_SUBVECTOR:
4689     return lowerINSERT_SUBVECTOR(Op, DAG);
4690   case ISD::INSERT_VECTOR_ELT:
4691     return lowerINSERT_VECTOR_ELT(Op, DAG);
4692   case ISD::EXTRACT_VECTOR_ELT:
4693     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4694   case ISD::VECTOR_SHUFFLE:
4695     return lowerVECTOR_SHUFFLE(Op, DAG);
4696   case ISD::BUILD_VECTOR:
4697     return lowerBUILD_VECTOR(Op, DAG);
4698   case ISD::FP_ROUND:
4699     return lowerFP_ROUND(Op, DAG);
4700   case ISD::TRAP:
4701     return lowerTRAP(Op, DAG);
4702   case ISD::DEBUGTRAP:
4703     return lowerDEBUGTRAP(Op, DAG);
4704   case ISD::FABS:
4705   case ISD::FNEG:
4706   case ISD::FCANONICALIZE:
4707   case ISD::BSWAP:
4708     return splitUnaryVectorOp(Op, DAG);
4709   case ISD::FMINNUM:
4710   case ISD::FMAXNUM:
4711     return lowerFMINNUM_FMAXNUM(Op, DAG);
4712   case ISD::FMA:
4713     return splitTernaryVectorOp(Op, DAG);
4714   case ISD::FP_TO_SINT:
4715   case ISD::FP_TO_UINT:
4716     return LowerFP_TO_INT(Op, DAG);
4717   case ISD::SHL:
4718   case ISD::SRA:
4719   case ISD::SRL:
4720   case ISD::ADD:
4721   case ISD::SUB:
4722   case ISD::MUL:
4723   case ISD::SMIN:
4724   case ISD::SMAX:
4725   case ISD::UMIN:
4726   case ISD::UMAX:
4727   case ISD::FADD:
4728   case ISD::FMUL:
4729   case ISD::FMINNUM_IEEE:
4730   case ISD::FMAXNUM_IEEE:
4731   case ISD::UADDSAT:
4732   case ISD::USUBSAT:
4733   case ISD::SADDSAT:
4734   case ISD::SSUBSAT:
4735     return splitBinaryVectorOp(Op, DAG);
4736   case ISD::SMULO:
4737   case ISD::UMULO:
4738     return lowerXMULO(Op, DAG);
4739   case ISD::SMUL_LOHI:
4740   case ISD::UMUL_LOHI:
4741     return lowerXMUL_LOHI(Op, DAG);
4742   case ISD::DYNAMIC_STACKALLOC:
4743     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4744   }
4745   return SDValue();
4746 }
4747 
4748 // Used for D16: Casts the result of an instruction into the right vector,
4749 // packs values if loads return unpacked values.
4750 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4751                                        const SDLoc &DL,
4752                                        SelectionDAG &DAG, bool Unpacked) {
4753   if (!LoadVT.isVector())
4754     return Result;
4755 
4756   // Cast back to the original packed type or to a larger type that is a
4757   // multiple of 32 bit for D16. Widening the return type is a required for
4758   // legalization.
4759   EVT FittingLoadVT = LoadVT;
4760   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4761     FittingLoadVT =
4762         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4763                          LoadVT.getVectorNumElements() + 1);
4764   }
4765 
4766   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4767     // Truncate to v2i16/v4i16.
4768     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4769 
4770     // Workaround legalizer not scalarizing truncate after vector op
4771     // legalization but not creating intermediate vector trunc.
4772     SmallVector<SDValue, 4> Elts;
4773     DAG.ExtractVectorElements(Result, Elts);
4774     for (SDValue &Elt : Elts)
4775       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4776 
4777     // Pad illegal v1i16/v3fi6 to v4i16
4778     if ((LoadVT.getVectorNumElements() % 2) == 1)
4779       Elts.push_back(DAG.getUNDEF(MVT::i16));
4780 
4781     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4782 
4783     // Bitcast to original type (v2f16/v4f16).
4784     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4785   }
4786 
4787   // Cast back to the original packed type.
4788   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4789 }
4790 
4791 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4792                                               MemSDNode *M,
4793                                               SelectionDAG &DAG,
4794                                               ArrayRef<SDValue> Ops,
4795                                               bool IsIntrinsic) const {
4796   SDLoc DL(M);
4797 
4798   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4799   EVT LoadVT = M->getValueType(0);
4800 
4801   EVT EquivLoadVT = LoadVT;
4802   if (LoadVT.isVector()) {
4803     if (Unpacked) {
4804       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4805                                      LoadVT.getVectorNumElements());
4806     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4807       // Widen v3f16 to legal type
4808       EquivLoadVT =
4809           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4810                            LoadVT.getVectorNumElements() + 1);
4811     }
4812   }
4813 
4814   // Change from v4f16/v2f16 to EquivLoadVT.
4815   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4816 
4817   SDValue Load
4818     = DAG.getMemIntrinsicNode(
4819       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4820       VTList, Ops, M->getMemoryVT(),
4821       M->getMemOperand());
4822 
4823   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4824 
4825   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4826 }
4827 
4828 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4829                                              SelectionDAG &DAG,
4830                                              ArrayRef<SDValue> Ops) const {
4831   SDLoc DL(M);
4832   EVT LoadVT = M->getValueType(0);
4833   EVT EltType = LoadVT.getScalarType();
4834   EVT IntVT = LoadVT.changeTypeToInteger();
4835 
4836   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4837 
4838   unsigned Opc =
4839       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4840 
4841   if (IsD16) {
4842     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4843   }
4844 
4845   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4846   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4847     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4848 
4849   if (isTypeLegal(LoadVT)) {
4850     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4851                                M->getMemOperand(), DAG);
4852   }
4853 
4854   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4855   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4856   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4857                                         M->getMemOperand(), DAG);
4858   return DAG.getMergeValues(
4859       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4860       DL);
4861 }
4862 
4863 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4864                                   SDNode *N, SelectionDAG &DAG) {
4865   EVT VT = N->getValueType(0);
4866   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4867   unsigned CondCode = CD->getZExtValue();
4868   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4869     return DAG.getUNDEF(VT);
4870 
4871   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4872 
4873   SDValue LHS = N->getOperand(1);
4874   SDValue RHS = N->getOperand(2);
4875 
4876   SDLoc DL(N);
4877 
4878   EVT CmpVT = LHS.getValueType();
4879   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4880     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4881       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4882     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4883     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4884   }
4885 
4886   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4887 
4888   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4889   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4890 
4891   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4892                               DAG.getCondCode(CCOpcode));
4893   if (VT.bitsEq(CCVT))
4894     return SetCC;
4895   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4896 }
4897 
4898 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4899                                   SDNode *N, SelectionDAG &DAG) {
4900   EVT VT = N->getValueType(0);
4901   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4902 
4903   unsigned CondCode = CD->getZExtValue();
4904   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4905     return DAG.getUNDEF(VT);
4906 
4907   SDValue Src0 = N->getOperand(1);
4908   SDValue Src1 = N->getOperand(2);
4909   EVT CmpVT = Src0.getValueType();
4910   SDLoc SL(N);
4911 
4912   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4913     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4914     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4915   }
4916 
4917   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4918   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4919   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4920   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4921   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4922                               Src1, DAG.getCondCode(CCOpcode));
4923   if (VT.bitsEq(CCVT))
4924     return SetCC;
4925   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4926 }
4927 
4928 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4929                                     SelectionDAG &DAG) {
4930   EVT VT = N->getValueType(0);
4931   SDValue Src = N->getOperand(1);
4932   SDLoc SL(N);
4933 
4934   if (Src.getOpcode() == ISD::SETCC) {
4935     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4936     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4937                        Src.getOperand(1), Src.getOperand(2));
4938   }
4939   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4940     // (ballot 0) -> 0
4941     if (Arg->isZero())
4942       return DAG.getConstant(0, SL, VT);
4943 
4944     // (ballot 1) -> EXEC/EXEC_LO
4945     if (Arg->isOne()) {
4946       Register Exec;
4947       if (VT.getScalarSizeInBits() == 32)
4948         Exec = AMDGPU::EXEC_LO;
4949       else if (VT.getScalarSizeInBits() == 64)
4950         Exec = AMDGPU::EXEC;
4951       else
4952         return SDValue();
4953 
4954       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4955     }
4956   }
4957 
4958   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4959   // ISD::SETNE)
4960   return DAG.getNode(
4961       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4962       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4963 }
4964 
4965 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4966                                           SmallVectorImpl<SDValue> &Results,
4967                                           SelectionDAG &DAG) const {
4968   switch (N->getOpcode()) {
4969   case ISD::INSERT_VECTOR_ELT: {
4970     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4971       Results.push_back(Res);
4972     return;
4973   }
4974   case ISD::EXTRACT_VECTOR_ELT: {
4975     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4976       Results.push_back(Res);
4977     return;
4978   }
4979   case ISD::INTRINSIC_WO_CHAIN: {
4980     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4981     switch (IID) {
4982     case Intrinsic::amdgcn_cvt_pkrtz: {
4983       SDValue Src0 = N->getOperand(1);
4984       SDValue Src1 = N->getOperand(2);
4985       SDLoc SL(N);
4986       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4987                                 Src0, Src1);
4988       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4989       return;
4990     }
4991     case Intrinsic::amdgcn_cvt_pknorm_i16:
4992     case Intrinsic::amdgcn_cvt_pknorm_u16:
4993     case Intrinsic::amdgcn_cvt_pk_i16:
4994     case Intrinsic::amdgcn_cvt_pk_u16: {
4995       SDValue Src0 = N->getOperand(1);
4996       SDValue Src1 = N->getOperand(2);
4997       SDLoc SL(N);
4998       unsigned Opcode;
4999 
5000       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
5001         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
5002       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
5003         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
5004       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
5005         Opcode = AMDGPUISD::CVT_PK_I16_I32;
5006       else
5007         Opcode = AMDGPUISD::CVT_PK_U16_U32;
5008 
5009       EVT VT = N->getValueType(0);
5010       if (isTypeLegal(VT))
5011         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
5012       else {
5013         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
5014         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
5015       }
5016       return;
5017     }
5018     }
5019     break;
5020   }
5021   case ISD::INTRINSIC_W_CHAIN: {
5022     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
5023       if (Res.getOpcode() == ISD::MERGE_VALUES) {
5024         // FIXME: Hacky
5025         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
5026           Results.push_back(Res.getOperand(I));
5027         }
5028       } else {
5029         Results.push_back(Res);
5030         Results.push_back(Res.getValue(1));
5031       }
5032       return;
5033     }
5034 
5035     break;
5036   }
5037   case ISD::SELECT: {
5038     SDLoc SL(N);
5039     EVT VT = N->getValueType(0);
5040     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
5041     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
5042     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
5043 
5044     EVT SelectVT = NewVT;
5045     if (NewVT.bitsLT(MVT::i32)) {
5046       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
5047       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
5048       SelectVT = MVT::i32;
5049     }
5050 
5051     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
5052                                     N->getOperand(0), LHS, RHS);
5053 
5054     if (NewVT != SelectVT)
5055       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
5056     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
5057     return;
5058   }
5059   case ISD::FNEG: {
5060     if (N->getValueType(0) != MVT::v2f16)
5061       break;
5062 
5063     SDLoc SL(N);
5064     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5065 
5066     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
5067                              BC,
5068                              DAG.getConstant(0x80008000, SL, MVT::i32));
5069     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5070     return;
5071   }
5072   case ISD::FABS: {
5073     if (N->getValueType(0) != MVT::v2f16)
5074       break;
5075 
5076     SDLoc SL(N);
5077     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5078 
5079     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
5080                              BC,
5081                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
5082     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5083     return;
5084   }
5085   default:
5086     break;
5087   }
5088 }
5089 
5090 /// Helper function for LowerBRCOND
5091 static SDNode *findUser(SDValue Value, unsigned Opcode) {
5092 
5093   SDNode *Parent = Value.getNode();
5094   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
5095        I != E; ++I) {
5096 
5097     if (I.getUse().get() != Value)
5098       continue;
5099 
5100     if (I->getOpcode() == Opcode)
5101       return *I;
5102   }
5103   return nullptr;
5104 }
5105 
5106 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
5107   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
5108     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
5109     case Intrinsic::amdgcn_if:
5110       return AMDGPUISD::IF;
5111     case Intrinsic::amdgcn_else:
5112       return AMDGPUISD::ELSE;
5113     case Intrinsic::amdgcn_loop:
5114       return AMDGPUISD::LOOP;
5115     case Intrinsic::amdgcn_end_cf:
5116       llvm_unreachable("should not occur");
5117     default:
5118       return 0;
5119     }
5120   }
5121 
5122   // break, if_break, else_break are all only used as inputs to loop, not
5123   // directly as branch conditions.
5124   return 0;
5125 }
5126 
5127 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
5128   const Triple &TT = getTargetMachine().getTargetTriple();
5129   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5130           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5131          AMDGPU::shouldEmitConstantsToTextSection(TT);
5132 }
5133 
5134 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
5135   // FIXME: Either avoid relying on address space here or change the default
5136   // address space for functions to avoid the explicit check.
5137   return (GV->getValueType()->isFunctionTy() ||
5138           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
5139          !shouldEmitFixup(GV) &&
5140          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
5141 }
5142 
5143 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
5144   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
5145 }
5146 
5147 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
5148   if (!GV->hasExternalLinkage())
5149     return true;
5150 
5151   const auto OS = getTargetMachine().getTargetTriple().getOS();
5152   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
5153 }
5154 
5155 /// This transforms the control flow intrinsics to get the branch destination as
5156 /// last parameter, also switches branch target with BR if the need arise
5157 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
5158                                       SelectionDAG &DAG) const {
5159   SDLoc DL(BRCOND);
5160 
5161   SDNode *Intr = BRCOND.getOperand(1).getNode();
5162   SDValue Target = BRCOND.getOperand(2);
5163   SDNode *BR = nullptr;
5164   SDNode *SetCC = nullptr;
5165 
5166   if (Intr->getOpcode() == ISD::SETCC) {
5167     // As long as we negate the condition everything is fine
5168     SetCC = Intr;
5169     Intr = SetCC->getOperand(0).getNode();
5170 
5171   } else {
5172     // Get the target from BR if we don't negate the condition
5173     BR = findUser(BRCOND, ISD::BR);
5174     assert(BR && "brcond missing unconditional branch user");
5175     Target = BR->getOperand(1);
5176   }
5177 
5178   unsigned CFNode = isCFIntrinsic(Intr);
5179   if (CFNode == 0) {
5180     // This is a uniform branch so we don't need to legalize.
5181     return BRCOND;
5182   }
5183 
5184   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5185                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5186 
5187   assert(!SetCC ||
5188         (SetCC->getConstantOperandVal(1) == 1 &&
5189          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5190                                                              ISD::SETNE));
5191 
5192   // operands of the new intrinsic call
5193   SmallVector<SDValue, 4> Ops;
5194   if (HaveChain)
5195     Ops.push_back(BRCOND.getOperand(0));
5196 
5197   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5198   Ops.push_back(Target);
5199 
5200   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5201 
5202   // build the new intrinsic call
5203   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5204 
5205   if (!HaveChain) {
5206     SDValue Ops[] =  {
5207       SDValue(Result, 0),
5208       BRCOND.getOperand(0)
5209     };
5210 
5211     Result = DAG.getMergeValues(Ops, DL).getNode();
5212   }
5213 
5214   if (BR) {
5215     // Give the branch instruction our target
5216     SDValue Ops[] = {
5217       BR->getOperand(0),
5218       BRCOND.getOperand(2)
5219     };
5220     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5221     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5222   }
5223 
5224   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5225 
5226   // Copy the intrinsic results to registers
5227   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5228     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5229     if (!CopyToReg)
5230       continue;
5231 
5232     Chain = DAG.getCopyToReg(
5233       Chain, DL,
5234       CopyToReg->getOperand(1),
5235       SDValue(Result, i - 1),
5236       SDValue());
5237 
5238     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5239   }
5240 
5241   // Remove the old intrinsic from the chain
5242   DAG.ReplaceAllUsesOfValueWith(
5243     SDValue(Intr, Intr->getNumValues() - 1),
5244     Intr->getOperand(0));
5245 
5246   return Chain;
5247 }
5248 
5249 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5250                                           SelectionDAG &DAG) const {
5251   MVT VT = Op.getSimpleValueType();
5252   SDLoc DL(Op);
5253   // Checking the depth
5254   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5255     return DAG.getConstant(0, DL, VT);
5256 
5257   MachineFunction &MF = DAG.getMachineFunction();
5258   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5259   // Check for kernel and shader functions
5260   if (Info->isEntryFunction())
5261     return DAG.getConstant(0, DL, VT);
5262 
5263   MachineFrameInfo &MFI = MF.getFrameInfo();
5264   // There is a call to @llvm.returnaddress in this function
5265   MFI.setReturnAddressIsTaken(true);
5266 
5267   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5268   // Get the return address reg and mark it as an implicit live-in
5269   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5270 
5271   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5272 }
5273 
5274 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5275                                             SDValue Op,
5276                                             const SDLoc &DL,
5277                                             EVT VT) const {
5278   return Op.getValueType().bitsLE(VT) ?
5279       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5280     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5281                 DAG.getTargetConstant(0, DL, MVT::i32));
5282 }
5283 
5284 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5285   assert(Op.getValueType() == MVT::f16 &&
5286          "Do not know how to custom lower FP_ROUND for non-f16 type");
5287 
5288   SDValue Src = Op.getOperand(0);
5289   EVT SrcVT = Src.getValueType();
5290   if (SrcVT != MVT::f64)
5291     return Op;
5292 
5293   SDLoc DL(Op);
5294 
5295   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5296   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5297   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5298 }
5299 
5300 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5301                                                SelectionDAG &DAG) const {
5302   EVT VT = Op.getValueType();
5303   const MachineFunction &MF = DAG.getMachineFunction();
5304   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5305   bool IsIEEEMode = Info->getMode().IEEE;
5306 
5307   // FIXME: Assert during selection that this is only selected for
5308   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5309   // mode functions, but this happens to be OK since it's only done in cases
5310   // where there is known no sNaN.
5311   if (IsIEEEMode)
5312     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5313 
5314   if (VT == MVT::v4f16)
5315     return splitBinaryVectorOp(Op, DAG);
5316   return Op;
5317 }
5318 
5319 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5320   EVT VT = Op.getValueType();
5321   SDLoc SL(Op);
5322   SDValue LHS = Op.getOperand(0);
5323   SDValue RHS = Op.getOperand(1);
5324   bool isSigned = Op.getOpcode() == ISD::SMULO;
5325 
5326   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5327     const APInt &C = RHSC->getAPIntValue();
5328     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5329     if (C.isPowerOf2()) {
5330       // smulo(x, signed_min) is same as umulo(x, signed_min).
5331       bool UseArithShift = isSigned && !C.isMinSignedValue();
5332       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5333       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5334       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5335           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5336                       SL, VT, Result, ShiftAmt),
5337           LHS, ISD::SETNE);
5338       return DAG.getMergeValues({ Result, Overflow }, SL);
5339     }
5340   }
5341 
5342   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5343   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5344                             SL, VT, LHS, RHS);
5345 
5346   SDValue Sign = isSigned
5347     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5348                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5349     : DAG.getConstant(0, SL, VT);
5350   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5351 
5352   return DAG.getMergeValues({ Result, Overflow }, SL);
5353 }
5354 
5355 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const {
5356   if (Op->isDivergent()) {
5357     // Select to V_MAD_[IU]64_[IU]32.
5358     return Op;
5359   }
5360   if (Subtarget->hasSMulHi()) {
5361     // Expand to S_MUL_I32 + S_MUL_HI_[IU]32.
5362     return SDValue();
5363   }
5364   // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to
5365   // calculate the high part, so we might as well do the whole thing with
5366   // V_MAD_[IU]64_[IU]32.
5367   return Op;
5368 }
5369 
5370 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5371   if (!Subtarget->isTrapHandlerEnabled() ||
5372       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5373     return lowerTrapEndpgm(Op, DAG);
5374 
5375   if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) {
5376     switch (*HsaAbiVer) {
5377     case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
5378     case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
5379       return lowerTrapHsaQueuePtr(Op, DAG);
5380     case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
5381       return Subtarget->supportsGetDoorbellID() ?
5382           lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG);
5383     }
5384   }
5385 
5386   llvm_unreachable("Unknown trap handler");
5387 }
5388 
5389 SDValue SITargetLowering::lowerTrapEndpgm(
5390     SDValue Op, SelectionDAG &DAG) const {
5391   SDLoc SL(Op);
5392   SDValue Chain = Op.getOperand(0);
5393   return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5394 }
5395 
5396 SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5397     SDValue Op, SelectionDAG &DAG) const {
5398   SDLoc SL(Op);
5399   SDValue Chain = Op.getOperand(0);
5400 
5401   MachineFunction &MF = DAG.getMachineFunction();
5402   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5403   Register UserSGPR = Info->getQueuePtrUserSGPR();
5404 
5405   SDValue QueuePtr;
5406   if (UserSGPR == AMDGPU::NoRegister) {
5407     // We probably are in a function incorrectly marked with
5408     // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the trap,
5409     // so just use a null pointer.
5410     QueuePtr = DAG.getConstant(0, SL, MVT::i64);
5411   } else {
5412     QueuePtr = CreateLiveInRegister(
5413       DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5414   }
5415 
5416   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5417   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5418                                    QueuePtr, SDValue());
5419 
5420   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5421   SDValue Ops[] = {
5422     ToReg,
5423     DAG.getTargetConstant(TrapID, SL, MVT::i16),
5424     SGPR01,
5425     ToReg.getValue(1)
5426   };
5427   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5428 }
5429 
5430 SDValue SITargetLowering::lowerTrapHsa(
5431     SDValue Op, SelectionDAG &DAG) const {
5432   SDLoc SL(Op);
5433   SDValue Chain = Op.getOperand(0);
5434 
5435   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5436   SDValue Ops[] = {
5437     Chain,
5438     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5439   };
5440   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5441 }
5442 
5443 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5444   SDLoc SL(Op);
5445   SDValue Chain = Op.getOperand(0);
5446   MachineFunction &MF = DAG.getMachineFunction();
5447 
5448   if (!Subtarget->isTrapHandlerEnabled() ||
5449       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5450     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5451                                      "debugtrap handler not supported",
5452                                      Op.getDebugLoc(),
5453                                      DS_Warning);
5454     LLVMContext &Ctx = MF.getFunction().getContext();
5455     Ctx.diagnose(NoTrap);
5456     return Chain;
5457   }
5458 
5459   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5460   SDValue Ops[] = {
5461     Chain,
5462     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5463   };
5464   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5465 }
5466 
5467 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5468                                              SelectionDAG &DAG) const {
5469   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5470   if (Subtarget->hasApertureRegs()) {
5471     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5472         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5473         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5474     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5475         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5476         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5477     unsigned Encoding =
5478         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5479         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5480         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5481 
5482     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5483     SDValue ApertureReg = SDValue(
5484         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5485     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5486     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5487   }
5488 
5489   MachineFunction &MF = DAG.getMachineFunction();
5490   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5491   Register UserSGPR = Info->getQueuePtrUserSGPR();
5492   if (UserSGPR == AMDGPU::NoRegister) {
5493     // We probably are in a function incorrectly marked with
5494     // amdgpu-no-queue-ptr. This is undefined.
5495     return DAG.getUNDEF(MVT::i32);
5496   }
5497 
5498   SDValue QueuePtr = CreateLiveInRegister(
5499     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5500 
5501   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5502   // private_segment_aperture_base_hi.
5503   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5504 
5505   SDValue Ptr =
5506       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5507 
5508   // TODO: Use custom target PseudoSourceValue.
5509   // TODO: We should use the value from the IR intrinsic call, but it might not
5510   // be available and how do we get it?
5511   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5512   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5513                      commonAlignment(Align(64), StructOffset),
5514                      MachineMemOperand::MODereferenceable |
5515                          MachineMemOperand::MOInvariant);
5516 }
5517 
5518 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5519                                              SelectionDAG &DAG) const {
5520   SDLoc SL(Op);
5521   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5522 
5523   SDValue Src = ASC->getOperand(0);
5524   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5525 
5526   const AMDGPUTargetMachine &TM =
5527     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5528 
5529   // flat -> local/private
5530   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5531     unsigned DestAS = ASC->getDestAddressSpace();
5532 
5533     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5534         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5535       unsigned NullVal = TM.getNullPointerValue(DestAS);
5536       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5537       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5538       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5539 
5540       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
5541                          NonNull, Ptr, SegmentNullPtr);
5542     }
5543   }
5544 
5545   // local/private -> flat
5546   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5547     unsigned SrcAS = ASC->getSrcAddressSpace();
5548 
5549     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5550         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5551       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5552       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5553 
5554       SDValue NonNull
5555         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5556 
5557       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5558       SDValue CvtPtr
5559         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5560 
5561       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5562                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5563                          FlatNullPtr);
5564     }
5565   }
5566 
5567   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5568       Src.getValueType() == MVT::i64)
5569     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5570 
5571   // global <-> flat are no-ops and never emitted.
5572 
5573   const MachineFunction &MF = DAG.getMachineFunction();
5574   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5575     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5576   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5577 
5578   return DAG.getUNDEF(ASC->getValueType(0));
5579 }
5580 
5581 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5582 // the small vector and inserting them into the big vector. That is better than
5583 // the default expansion of doing it via a stack slot. Even though the use of
5584 // the stack slot would be optimized away afterwards, the stack slot itself
5585 // remains.
5586 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5587                                                 SelectionDAG &DAG) const {
5588   SDValue Vec = Op.getOperand(0);
5589   SDValue Ins = Op.getOperand(1);
5590   SDValue Idx = Op.getOperand(2);
5591   EVT VecVT = Vec.getValueType();
5592   EVT InsVT = Ins.getValueType();
5593   EVT EltVT = VecVT.getVectorElementType();
5594   unsigned InsNumElts = InsVT.getVectorNumElements();
5595   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5596   SDLoc SL(Op);
5597 
5598   for (unsigned I = 0; I != InsNumElts; ++I) {
5599     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5600                               DAG.getConstant(I, SL, MVT::i32));
5601     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5602                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5603   }
5604   return Vec;
5605 }
5606 
5607 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5608                                                  SelectionDAG &DAG) const {
5609   SDValue Vec = Op.getOperand(0);
5610   SDValue InsVal = Op.getOperand(1);
5611   SDValue Idx = Op.getOperand(2);
5612   EVT VecVT = Vec.getValueType();
5613   EVT EltVT = VecVT.getVectorElementType();
5614   unsigned VecSize = VecVT.getSizeInBits();
5615   unsigned EltSize = EltVT.getSizeInBits();
5616 
5617 
5618   assert(VecSize <= 64);
5619 
5620   unsigned NumElts = VecVT.getVectorNumElements();
5621   SDLoc SL(Op);
5622   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5623 
5624   if (NumElts == 4 && EltSize == 16 && KIdx) {
5625     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5626 
5627     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5628                                  DAG.getConstant(0, SL, MVT::i32));
5629     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5630                                  DAG.getConstant(1, SL, MVT::i32));
5631 
5632     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5633     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5634 
5635     unsigned Idx = KIdx->getZExtValue();
5636     bool InsertLo = Idx < 2;
5637     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5638       InsertLo ? LoVec : HiVec,
5639       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5640       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5641 
5642     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5643 
5644     SDValue Concat = InsertLo ?
5645       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5646       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5647 
5648     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5649   }
5650 
5651   if (isa<ConstantSDNode>(Idx))
5652     return SDValue();
5653 
5654   MVT IntVT = MVT::getIntegerVT(VecSize);
5655 
5656   // Avoid stack access for dynamic indexing.
5657   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5658 
5659   // Create a congruent vector with the target value in each element so that
5660   // the required element can be masked and ORed into the target vector.
5661   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5662                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5663 
5664   assert(isPowerOf2_32(EltSize));
5665   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5666 
5667   // Convert vector index to bit-index.
5668   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5669 
5670   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5671   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5672                             DAG.getConstant(0xffff, SL, IntVT),
5673                             ScaledIdx);
5674 
5675   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5676   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5677                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5678 
5679   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5680   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5681 }
5682 
5683 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5684                                                   SelectionDAG &DAG) const {
5685   SDLoc SL(Op);
5686 
5687   EVT ResultVT = Op.getValueType();
5688   SDValue Vec = Op.getOperand(0);
5689   SDValue Idx = Op.getOperand(1);
5690   EVT VecVT = Vec.getValueType();
5691   unsigned VecSize = VecVT.getSizeInBits();
5692   EVT EltVT = VecVT.getVectorElementType();
5693   assert(VecSize <= 64);
5694 
5695   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5696 
5697   // Make sure we do any optimizations that will make it easier to fold
5698   // source modifiers before obscuring it with bit operations.
5699 
5700   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5701   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5702     return Combined;
5703 
5704   unsigned EltSize = EltVT.getSizeInBits();
5705   assert(isPowerOf2_32(EltSize));
5706 
5707   MVT IntVT = MVT::getIntegerVT(VecSize);
5708   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5709 
5710   // Convert vector index to bit-index (* EltSize)
5711   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5712 
5713   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5714   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5715 
5716   if (ResultVT == MVT::f16) {
5717     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5718     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5719   }
5720 
5721   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5722 }
5723 
5724 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5725   assert(Elt % 2 == 0);
5726   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5727 }
5728 
5729 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5730                                               SelectionDAG &DAG) const {
5731   SDLoc SL(Op);
5732   EVT ResultVT = Op.getValueType();
5733   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5734 
5735   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5736   EVT EltVT = PackVT.getVectorElementType();
5737   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5738 
5739   // vector_shuffle <0,1,6,7> lhs, rhs
5740   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5741   //
5742   // vector_shuffle <6,7,2,3> lhs, rhs
5743   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5744   //
5745   // vector_shuffle <6,7,0,1> lhs, rhs
5746   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5747 
5748   // Avoid scalarizing when both halves are reading from consecutive elements.
5749   SmallVector<SDValue, 4> Pieces;
5750   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5751     if (elementPairIsContiguous(SVN->getMask(), I)) {
5752       const int Idx = SVN->getMaskElt(I);
5753       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5754       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5755       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5756                                     PackVT, SVN->getOperand(VecIdx),
5757                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5758       Pieces.push_back(SubVec);
5759     } else {
5760       const int Idx0 = SVN->getMaskElt(I);
5761       const int Idx1 = SVN->getMaskElt(I + 1);
5762       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5763       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5764       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5765       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5766 
5767       SDValue Vec0 = SVN->getOperand(VecIdx0);
5768       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5769                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5770 
5771       SDValue Vec1 = SVN->getOperand(VecIdx1);
5772       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5773                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5774       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5775     }
5776   }
5777 
5778   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5779 }
5780 
5781 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5782                                             SelectionDAG &DAG) const {
5783   SDLoc SL(Op);
5784   EVT VT = Op.getValueType();
5785 
5786   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5787     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5788 
5789     // Turn into pair of packed build_vectors.
5790     // TODO: Special case for constants that can be materialized with s_mov_b64.
5791     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5792                                     { Op.getOperand(0), Op.getOperand(1) });
5793     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5794                                     { Op.getOperand(2), Op.getOperand(3) });
5795 
5796     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5797     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5798 
5799     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5800     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5801   }
5802 
5803   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5804   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5805 
5806   SDValue Lo = Op.getOperand(0);
5807   SDValue Hi = Op.getOperand(1);
5808 
5809   // Avoid adding defined bits with the zero_extend.
5810   if (Hi.isUndef()) {
5811     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5812     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5813     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5814   }
5815 
5816   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5817   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5818 
5819   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5820                               DAG.getConstant(16, SL, MVT::i32));
5821   if (Lo.isUndef())
5822     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5823 
5824   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5825   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5826 
5827   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5828   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5829 }
5830 
5831 bool
5832 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5833   // We can fold offsets for anything that doesn't require a GOT relocation.
5834   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5835           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5836           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5837          !shouldEmitGOTReloc(GA->getGlobal());
5838 }
5839 
5840 static SDValue
5841 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5842                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5843                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5844   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5845   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5846   // lowered to the following code sequence:
5847   //
5848   // For constant address space:
5849   //   s_getpc_b64 s[0:1]
5850   //   s_add_u32 s0, s0, $symbol
5851   //   s_addc_u32 s1, s1, 0
5852   //
5853   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5854   //   a fixup or relocation is emitted to replace $symbol with a literal
5855   //   constant, which is a pc-relative offset from the encoding of the $symbol
5856   //   operand to the global variable.
5857   //
5858   // For global address space:
5859   //   s_getpc_b64 s[0:1]
5860   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5861   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5862   //
5863   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5864   //   fixups or relocations are emitted to replace $symbol@*@lo and
5865   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5866   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5867   //   operand to the global variable.
5868   //
5869   // What we want here is an offset from the value returned by s_getpc
5870   // (which is the address of the s_add_u32 instruction) to the global
5871   // variable, but since the encoding of $symbol starts 4 bytes after the start
5872   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5873   // small. This requires us to add 4 to the global variable offset in order to
5874   // compute the correct address. Similarly for the s_addc_u32 instruction, the
5875   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
5876   // instruction.
5877   SDValue PtrLo =
5878       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5879   SDValue PtrHi;
5880   if (GAFlags == SIInstrInfo::MO_NONE) {
5881     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5882   } else {
5883     PtrHi =
5884         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
5885   }
5886   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5887 }
5888 
5889 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5890                                              SDValue Op,
5891                                              SelectionDAG &DAG) const {
5892   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5893   SDLoc DL(GSD);
5894   EVT PtrVT = Op.getValueType();
5895 
5896   const GlobalValue *GV = GSD->getGlobal();
5897   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5898        shouldUseLDSConstAddress(GV)) ||
5899       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5900       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
5901     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5902         GV->hasExternalLinkage()) {
5903       Type *Ty = GV->getValueType();
5904       // HIP uses an unsized array `extern __shared__ T s[]` or similar
5905       // zero-sized type in other languages to declare the dynamic shared
5906       // memory which size is not known at the compile time. They will be
5907       // allocated by the runtime and placed directly after the static
5908       // allocated ones. They all share the same offset.
5909       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
5910         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
5911         // Adjust alignment for that dynamic shared memory array.
5912         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
5913         return SDValue(
5914             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
5915       }
5916     }
5917     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5918   }
5919 
5920   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5921     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5922                                             SIInstrInfo::MO_ABS32_LO);
5923     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5924   }
5925 
5926   if (shouldEmitFixup(GV))
5927     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5928   else if (shouldEmitPCReloc(GV))
5929     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5930                                    SIInstrInfo::MO_REL32);
5931 
5932   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5933                                             SIInstrInfo::MO_GOTPCREL32);
5934 
5935   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5936   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5937   const DataLayout &DataLayout = DAG.getDataLayout();
5938   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
5939   MachinePointerInfo PtrInfo
5940     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5941 
5942   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
5943                      MachineMemOperand::MODereferenceable |
5944                          MachineMemOperand::MOInvariant);
5945 }
5946 
5947 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5948                                    const SDLoc &DL, SDValue V) const {
5949   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5950   // the destination register.
5951   //
5952   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5953   // so we will end up with redundant moves to m0.
5954   //
5955   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5956 
5957   // A Null SDValue creates a glue result.
5958   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5959                                   V, Chain);
5960   return SDValue(M0, 0);
5961 }
5962 
5963 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5964                                                  SDValue Op,
5965                                                  MVT VT,
5966                                                  unsigned Offset) const {
5967   SDLoc SL(Op);
5968   SDValue Param = lowerKernargMemParameter(
5969       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
5970   // The local size values will have the hi 16-bits as zero.
5971   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5972                      DAG.getValueType(VT));
5973 }
5974 
5975 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5976                                         EVT VT) {
5977   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5978                                       "non-hsa intrinsic with hsa target",
5979                                       DL.getDebugLoc());
5980   DAG.getContext()->diagnose(BadIntrin);
5981   return DAG.getUNDEF(VT);
5982 }
5983 
5984 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5985                                          EVT VT) {
5986   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5987                                       "intrinsic not supported on subtarget",
5988                                       DL.getDebugLoc());
5989   DAG.getContext()->diagnose(BadIntrin);
5990   return DAG.getUNDEF(VT);
5991 }
5992 
5993 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5994                                     ArrayRef<SDValue> Elts) {
5995   assert(!Elts.empty());
5996   MVT Type;
5997   unsigned NumElts = Elts.size();
5998 
5999   if (NumElts <= 8) {
6000     Type = MVT::getVectorVT(MVT::f32, NumElts);
6001   } else {
6002     assert(Elts.size() <= 16);
6003     Type = MVT::v16f32;
6004     NumElts = 16;
6005   }
6006 
6007   SmallVector<SDValue, 16> VecElts(NumElts);
6008   for (unsigned i = 0; i < Elts.size(); ++i) {
6009     SDValue Elt = Elts[i];
6010     if (Elt.getValueType() != MVT::f32)
6011       Elt = DAG.getBitcast(MVT::f32, Elt);
6012     VecElts[i] = Elt;
6013   }
6014   for (unsigned i = Elts.size(); i < NumElts; ++i)
6015     VecElts[i] = DAG.getUNDEF(MVT::f32);
6016 
6017   if (NumElts == 1)
6018     return VecElts[0];
6019   return DAG.getBuildVector(Type, DL, VecElts);
6020 }
6021 
6022 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
6023                               SDValue Src, int ExtraElts) {
6024   EVT SrcVT = Src.getValueType();
6025 
6026   SmallVector<SDValue, 8> Elts;
6027 
6028   if (SrcVT.isVector())
6029     DAG.ExtractVectorElements(Src, Elts);
6030   else
6031     Elts.push_back(Src);
6032 
6033   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
6034   while (ExtraElts--)
6035     Elts.push_back(Undef);
6036 
6037   return DAG.getBuildVector(CastVT, DL, Elts);
6038 }
6039 
6040 // Re-construct the required return value for a image load intrinsic.
6041 // This is more complicated due to the optional use TexFailCtrl which means the required
6042 // return type is an aggregate
6043 static SDValue constructRetValue(SelectionDAG &DAG,
6044                                  MachineSDNode *Result,
6045                                  ArrayRef<EVT> ResultTypes,
6046                                  bool IsTexFail, bool Unpacked, bool IsD16,
6047                                  int DMaskPop, int NumVDataDwords,
6048                                  const SDLoc &DL) {
6049   // Determine the required return type. This is the same regardless of IsTexFail flag
6050   EVT ReqRetVT = ResultTypes[0];
6051   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
6052   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6053     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
6054 
6055   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6056     DMaskPop : (DMaskPop + 1) / 2;
6057 
6058   MVT DataDwordVT = NumDataDwords == 1 ?
6059     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
6060 
6061   MVT MaskPopVT = MaskPopDwords == 1 ?
6062     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
6063 
6064   SDValue Data(Result, 0);
6065   SDValue TexFail;
6066 
6067   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
6068     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
6069     if (MaskPopVT.isVector()) {
6070       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
6071                          SDValue(Result, 0), ZeroIdx);
6072     } else {
6073       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
6074                          SDValue(Result, 0), ZeroIdx);
6075     }
6076   }
6077 
6078   if (DataDwordVT.isVector())
6079     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
6080                           NumDataDwords - MaskPopDwords);
6081 
6082   if (IsD16)
6083     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
6084 
6085   EVT LegalReqRetVT = ReqRetVT;
6086   if (!ReqRetVT.isVector()) {
6087     if (!Data.getValueType().isInteger())
6088       Data = DAG.getNode(ISD::BITCAST, DL,
6089                          Data.getValueType().changeTypeToInteger(), Data);
6090     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
6091   } else {
6092     // We need to widen the return vector to a legal type
6093     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
6094         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
6095       LegalReqRetVT =
6096           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
6097                            ReqRetVT.getVectorNumElements() + 1);
6098     }
6099   }
6100   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
6101 
6102   if (IsTexFail) {
6103     TexFail =
6104         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
6105                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
6106 
6107     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
6108   }
6109 
6110   if (Result->getNumValues() == 1)
6111     return Data;
6112 
6113   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
6114 }
6115 
6116 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
6117                          SDValue *LWE, bool &IsTexFail) {
6118   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
6119 
6120   uint64_t Value = TexFailCtrlConst->getZExtValue();
6121   if (Value) {
6122     IsTexFail = true;
6123   }
6124 
6125   SDLoc DL(TexFailCtrlConst);
6126   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
6127   Value &= ~(uint64_t)0x1;
6128   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
6129   Value &= ~(uint64_t)0x2;
6130 
6131   return Value == 0;
6132 }
6133 
6134 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
6135                                       MVT PackVectorVT,
6136                                       SmallVectorImpl<SDValue> &PackedAddrs,
6137                                       unsigned DimIdx, unsigned EndIdx,
6138                                       unsigned NumGradients) {
6139   SDLoc DL(Op);
6140   for (unsigned I = DimIdx; I < EndIdx; I++) {
6141     SDValue Addr = Op.getOperand(I);
6142 
6143     // Gradients are packed with undef for each coordinate.
6144     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
6145     // 1D: undef,dx/dh; undef,dx/dv
6146     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
6147     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
6148     if (((I + 1) >= EndIdx) ||
6149         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
6150                                          I == DimIdx + NumGradients - 1))) {
6151       if (Addr.getValueType() != MVT::i16)
6152         Addr = DAG.getBitcast(MVT::i16, Addr);
6153       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
6154     } else {
6155       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
6156       I++;
6157     }
6158     Addr = DAG.getBitcast(MVT::f32, Addr);
6159     PackedAddrs.push_back(Addr);
6160   }
6161 }
6162 
6163 SDValue SITargetLowering::lowerImage(SDValue Op,
6164                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
6165                                      SelectionDAG &DAG, bool WithChain) const {
6166   SDLoc DL(Op);
6167   MachineFunction &MF = DAG.getMachineFunction();
6168   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
6169   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
6170       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
6171   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
6172   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
6173       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
6174   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
6175       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
6176   unsigned IntrOpcode = Intr->BaseOpcode;
6177   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6178 
6179   SmallVector<EVT, 3> ResultTypes(Op->values());
6180   SmallVector<EVT, 3> OrigResultTypes(Op->values());
6181   bool IsD16 = false;
6182   bool IsG16 = false;
6183   bool IsA16 = false;
6184   SDValue VData;
6185   int NumVDataDwords;
6186   bool AdjustRetType = false;
6187 
6188   // Offset of intrinsic arguments
6189   const unsigned ArgOffset = WithChain ? 2 : 1;
6190 
6191   unsigned DMask;
6192   unsigned DMaskLanes = 0;
6193 
6194   if (BaseOpcode->Atomic) {
6195     VData = Op.getOperand(2);
6196 
6197     bool Is64Bit = VData.getValueType() == MVT::i64;
6198     if (BaseOpcode->AtomicX2) {
6199       SDValue VData2 = Op.getOperand(3);
6200       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6201                                  {VData, VData2});
6202       if (Is64Bit)
6203         VData = DAG.getBitcast(MVT::v4i32, VData);
6204 
6205       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6206       DMask = Is64Bit ? 0xf : 0x3;
6207       NumVDataDwords = Is64Bit ? 4 : 2;
6208     } else {
6209       DMask = Is64Bit ? 0x3 : 0x1;
6210       NumVDataDwords = Is64Bit ? 2 : 1;
6211     }
6212   } else {
6213     auto *DMaskConst =
6214         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6215     DMask = DMaskConst->getZExtValue();
6216     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6217 
6218     if (BaseOpcode->Store) {
6219       VData = Op.getOperand(2);
6220 
6221       MVT StoreVT = VData.getSimpleValueType();
6222       if (StoreVT.getScalarType() == MVT::f16) {
6223         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6224           return Op; // D16 is unsupported for this instruction
6225 
6226         IsD16 = true;
6227         VData = handleD16VData(VData, DAG, true);
6228       }
6229 
6230       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6231     } else {
6232       // Work out the num dwords based on the dmask popcount and underlying type
6233       // and whether packing is supported.
6234       MVT LoadVT = ResultTypes[0].getSimpleVT();
6235       if (LoadVT.getScalarType() == MVT::f16) {
6236         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6237           return Op; // D16 is unsupported for this instruction
6238 
6239         IsD16 = true;
6240       }
6241 
6242       // Confirm that the return type is large enough for the dmask specified
6243       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6244           (!LoadVT.isVector() && DMaskLanes > 1))
6245           return Op;
6246 
6247       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6248       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6249       // instructions.
6250       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6251           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6252         NumVDataDwords = (DMaskLanes + 1) / 2;
6253       else
6254         NumVDataDwords = DMaskLanes;
6255 
6256       AdjustRetType = true;
6257     }
6258   }
6259 
6260   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6261   SmallVector<SDValue, 4> VAddrs;
6262 
6263   // Optimize _L to _LZ when _L is zero
6264   if (LZMappingInfo) {
6265     if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>(
6266             Op.getOperand(ArgOffset + Intr->LodIndex))) {
6267       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
6268         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
6269         VAddrEnd--;                      // remove 'lod'
6270       }
6271     }
6272   }
6273 
6274   // Optimize _mip away, when 'lod' is zero
6275   if (MIPMappingInfo) {
6276     if (auto *ConstantLod = dyn_cast<ConstantSDNode>(
6277             Op.getOperand(ArgOffset + Intr->MipIndex))) {
6278       if (ConstantLod->isZero()) {
6279         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
6280         VAddrEnd--;                           // remove 'mip'
6281       }
6282     }
6283   }
6284 
6285   // Push back extra arguments.
6286   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++)
6287     VAddrs.push_back(Op.getOperand(ArgOffset + I));
6288 
6289   // Check for 16 bit addresses or derivatives and pack if true.
6290   MVT VAddrVT =
6291       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6292   MVT VAddrScalarVT = VAddrVT.getScalarType();
6293   MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6294   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6295 
6296   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6297   VAddrScalarVT = VAddrVT.getScalarType();
6298   MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6299   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6300 
6301   if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
6302     // 16 bit gradients are supported, but are tied to the A16 control
6303     // so both gradients and addresses must be 16 bit
6304     LLVM_DEBUG(
6305         dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6306                   "require 16 bit args for both gradients and addresses");
6307     return Op;
6308   }
6309 
6310   if (IsA16) {
6311     if (!ST->hasA16()) {
6312       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6313                            "support 16 bit addresses\n");
6314       return Op;
6315     }
6316   }
6317 
6318   // We've dealt with incorrect input so we know that if IsA16, IsG16
6319   // are set then we have to compress/pack operands (either address,
6320   // gradient or both)
6321   // In the case where a16 and gradients are tied (no G16 support) then we
6322   // have already verified that both IsA16 and IsG16 are true
6323   if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
6324     // Activate g16
6325     const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6326         AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6327     IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6328   }
6329 
6330   // Add gradients (packed or unpacked)
6331   if (IsG16) {
6332     // Pack the gradients
6333     // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6334     packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
6335                               ArgOffset + Intr->GradientStart,
6336                               ArgOffset + Intr->CoordStart, Intr->NumGradients);
6337   } else {
6338     for (unsigned I = ArgOffset + Intr->GradientStart;
6339          I < ArgOffset + Intr->CoordStart; I++)
6340       VAddrs.push_back(Op.getOperand(I));
6341   }
6342 
6343   // Add addresses (packed or unpacked)
6344   if (IsA16) {
6345     packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
6346                               ArgOffset + Intr->CoordStart, VAddrEnd,
6347                               0 /* No gradients */);
6348   } else {
6349     // Add uncompressed address
6350     for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6351       VAddrs.push_back(Op.getOperand(I));
6352   }
6353 
6354   // If the register allocator cannot place the address registers contiguously
6355   // without introducing moves, then using the non-sequential address encoding
6356   // is always preferable, since it saves VALU instructions and is usually a
6357   // wash in terms of code size or even better.
6358   //
6359   // However, we currently have no way of hinting to the register allocator that
6360   // MIMG addresses should be placed contiguously when it is possible to do so,
6361   // so force non-NSA for the common 2-address case as a heuristic.
6362   //
6363   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6364   // allocation when possible.
6365   bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) &&
6366                 VAddrs.size() >= 3 &&
6367                 VAddrs.size() <= (unsigned)ST->getNSAMaxSize();
6368   SDValue VAddr;
6369   if (!UseNSA)
6370     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6371 
6372   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6373   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6374   SDValue Unorm;
6375   if (!BaseOpcode->Sampler) {
6376     Unorm = True;
6377   } else {
6378     auto UnormConst =
6379         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6380 
6381     Unorm = UnormConst->getZExtValue() ? True : False;
6382   }
6383 
6384   SDValue TFE;
6385   SDValue LWE;
6386   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6387   bool IsTexFail = false;
6388   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6389     return Op;
6390 
6391   if (IsTexFail) {
6392     if (!DMaskLanes) {
6393       // Expecting to get an error flag since TFC is on - and dmask is 0
6394       // Force dmask to be at least 1 otherwise the instruction will fail
6395       DMask = 0x1;
6396       DMaskLanes = 1;
6397       NumVDataDwords = 1;
6398     }
6399     NumVDataDwords += 1;
6400     AdjustRetType = true;
6401   }
6402 
6403   // Has something earlier tagged that the return type needs adjusting
6404   // This happens if the instruction is a load or has set TexFailCtrl flags
6405   if (AdjustRetType) {
6406     // NumVDataDwords reflects the true number of dwords required in the return type
6407     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6408       // This is a no-op load. This can be eliminated
6409       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6410       if (isa<MemSDNode>(Op))
6411         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6412       return Undef;
6413     }
6414 
6415     EVT NewVT = NumVDataDwords > 1 ?
6416                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6417                 : MVT::i32;
6418 
6419     ResultTypes[0] = NewVT;
6420     if (ResultTypes.size() == 3) {
6421       // Original result was aggregate type used for TexFailCtrl results
6422       // The actual instruction returns as a vector type which has now been
6423       // created. Remove the aggregate result.
6424       ResultTypes.erase(&ResultTypes[1]);
6425     }
6426   }
6427 
6428   unsigned CPol = cast<ConstantSDNode>(
6429       Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6430   if (BaseOpcode->Atomic)
6431     CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6432   if (CPol & ~AMDGPU::CPol::ALL)
6433     return Op;
6434 
6435   SmallVector<SDValue, 26> Ops;
6436   if (BaseOpcode->Store || BaseOpcode->Atomic)
6437     Ops.push_back(VData); // vdata
6438   if (UseNSA)
6439     append_range(Ops, VAddrs);
6440   else
6441     Ops.push_back(VAddr);
6442   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6443   if (BaseOpcode->Sampler)
6444     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6445   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6446   if (IsGFX10Plus)
6447     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6448   Ops.push_back(Unorm);
6449   Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6450   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6451                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6452   if (IsGFX10Plus)
6453     Ops.push_back(IsA16 ? True : False);
6454   if (!Subtarget->hasGFX90AInsts()) {
6455     Ops.push_back(TFE); //tfe
6456   } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6457     report_fatal_error("TFE is not supported on this GPU");
6458   }
6459   Ops.push_back(LWE); // lwe
6460   if (!IsGFX10Plus)
6461     Ops.push_back(DimInfo->DA ? True : False);
6462   if (BaseOpcode->HasD16)
6463     Ops.push_back(IsD16 ? True : False);
6464   if (isa<MemSDNode>(Op))
6465     Ops.push_back(Op.getOperand(0)); // chain
6466 
6467   int NumVAddrDwords =
6468       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6469   int Opcode = -1;
6470 
6471   if (IsGFX10Plus) {
6472     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6473                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6474                                           : AMDGPU::MIMGEncGfx10Default,
6475                                    NumVDataDwords, NumVAddrDwords);
6476   } else {
6477     if (Subtarget->hasGFX90AInsts()) {
6478       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6479                                      NumVDataDwords, NumVAddrDwords);
6480       if (Opcode == -1)
6481         report_fatal_error(
6482             "requested image instruction is not supported on this GPU");
6483     }
6484     if (Opcode == -1 &&
6485         Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6486       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6487                                      NumVDataDwords, NumVAddrDwords);
6488     if (Opcode == -1)
6489       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6490                                      NumVDataDwords, NumVAddrDwords);
6491   }
6492   assert(Opcode != -1);
6493 
6494   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6495   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6496     MachineMemOperand *MemRef = MemOp->getMemOperand();
6497     DAG.setNodeMemRefs(NewNode, {MemRef});
6498   }
6499 
6500   if (BaseOpcode->AtomicX2) {
6501     SmallVector<SDValue, 1> Elt;
6502     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6503     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6504   }
6505   if (BaseOpcode->Store)
6506     return SDValue(NewNode, 0);
6507   return constructRetValue(DAG, NewNode,
6508                            OrigResultTypes, IsTexFail,
6509                            Subtarget->hasUnpackedD16VMem(), IsD16,
6510                            DMaskLanes, NumVDataDwords, DL);
6511 }
6512 
6513 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6514                                        SDValue Offset, SDValue CachePolicy,
6515                                        SelectionDAG &DAG) const {
6516   MachineFunction &MF = DAG.getMachineFunction();
6517 
6518   const DataLayout &DataLayout = DAG.getDataLayout();
6519   Align Alignment =
6520       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6521 
6522   MachineMemOperand *MMO = MF.getMachineMemOperand(
6523       MachinePointerInfo(),
6524       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6525           MachineMemOperand::MOInvariant,
6526       VT.getStoreSize(), Alignment);
6527 
6528   if (!Offset->isDivergent()) {
6529     SDValue Ops[] = {
6530         Rsrc,
6531         Offset, // Offset
6532         CachePolicy
6533     };
6534 
6535     // Widen vec3 load to vec4.
6536     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6537       EVT WidenedVT =
6538           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6539       auto WidenedOp = DAG.getMemIntrinsicNode(
6540           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6541           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6542       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6543                                    DAG.getVectorIdxConstant(0, DL));
6544       return Subvector;
6545     }
6546 
6547     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6548                                    DAG.getVTList(VT), Ops, VT, MMO);
6549   }
6550 
6551   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6552   // assume that the buffer is unswizzled.
6553   SmallVector<SDValue, 4> Loads;
6554   unsigned NumLoads = 1;
6555   MVT LoadVT = VT.getSimpleVT();
6556   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6557   assert((LoadVT.getScalarType() == MVT::i32 ||
6558           LoadVT.getScalarType() == MVT::f32));
6559 
6560   if (NumElts == 8 || NumElts == 16) {
6561     NumLoads = NumElts / 4;
6562     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6563   }
6564 
6565   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6566   SDValue Ops[] = {
6567       DAG.getEntryNode(),                               // Chain
6568       Rsrc,                                             // rsrc
6569       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6570       {},                                               // voffset
6571       {},                                               // soffset
6572       {},                                               // offset
6573       CachePolicy,                                      // cachepolicy
6574       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6575   };
6576 
6577   // Use the alignment to ensure that the required offsets will fit into the
6578   // immediate offsets.
6579   setBufferOffsets(Offset, DAG, &Ops[3],
6580                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6581 
6582   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6583   for (unsigned i = 0; i < NumLoads; ++i) {
6584     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6585     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6586                                         LoadVT, MMO, DAG));
6587   }
6588 
6589   if (NumElts == 8 || NumElts == 16)
6590     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6591 
6592   return Loads[0];
6593 }
6594 
6595 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6596                                                   SelectionDAG &DAG) const {
6597   MachineFunction &MF = DAG.getMachineFunction();
6598   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6599 
6600   EVT VT = Op.getValueType();
6601   SDLoc DL(Op);
6602   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6603 
6604   // TODO: Should this propagate fast-math-flags?
6605 
6606   switch (IntrinsicID) {
6607   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6608     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6609       return emitNonHSAIntrinsicError(DAG, DL, VT);
6610     return getPreloadedValue(DAG, *MFI, VT,
6611                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6612   }
6613   case Intrinsic::amdgcn_dispatch_ptr:
6614   case Intrinsic::amdgcn_queue_ptr: {
6615     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6616       DiagnosticInfoUnsupported BadIntrin(
6617           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6618           DL.getDebugLoc());
6619       DAG.getContext()->diagnose(BadIntrin);
6620       return DAG.getUNDEF(VT);
6621     }
6622 
6623     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6624       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6625     return getPreloadedValue(DAG, *MFI, VT, RegID);
6626   }
6627   case Intrinsic::amdgcn_implicitarg_ptr: {
6628     if (MFI->isEntryFunction())
6629       return getImplicitArgPtr(DAG, DL);
6630     return getPreloadedValue(DAG, *MFI, VT,
6631                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6632   }
6633   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6634     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6635       // This only makes sense to call in a kernel, so just lower to null.
6636       return DAG.getConstant(0, DL, VT);
6637     }
6638 
6639     return getPreloadedValue(DAG, *MFI, VT,
6640                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6641   }
6642   case Intrinsic::amdgcn_dispatch_id: {
6643     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6644   }
6645   case Intrinsic::amdgcn_rcp:
6646     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6647   case Intrinsic::amdgcn_rsq:
6648     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6649   case Intrinsic::amdgcn_rsq_legacy:
6650     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6651       return emitRemovedIntrinsicError(DAG, DL, VT);
6652     return SDValue();
6653   case Intrinsic::amdgcn_rcp_legacy:
6654     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6655       return emitRemovedIntrinsicError(DAG, DL, VT);
6656     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6657   case Intrinsic::amdgcn_rsq_clamp: {
6658     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6659       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6660 
6661     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6662     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6663     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6664 
6665     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6666     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6667                               DAG.getConstantFP(Max, DL, VT));
6668     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6669                        DAG.getConstantFP(Min, DL, VT));
6670   }
6671   case Intrinsic::r600_read_ngroups_x:
6672     if (Subtarget->isAmdHsaOS())
6673       return emitNonHSAIntrinsicError(DAG, DL, VT);
6674 
6675     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6676                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6677                                     false);
6678   case Intrinsic::r600_read_ngroups_y:
6679     if (Subtarget->isAmdHsaOS())
6680       return emitNonHSAIntrinsicError(DAG, DL, VT);
6681 
6682     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6683                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6684                                     false);
6685   case Intrinsic::r600_read_ngroups_z:
6686     if (Subtarget->isAmdHsaOS())
6687       return emitNonHSAIntrinsicError(DAG, DL, VT);
6688 
6689     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6690                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6691                                     false);
6692   case Intrinsic::r600_read_global_size_x:
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_X,
6698                                     Align(4), false);
6699   case Intrinsic::r600_read_global_size_y:
6700     if (Subtarget->isAmdHsaOS())
6701       return emitNonHSAIntrinsicError(DAG, DL, VT);
6702 
6703     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6704                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6705                                     Align(4), false);
6706   case Intrinsic::r600_read_global_size_z:
6707     if (Subtarget->isAmdHsaOS())
6708       return emitNonHSAIntrinsicError(DAG, DL, VT);
6709 
6710     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6711                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6712                                     Align(4), false);
6713   case Intrinsic::r600_read_local_size_x:
6714     if (Subtarget->isAmdHsaOS())
6715       return emitNonHSAIntrinsicError(DAG, DL, VT);
6716 
6717     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6718                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6719   case Intrinsic::r600_read_local_size_y:
6720     if (Subtarget->isAmdHsaOS())
6721       return emitNonHSAIntrinsicError(DAG, DL, VT);
6722 
6723     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6724                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6725   case Intrinsic::r600_read_local_size_z:
6726     if (Subtarget->isAmdHsaOS())
6727       return emitNonHSAIntrinsicError(DAG, DL, VT);
6728 
6729     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6730                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6731   case Intrinsic::amdgcn_workgroup_id_x:
6732     return getPreloadedValue(DAG, *MFI, VT,
6733                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6734   case Intrinsic::amdgcn_workgroup_id_y:
6735     return getPreloadedValue(DAG, *MFI, VT,
6736                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6737   case Intrinsic::amdgcn_workgroup_id_z:
6738     return getPreloadedValue(DAG, *MFI, VT,
6739                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6740   case Intrinsic::amdgcn_workitem_id_x:
6741     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6742                           SDLoc(DAG.getEntryNode()),
6743                           MFI->getArgInfo().WorkItemIDX);
6744   case Intrinsic::amdgcn_workitem_id_y:
6745     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6746                           SDLoc(DAG.getEntryNode()),
6747                           MFI->getArgInfo().WorkItemIDY);
6748   case Intrinsic::amdgcn_workitem_id_z:
6749     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6750                           SDLoc(DAG.getEntryNode()),
6751                           MFI->getArgInfo().WorkItemIDZ);
6752   case Intrinsic::amdgcn_wavefrontsize:
6753     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6754                            SDLoc(Op), MVT::i32);
6755   case Intrinsic::amdgcn_s_buffer_load: {
6756     unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6757     if (CPol & ~AMDGPU::CPol::ALL)
6758       return Op;
6759     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6760                         DAG);
6761   }
6762   case Intrinsic::amdgcn_fdiv_fast:
6763     return lowerFDIV_FAST(Op, DAG);
6764   case Intrinsic::amdgcn_sin:
6765     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6766 
6767   case Intrinsic::amdgcn_cos:
6768     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6769 
6770   case Intrinsic::amdgcn_mul_u24:
6771     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6772   case Intrinsic::amdgcn_mul_i24:
6773     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6774 
6775   case Intrinsic::amdgcn_log_clamp: {
6776     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6777       return SDValue();
6778 
6779     return emitRemovedIntrinsicError(DAG, DL, VT);
6780   }
6781   case Intrinsic::amdgcn_ldexp:
6782     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6783                        Op.getOperand(1), Op.getOperand(2));
6784 
6785   case Intrinsic::amdgcn_fract:
6786     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6787 
6788   case Intrinsic::amdgcn_class:
6789     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6790                        Op.getOperand(1), Op.getOperand(2));
6791   case Intrinsic::amdgcn_div_fmas:
6792     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6793                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6794                        Op.getOperand(4));
6795 
6796   case Intrinsic::amdgcn_div_fixup:
6797     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6798                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6799 
6800   case Intrinsic::amdgcn_div_scale: {
6801     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6802 
6803     // Translate to the operands expected by the machine instruction. The
6804     // first parameter must be the same as the first instruction.
6805     SDValue Numerator = Op.getOperand(1);
6806     SDValue Denominator = Op.getOperand(2);
6807 
6808     // Note this order is opposite of the machine instruction's operations,
6809     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6810     // intrinsic has the numerator as the first operand to match a normal
6811     // division operation.
6812 
6813     SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator;
6814 
6815     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6816                        Denominator, Numerator);
6817   }
6818   case Intrinsic::amdgcn_icmp: {
6819     // There is a Pat that handles this variant, so return it as-is.
6820     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6821         Op.getConstantOperandVal(2) == 0 &&
6822         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6823       return Op;
6824     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6825   }
6826   case Intrinsic::amdgcn_fcmp: {
6827     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6828   }
6829   case Intrinsic::amdgcn_ballot:
6830     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6831   case Intrinsic::amdgcn_fmed3:
6832     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6833                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6834   case Intrinsic::amdgcn_fdot2:
6835     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6836                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6837                        Op.getOperand(4));
6838   case Intrinsic::amdgcn_fmul_legacy:
6839     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6840                        Op.getOperand(1), Op.getOperand(2));
6841   case Intrinsic::amdgcn_sffbh:
6842     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6843   case Intrinsic::amdgcn_sbfe:
6844     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6845                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6846   case Intrinsic::amdgcn_ubfe:
6847     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6848                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6849   case Intrinsic::amdgcn_cvt_pkrtz:
6850   case Intrinsic::amdgcn_cvt_pknorm_i16:
6851   case Intrinsic::amdgcn_cvt_pknorm_u16:
6852   case Intrinsic::amdgcn_cvt_pk_i16:
6853   case Intrinsic::amdgcn_cvt_pk_u16: {
6854     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6855     EVT VT = Op.getValueType();
6856     unsigned Opcode;
6857 
6858     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6859       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6860     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6861       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6862     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6863       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6864     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6865       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6866     else
6867       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6868 
6869     if (isTypeLegal(VT))
6870       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6871 
6872     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6873                                Op.getOperand(1), Op.getOperand(2));
6874     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6875   }
6876   case Intrinsic::amdgcn_fmad_ftz:
6877     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6878                        Op.getOperand(2), Op.getOperand(3));
6879 
6880   case Intrinsic::amdgcn_if_break:
6881     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6882                                       Op->getOperand(1), Op->getOperand(2)), 0);
6883 
6884   case Intrinsic::amdgcn_groupstaticsize: {
6885     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6886     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6887       return Op;
6888 
6889     const Module *M = MF.getFunction().getParent();
6890     const GlobalValue *GV =
6891         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6892     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6893                                             SIInstrInfo::MO_ABS32_LO);
6894     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6895   }
6896   case Intrinsic::amdgcn_is_shared:
6897   case Intrinsic::amdgcn_is_private: {
6898     SDLoc SL(Op);
6899     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6900       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6901     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6902     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6903                                  Op.getOperand(1));
6904 
6905     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6906                                 DAG.getConstant(1, SL, MVT::i32));
6907     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6908   }
6909   case Intrinsic::amdgcn_alignbit:
6910     return DAG.getNode(ISD::FSHR, DL, VT,
6911                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6912   case Intrinsic::amdgcn_perm:
6913     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
6914                        Op.getOperand(2), Op.getOperand(3));
6915   case Intrinsic::amdgcn_reloc_constant: {
6916     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6917     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6918     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6919     auto RelocSymbol = cast<GlobalVariable>(
6920         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6921     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6922                                             SIInstrInfo::MO_ABS32_LO);
6923     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6924   }
6925   default:
6926     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6927             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6928       return lowerImage(Op, ImageDimIntr, DAG, false);
6929 
6930     return Op;
6931   }
6932 }
6933 
6934 /// Update \p MMO based on the offset inputs to an intrinsic.
6935 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset,
6936                             SDValue SOffset, SDValue Offset,
6937                             SDValue VIndex = SDValue()) {
6938   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6939       !isa<ConstantSDNode>(Offset)) {
6940     // The combined offset is not known to be constant, so we cannot represent
6941     // it in the MMO. Give up.
6942     MMO->setValue((Value *)nullptr);
6943     return;
6944   }
6945 
6946   if (VIndex && (!isa<ConstantSDNode>(VIndex) ||
6947                  !cast<ConstantSDNode>(VIndex)->isZero())) {
6948     // The strided index component of the address is not known to be zero, so we
6949     // cannot represent it in the MMO. Give up.
6950     MMO->setValue((Value *)nullptr);
6951     return;
6952   }
6953 
6954   MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() +
6955                  cast<ConstantSDNode>(SOffset)->getSExtValue() +
6956                  cast<ConstantSDNode>(Offset)->getSExtValue());
6957 }
6958 
6959 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
6960                                                      SelectionDAG &DAG,
6961                                                      unsigned NewOpcode) const {
6962   SDLoc DL(Op);
6963 
6964   SDValue VData = Op.getOperand(2);
6965   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6966   SDValue Ops[] = {
6967     Op.getOperand(0), // Chain
6968     VData,            // vdata
6969     Op.getOperand(3), // rsrc
6970     DAG.getConstant(0, DL, MVT::i32), // vindex
6971     Offsets.first,    // voffset
6972     Op.getOperand(5), // soffset
6973     Offsets.second,   // offset
6974     Op.getOperand(6), // cachepolicy
6975     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6976   };
6977 
6978   auto *M = cast<MemSDNode>(Op);
6979   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
6980 
6981   EVT MemVT = VData.getValueType();
6982   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6983                                  M->getMemOperand());
6984 }
6985 
6986 // Return a value to use for the idxen operand by examining the vindex operand.
6987 static unsigned getIdxEn(SDValue VIndex) {
6988   if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex))
6989     // No need to set idxen if vindex is known to be zero.
6990     return VIndexC->getZExtValue() != 0;
6991   return 1;
6992 }
6993 
6994 SDValue
6995 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
6996                                                 unsigned NewOpcode) const {
6997   SDLoc DL(Op);
6998 
6999   SDValue VData = Op.getOperand(2);
7000   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7001   SDValue Ops[] = {
7002     Op.getOperand(0), // Chain
7003     VData,            // vdata
7004     Op.getOperand(3), // rsrc
7005     Op.getOperand(4), // vindex
7006     Offsets.first,    // voffset
7007     Op.getOperand(6), // soffset
7008     Offsets.second,   // offset
7009     Op.getOperand(7), // cachepolicy
7010     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7011   };
7012 
7013   auto *M = cast<MemSDNode>(Op);
7014   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7015 
7016   EVT MemVT = VData.getValueType();
7017   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7018                                  M->getMemOperand());
7019 }
7020 
7021 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
7022                                                  SelectionDAG &DAG) const {
7023   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7024   SDLoc DL(Op);
7025 
7026   switch (IntrID) {
7027   case Intrinsic::amdgcn_ds_ordered_add:
7028   case Intrinsic::amdgcn_ds_ordered_swap: {
7029     MemSDNode *M = cast<MemSDNode>(Op);
7030     SDValue Chain = M->getOperand(0);
7031     SDValue M0 = M->getOperand(2);
7032     SDValue Value = M->getOperand(3);
7033     unsigned IndexOperand = M->getConstantOperandVal(7);
7034     unsigned WaveRelease = M->getConstantOperandVal(8);
7035     unsigned WaveDone = M->getConstantOperandVal(9);
7036 
7037     unsigned OrderedCountIndex = IndexOperand & 0x3f;
7038     IndexOperand &= ~0x3f;
7039     unsigned CountDw = 0;
7040 
7041     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
7042       CountDw = (IndexOperand >> 24) & 0xf;
7043       IndexOperand &= ~(0xf << 24);
7044 
7045       if (CountDw < 1 || CountDw > 4) {
7046         report_fatal_error(
7047             "ds_ordered_count: dword count must be between 1 and 4");
7048       }
7049     }
7050 
7051     if (IndexOperand)
7052       report_fatal_error("ds_ordered_count: bad index operand");
7053 
7054     if (WaveDone && !WaveRelease)
7055       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
7056 
7057     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
7058     unsigned ShaderType =
7059         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
7060     unsigned Offset0 = OrderedCountIndex << 2;
7061     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
7062                        (Instruction << 4);
7063 
7064     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
7065       Offset1 |= (CountDw - 1) << 6;
7066 
7067     unsigned Offset = Offset0 | (Offset1 << 8);
7068 
7069     SDValue Ops[] = {
7070       Chain,
7071       Value,
7072       DAG.getTargetConstant(Offset, DL, MVT::i16),
7073       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
7074     };
7075     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
7076                                    M->getVTList(), Ops, M->getMemoryVT(),
7077                                    M->getMemOperand());
7078   }
7079   case Intrinsic::amdgcn_ds_fadd: {
7080     MemSDNode *M = cast<MemSDNode>(Op);
7081     unsigned Opc;
7082     switch (IntrID) {
7083     case Intrinsic::amdgcn_ds_fadd:
7084       Opc = ISD::ATOMIC_LOAD_FADD;
7085       break;
7086     }
7087 
7088     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
7089                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
7090                          M->getMemOperand());
7091   }
7092   case Intrinsic::amdgcn_atomic_inc:
7093   case Intrinsic::amdgcn_atomic_dec:
7094   case Intrinsic::amdgcn_ds_fmin:
7095   case Intrinsic::amdgcn_ds_fmax: {
7096     MemSDNode *M = cast<MemSDNode>(Op);
7097     unsigned Opc;
7098     switch (IntrID) {
7099     case Intrinsic::amdgcn_atomic_inc:
7100       Opc = AMDGPUISD::ATOMIC_INC;
7101       break;
7102     case Intrinsic::amdgcn_atomic_dec:
7103       Opc = AMDGPUISD::ATOMIC_DEC;
7104       break;
7105     case Intrinsic::amdgcn_ds_fmin:
7106       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
7107       break;
7108     case Intrinsic::amdgcn_ds_fmax:
7109       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
7110       break;
7111     default:
7112       llvm_unreachable("Unknown intrinsic!");
7113     }
7114     SDValue Ops[] = {
7115       M->getOperand(0), // Chain
7116       M->getOperand(2), // Ptr
7117       M->getOperand(3)  // Value
7118     };
7119 
7120     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
7121                                    M->getMemoryVT(), M->getMemOperand());
7122   }
7123   case Intrinsic::amdgcn_buffer_load:
7124   case Intrinsic::amdgcn_buffer_load_format: {
7125     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
7126     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7127     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7128     SDValue Ops[] = {
7129       Op.getOperand(0), // Chain
7130       Op.getOperand(2), // rsrc
7131       Op.getOperand(3), // vindex
7132       SDValue(),        // voffset -- will be set by setBufferOffsets
7133       SDValue(),        // soffset -- will be set by setBufferOffsets
7134       SDValue(),        // offset -- will be set by setBufferOffsets
7135       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7136       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7137     };
7138     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
7139 
7140     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
7141         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
7142 
7143     EVT VT = Op.getValueType();
7144     EVT IntVT = VT.changeTypeToInteger();
7145     auto *M = cast<MemSDNode>(Op);
7146     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7147     EVT LoadVT = Op.getValueType();
7148 
7149     if (LoadVT.getScalarType() == MVT::f16)
7150       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
7151                                  M, DAG, Ops);
7152 
7153     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
7154     if (LoadVT.getScalarType() == MVT::i8 ||
7155         LoadVT.getScalarType() == MVT::i16)
7156       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
7157 
7158     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
7159                                M->getMemOperand(), DAG);
7160   }
7161   case Intrinsic::amdgcn_raw_buffer_load:
7162   case Intrinsic::amdgcn_raw_buffer_load_format: {
7163     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
7164 
7165     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7166     SDValue Ops[] = {
7167       Op.getOperand(0), // Chain
7168       Op.getOperand(2), // rsrc
7169       DAG.getConstant(0, DL, MVT::i32), // vindex
7170       Offsets.first,    // voffset
7171       Op.getOperand(4), // soffset
7172       Offsets.second,   // offset
7173       Op.getOperand(5), // cachepolicy, swizzled buffer
7174       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7175     };
7176 
7177     auto *M = cast<MemSDNode>(Op);
7178     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]);
7179     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
7180   }
7181   case Intrinsic::amdgcn_struct_buffer_load:
7182   case Intrinsic::amdgcn_struct_buffer_load_format: {
7183     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
7184 
7185     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7186     SDValue Ops[] = {
7187       Op.getOperand(0), // Chain
7188       Op.getOperand(2), // rsrc
7189       Op.getOperand(3), // vindex
7190       Offsets.first,    // voffset
7191       Op.getOperand(5), // soffset
7192       Offsets.second,   // offset
7193       Op.getOperand(6), // cachepolicy, swizzled buffer
7194       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7195     };
7196 
7197     auto *M = cast<MemSDNode>(Op);
7198     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7199     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7200   }
7201   case Intrinsic::amdgcn_tbuffer_load: {
7202     MemSDNode *M = cast<MemSDNode>(Op);
7203     EVT LoadVT = Op.getValueType();
7204 
7205     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7206     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7207     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7208     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7209     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7210     SDValue Ops[] = {
7211       Op.getOperand(0),  // Chain
7212       Op.getOperand(2),  // rsrc
7213       Op.getOperand(3),  // vindex
7214       Op.getOperand(4),  // voffset
7215       Op.getOperand(5),  // soffset
7216       Op.getOperand(6),  // offset
7217       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7218       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7219       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7220     };
7221 
7222     if (LoadVT.getScalarType() == MVT::f16)
7223       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7224                                  M, DAG, Ops);
7225     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7226                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7227                                DAG);
7228   }
7229   case Intrinsic::amdgcn_raw_tbuffer_load: {
7230     MemSDNode *M = cast<MemSDNode>(Op);
7231     EVT LoadVT = Op.getValueType();
7232     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7233 
7234     SDValue Ops[] = {
7235       Op.getOperand(0),  // Chain
7236       Op.getOperand(2),  // rsrc
7237       DAG.getConstant(0, DL, MVT::i32), // vindex
7238       Offsets.first,     // voffset
7239       Op.getOperand(4),  // soffset
7240       Offsets.second,    // offset
7241       Op.getOperand(5),  // format
7242       Op.getOperand(6),  // cachepolicy, swizzled buffer
7243       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7244     };
7245 
7246     if (LoadVT.getScalarType() == MVT::f16)
7247       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7248                                  M, DAG, Ops);
7249     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7250                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7251                                DAG);
7252   }
7253   case Intrinsic::amdgcn_struct_tbuffer_load: {
7254     MemSDNode *M = cast<MemSDNode>(Op);
7255     EVT LoadVT = Op.getValueType();
7256     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7257 
7258     SDValue Ops[] = {
7259       Op.getOperand(0),  // Chain
7260       Op.getOperand(2),  // rsrc
7261       Op.getOperand(3),  // vindex
7262       Offsets.first,     // voffset
7263       Op.getOperand(5),  // soffset
7264       Offsets.second,    // offset
7265       Op.getOperand(6),  // format
7266       Op.getOperand(7),  // cachepolicy, swizzled buffer
7267       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7268     };
7269 
7270     if (LoadVT.getScalarType() == MVT::f16)
7271       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7272                                  M, DAG, Ops);
7273     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7274                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7275                                DAG);
7276   }
7277   case Intrinsic::amdgcn_buffer_atomic_swap:
7278   case Intrinsic::amdgcn_buffer_atomic_add:
7279   case Intrinsic::amdgcn_buffer_atomic_sub:
7280   case Intrinsic::amdgcn_buffer_atomic_csub:
7281   case Intrinsic::amdgcn_buffer_atomic_smin:
7282   case Intrinsic::amdgcn_buffer_atomic_umin:
7283   case Intrinsic::amdgcn_buffer_atomic_smax:
7284   case Intrinsic::amdgcn_buffer_atomic_umax:
7285   case Intrinsic::amdgcn_buffer_atomic_and:
7286   case Intrinsic::amdgcn_buffer_atomic_or:
7287   case Intrinsic::amdgcn_buffer_atomic_xor:
7288   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7289     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7290     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7291     SDValue Ops[] = {
7292       Op.getOperand(0), // Chain
7293       Op.getOperand(2), // vdata
7294       Op.getOperand(3), // rsrc
7295       Op.getOperand(4), // vindex
7296       SDValue(),        // voffset -- will be set by setBufferOffsets
7297       SDValue(),        // soffset -- will be set by setBufferOffsets
7298       SDValue(),        // offset -- will be set by setBufferOffsets
7299       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7300       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7301     };
7302     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7303 
7304     EVT VT = Op.getValueType();
7305 
7306     auto *M = cast<MemSDNode>(Op);
7307     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7308     unsigned Opcode = 0;
7309 
7310     switch (IntrID) {
7311     case Intrinsic::amdgcn_buffer_atomic_swap:
7312       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7313       break;
7314     case Intrinsic::amdgcn_buffer_atomic_add:
7315       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7316       break;
7317     case Intrinsic::amdgcn_buffer_atomic_sub:
7318       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7319       break;
7320     case Intrinsic::amdgcn_buffer_atomic_csub:
7321       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7322       break;
7323     case Intrinsic::amdgcn_buffer_atomic_smin:
7324       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7325       break;
7326     case Intrinsic::amdgcn_buffer_atomic_umin:
7327       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7328       break;
7329     case Intrinsic::amdgcn_buffer_atomic_smax:
7330       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7331       break;
7332     case Intrinsic::amdgcn_buffer_atomic_umax:
7333       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7334       break;
7335     case Intrinsic::amdgcn_buffer_atomic_and:
7336       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7337       break;
7338     case Intrinsic::amdgcn_buffer_atomic_or:
7339       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7340       break;
7341     case Intrinsic::amdgcn_buffer_atomic_xor:
7342       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7343       break;
7344     case Intrinsic::amdgcn_buffer_atomic_fadd:
7345       if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7346         DiagnosticInfoUnsupported
7347           NoFpRet(DAG.getMachineFunction().getFunction(),
7348                   "return versions of fp atomics not supported",
7349                   DL.getDebugLoc(), DS_Error);
7350         DAG.getContext()->diagnose(NoFpRet);
7351         return SDValue();
7352       }
7353       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7354       break;
7355     default:
7356       llvm_unreachable("unhandled atomic opcode");
7357     }
7358 
7359     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7360                                    M->getMemOperand());
7361   }
7362   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7363     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7364   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7365     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7366   case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7367     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7368   case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7369     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7370   case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7371     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7372   case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7373     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7374   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7375     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7376   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7377     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7378   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7379     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7380   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7381     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7382   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7383     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7384   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7385     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7386   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7387     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7388   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7389     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7390   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7391     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7392   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7393     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7394   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7395     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7396   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7397     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7398   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7399     return lowerStructBufferAtomicIntrin(Op, DAG,
7400                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7401   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7402     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7403   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7404     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7405   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7406     return lowerStructBufferAtomicIntrin(Op, DAG,
7407                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7408   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7409     return lowerStructBufferAtomicIntrin(Op, DAG,
7410                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7411   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7412     return lowerStructBufferAtomicIntrin(Op, DAG,
7413                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7414   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7415     return lowerStructBufferAtomicIntrin(Op, DAG,
7416                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7417   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7418     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7419   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7420     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7421   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7422     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7423   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7424     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7425   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7426     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7427 
7428   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7429     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7430     unsigned IdxEn = getIdxEn(Op.getOperand(5));
7431     SDValue Ops[] = {
7432       Op.getOperand(0), // Chain
7433       Op.getOperand(2), // src
7434       Op.getOperand(3), // cmp
7435       Op.getOperand(4), // rsrc
7436       Op.getOperand(5), // vindex
7437       SDValue(),        // voffset -- will be set by setBufferOffsets
7438       SDValue(),        // soffset -- will be set by setBufferOffsets
7439       SDValue(),        // offset -- will be set by setBufferOffsets
7440       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7441       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7442     };
7443     setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7444 
7445     EVT VT = Op.getValueType();
7446     auto *M = cast<MemSDNode>(Op);
7447     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7448 
7449     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7450                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7451   }
7452   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7453     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7454     SDValue Ops[] = {
7455       Op.getOperand(0), // Chain
7456       Op.getOperand(2), // src
7457       Op.getOperand(3), // cmp
7458       Op.getOperand(4), // rsrc
7459       DAG.getConstant(0, DL, MVT::i32), // vindex
7460       Offsets.first,    // voffset
7461       Op.getOperand(6), // soffset
7462       Offsets.second,   // offset
7463       Op.getOperand(7), // cachepolicy
7464       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7465     };
7466     EVT VT = Op.getValueType();
7467     auto *M = cast<MemSDNode>(Op);
7468     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]);
7469 
7470     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7471                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7472   }
7473   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7474     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7475     SDValue Ops[] = {
7476       Op.getOperand(0), // Chain
7477       Op.getOperand(2), // src
7478       Op.getOperand(3), // cmp
7479       Op.getOperand(4), // rsrc
7480       Op.getOperand(5), // vindex
7481       Offsets.first,    // voffset
7482       Op.getOperand(7), // soffset
7483       Offsets.second,   // offset
7484       Op.getOperand(8), // cachepolicy
7485       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7486     };
7487     EVT VT = Op.getValueType();
7488     auto *M = cast<MemSDNode>(Op);
7489     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7490 
7491     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7492                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7493   }
7494   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7495     MemSDNode *M = cast<MemSDNode>(Op);
7496     SDValue NodePtr = M->getOperand(2);
7497     SDValue RayExtent = M->getOperand(3);
7498     SDValue RayOrigin = M->getOperand(4);
7499     SDValue RayDir = M->getOperand(5);
7500     SDValue RayInvDir = M->getOperand(6);
7501     SDValue TDescr = M->getOperand(7);
7502 
7503     assert(NodePtr.getValueType() == MVT::i32 ||
7504            NodePtr.getValueType() == MVT::i64);
7505     assert(RayDir.getValueType() == MVT::v4f16 ||
7506            RayDir.getValueType() == MVT::v4f32);
7507 
7508     if (!Subtarget->hasGFX10_AEncoding()) {
7509       emitRemovedIntrinsicError(DAG, DL, Op.getValueType());
7510       return SDValue();
7511     }
7512 
7513     const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7514     const bool Is64 = NodePtr.getValueType() == MVT::i64;
7515     const unsigned NumVDataDwords = 4;
7516     const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
7517     const bool UseNSA = Subtarget->hasNSAEncoding() &&
7518                         NumVAddrDwords <= Subtarget->getNSAMaxSize();
7519     const unsigned BaseOpcodes[2][2] = {
7520         {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
7521         {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
7522          AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
7523     int Opcode;
7524     if (UseNSA) {
7525       Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7526                                      AMDGPU::MIMGEncGfx10NSA, NumVDataDwords,
7527                                      NumVAddrDwords);
7528     } else {
7529       Opcode = AMDGPU::getMIMGOpcode(
7530           BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords,
7531           PowerOf2Ceil(NumVAddrDwords));
7532     }
7533     assert(Opcode != -1);
7534 
7535     SmallVector<SDValue, 16> Ops;
7536 
7537     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7538       SmallVector<SDValue, 3> Lanes;
7539       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7540       if (Lanes[0].getValueSizeInBits() == 32) {
7541         for (unsigned I = 0; I < 3; ++I)
7542           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7543       } else {
7544         if (IsAligned) {
7545           Ops.push_back(
7546             DAG.getBitcast(MVT::i32,
7547                            DAG.getBuildVector(MVT::v2f16, DL,
7548                                               { Lanes[0], Lanes[1] })));
7549           Ops.push_back(Lanes[2]);
7550         } else {
7551           SDValue Elt0 = Ops.pop_back_val();
7552           Ops.push_back(
7553             DAG.getBitcast(MVT::i32,
7554                            DAG.getBuildVector(MVT::v2f16, DL,
7555                                               { Elt0, Lanes[0] })));
7556           Ops.push_back(
7557             DAG.getBitcast(MVT::i32,
7558                            DAG.getBuildVector(MVT::v2f16, DL,
7559                                               { Lanes[1], Lanes[2] })));
7560         }
7561       }
7562     };
7563 
7564     if (Is64)
7565       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7566     else
7567       Ops.push_back(NodePtr);
7568 
7569     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7570     packLanes(RayOrigin, true);
7571     packLanes(RayDir, true);
7572     packLanes(RayInvDir, false);
7573 
7574     if (!UseNSA) {
7575       // Build a single vector containing all the operands so far prepared.
7576       if (NumVAddrDwords > 8) {
7577         SDValue Undef = DAG.getUNDEF(MVT::i32);
7578         Ops.append(16 - Ops.size(), Undef);
7579       }
7580       assert(Ops.size() == 8 || Ops.size() == 16);
7581       SDValue MergedOps = DAG.getBuildVector(
7582           Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops);
7583       Ops.clear();
7584       Ops.push_back(MergedOps);
7585     }
7586 
7587     Ops.push_back(TDescr);
7588     if (IsA16)
7589       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7590     Ops.push_back(M->getChain());
7591 
7592     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7593     MachineMemOperand *MemRef = M->getMemOperand();
7594     DAG.setNodeMemRefs(NewNode, {MemRef});
7595     return SDValue(NewNode, 0);
7596   }
7597   case Intrinsic::amdgcn_global_atomic_fadd:
7598     if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7599       DiagnosticInfoUnsupported
7600         NoFpRet(DAG.getMachineFunction().getFunction(),
7601                 "return versions of fp atomics not supported",
7602                 DL.getDebugLoc(), DS_Error);
7603       DAG.getContext()->diagnose(NoFpRet);
7604       return SDValue();
7605     }
7606     LLVM_FALLTHROUGH;
7607   case Intrinsic::amdgcn_global_atomic_fmin:
7608   case Intrinsic::amdgcn_global_atomic_fmax:
7609   case Intrinsic::amdgcn_flat_atomic_fadd:
7610   case Intrinsic::amdgcn_flat_atomic_fmin:
7611   case Intrinsic::amdgcn_flat_atomic_fmax: {
7612     MemSDNode *M = cast<MemSDNode>(Op);
7613     SDValue Ops[] = {
7614       M->getOperand(0), // Chain
7615       M->getOperand(2), // Ptr
7616       M->getOperand(3)  // Value
7617     };
7618     unsigned Opcode = 0;
7619     switch (IntrID) {
7620     case Intrinsic::amdgcn_global_atomic_fadd:
7621     case Intrinsic::amdgcn_flat_atomic_fadd: {
7622       EVT VT = Op.getOperand(3).getValueType();
7623       return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7624                            DAG.getVTList(VT, MVT::Other), Ops,
7625                            M->getMemOperand());
7626     }
7627     case Intrinsic::amdgcn_global_atomic_fmin:
7628     case Intrinsic::amdgcn_flat_atomic_fmin: {
7629       Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7630       break;
7631     }
7632     case Intrinsic::amdgcn_global_atomic_fmax:
7633     case Intrinsic::amdgcn_flat_atomic_fmax: {
7634       Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7635       break;
7636     }
7637     default:
7638       llvm_unreachable("unhandled atomic opcode");
7639     }
7640     return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7641                                    M->getVTList(), Ops, M->getMemoryVT(),
7642                                    M->getMemOperand());
7643   }
7644   default:
7645 
7646     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7647             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7648       return lowerImage(Op, ImageDimIntr, DAG, true);
7649 
7650     return SDValue();
7651   }
7652 }
7653 
7654 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7655 // dwordx4 if on SI.
7656 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7657                                               SDVTList VTList,
7658                                               ArrayRef<SDValue> Ops, EVT MemVT,
7659                                               MachineMemOperand *MMO,
7660                                               SelectionDAG &DAG) const {
7661   EVT VT = VTList.VTs[0];
7662   EVT WidenedVT = VT;
7663   EVT WidenedMemVT = MemVT;
7664   if (!Subtarget->hasDwordx3LoadStores() &&
7665       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7666     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7667                                  WidenedVT.getVectorElementType(), 4);
7668     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7669                                     WidenedMemVT.getVectorElementType(), 4);
7670     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7671   }
7672 
7673   assert(VTList.NumVTs == 2);
7674   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7675 
7676   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7677                                        WidenedMemVT, MMO);
7678   if (WidenedVT != VT) {
7679     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7680                                DAG.getVectorIdxConstant(0, DL));
7681     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7682   }
7683   return NewOp;
7684 }
7685 
7686 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7687                                          bool ImageStore) const {
7688   EVT StoreVT = VData.getValueType();
7689 
7690   // No change for f16 and legal vector D16 types.
7691   if (!StoreVT.isVector())
7692     return VData;
7693 
7694   SDLoc DL(VData);
7695   unsigned NumElements = StoreVT.getVectorNumElements();
7696 
7697   if (Subtarget->hasUnpackedD16VMem()) {
7698     // We need to unpack the packed data to store.
7699     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7700     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7701 
7702     EVT EquivStoreVT =
7703         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7704     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7705     return DAG.UnrollVectorOp(ZExt.getNode());
7706   }
7707 
7708   // The sq block of gfx8.1 does not estimate register use correctly for d16
7709   // image store instructions. The data operand is computed as if it were not a
7710   // d16 image instruction.
7711   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7712     // Bitcast to i16
7713     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7714     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7715 
7716     // Decompose into scalars
7717     SmallVector<SDValue, 4> Elts;
7718     DAG.ExtractVectorElements(IntVData, Elts);
7719 
7720     // Group pairs of i16 into v2i16 and bitcast to i32
7721     SmallVector<SDValue, 4> PackedElts;
7722     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7723       SDValue Pair =
7724           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7725       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7726       PackedElts.push_back(IntPair);
7727     }
7728     if ((NumElements % 2) == 1) {
7729       // Handle v3i16
7730       unsigned I = Elts.size() / 2;
7731       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7732                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7733       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7734       PackedElts.push_back(IntPair);
7735     }
7736 
7737     // Pad using UNDEF
7738     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7739 
7740     // Build final vector
7741     EVT VecVT =
7742         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7743     return DAG.getBuildVector(VecVT, DL, PackedElts);
7744   }
7745 
7746   if (NumElements == 3) {
7747     EVT IntStoreVT =
7748         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7749     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7750 
7751     EVT WidenedStoreVT = EVT::getVectorVT(
7752         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7753     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7754                                          WidenedStoreVT.getStoreSizeInBits());
7755     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7756     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7757   }
7758 
7759   assert(isTypeLegal(StoreVT));
7760   return VData;
7761 }
7762 
7763 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7764                                               SelectionDAG &DAG) const {
7765   SDLoc DL(Op);
7766   SDValue Chain = Op.getOperand(0);
7767   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7768   MachineFunction &MF = DAG.getMachineFunction();
7769 
7770   switch (IntrinsicID) {
7771   case Intrinsic::amdgcn_exp_compr: {
7772     SDValue Src0 = Op.getOperand(4);
7773     SDValue Src1 = Op.getOperand(5);
7774     // Hack around illegal type on SI by directly selecting it.
7775     if (isTypeLegal(Src0.getValueType()))
7776       return SDValue();
7777 
7778     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7779     SDValue Undef = DAG.getUNDEF(MVT::f32);
7780     const SDValue Ops[] = {
7781       Op.getOperand(2), // tgt
7782       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7783       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7784       Undef, // src2
7785       Undef, // src3
7786       Op.getOperand(7), // vm
7787       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7788       Op.getOperand(3), // en
7789       Op.getOperand(0) // Chain
7790     };
7791 
7792     unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7793     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7794   }
7795   case Intrinsic::amdgcn_s_barrier: {
7796     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7797       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7798       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7799       if (WGSize <= ST.getWavefrontSize())
7800         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7801                                           Op.getOperand(0)), 0);
7802     }
7803     return SDValue();
7804   };
7805   case Intrinsic::amdgcn_tbuffer_store: {
7806     SDValue VData = Op.getOperand(2);
7807     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7808     if (IsD16)
7809       VData = handleD16VData(VData, DAG);
7810     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7811     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7812     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7813     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7814     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7815     SDValue Ops[] = {
7816       Chain,
7817       VData,             // vdata
7818       Op.getOperand(3),  // rsrc
7819       Op.getOperand(4),  // vindex
7820       Op.getOperand(5),  // voffset
7821       Op.getOperand(6),  // soffset
7822       Op.getOperand(7),  // offset
7823       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7824       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7825       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7826     };
7827     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7828                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7829     MemSDNode *M = cast<MemSDNode>(Op);
7830     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7831                                    M->getMemoryVT(), M->getMemOperand());
7832   }
7833 
7834   case Intrinsic::amdgcn_struct_tbuffer_store: {
7835     SDValue VData = Op.getOperand(2);
7836     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7837     if (IsD16)
7838       VData = handleD16VData(VData, DAG);
7839     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7840     SDValue Ops[] = {
7841       Chain,
7842       VData,             // vdata
7843       Op.getOperand(3),  // rsrc
7844       Op.getOperand(4),  // vindex
7845       Offsets.first,     // voffset
7846       Op.getOperand(6),  // soffset
7847       Offsets.second,    // offset
7848       Op.getOperand(7),  // format
7849       Op.getOperand(8),  // cachepolicy, swizzled buffer
7850       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7851     };
7852     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7853                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7854     MemSDNode *M = cast<MemSDNode>(Op);
7855     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7856                                    M->getMemoryVT(), M->getMemOperand());
7857   }
7858 
7859   case Intrinsic::amdgcn_raw_tbuffer_store: {
7860     SDValue VData = Op.getOperand(2);
7861     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7862     if (IsD16)
7863       VData = handleD16VData(VData, DAG);
7864     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7865     SDValue Ops[] = {
7866       Chain,
7867       VData,             // vdata
7868       Op.getOperand(3),  // rsrc
7869       DAG.getConstant(0, DL, MVT::i32), // vindex
7870       Offsets.first,     // voffset
7871       Op.getOperand(5),  // soffset
7872       Offsets.second,    // offset
7873       Op.getOperand(6),  // format
7874       Op.getOperand(7),  // cachepolicy, swizzled buffer
7875       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7876     };
7877     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7878                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7879     MemSDNode *M = cast<MemSDNode>(Op);
7880     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7881                                    M->getMemoryVT(), M->getMemOperand());
7882   }
7883 
7884   case Intrinsic::amdgcn_buffer_store:
7885   case Intrinsic::amdgcn_buffer_store_format: {
7886     SDValue VData = Op.getOperand(2);
7887     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7888     if (IsD16)
7889       VData = handleD16VData(VData, DAG);
7890     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7891     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7892     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7893     SDValue Ops[] = {
7894       Chain,
7895       VData,
7896       Op.getOperand(3), // rsrc
7897       Op.getOperand(4), // vindex
7898       SDValue(), // voffset -- will be set by setBufferOffsets
7899       SDValue(), // soffset -- will be set by setBufferOffsets
7900       SDValue(), // offset -- will be set by setBufferOffsets
7901       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7902       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7903     };
7904     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7905 
7906     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7907                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7908     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7909     MemSDNode *M = cast<MemSDNode>(Op);
7910     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7911 
7912     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7913     EVT VDataType = VData.getValueType().getScalarType();
7914     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7915       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7916 
7917     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7918                                    M->getMemoryVT(), M->getMemOperand());
7919   }
7920 
7921   case Intrinsic::amdgcn_raw_buffer_store:
7922   case Intrinsic::amdgcn_raw_buffer_store_format: {
7923     const bool IsFormat =
7924         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7925 
7926     SDValue VData = Op.getOperand(2);
7927     EVT VDataVT = VData.getValueType();
7928     EVT EltType = VDataVT.getScalarType();
7929     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7930     if (IsD16) {
7931       VData = handleD16VData(VData, DAG);
7932       VDataVT = VData.getValueType();
7933     }
7934 
7935     if (!isTypeLegal(VDataVT)) {
7936       VData =
7937           DAG.getNode(ISD::BITCAST, DL,
7938                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7939     }
7940 
7941     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7942     SDValue Ops[] = {
7943       Chain,
7944       VData,
7945       Op.getOperand(3), // rsrc
7946       DAG.getConstant(0, DL, MVT::i32), // vindex
7947       Offsets.first,    // voffset
7948       Op.getOperand(5), // soffset
7949       Offsets.second,   // offset
7950       Op.getOperand(6), // cachepolicy, swizzled buffer
7951       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7952     };
7953     unsigned Opc =
7954         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7955     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7956     MemSDNode *M = cast<MemSDNode>(Op);
7957     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
7958 
7959     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7960     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7961       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7962 
7963     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7964                                    M->getMemoryVT(), M->getMemOperand());
7965   }
7966 
7967   case Intrinsic::amdgcn_struct_buffer_store:
7968   case Intrinsic::amdgcn_struct_buffer_store_format: {
7969     const bool IsFormat =
7970         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7971 
7972     SDValue VData = Op.getOperand(2);
7973     EVT VDataVT = VData.getValueType();
7974     EVT EltType = VDataVT.getScalarType();
7975     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7976 
7977     if (IsD16) {
7978       VData = handleD16VData(VData, DAG);
7979       VDataVT = VData.getValueType();
7980     }
7981 
7982     if (!isTypeLegal(VDataVT)) {
7983       VData =
7984           DAG.getNode(ISD::BITCAST, DL,
7985                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7986     }
7987 
7988     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7989     SDValue Ops[] = {
7990       Chain,
7991       VData,
7992       Op.getOperand(3), // rsrc
7993       Op.getOperand(4), // vindex
7994       Offsets.first,    // voffset
7995       Op.getOperand(6), // soffset
7996       Offsets.second,   // offset
7997       Op.getOperand(7), // cachepolicy, swizzled buffer
7998       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7999     };
8000     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
8001                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8002     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8003     MemSDNode *M = cast<MemSDNode>(Op);
8004     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8005 
8006     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8007     EVT VDataType = VData.getValueType().getScalarType();
8008     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8009       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8010 
8011     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8012                                    M->getMemoryVT(), M->getMemOperand());
8013   }
8014   case Intrinsic::amdgcn_end_cf:
8015     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
8016                                       Op->getOperand(2), Chain), 0);
8017 
8018   default: {
8019     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
8020             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
8021       return lowerImage(Op, ImageDimIntr, DAG, true);
8022 
8023     return Op;
8024   }
8025   }
8026 }
8027 
8028 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
8029 // offset (the offset that is included in bounds checking and swizzling, to be
8030 // split between the instruction's voffset and immoffset fields) and soffset
8031 // (the offset that is excluded from bounds checking and swizzling, to go in
8032 // the instruction's soffset field).  This function takes the first kind of
8033 // offset and figures out how to split it between voffset and immoffset.
8034 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
8035     SDValue Offset, SelectionDAG &DAG) const {
8036   SDLoc DL(Offset);
8037   const unsigned MaxImm = 4095;
8038   SDValue N0 = Offset;
8039   ConstantSDNode *C1 = nullptr;
8040 
8041   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
8042     N0 = SDValue();
8043   else if (DAG.isBaseWithConstantOffset(N0)) {
8044     C1 = cast<ConstantSDNode>(N0.getOperand(1));
8045     N0 = N0.getOperand(0);
8046   }
8047 
8048   if (C1) {
8049     unsigned ImmOffset = C1->getZExtValue();
8050     // If the immediate value is too big for the immoffset field, put the value
8051     // and -4096 into the immoffset field so that the value that is copied/added
8052     // for the voffset field is a multiple of 4096, and it stands more chance
8053     // of being CSEd with the copy/add for another similar load/store.
8054     // However, do not do that rounding down to a multiple of 4096 if that is a
8055     // negative number, as it appears to be illegal to have a negative offset
8056     // in the vgpr, even if adding the immediate offset makes it positive.
8057     unsigned Overflow = ImmOffset & ~MaxImm;
8058     ImmOffset -= Overflow;
8059     if ((int32_t)Overflow < 0) {
8060       Overflow += ImmOffset;
8061       ImmOffset = 0;
8062     }
8063     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
8064     if (Overflow) {
8065       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
8066       if (!N0)
8067         N0 = OverflowVal;
8068       else {
8069         SDValue Ops[] = { N0, OverflowVal };
8070         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
8071       }
8072     }
8073   }
8074   if (!N0)
8075     N0 = DAG.getConstant(0, DL, MVT::i32);
8076   if (!C1)
8077     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
8078   return {N0, SDValue(C1, 0)};
8079 }
8080 
8081 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
8082 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
8083 // pointed to by Offsets.
8084 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
8085                                         SelectionDAG &DAG, SDValue *Offsets,
8086                                         Align Alignment) const {
8087   SDLoc DL(CombinedOffset);
8088   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
8089     uint32_t Imm = C->getZExtValue();
8090     uint32_t SOffset, ImmOffset;
8091     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
8092                                  Alignment)) {
8093       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
8094       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8095       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8096       return;
8097     }
8098   }
8099   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
8100     SDValue N0 = CombinedOffset.getOperand(0);
8101     SDValue N1 = CombinedOffset.getOperand(1);
8102     uint32_t SOffset, ImmOffset;
8103     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
8104     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
8105                                                 Subtarget, Alignment)) {
8106       Offsets[0] = N0;
8107       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8108       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8109       return;
8110     }
8111   }
8112   Offsets[0] = CombinedOffset;
8113   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
8114   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
8115 }
8116 
8117 // Handle 8 bit and 16 bit buffer loads
8118 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
8119                                                      EVT LoadVT, SDLoc DL,
8120                                                      ArrayRef<SDValue> Ops,
8121                                                      MemSDNode *M) const {
8122   EVT IntVT = LoadVT.changeTypeToInteger();
8123   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
8124          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
8125 
8126   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
8127   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
8128                                                Ops, IntVT,
8129                                                M->getMemOperand());
8130   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
8131   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
8132 
8133   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
8134 }
8135 
8136 // Handle 8 bit and 16 bit buffer stores
8137 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
8138                                                       EVT VDataType, SDLoc DL,
8139                                                       SDValue Ops[],
8140                                                       MemSDNode *M) const {
8141   if (VDataType == MVT::f16)
8142     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
8143 
8144   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
8145   Ops[1] = BufferStoreExt;
8146   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
8147                                  AMDGPUISD::BUFFER_STORE_SHORT;
8148   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
8149   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
8150                                      M->getMemOperand());
8151 }
8152 
8153 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
8154                                  ISD::LoadExtType ExtType, SDValue Op,
8155                                  const SDLoc &SL, EVT VT) {
8156   if (VT.bitsLT(Op.getValueType()))
8157     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
8158 
8159   switch (ExtType) {
8160   case ISD::SEXTLOAD:
8161     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
8162   case ISD::ZEXTLOAD:
8163     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
8164   case ISD::EXTLOAD:
8165     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
8166   case ISD::NON_EXTLOAD:
8167     return Op;
8168   }
8169 
8170   llvm_unreachable("invalid ext type");
8171 }
8172 
8173 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
8174   SelectionDAG &DAG = DCI.DAG;
8175   if (Ld->getAlignment() < 4 || Ld->isDivergent())
8176     return SDValue();
8177 
8178   // FIXME: Constant loads should all be marked invariant.
8179   unsigned AS = Ld->getAddressSpace();
8180   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
8181       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
8182       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
8183     return SDValue();
8184 
8185   // Don't do this early, since it may interfere with adjacent load merging for
8186   // illegal types. We can avoid losing alignment information for exotic types
8187   // pre-legalize.
8188   EVT MemVT = Ld->getMemoryVT();
8189   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
8190       MemVT.getSizeInBits() >= 32)
8191     return SDValue();
8192 
8193   SDLoc SL(Ld);
8194 
8195   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
8196          "unexpected vector extload");
8197 
8198   // TODO: Drop only high part of range.
8199   SDValue Ptr = Ld->getBasePtr();
8200   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
8201                                 MVT::i32, SL, Ld->getChain(), Ptr,
8202                                 Ld->getOffset(),
8203                                 Ld->getPointerInfo(), MVT::i32,
8204                                 Ld->getAlignment(),
8205                                 Ld->getMemOperand()->getFlags(),
8206                                 Ld->getAAInfo(),
8207                                 nullptr); // Drop ranges
8208 
8209   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
8210   if (MemVT.isFloatingPoint()) {
8211     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
8212            "unexpected fp extload");
8213     TruncVT = MemVT.changeTypeToInteger();
8214   }
8215 
8216   SDValue Cvt = NewLoad;
8217   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
8218     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
8219                       DAG.getValueType(TruncVT));
8220   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
8221              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
8222     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
8223   } else {
8224     assert(Ld->getExtensionType() == ISD::EXTLOAD);
8225   }
8226 
8227   EVT VT = Ld->getValueType(0);
8228   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8229 
8230   DCI.AddToWorklist(Cvt.getNode());
8231 
8232   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
8233   // the appropriate extension from the 32-bit load.
8234   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
8235   DCI.AddToWorklist(Cvt.getNode());
8236 
8237   // Handle conversion back to floating point if necessary.
8238   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8239 
8240   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8241 }
8242 
8243 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8244   SDLoc DL(Op);
8245   LoadSDNode *Load = cast<LoadSDNode>(Op);
8246   ISD::LoadExtType ExtType = Load->getExtensionType();
8247   EVT MemVT = Load->getMemoryVT();
8248 
8249   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8250     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8251       return SDValue();
8252 
8253     // FIXME: Copied from PPC
8254     // First, load into 32 bits, then truncate to 1 bit.
8255 
8256     SDValue Chain = Load->getChain();
8257     SDValue BasePtr = Load->getBasePtr();
8258     MachineMemOperand *MMO = Load->getMemOperand();
8259 
8260     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8261 
8262     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8263                                    BasePtr, RealMemVT, MMO);
8264 
8265     if (!MemVT.isVector()) {
8266       SDValue Ops[] = {
8267         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8268         NewLD.getValue(1)
8269       };
8270 
8271       return DAG.getMergeValues(Ops, DL);
8272     }
8273 
8274     SmallVector<SDValue, 3> Elts;
8275     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8276       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8277                                 DAG.getConstant(I, DL, MVT::i32));
8278 
8279       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8280     }
8281 
8282     SDValue Ops[] = {
8283       DAG.getBuildVector(MemVT, DL, Elts),
8284       NewLD.getValue(1)
8285     };
8286 
8287     return DAG.getMergeValues(Ops, DL);
8288   }
8289 
8290   if (!MemVT.isVector())
8291     return SDValue();
8292 
8293   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8294          "Custom lowering for non-i32 vectors hasn't been implemented.");
8295 
8296   unsigned Alignment = Load->getAlignment();
8297   unsigned AS = Load->getAddressSpace();
8298   if (Subtarget->hasLDSMisalignedBug() &&
8299       AS == AMDGPUAS::FLAT_ADDRESS &&
8300       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8301     return SplitVectorLoad(Op, DAG);
8302   }
8303 
8304   MachineFunction &MF = DAG.getMachineFunction();
8305   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8306   // If there is a possibilty that flat instruction access scratch memory
8307   // then we need to use the same legalization rules we use for private.
8308   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8309       !Subtarget->hasMultiDwordFlatScratchAddressing())
8310     AS = MFI->hasFlatScratchInit() ?
8311          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8312 
8313   unsigned NumElements = MemVT.getVectorNumElements();
8314 
8315   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8316       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8317     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8318       if (MemVT.isPow2VectorType())
8319         return SDValue();
8320       return WidenOrSplitVectorLoad(Op, DAG);
8321     }
8322     // Non-uniform loads will be selected to MUBUF instructions, so they
8323     // have the same legalization requirements as global and private
8324     // loads.
8325     //
8326   }
8327 
8328   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8329       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8330       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8331     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8332         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8333         Alignment >= 4 && NumElements < 32) {
8334       if (MemVT.isPow2VectorType())
8335         return SDValue();
8336       return WidenOrSplitVectorLoad(Op, DAG);
8337     }
8338     // Non-uniform loads will be selected to MUBUF instructions, so they
8339     // have the same legalization requirements as global and private
8340     // loads.
8341     //
8342   }
8343   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8344       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8345       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8346       AS == AMDGPUAS::FLAT_ADDRESS) {
8347     if (NumElements > 4)
8348       return SplitVectorLoad(Op, DAG);
8349     // v3 loads not supported on SI.
8350     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8351       return WidenOrSplitVectorLoad(Op, DAG);
8352 
8353     // v3 and v4 loads are supported for private and global memory.
8354     return SDValue();
8355   }
8356   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8357     // Depending on the setting of the private_element_size field in the
8358     // resource descriptor, we can only make private accesses up to a certain
8359     // size.
8360     switch (Subtarget->getMaxPrivateElementSize()) {
8361     case 4: {
8362       SDValue Ops[2];
8363       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8364       return DAG.getMergeValues(Ops, DL);
8365     }
8366     case 8:
8367       if (NumElements > 2)
8368         return SplitVectorLoad(Op, DAG);
8369       return SDValue();
8370     case 16:
8371       // Same as global/flat
8372       if (NumElements > 4)
8373         return SplitVectorLoad(Op, DAG);
8374       // v3 loads not supported on SI.
8375       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8376         return WidenOrSplitVectorLoad(Op, DAG);
8377 
8378       return SDValue();
8379     default:
8380       llvm_unreachable("unsupported private_element_size");
8381     }
8382   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8383     // Use ds_read_b128 or ds_read_b96 when possible.
8384     if (Subtarget->hasDS96AndDS128() &&
8385         ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) ||
8386          MemVT.getStoreSize() == 12) &&
8387         allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8388                                            Load->getAlign()))
8389       return SDValue();
8390 
8391     if (NumElements > 2)
8392       return SplitVectorLoad(Op, DAG);
8393 
8394     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8395     // address is negative, then the instruction is incorrectly treated as
8396     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8397     // loads here to avoid emitting ds_read2_b32. We may re-combine the
8398     // load later in the SILoadStoreOptimizer.
8399     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
8400         NumElements == 2 && MemVT.getStoreSize() == 8 &&
8401         Load->getAlignment() < 8) {
8402       return SplitVectorLoad(Op, DAG);
8403     }
8404   }
8405 
8406   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8407                                       MemVT, *Load->getMemOperand())) {
8408     SDValue Ops[2];
8409     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8410     return DAG.getMergeValues(Ops, DL);
8411   }
8412 
8413   return SDValue();
8414 }
8415 
8416 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8417   EVT VT = Op.getValueType();
8418   assert(VT.getSizeInBits() == 64);
8419 
8420   SDLoc DL(Op);
8421   SDValue Cond = Op.getOperand(0);
8422 
8423   if (Subtarget->hasScalarCompareEq64() && Op->getOperand(0)->hasOneUse() &&
8424       !Op->isDivergent()) {
8425     if (VT == MVT::i64)
8426       return Op;
8427     SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(1));
8428     SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(2));
8429     return DAG.getNode(ISD::BITCAST, DL, VT,
8430                        DAG.getSelect(DL, MVT::i64, Cond, LHS, RHS));
8431   }
8432 
8433   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8434   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8435 
8436   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8437   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8438 
8439   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8440   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8441 
8442   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8443 
8444   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8445   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8446 
8447   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8448 
8449   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8450   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8451 }
8452 
8453 // Catch division cases where we can use shortcuts with rcp and rsq
8454 // instructions.
8455 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8456                                               SelectionDAG &DAG) const {
8457   SDLoc SL(Op);
8458   SDValue LHS = Op.getOperand(0);
8459   SDValue RHS = Op.getOperand(1);
8460   EVT VT = Op.getValueType();
8461   const SDNodeFlags Flags = Op->getFlags();
8462 
8463   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8464 
8465   // Without !fpmath accuracy information, we can't do more because we don't
8466   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8467   if (!AllowInaccurateRcp)
8468     return SDValue();
8469 
8470   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8471     if (CLHS->isExactlyValue(1.0)) {
8472       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8473       // the CI documentation has a worst case error of 1 ulp.
8474       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8475       // use it as long as we aren't trying to use denormals.
8476       //
8477       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8478 
8479       // 1.0 / sqrt(x) -> rsq(x)
8480 
8481       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8482       // error seems really high at 2^29 ULP.
8483       if (RHS.getOpcode() == ISD::FSQRT)
8484         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8485 
8486       // 1.0 / x -> rcp(x)
8487       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8488     }
8489 
8490     // Same as for 1.0, but expand the sign out of the constant.
8491     if (CLHS->isExactlyValue(-1.0)) {
8492       // -1.0 / x -> rcp (fneg x)
8493       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8494       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8495     }
8496   }
8497 
8498   // Turn into multiply by the reciprocal.
8499   // x / y -> x * (1.0 / y)
8500   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8501   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8502 }
8503 
8504 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8505                                                 SelectionDAG &DAG) const {
8506   SDLoc SL(Op);
8507   SDValue X = Op.getOperand(0);
8508   SDValue Y = Op.getOperand(1);
8509   EVT VT = Op.getValueType();
8510   const SDNodeFlags Flags = Op->getFlags();
8511 
8512   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8513                             DAG.getTarget().Options.UnsafeFPMath;
8514   if (!AllowInaccurateDiv)
8515     return SDValue();
8516 
8517   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8518   SDValue One = DAG.getConstantFP(1.0, SL, VT);
8519 
8520   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8521   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8522 
8523   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8524   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8525   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8526   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8527   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8528   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8529 }
8530 
8531 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8532                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8533                           SDNodeFlags Flags) {
8534   if (GlueChain->getNumValues() <= 1) {
8535     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8536   }
8537 
8538   assert(GlueChain->getNumValues() == 3);
8539 
8540   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8541   switch (Opcode) {
8542   default: llvm_unreachable("no chain equivalent for opcode");
8543   case ISD::FMUL:
8544     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8545     break;
8546   }
8547 
8548   return DAG.getNode(Opcode, SL, VTList,
8549                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8550                      Flags);
8551 }
8552 
8553 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8554                            EVT VT, SDValue A, SDValue B, SDValue C,
8555                            SDValue GlueChain, SDNodeFlags Flags) {
8556   if (GlueChain->getNumValues() <= 1) {
8557     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8558   }
8559 
8560   assert(GlueChain->getNumValues() == 3);
8561 
8562   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8563   switch (Opcode) {
8564   default: llvm_unreachable("no chain equivalent for opcode");
8565   case ISD::FMA:
8566     Opcode = AMDGPUISD::FMA_W_CHAIN;
8567     break;
8568   }
8569 
8570   return DAG.getNode(Opcode, SL, VTList,
8571                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8572                      Flags);
8573 }
8574 
8575 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8576   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8577     return FastLowered;
8578 
8579   SDLoc SL(Op);
8580   SDValue Src0 = Op.getOperand(0);
8581   SDValue Src1 = Op.getOperand(1);
8582 
8583   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8584   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8585 
8586   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8587   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8588 
8589   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8590   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8591 
8592   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8593 }
8594 
8595 // Faster 2.5 ULP division that does not support denormals.
8596 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8597   SDLoc SL(Op);
8598   SDValue LHS = Op.getOperand(1);
8599   SDValue RHS = Op.getOperand(2);
8600 
8601   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8602 
8603   const APFloat K0Val(BitsToFloat(0x6f800000));
8604   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8605 
8606   const APFloat K1Val(BitsToFloat(0x2f800000));
8607   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8608 
8609   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8610 
8611   EVT SetCCVT =
8612     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8613 
8614   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8615 
8616   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8617 
8618   // TODO: Should this propagate fast-math-flags?
8619   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8620 
8621   // rcp does not support denormals.
8622   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8623 
8624   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8625 
8626   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8627 }
8628 
8629 // Returns immediate value for setting the F32 denorm mode when using the
8630 // S_DENORM_MODE instruction.
8631 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8632                                     const SDLoc &SL, const GCNSubtarget *ST) {
8633   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8634   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8635                                 ? FP_DENORM_FLUSH_NONE
8636                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8637 
8638   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8639   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8640 }
8641 
8642 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8643   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8644     return FastLowered;
8645 
8646   // The selection matcher assumes anything with a chain selecting to a
8647   // mayRaiseFPException machine instruction. Since we're introducing a chain
8648   // here, we need to explicitly report nofpexcept for the regular fdiv
8649   // lowering.
8650   SDNodeFlags Flags = Op->getFlags();
8651   Flags.setNoFPExcept(true);
8652 
8653   SDLoc SL(Op);
8654   SDValue LHS = Op.getOperand(0);
8655   SDValue RHS = Op.getOperand(1);
8656 
8657   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8658 
8659   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8660 
8661   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8662                                           {RHS, RHS, LHS}, Flags);
8663   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8664                                         {LHS, RHS, LHS}, Flags);
8665 
8666   // Denominator is scaled to not be denormal, so using rcp is ok.
8667   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8668                                   DenominatorScaled, Flags);
8669   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8670                                      DenominatorScaled, Flags);
8671 
8672   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8673                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8674                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8675   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8676 
8677   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8678 
8679   if (!HasFP32Denormals) {
8680     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8681     // lowering. The chain dependence is insufficient, and we need glue. We do
8682     // not need the glue variants in a strictfp function.
8683 
8684     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8685 
8686     SDNode *EnableDenorm;
8687     if (Subtarget->hasDenormModeInst()) {
8688       const SDValue EnableDenormValue =
8689           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8690 
8691       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8692                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8693     } else {
8694       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8695                                                         SL, MVT::i32);
8696       EnableDenorm =
8697           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8698                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8699     }
8700 
8701     SDValue Ops[3] = {
8702       NegDivScale0,
8703       SDValue(EnableDenorm, 0),
8704       SDValue(EnableDenorm, 1)
8705     };
8706 
8707     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8708   }
8709 
8710   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8711                              ApproxRcp, One, NegDivScale0, Flags);
8712 
8713   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8714                              ApproxRcp, Fma0, Flags);
8715 
8716   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8717                            Fma1, Fma1, Flags);
8718 
8719   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8720                              NumeratorScaled, Mul, Flags);
8721 
8722   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8723                              Fma2, Fma1, Mul, Fma2, Flags);
8724 
8725   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8726                              NumeratorScaled, Fma3, Flags);
8727 
8728   if (!HasFP32Denormals) {
8729     SDNode *DisableDenorm;
8730     if (Subtarget->hasDenormModeInst()) {
8731       const SDValue DisableDenormValue =
8732           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8733 
8734       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8735                                   Fma4.getValue(1), DisableDenormValue,
8736                                   Fma4.getValue(2)).getNode();
8737     } else {
8738       const SDValue DisableDenormValue =
8739           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8740 
8741       DisableDenorm = DAG.getMachineNode(
8742           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8743           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8744     }
8745 
8746     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8747                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8748     DAG.setRoot(OutputChain);
8749   }
8750 
8751   SDValue Scale = NumeratorScaled.getValue(1);
8752   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8753                              {Fma4, Fma1, Fma3, Scale}, Flags);
8754 
8755   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8756 }
8757 
8758 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8759   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
8760     return FastLowered;
8761 
8762   SDLoc SL(Op);
8763   SDValue X = Op.getOperand(0);
8764   SDValue Y = Op.getOperand(1);
8765 
8766   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8767 
8768   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8769 
8770   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8771 
8772   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8773 
8774   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8775 
8776   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8777 
8778   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8779 
8780   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8781 
8782   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8783 
8784   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8785   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8786 
8787   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8788                              NegDivScale0, Mul, DivScale1);
8789 
8790   SDValue Scale;
8791 
8792   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8793     // Workaround a hardware bug on SI where the condition output from div_scale
8794     // is not usable.
8795 
8796     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8797 
8798     // Figure out if the scale to use for div_fmas.
8799     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8800     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8801     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8802     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8803 
8804     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8805     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8806 
8807     SDValue Scale0Hi
8808       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8809     SDValue Scale1Hi
8810       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8811 
8812     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8813     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8814     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8815   } else {
8816     Scale = DivScale1.getValue(1);
8817   }
8818 
8819   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8820                              Fma4, Fma3, Mul, Scale);
8821 
8822   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8823 }
8824 
8825 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8826   EVT VT = Op.getValueType();
8827 
8828   if (VT == MVT::f32)
8829     return LowerFDIV32(Op, DAG);
8830 
8831   if (VT == MVT::f64)
8832     return LowerFDIV64(Op, DAG);
8833 
8834   if (VT == MVT::f16)
8835     return LowerFDIV16(Op, DAG);
8836 
8837   llvm_unreachable("Unexpected type for fdiv");
8838 }
8839 
8840 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8841   SDLoc DL(Op);
8842   StoreSDNode *Store = cast<StoreSDNode>(Op);
8843   EVT VT = Store->getMemoryVT();
8844 
8845   if (VT == MVT::i1) {
8846     return DAG.getTruncStore(Store->getChain(), DL,
8847        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8848        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8849   }
8850 
8851   assert(VT.isVector() &&
8852          Store->getValue().getValueType().getScalarType() == MVT::i32);
8853 
8854   unsigned AS = Store->getAddressSpace();
8855   if (Subtarget->hasLDSMisalignedBug() &&
8856       AS == AMDGPUAS::FLAT_ADDRESS &&
8857       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8858     return SplitVectorStore(Op, DAG);
8859   }
8860 
8861   MachineFunction &MF = DAG.getMachineFunction();
8862   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8863   // If there is a possibilty that flat instruction access scratch memory
8864   // then we need to use the same legalization rules we use for private.
8865   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8866       !Subtarget->hasMultiDwordFlatScratchAddressing())
8867     AS = MFI->hasFlatScratchInit() ?
8868          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8869 
8870   unsigned NumElements = VT.getVectorNumElements();
8871   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8872       AS == AMDGPUAS::FLAT_ADDRESS) {
8873     if (NumElements > 4)
8874       return SplitVectorStore(Op, DAG);
8875     // v3 stores not supported on SI.
8876     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8877       return SplitVectorStore(Op, DAG);
8878 
8879     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8880                                         VT, *Store->getMemOperand()))
8881       return expandUnalignedStore(Store, DAG);
8882 
8883     return SDValue();
8884   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8885     switch (Subtarget->getMaxPrivateElementSize()) {
8886     case 4:
8887       return scalarizeVectorStore(Store, DAG);
8888     case 8:
8889       if (NumElements > 2)
8890         return SplitVectorStore(Op, DAG);
8891       return SDValue();
8892     case 16:
8893       if (NumElements > 4 ||
8894           (NumElements == 3 && !Subtarget->enableFlatScratch()))
8895         return SplitVectorStore(Op, DAG);
8896       return SDValue();
8897     default:
8898       llvm_unreachable("unsupported private_element_size");
8899     }
8900   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8901     // Use ds_write_b128 or ds_write_b96 when possible.
8902     if (Subtarget->hasDS96AndDS128() &&
8903         ((Subtarget->useDS128() && VT.getStoreSize() == 16) ||
8904          (VT.getStoreSize() == 12)) &&
8905         allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
8906                                            Store->getAlign()))
8907       return SDValue();
8908 
8909     if (NumElements > 2)
8910       return SplitVectorStore(Op, DAG);
8911 
8912     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8913     // address is negative, then the instruction is incorrectly treated as
8914     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8915     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8916     // store later in the SILoadStoreOptimizer.
8917     if (!Subtarget->hasUsableDSOffset() &&
8918         NumElements == 2 && VT.getStoreSize() == 8 &&
8919         Store->getAlignment() < 8) {
8920       return SplitVectorStore(Op, DAG);
8921     }
8922 
8923     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8924                                         VT, *Store->getMemOperand())) {
8925       if (VT.isVector())
8926         return SplitVectorStore(Op, DAG);
8927       return expandUnalignedStore(Store, DAG);
8928     }
8929 
8930     return SDValue();
8931   } else {
8932     llvm_unreachable("unhandled address space");
8933   }
8934 }
8935 
8936 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8937   SDLoc DL(Op);
8938   EVT VT = Op.getValueType();
8939   SDValue Arg = Op.getOperand(0);
8940   SDValue TrigVal;
8941 
8942   // Propagate fast-math flags so that the multiply we introduce can be folded
8943   // if Arg is already the result of a multiply by constant.
8944   auto Flags = Op->getFlags();
8945 
8946   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
8947 
8948   if (Subtarget->hasTrigReducedRange()) {
8949     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8950     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
8951   } else {
8952     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8953   }
8954 
8955   switch (Op.getOpcode()) {
8956   case ISD::FCOS:
8957     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
8958   case ISD::FSIN:
8959     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
8960   default:
8961     llvm_unreachable("Wrong trig opcode");
8962   }
8963 }
8964 
8965 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8966   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8967   assert(AtomicNode->isCompareAndSwap());
8968   unsigned AS = AtomicNode->getAddressSpace();
8969 
8970   // No custom lowering required for local address space
8971   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
8972     return Op;
8973 
8974   // Non-local address space requires custom lowering for atomic compare
8975   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8976   SDLoc DL(Op);
8977   SDValue ChainIn = Op.getOperand(0);
8978   SDValue Addr = Op.getOperand(1);
8979   SDValue Old = Op.getOperand(2);
8980   SDValue New = Op.getOperand(3);
8981   EVT VT = Op.getValueType();
8982   MVT SimpleVT = VT.getSimpleVT();
8983   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8984 
8985   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8986   SDValue Ops[] = { ChainIn, Addr, NewOld };
8987 
8988   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8989                                  Ops, VT, AtomicNode->getMemOperand());
8990 }
8991 
8992 //===----------------------------------------------------------------------===//
8993 // Custom DAG optimizations
8994 //===----------------------------------------------------------------------===//
8995 
8996 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8997                                                      DAGCombinerInfo &DCI) const {
8998   EVT VT = N->getValueType(0);
8999   EVT ScalarVT = VT.getScalarType();
9000   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
9001     return SDValue();
9002 
9003   SelectionDAG &DAG = DCI.DAG;
9004   SDLoc DL(N);
9005 
9006   SDValue Src = N->getOperand(0);
9007   EVT SrcVT = Src.getValueType();
9008 
9009   // TODO: We could try to match extracting the higher bytes, which would be
9010   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
9011   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
9012   // about in practice.
9013   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
9014     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
9015       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
9016       DCI.AddToWorklist(Cvt.getNode());
9017 
9018       // For the f16 case, fold to a cast to f32 and then cast back to f16.
9019       if (ScalarVT != MVT::f32) {
9020         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
9021                           DAG.getTargetConstant(0, DL, MVT::i32));
9022       }
9023       return Cvt;
9024     }
9025   }
9026 
9027   return SDValue();
9028 }
9029 
9030 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
9031 
9032 // This is a variant of
9033 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
9034 //
9035 // The normal DAG combiner will do this, but only if the add has one use since
9036 // that would increase the number of instructions.
9037 //
9038 // This prevents us from seeing a constant offset that can be folded into a
9039 // memory instruction's addressing mode. If we know the resulting add offset of
9040 // a pointer can be folded into an addressing offset, we can replace the pointer
9041 // operand with the add of new constant offset. This eliminates one of the uses,
9042 // and may allow the remaining use to also be simplified.
9043 //
9044 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
9045                                                unsigned AddrSpace,
9046                                                EVT MemVT,
9047                                                DAGCombinerInfo &DCI) const {
9048   SDValue N0 = N->getOperand(0);
9049   SDValue N1 = N->getOperand(1);
9050 
9051   // We only do this to handle cases where it's profitable when there are
9052   // multiple uses of the add, so defer to the standard combine.
9053   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
9054       N0->hasOneUse())
9055     return SDValue();
9056 
9057   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
9058   if (!CN1)
9059     return SDValue();
9060 
9061   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9062   if (!CAdd)
9063     return SDValue();
9064 
9065   // If the resulting offset is too large, we can't fold it into the addressing
9066   // mode offset.
9067   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
9068   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
9069 
9070   AddrMode AM;
9071   AM.HasBaseReg = true;
9072   AM.BaseOffs = Offset.getSExtValue();
9073   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
9074     return SDValue();
9075 
9076   SelectionDAG &DAG = DCI.DAG;
9077   SDLoc SL(N);
9078   EVT VT = N->getValueType(0);
9079 
9080   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
9081   SDValue COffset = DAG.getConstant(Offset, SL, VT);
9082 
9083   SDNodeFlags Flags;
9084   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
9085                           (N0.getOpcode() == ISD::OR ||
9086                            N0->getFlags().hasNoUnsignedWrap()));
9087 
9088   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
9089 }
9090 
9091 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
9092 /// by the chain and intrinsic ID. Theoretically we would also need to check the
9093 /// specific intrinsic, but they all place the pointer operand first.
9094 static unsigned getBasePtrIndex(const MemSDNode *N) {
9095   switch (N->getOpcode()) {
9096   case ISD::STORE:
9097   case ISD::INTRINSIC_W_CHAIN:
9098   case ISD::INTRINSIC_VOID:
9099     return 2;
9100   default:
9101     return 1;
9102   }
9103 }
9104 
9105 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
9106                                                   DAGCombinerInfo &DCI) const {
9107   SelectionDAG &DAG = DCI.DAG;
9108   SDLoc SL(N);
9109 
9110   unsigned PtrIdx = getBasePtrIndex(N);
9111   SDValue Ptr = N->getOperand(PtrIdx);
9112 
9113   // TODO: We could also do this for multiplies.
9114   if (Ptr.getOpcode() == ISD::SHL) {
9115     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
9116                                           N->getMemoryVT(), DCI);
9117     if (NewPtr) {
9118       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
9119 
9120       NewOps[PtrIdx] = NewPtr;
9121       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
9122     }
9123   }
9124 
9125   return SDValue();
9126 }
9127 
9128 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
9129   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
9130          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
9131          (Opc == ISD::XOR && Val == 0);
9132 }
9133 
9134 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
9135 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
9136 // integer combine opportunities since most 64-bit operations are decomposed
9137 // this way.  TODO: We won't want this for SALU especially if it is an inline
9138 // immediate.
9139 SDValue SITargetLowering::splitBinaryBitConstantOp(
9140   DAGCombinerInfo &DCI,
9141   const SDLoc &SL,
9142   unsigned Opc, SDValue LHS,
9143   const ConstantSDNode *CRHS) const {
9144   uint64_t Val = CRHS->getZExtValue();
9145   uint32_t ValLo = Lo_32(Val);
9146   uint32_t ValHi = Hi_32(Val);
9147   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9148 
9149     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
9150          bitOpWithConstantIsReducible(Opc, ValHi)) ||
9151         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
9152     // If we need to materialize a 64-bit immediate, it will be split up later
9153     // anyway. Avoid creating the harder to understand 64-bit immediate
9154     // materialization.
9155     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
9156   }
9157 
9158   return SDValue();
9159 }
9160 
9161 // Returns true if argument is a boolean value which is not serialized into
9162 // memory or argument and does not require v_cndmask_b32 to be deserialized.
9163 static bool isBoolSGPR(SDValue V) {
9164   if (V.getValueType() != MVT::i1)
9165     return false;
9166   switch (V.getOpcode()) {
9167   default:
9168     break;
9169   case ISD::SETCC:
9170   case AMDGPUISD::FP_CLASS:
9171     return true;
9172   case ISD::AND:
9173   case ISD::OR:
9174   case ISD::XOR:
9175     return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
9176   }
9177   return false;
9178 }
9179 
9180 // If a constant has all zeroes or all ones within each byte return it.
9181 // Otherwise return 0.
9182 static uint32_t getConstantPermuteMask(uint32_t C) {
9183   // 0xff for any zero byte in the mask
9184   uint32_t ZeroByteMask = 0;
9185   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
9186   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
9187   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
9188   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
9189   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
9190   if ((NonZeroByteMask & C) != NonZeroByteMask)
9191     return 0; // Partial bytes selected.
9192   return C;
9193 }
9194 
9195 // Check if a node selects whole bytes from its operand 0 starting at a byte
9196 // boundary while masking the rest. Returns select mask as in the v_perm_b32
9197 // or -1 if not succeeded.
9198 // Note byte select encoding:
9199 // value 0-3 selects corresponding source byte;
9200 // value 0xc selects zero;
9201 // value 0xff selects 0xff.
9202 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
9203   assert(V.getValueSizeInBits() == 32);
9204 
9205   if (V.getNumOperands() != 2)
9206     return ~0;
9207 
9208   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
9209   if (!N1)
9210     return ~0;
9211 
9212   uint32_t C = N1->getZExtValue();
9213 
9214   switch (V.getOpcode()) {
9215   default:
9216     break;
9217   case ISD::AND:
9218     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9219       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
9220     }
9221     break;
9222 
9223   case ISD::OR:
9224     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9225       return (0x03020100 & ~ConstMask) | ConstMask;
9226     }
9227     break;
9228 
9229   case ISD::SHL:
9230     if (C % 8)
9231       return ~0;
9232 
9233     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
9234 
9235   case ISD::SRL:
9236     if (C % 8)
9237       return ~0;
9238 
9239     return uint32_t(0x0c0c0c0c03020100ull >> C);
9240   }
9241 
9242   return ~0;
9243 }
9244 
9245 SDValue SITargetLowering::performAndCombine(SDNode *N,
9246                                             DAGCombinerInfo &DCI) const {
9247   if (DCI.isBeforeLegalize())
9248     return SDValue();
9249 
9250   SelectionDAG &DAG = DCI.DAG;
9251   EVT VT = N->getValueType(0);
9252   SDValue LHS = N->getOperand(0);
9253   SDValue RHS = N->getOperand(1);
9254 
9255 
9256   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9257   if (VT == MVT::i64 && CRHS) {
9258     if (SDValue Split
9259         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9260       return Split;
9261   }
9262 
9263   if (CRHS && VT == MVT::i32) {
9264     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9265     // nb = number of trailing zeroes in mask
9266     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9267     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9268     uint64_t Mask = CRHS->getZExtValue();
9269     unsigned Bits = countPopulation(Mask);
9270     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9271         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9272       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9273         unsigned Shift = CShift->getZExtValue();
9274         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9275         unsigned Offset = NB + Shift;
9276         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9277           SDLoc SL(N);
9278           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9279                                     LHS->getOperand(0),
9280                                     DAG.getConstant(Offset, SL, MVT::i32),
9281                                     DAG.getConstant(Bits, SL, MVT::i32));
9282           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9283           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9284                                     DAG.getValueType(NarrowVT));
9285           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9286                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9287           return Shl;
9288         }
9289       }
9290     }
9291 
9292     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9293     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9294         isa<ConstantSDNode>(LHS.getOperand(2))) {
9295       uint32_t Sel = getConstantPermuteMask(Mask);
9296       if (!Sel)
9297         return SDValue();
9298 
9299       // Select 0xc for all zero bytes
9300       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9301       SDLoc DL(N);
9302       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9303                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9304     }
9305   }
9306 
9307   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9308   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9309   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9310     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9311     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9312 
9313     SDValue X = LHS.getOperand(0);
9314     SDValue Y = RHS.getOperand(0);
9315     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9316       return SDValue();
9317 
9318     if (LCC == ISD::SETO) {
9319       if (X != LHS.getOperand(1))
9320         return SDValue();
9321 
9322       if (RCC == ISD::SETUNE) {
9323         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9324         if (!C1 || !C1->isInfinity() || C1->isNegative())
9325           return SDValue();
9326 
9327         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9328                               SIInstrFlags::N_SUBNORMAL |
9329                               SIInstrFlags::N_ZERO |
9330                               SIInstrFlags::P_ZERO |
9331                               SIInstrFlags::P_SUBNORMAL |
9332                               SIInstrFlags::P_NORMAL;
9333 
9334         static_assert(((~(SIInstrFlags::S_NAN |
9335                           SIInstrFlags::Q_NAN |
9336                           SIInstrFlags::N_INFINITY |
9337                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9338                       "mask not equal");
9339 
9340         SDLoc DL(N);
9341         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9342                            X, DAG.getConstant(Mask, DL, MVT::i32));
9343       }
9344     }
9345   }
9346 
9347   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9348     std::swap(LHS, RHS);
9349 
9350   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9351       RHS.hasOneUse()) {
9352     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9353     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9354     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9355     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9356     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9357         (RHS.getOperand(0) == LHS.getOperand(0) &&
9358          LHS.getOperand(0) == LHS.getOperand(1))) {
9359       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9360       unsigned NewMask = LCC == ISD::SETO ?
9361         Mask->getZExtValue() & ~OrdMask :
9362         Mask->getZExtValue() & OrdMask;
9363 
9364       SDLoc DL(N);
9365       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9366                          DAG.getConstant(NewMask, DL, MVT::i32));
9367     }
9368   }
9369 
9370   if (VT == MVT::i32 &&
9371       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9372     // and x, (sext cc from i1) => select cc, x, 0
9373     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9374       std::swap(LHS, RHS);
9375     if (isBoolSGPR(RHS.getOperand(0)))
9376       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9377                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9378   }
9379 
9380   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9381   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9382   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9383       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9384     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9385     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9386     if (LHSMask != ~0u && RHSMask != ~0u) {
9387       // Canonicalize the expression in an attempt to have fewer unique masks
9388       // and therefore fewer registers used to hold the masks.
9389       if (LHSMask > RHSMask) {
9390         std::swap(LHSMask, RHSMask);
9391         std::swap(LHS, RHS);
9392       }
9393 
9394       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9395       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9396       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9397       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9398 
9399       // Check of we need to combine values from two sources within a byte.
9400       if (!(LHSUsedLanes & RHSUsedLanes) &&
9401           // If we select high and lower word keep it for SDWA.
9402           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9403           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9404         // Each byte in each mask is either selector mask 0-3, or has higher
9405         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9406         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9407         // mask which is not 0xff wins. By anding both masks we have a correct
9408         // result except that 0x0c shall be corrected to give 0x0c only.
9409         uint32_t Mask = LHSMask & RHSMask;
9410         for (unsigned I = 0; I < 32; I += 8) {
9411           uint32_t ByteSel = 0xff << I;
9412           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9413             Mask &= (0x0c << I) & 0xffffffff;
9414         }
9415 
9416         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9417         // or 0x0c.
9418         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9419         SDLoc DL(N);
9420 
9421         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9422                            LHS.getOperand(0), RHS.getOperand(0),
9423                            DAG.getConstant(Sel, DL, MVT::i32));
9424       }
9425     }
9426   }
9427 
9428   return SDValue();
9429 }
9430 
9431 SDValue SITargetLowering::performOrCombine(SDNode *N,
9432                                            DAGCombinerInfo &DCI) const {
9433   SelectionDAG &DAG = DCI.DAG;
9434   SDValue LHS = N->getOperand(0);
9435   SDValue RHS = N->getOperand(1);
9436 
9437   EVT VT = N->getValueType(0);
9438   if (VT == MVT::i1) {
9439     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9440     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9441         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9442       SDValue Src = LHS.getOperand(0);
9443       if (Src != RHS.getOperand(0))
9444         return SDValue();
9445 
9446       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9447       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9448       if (!CLHS || !CRHS)
9449         return SDValue();
9450 
9451       // Only 10 bits are used.
9452       static const uint32_t MaxMask = 0x3ff;
9453 
9454       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9455       SDLoc DL(N);
9456       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9457                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9458     }
9459 
9460     return SDValue();
9461   }
9462 
9463   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9464   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9465       LHS.getOpcode() == AMDGPUISD::PERM &&
9466       isa<ConstantSDNode>(LHS.getOperand(2))) {
9467     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9468     if (!Sel)
9469       return SDValue();
9470 
9471     Sel |= LHS.getConstantOperandVal(2);
9472     SDLoc DL(N);
9473     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9474                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9475   }
9476 
9477   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9478   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9479   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9480       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9481     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9482     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9483     if (LHSMask != ~0u && RHSMask != ~0u) {
9484       // Canonicalize the expression in an attempt to have fewer unique masks
9485       // and therefore fewer registers used to hold the masks.
9486       if (LHSMask > RHSMask) {
9487         std::swap(LHSMask, RHSMask);
9488         std::swap(LHS, RHS);
9489       }
9490 
9491       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9492       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9493       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9494       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9495 
9496       // Check of we need to combine values from two sources within a byte.
9497       if (!(LHSUsedLanes & RHSUsedLanes) &&
9498           // If we select high and lower word keep it for SDWA.
9499           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9500           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9501         // Kill zero bytes selected by other mask. Zero value is 0xc.
9502         LHSMask &= ~RHSUsedLanes;
9503         RHSMask &= ~LHSUsedLanes;
9504         // Add 4 to each active LHS lane
9505         LHSMask |= LHSUsedLanes & 0x04040404;
9506         // Combine masks
9507         uint32_t Sel = LHSMask | RHSMask;
9508         SDLoc DL(N);
9509 
9510         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9511                            LHS.getOperand(0), RHS.getOperand(0),
9512                            DAG.getConstant(Sel, DL, MVT::i32));
9513       }
9514     }
9515   }
9516 
9517   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9518     return SDValue();
9519 
9520   // TODO: This could be a generic combine with a predicate for extracting the
9521   // high half of an integer being free.
9522 
9523   // (or i64:x, (zero_extend i32:y)) ->
9524   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9525   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9526       RHS.getOpcode() != ISD::ZERO_EXTEND)
9527     std::swap(LHS, RHS);
9528 
9529   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9530     SDValue ExtSrc = RHS.getOperand(0);
9531     EVT SrcVT = ExtSrc.getValueType();
9532     if (SrcVT == MVT::i32) {
9533       SDLoc SL(N);
9534       SDValue LowLHS, HiBits;
9535       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9536       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9537 
9538       DCI.AddToWorklist(LowOr.getNode());
9539       DCI.AddToWorklist(HiBits.getNode());
9540 
9541       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9542                                 LowOr, HiBits);
9543       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9544     }
9545   }
9546 
9547   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9548   if (CRHS) {
9549     if (SDValue Split
9550           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR,
9551                                      N->getOperand(0), CRHS))
9552       return Split;
9553   }
9554 
9555   return SDValue();
9556 }
9557 
9558 SDValue SITargetLowering::performXorCombine(SDNode *N,
9559                                             DAGCombinerInfo &DCI) const {
9560   EVT VT = N->getValueType(0);
9561   if (VT != MVT::i64)
9562     return SDValue();
9563 
9564   SDValue LHS = N->getOperand(0);
9565   SDValue RHS = N->getOperand(1);
9566 
9567   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9568   if (CRHS) {
9569     if (SDValue Split
9570           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9571       return Split;
9572   }
9573 
9574   return SDValue();
9575 }
9576 
9577 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9578                                                    DAGCombinerInfo &DCI) const {
9579   if (!Subtarget->has16BitInsts() ||
9580       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9581     return SDValue();
9582 
9583   EVT VT = N->getValueType(0);
9584   if (VT != MVT::i32)
9585     return SDValue();
9586 
9587   SDValue Src = N->getOperand(0);
9588   if (Src.getValueType() != MVT::i16)
9589     return SDValue();
9590 
9591   return SDValue();
9592 }
9593 
9594 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9595                                                         DAGCombinerInfo &DCI)
9596                                                         const {
9597   SDValue Src = N->getOperand(0);
9598   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9599 
9600   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9601       VTSign->getVT() == MVT::i8) ||
9602       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9603       VTSign->getVT() == MVT::i16)) &&
9604       Src.hasOneUse()) {
9605     auto *M = cast<MemSDNode>(Src);
9606     SDValue Ops[] = {
9607       Src.getOperand(0), // Chain
9608       Src.getOperand(1), // rsrc
9609       Src.getOperand(2), // vindex
9610       Src.getOperand(3), // voffset
9611       Src.getOperand(4), // soffset
9612       Src.getOperand(5), // offset
9613       Src.getOperand(6),
9614       Src.getOperand(7)
9615     };
9616     // replace with BUFFER_LOAD_BYTE/SHORT
9617     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9618                                          Src.getOperand(0).getValueType());
9619     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9620                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9621     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9622                                                           ResList,
9623                                                           Ops, M->getMemoryVT(),
9624                                                           M->getMemOperand());
9625     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9626                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9627   }
9628   return SDValue();
9629 }
9630 
9631 SDValue SITargetLowering::performClassCombine(SDNode *N,
9632                                               DAGCombinerInfo &DCI) const {
9633   SelectionDAG &DAG = DCI.DAG;
9634   SDValue Mask = N->getOperand(1);
9635 
9636   // fp_class x, 0 -> false
9637   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9638     if (CMask->isZero())
9639       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9640   }
9641 
9642   if (N->getOperand(0).isUndef())
9643     return DAG.getUNDEF(MVT::i1);
9644 
9645   return SDValue();
9646 }
9647 
9648 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9649                                             DAGCombinerInfo &DCI) const {
9650   EVT VT = N->getValueType(0);
9651   SDValue N0 = N->getOperand(0);
9652 
9653   if (N0.isUndef())
9654     return N0;
9655 
9656   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9657                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9658     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9659                            N->getFlags());
9660   }
9661 
9662   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9663     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9664                            N0.getOperand(0), N->getFlags());
9665   }
9666 
9667   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9668 }
9669 
9670 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9671                                        unsigned MaxDepth) const {
9672   unsigned Opcode = Op.getOpcode();
9673   if (Opcode == ISD::FCANONICALIZE)
9674     return true;
9675 
9676   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9677     auto F = CFP->getValueAPF();
9678     if (F.isNaN() && F.isSignaling())
9679       return false;
9680     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9681   }
9682 
9683   // If source is a result of another standard FP operation it is already in
9684   // canonical form.
9685   if (MaxDepth == 0)
9686     return false;
9687 
9688   switch (Opcode) {
9689   // These will flush denorms if required.
9690   case ISD::FADD:
9691   case ISD::FSUB:
9692   case ISD::FMUL:
9693   case ISD::FCEIL:
9694   case ISD::FFLOOR:
9695   case ISD::FMA:
9696   case ISD::FMAD:
9697   case ISD::FSQRT:
9698   case ISD::FDIV:
9699   case ISD::FREM:
9700   case ISD::FP_ROUND:
9701   case ISD::FP_EXTEND:
9702   case AMDGPUISD::FMUL_LEGACY:
9703   case AMDGPUISD::FMAD_FTZ:
9704   case AMDGPUISD::RCP:
9705   case AMDGPUISD::RSQ:
9706   case AMDGPUISD::RSQ_CLAMP:
9707   case AMDGPUISD::RCP_LEGACY:
9708   case AMDGPUISD::RCP_IFLAG:
9709   case AMDGPUISD::DIV_SCALE:
9710   case AMDGPUISD::DIV_FMAS:
9711   case AMDGPUISD::DIV_FIXUP:
9712   case AMDGPUISD::FRACT:
9713   case AMDGPUISD::LDEXP:
9714   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9715   case AMDGPUISD::CVT_F32_UBYTE0:
9716   case AMDGPUISD::CVT_F32_UBYTE1:
9717   case AMDGPUISD::CVT_F32_UBYTE2:
9718   case AMDGPUISD::CVT_F32_UBYTE3:
9719     return true;
9720 
9721   // It can/will be lowered or combined as a bit operation.
9722   // Need to check their input recursively to handle.
9723   case ISD::FNEG:
9724   case ISD::FABS:
9725   case ISD::FCOPYSIGN:
9726     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9727 
9728   case ISD::FSIN:
9729   case ISD::FCOS:
9730   case ISD::FSINCOS:
9731     return Op.getValueType().getScalarType() != MVT::f16;
9732 
9733   case ISD::FMINNUM:
9734   case ISD::FMAXNUM:
9735   case ISD::FMINNUM_IEEE:
9736   case ISD::FMAXNUM_IEEE:
9737   case AMDGPUISD::CLAMP:
9738   case AMDGPUISD::FMED3:
9739   case AMDGPUISD::FMAX3:
9740   case AMDGPUISD::FMIN3: {
9741     // FIXME: Shouldn't treat the generic operations different based these.
9742     // However, we aren't really required to flush the result from
9743     // minnum/maxnum..
9744 
9745     // snans will be quieted, so we only need to worry about denormals.
9746     if (Subtarget->supportsMinMaxDenormModes() ||
9747         denormalsEnabledForType(DAG, Op.getValueType()))
9748       return true;
9749 
9750     // Flushing may be required.
9751     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9752     // targets need to check their input recursively.
9753 
9754     // FIXME: Does this apply with clamp? It's implemented with max.
9755     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9756       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9757         return false;
9758     }
9759 
9760     return true;
9761   }
9762   case ISD::SELECT: {
9763     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9764            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9765   }
9766   case ISD::BUILD_VECTOR: {
9767     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9768       SDValue SrcOp = Op.getOperand(i);
9769       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9770         return false;
9771     }
9772 
9773     return true;
9774   }
9775   case ISD::EXTRACT_VECTOR_ELT:
9776   case ISD::EXTRACT_SUBVECTOR: {
9777     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9778   }
9779   case ISD::INSERT_VECTOR_ELT: {
9780     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9781            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9782   }
9783   case ISD::UNDEF:
9784     // Could be anything.
9785     return false;
9786 
9787   case ISD::BITCAST:
9788     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9789   case ISD::TRUNCATE: {
9790     // Hack round the mess we make when legalizing extract_vector_elt
9791     if (Op.getValueType() == MVT::i16) {
9792       SDValue TruncSrc = Op.getOperand(0);
9793       if (TruncSrc.getValueType() == MVT::i32 &&
9794           TruncSrc.getOpcode() == ISD::BITCAST &&
9795           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9796         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9797       }
9798     }
9799     return false;
9800   }
9801   case ISD::INTRINSIC_WO_CHAIN: {
9802     unsigned IntrinsicID
9803       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9804     // TODO: Handle more intrinsics
9805     switch (IntrinsicID) {
9806     case Intrinsic::amdgcn_cvt_pkrtz:
9807     case Intrinsic::amdgcn_cubeid:
9808     case Intrinsic::amdgcn_frexp_mant:
9809     case Intrinsic::amdgcn_fdot2:
9810     case Intrinsic::amdgcn_rcp:
9811     case Intrinsic::amdgcn_rsq:
9812     case Intrinsic::amdgcn_rsq_clamp:
9813     case Intrinsic::amdgcn_rcp_legacy:
9814     case Intrinsic::amdgcn_rsq_legacy:
9815     case Intrinsic::amdgcn_trig_preop:
9816       return true;
9817     default:
9818       break;
9819     }
9820 
9821     LLVM_FALLTHROUGH;
9822   }
9823   default:
9824     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9825            DAG.isKnownNeverSNaN(Op);
9826   }
9827 
9828   llvm_unreachable("invalid operation");
9829 }
9830 
9831 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
9832                                        unsigned MaxDepth) const {
9833   MachineRegisterInfo &MRI = MF.getRegInfo();
9834   MachineInstr *MI = MRI.getVRegDef(Reg);
9835   unsigned Opcode = MI->getOpcode();
9836 
9837   if (Opcode == AMDGPU::G_FCANONICALIZE)
9838     return true;
9839 
9840   if (Opcode == AMDGPU::G_FCONSTANT) {
9841     auto F = MI->getOperand(1).getFPImm()->getValueAPF();
9842     if (F.isNaN() && F.isSignaling())
9843       return false;
9844     return !F.isDenormal() || denormalsEnabledForType(MRI.getType(Reg), MF);
9845   }
9846 
9847   if (MaxDepth == 0)
9848     return false;
9849 
9850   switch (Opcode) {
9851   case AMDGPU::G_FMINNUM_IEEE:
9852   case AMDGPU::G_FMAXNUM_IEEE: {
9853     if (Subtarget->supportsMinMaxDenormModes() ||
9854         denormalsEnabledForType(MRI.getType(Reg), MF))
9855       return true;
9856     for (const MachineOperand &MO : llvm::drop_begin(MI->operands()))
9857       if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1))
9858         return false;
9859     return true;
9860   }
9861   default:
9862     return denormalsEnabledForType(MRI.getType(Reg), MF) &&
9863            isKnownNeverSNaN(Reg, MRI);
9864   }
9865 
9866   llvm_unreachable("invalid operation");
9867 }
9868 
9869 // Constant fold canonicalize.
9870 SDValue SITargetLowering::getCanonicalConstantFP(
9871   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9872   // Flush denormals to 0 if not enabled.
9873   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9874     return DAG.getConstantFP(0.0, SL, VT);
9875 
9876   if (C.isNaN()) {
9877     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9878     if (C.isSignaling()) {
9879       // Quiet a signaling NaN.
9880       // FIXME: Is this supposed to preserve payload bits?
9881       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9882     }
9883 
9884     // Make sure it is the canonical NaN bitpattern.
9885     //
9886     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9887     // immediate?
9888     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9889       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9890   }
9891 
9892   // Already canonical.
9893   return DAG.getConstantFP(C, SL, VT);
9894 }
9895 
9896 static bool vectorEltWillFoldAway(SDValue Op) {
9897   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9898 }
9899 
9900 SDValue SITargetLowering::performFCanonicalizeCombine(
9901   SDNode *N,
9902   DAGCombinerInfo &DCI) const {
9903   SelectionDAG &DAG = DCI.DAG;
9904   SDValue N0 = N->getOperand(0);
9905   EVT VT = N->getValueType(0);
9906 
9907   // fcanonicalize undef -> qnan
9908   if (N0.isUndef()) {
9909     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9910     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9911   }
9912 
9913   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9914     EVT VT = N->getValueType(0);
9915     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9916   }
9917 
9918   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9919   //                                                   (fcanonicalize k)
9920   //
9921   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9922 
9923   // TODO: This could be better with wider vectors that will be split to v2f16,
9924   // and to consider uses since there aren't that many packed operations.
9925   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9926       isTypeLegal(MVT::v2f16)) {
9927     SDLoc SL(N);
9928     SDValue NewElts[2];
9929     SDValue Lo = N0.getOperand(0);
9930     SDValue Hi = N0.getOperand(1);
9931     EVT EltVT = Lo.getValueType();
9932 
9933     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9934       for (unsigned I = 0; I != 2; ++I) {
9935         SDValue Op = N0.getOperand(I);
9936         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9937           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9938                                               CFP->getValueAPF());
9939         } else if (Op.isUndef()) {
9940           // Handled below based on what the other operand is.
9941           NewElts[I] = Op;
9942         } else {
9943           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9944         }
9945       }
9946 
9947       // If one half is undef, and one is constant, perfer a splat vector rather
9948       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9949       // cheaper to use and may be free with a packed operation.
9950       if (NewElts[0].isUndef()) {
9951         if (isa<ConstantFPSDNode>(NewElts[1]))
9952           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9953             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9954       }
9955 
9956       if (NewElts[1].isUndef()) {
9957         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9958           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9959       }
9960 
9961       return DAG.getBuildVector(VT, SL, NewElts);
9962     }
9963   }
9964 
9965   unsigned SrcOpc = N0.getOpcode();
9966 
9967   // If it's free to do so, push canonicalizes further up the source, which may
9968   // find a canonical source.
9969   //
9970   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9971   // sNaNs.
9972   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9973     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9974     if (CRHS && N0.hasOneUse()) {
9975       SDLoc SL(N);
9976       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9977                                    N0.getOperand(0));
9978       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9979       DCI.AddToWorklist(Canon0.getNode());
9980 
9981       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9982     }
9983   }
9984 
9985   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9986 }
9987 
9988 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9989   switch (Opc) {
9990   case ISD::FMAXNUM:
9991   case ISD::FMAXNUM_IEEE:
9992     return AMDGPUISD::FMAX3;
9993   case ISD::SMAX:
9994     return AMDGPUISD::SMAX3;
9995   case ISD::UMAX:
9996     return AMDGPUISD::UMAX3;
9997   case ISD::FMINNUM:
9998   case ISD::FMINNUM_IEEE:
9999     return AMDGPUISD::FMIN3;
10000   case ISD::SMIN:
10001     return AMDGPUISD::SMIN3;
10002   case ISD::UMIN:
10003     return AMDGPUISD::UMIN3;
10004   default:
10005     llvm_unreachable("Not a min/max opcode");
10006   }
10007 }
10008 
10009 SDValue SITargetLowering::performIntMed3ImmCombine(
10010   SelectionDAG &DAG, const SDLoc &SL,
10011   SDValue Op0, SDValue Op1, bool Signed) const {
10012   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
10013   if (!K1)
10014     return SDValue();
10015 
10016   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
10017   if (!K0)
10018     return SDValue();
10019 
10020   if (Signed) {
10021     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
10022       return SDValue();
10023   } else {
10024     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
10025       return SDValue();
10026   }
10027 
10028   EVT VT = K0->getValueType(0);
10029   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
10030   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
10031     return DAG.getNode(Med3Opc, SL, VT,
10032                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
10033   }
10034 
10035   // If there isn't a 16-bit med3 operation, convert to 32-bit.
10036   if (VT == MVT::i16) {
10037     MVT NVT = MVT::i32;
10038     unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
10039 
10040     SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
10041     SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
10042     SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
10043 
10044     SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
10045     return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
10046   }
10047 
10048   return SDValue();
10049 }
10050 
10051 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
10052   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
10053     return C;
10054 
10055   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
10056     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
10057       return C;
10058   }
10059 
10060   return nullptr;
10061 }
10062 
10063 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
10064                                                   const SDLoc &SL,
10065                                                   SDValue Op0,
10066                                                   SDValue Op1) const {
10067   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
10068   if (!K1)
10069     return SDValue();
10070 
10071   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
10072   if (!K0)
10073     return SDValue();
10074 
10075   // Ordered >= (although NaN inputs should have folded away by now).
10076   if (K0->getValueAPF() > K1->getValueAPF())
10077     return SDValue();
10078 
10079   const MachineFunction &MF = DAG.getMachineFunction();
10080   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10081 
10082   // TODO: Check IEEE bit enabled?
10083   EVT VT = Op0.getValueType();
10084   if (Info->getMode().DX10Clamp) {
10085     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
10086     // hardware fmed3 behavior converting to a min.
10087     // FIXME: Should this be allowing -0.0?
10088     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
10089       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
10090   }
10091 
10092   // med3 for f16 is only available on gfx9+, and not available for v2f16.
10093   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
10094     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
10095     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
10096     // then give the other result, which is different from med3 with a NaN
10097     // input.
10098     SDValue Var = Op0.getOperand(0);
10099     if (!DAG.isKnownNeverSNaN(Var))
10100       return SDValue();
10101 
10102     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10103 
10104     if ((!K0->hasOneUse() ||
10105          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
10106         (!K1->hasOneUse() ||
10107          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
10108       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
10109                          Var, SDValue(K0, 0), SDValue(K1, 0));
10110     }
10111   }
10112 
10113   return SDValue();
10114 }
10115 
10116 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
10117                                                DAGCombinerInfo &DCI) const {
10118   SelectionDAG &DAG = DCI.DAG;
10119 
10120   EVT VT = N->getValueType(0);
10121   unsigned Opc = N->getOpcode();
10122   SDValue Op0 = N->getOperand(0);
10123   SDValue Op1 = N->getOperand(1);
10124 
10125   // Only do this if the inner op has one use since this will just increases
10126   // register pressure for no benefit.
10127 
10128   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
10129       !VT.isVector() &&
10130       (VT == MVT::i32 || VT == MVT::f32 ||
10131        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
10132     // max(max(a, b), c) -> max3(a, b, c)
10133     // min(min(a, b), c) -> min3(a, b, c)
10134     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
10135       SDLoc DL(N);
10136       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10137                          DL,
10138                          N->getValueType(0),
10139                          Op0.getOperand(0),
10140                          Op0.getOperand(1),
10141                          Op1);
10142     }
10143 
10144     // Try commuted.
10145     // max(a, max(b, c)) -> max3(a, b, c)
10146     // min(a, min(b, c)) -> min3(a, b, c)
10147     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
10148       SDLoc DL(N);
10149       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10150                          DL,
10151                          N->getValueType(0),
10152                          Op0,
10153                          Op1.getOperand(0),
10154                          Op1.getOperand(1));
10155     }
10156   }
10157 
10158   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
10159   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
10160     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
10161       return Med3;
10162   }
10163 
10164   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
10165     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
10166       return Med3;
10167   }
10168 
10169   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
10170   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
10171        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
10172        (Opc == AMDGPUISD::FMIN_LEGACY &&
10173         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
10174       (VT == MVT::f32 || VT == MVT::f64 ||
10175        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
10176        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
10177       Op0.hasOneUse()) {
10178     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
10179       return Res;
10180   }
10181 
10182   return SDValue();
10183 }
10184 
10185 static bool isClampZeroToOne(SDValue A, SDValue B) {
10186   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
10187     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
10188       // FIXME: Should this be allowing -0.0?
10189       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
10190              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
10191     }
10192   }
10193 
10194   return false;
10195 }
10196 
10197 // FIXME: Should only worry about snans for version with chain.
10198 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
10199                                               DAGCombinerInfo &DCI) const {
10200   EVT VT = N->getValueType(0);
10201   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
10202   // NaNs. With a NaN input, the order of the operands may change the result.
10203 
10204   SelectionDAG &DAG = DCI.DAG;
10205   SDLoc SL(N);
10206 
10207   SDValue Src0 = N->getOperand(0);
10208   SDValue Src1 = N->getOperand(1);
10209   SDValue Src2 = N->getOperand(2);
10210 
10211   if (isClampZeroToOne(Src0, Src1)) {
10212     // const_a, const_b, x -> clamp is safe in all cases including signaling
10213     // nans.
10214     // FIXME: Should this be allowing -0.0?
10215     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
10216   }
10217 
10218   const MachineFunction &MF = DAG.getMachineFunction();
10219   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10220 
10221   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
10222   // handling no dx10-clamp?
10223   if (Info->getMode().DX10Clamp) {
10224     // If NaNs is clamped to 0, we are free to reorder the inputs.
10225 
10226     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10227       std::swap(Src0, Src1);
10228 
10229     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10230       std::swap(Src1, Src2);
10231 
10232     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10233       std::swap(Src0, Src1);
10234 
10235     if (isClampZeroToOne(Src1, Src2))
10236       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10237   }
10238 
10239   return SDValue();
10240 }
10241 
10242 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10243                                                  DAGCombinerInfo &DCI) const {
10244   SDValue Src0 = N->getOperand(0);
10245   SDValue Src1 = N->getOperand(1);
10246   if (Src0.isUndef() && Src1.isUndef())
10247     return DCI.DAG.getUNDEF(N->getValueType(0));
10248   return SDValue();
10249 }
10250 
10251 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10252 // expanded into a set of cmp/select instructions.
10253 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10254                                                 unsigned NumElem,
10255                                                 bool IsDivergentIdx) {
10256   if (UseDivergentRegisterIndexing)
10257     return false;
10258 
10259   unsigned VecSize = EltSize * NumElem;
10260 
10261   // Sub-dword vectors of size 2 dword or less have better implementation.
10262   if (VecSize <= 64 && EltSize < 32)
10263     return false;
10264 
10265   // Always expand the rest of sub-dword instructions, otherwise it will be
10266   // lowered via memory.
10267   if (EltSize < 32)
10268     return true;
10269 
10270   // Always do this if var-idx is divergent, otherwise it will become a loop.
10271   if (IsDivergentIdx)
10272     return true;
10273 
10274   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10275   unsigned NumInsts = NumElem /* Number of compares */ +
10276                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10277   return NumInsts <= 16;
10278 }
10279 
10280 static bool shouldExpandVectorDynExt(SDNode *N) {
10281   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10282   if (isa<ConstantSDNode>(Idx))
10283     return false;
10284 
10285   SDValue Vec = N->getOperand(0);
10286   EVT VecVT = Vec.getValueType();
10287   EVT EltVT = VecVT.getVectorElementType();
10288   unsigned EltSize = EltVT.getSizeInBits();
10289   unsigned NumElem = VecVT.getVectorNumElements();
10290 
10291   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
10292                                                     Idx->isDivergent());
10293 }
10294 
10295 SDValue SITargetLowering::performExtractVectorEltCombine(
10296   SDNode *N, DAGCombinerInfo &DCI) const {
10297   SDValue Vec = N->getOperand(0);
10298   SelectionDAG &DAG = DCI.DAG;
10299 
10300   EVT VecVT = Vec.getValueType();
10301   EVT EltVT = VecVT.getVectorElementType();
10302 
10303   if ((Vec.getOpcode() == ISD::FNEG ||
10304        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10305     SDLoc SL(N);
10306     EVT EltVT = N->getValueType(0);
10307     SDValue Idx = N->getOperand(1);
10308     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10309                               Vec.getOperand(0), Idx);
10310     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10311   }
10312 
10313   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10314   //    =>
10315   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10316   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10317   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10318   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10319     SDLoc SL(N);
10320     EVT EltVT = N->getValueType(0);
10321     SDValue Idx = N->getOperand(1);
10322     unsigned Opc = Vec.getOpcode();
10323 
10324     switch(Opc) {
10325     default:
10326       break;
10327       // TODO: Support other binary operations.
10328     case ISD::FADD:
10329     case ISD::FSUB:
10330     case ISD::FMUL:
10331     case ISD::ADD:
10332     case ISD::UMIN:
10333     case ISD::UMAX:
10334     case ISD::SMIN:
10335     case ISD::SMAX:
10336     case ISD::FMAXNUM:
10337     case ISD::FMINNUM:
10338     case ISD::FMAXNUM_IEEE:
10339     case ISD::FMINNUM_IEEE: {
10340       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10341                                  Vec.getOperand(0), Idx);
10342       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10343                                  Vec.getOperand(1), Idx);
10344 
10345       DCI.AddToWorklist(Elt0.getNode());
10346       DCI.AddToWorklist(Elt1.getNode());
10347       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10348     }
10349     }
10350   }
10351 
10352   unsigned VecSize = VecVT.getSizeInBits();
10353   unsigned EltSize = EltVT.getSizeInBits();
10354 
10355   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10356   if (::shouldExpandVectorDynExt(N)) {
10357     SDLoc SL(N);
10358     SDValue Idx = N->getOperand(1);
10359     SDValue V;
10360     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10361       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10362       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10363       if (I == 0)
10364         V = Elt;
10365       else
10366         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10367     }
10368     return V;
10369   }
10370 
10371   if (!DCI.isBeforeLegalize())
10372     return SDValue();
10373 
10374   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10375   // elements. This exposes more load reduction opportunities by replacing
10376   // multiple small extract_vector_elements with a single 32-bit extract.
10377   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10378   if (isa<MemSDNode>(Vec) &&
10379       EltSize <= 16 &&
10380       EltVT.isByteSized() &&
10381       VecSize > 32 &&
10382       VecSize % 32 == 0 &&
10383       Idx) {
10384     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10385 
10386     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10387     unsigned EltIdx = BitIndex / 32;
10388     unsigned LeftoverBitIdx = BitIndex % 32;
10389     SDLoc SL(N);
10390 
10391     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10392     DCI.AddToWorklist(Cast.getNode());
10393 
10394     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10395                               DAG.getConstant(EltIdx, SL, MVT::i32));
10396     DCI.AddToWorklist(Elt.getNode());
10397     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10398                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10399     DCI.AddToWorklist(Srl.getNode());
10400 
10401     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10402     DCI.AddToWorklist(Trunc.getNode());
10403     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10404   }
10405 
10406   return SDValue();
10407 }
10408 
10409 SDValue
10410 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10411                                                 DAGCombinerInfo &DCI) const {
10412   SDValue Vec = N->getOperand(0);
10413   SDValue Idx = N->getOperand(2);
10414   EVT VecVT = Vec.getValueType();
10415   EVT EltVT = VecVT.getVectorElementType();
10416 
10417   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10418   // => BUILD_VECTOR n x select (e, const-idx)
10419   if (!::shouldExpandVectorDynExt(N))
10420     return SDValue();
10421 
10422   SelectionDAG &DAG = DCI.DAG;
10423   SDLoc SL(N);
10424   SDValue Ins = N->getOperand(1);
10425   EVT IdxVT = Idx.getValueType();
10426 
10427   SmallVector<SDValue, 16> Ops;
10428   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10429     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10430     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10431     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10432     Ops.push_back(V);
10433   }
10434 
10435   return DAG.getBuildVector(VecVT, SL, Ops);
10436 }
10437 
10438 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10439                                           const SDNode *N0,
10440                                           const SDNode *N1) const {
10441   EVT VT = N0->getValueType(0);
10442 
10443   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10444   // support denormals ever.
10445   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10446        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10447         getSubtarget()->hasMadF16())) &&
10448        isOperationLegal(ISD::FMAD, VT))
10449     return ISD::FMAD;
10450 
10451   const TargetOptions &Options = DAG.getTarget().Options;
10452   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10453        (N0->getFlags().hasAllowContract() &&
10454         N1->getFlags().hasAllowContract())) &&
10455       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10456     return ISD::FMA;
10457   }
10458 
10459   return 0;
10460 }
10461 
10462 // For a reassociatable opcode perform:
10463 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10464 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10465                                                SelectionDAG &DAG) const {
10466   EVT VT = N->getValueType(0);
10467   if (VT != MVT::i32 && VT != MVT::i64)
10468     return SDValue();
10469 
10470   unsigned Opc = N->getOpcode();
10471   SDValue Op0 = N->getOperand(0);
10472   SDValue Op1 = N->getOperand(1);
10473 
10474   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10475     return SDValue();
10476 
10477   if (Op0->isDivergent())
10478     std::swap(Op0, Op1);
10479 
10480   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10481     return SDValue();
10482 
10483   SDValue Op2 = Op1.getOperand(1);
10484   Op1 = Op1.getOperand(0);
10485   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10486     return SDValue();
10487 
10488   if (Op1->isDivergent())
10489     std::swap(Op1, Op2);
10490 
10491   // If either operand is constant this will conflict with
10492   // DAGCombiner::ReassociateOps().
10493   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
10494       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
10495     return SDValue();
10496 
10497   SDLoc SL(N);
10498   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10499   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10500 }
10501 
10502 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10503                            EVT VT,
10504                            SDValue N0, SDValue N1, SDValue N2,
10505                            bool Signed) {
10506   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10507   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10508   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10509   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10510 }
10511 
10512 SDValue SITargetLowering::performAddCombine(SDNode *N,
10513                                             DAGCombinerInfo &DCI) const {
10514   SelectionDAG &DAG = DCI.DAG;
10515   EVT VT = N->getValueType(0);
10516   SDLoc SL(N);
10517   SDValue LHS = N->getOperand(0);
10518   SDValue RHS = N->getOperand(1);
10519 
10520   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10521       && Subtarget->hasMad64_32() &&
10522       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10523       VT.getScalarSizeInBits() <= 64) {
10524     if (LHS.getOpcode() != ISD::MUL)
10525       std::swap(LHS, RHS);
10526 
10527     SDValue MulLHS = LHS.getOperand(0);
10528     SDValue MulRHS = LHS.getOperand(1);
10529     SDValue AddRHS = RHS;
10530 
10531     // TODO: Maybe restrict if SGPR inputs.
10532     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10533         numBitsUnsigned(MulRHS, DAG) <= 32) {
10534       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10535       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10536       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10537       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10538     }
10539 
10540     if (numBitsSigned(MulLHS, DAG) <= 32 && numBitsSigned(MulRHS, DAG) <= 32) {
10541       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10542       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10543       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10544       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10545     }
10546 
10547     return SDValue();
10548   }
10549 
10550   if (SDValue V = reassociateScalarOps(N, DAG)) {
10551     return V;
10552   }
10553 
10554   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10555     return SDValue();
10556 
10557   // add x, zext (setcc) => addcarry x, 0, setcc
10558   // add x, sext (setcc) => subcarry x, 0, setcc
10559   unsigned Opc = LHS.getOpcode();
10560   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10561       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10562     std::swap(RHS, LHS);
10563 
10564   Opc = RHS.getOpcode();
10565   switch (Opc) {
10566   default: break;
10567   case ISD::ZERO_EXTEND:
10568   case ISD::SIGN_EXTEND:
10569   case ISD::ANY_EXTEND: {
10570     auto Cond = RHS.getOperand(0);
10571     // If this won't be a real VOPC output, we would still need to insert an
10572     // extra instruction anyway.
10573     if (!isBoolSGPR(Cond))
10574       break;
10575     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10576     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10577     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10578     return DAG.getNode(Opc, SL, VTList, Args);
10579   }
10580   case ISD::ADDCARRY: {
10581     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10582     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10583     if (!C || C->getZExtValue() != 0) break;
10584     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10585     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10586   }
10587   }
10588   return SDValue();
10589 }
10590 
10591 SDValue SITargetLowering::performSubCombine(SDNode *N,
10592                                             DAGCombinerInfo &DCI) const {
10593   SelectionDAG &DAG = DCI.DAG;
10594   EVT VT = N->getValueType(0);
10595 
10596   if (VT != MVT::i32)
10597     return SDValue();
10598 
10599   SDLoc SL(N);
10600   SDValue LHS = N->getOperand(0);
10601   SDValue RHS = N->getOperand(1);
10602 
10603   // sub x, zext (setcc) => subcarry x, 0, setcc
10604   // sub x, sext (setcc) => addcarry x, 0, setcc
10605   unsigned Opc = RHS.getOpcode();
10606   switch (Opc) {
10607   default: break;
10608   case ISD::ZERO_EXTEND:
10609   case ISD::SIGN_EXTEND:
10610   case ISD::ANY_EXTEND: {
10611     auto Cond = RHS.getOperand(0);
10612     // If this won't be a real VOPC output, we would still need to insert an
10613     // extra instruction anyway.
10614     if (!isBoolSGPR(Cond))
10615       break;
10616     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10617     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10618     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10619     return DAG.getNode(Opc, SL, VTList, Args);
10620   }
10621   }
10622 
10623   if (LHS.getOpcode() == ISD::SUBCARRY) {
10624     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10625     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10626     if (!C || !C->isZero())
10627       return SDValue();
10628     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10629     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10630   }
10631   return SDValue();
10632 }
10633 
10634 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10635   DAGCombinerInfo &DCI) const {
10636 
10637   if (N->getValueType(0) != MVT::i32)
10638     return SDValue();
10639 
10640   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10641   if (!C || C->getZExtValue() != 0)
10642     return SDValue();
10643 
10644   SelectionDAG &DAG = DCI.DAG;
10645   SDValue LHS = N->getOperand(0);
10646 
10647   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10648   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10649   unsigned LHSOpc = LHS.getOpcode();
10650   unsigned Opc = N->getOpcode();
10651   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10652       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10653     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10654     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10655   }
10656   return SDValue();
10657 }
10658 
10659 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10660                                              DAGCombinerInfo &DCI) const {
10661   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10662     return SDValue();
10663 
10664   SelectionDAG &DAG = DCI.DAG;
10665   EVT VT = N->getValueType(0);
10666 
10667   SDLoc SL(N);
10668   SDValue LHS = N->getOperand(0);
10669   SDValue RHS = N->getOperand(1);
10670 
10671   // These should really be instruction patterns, but writing patterns with
10672   // source modiifiers is a pain.
10673 
10674   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10675   if (LHS.getOpcode() == ISD::FADD) {
10676     SDValue A = LHS.getOperand(0);
10677     if (A == LHS.getOperand(1)) {
10678       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10679       if (FusedOp != 0) {
10680         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10681         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10682       }
10683     }
10684   }
10685 
10686   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10687   if (RHS.getOpcode() == ISD::FADD) {
10688     SDValue A = RHS.getOperand(0);
10689     if (A == RHS.getOperand(1)) {
10690       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10691       if (FusedOp != 0) {
10692         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10693         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10694       }
10695     }
10696   }
10697 
10698   return SDValue();
10699 }
10700 
10701 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10702                                              DAGCombinerInfo &DCI) const {
10703   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10704     return SDValue();
10705 
10706   SelectionDAG &DAG = DCI.DAG;
10707   SDLoc SL(N);
10708   EVT VT = N->getValueType(0);
10709   assert(!VT.isVector());
10710 
10711   // Try to get the fneg to fold into the source modifier. This undoes generic
10712   // DAG combines and folds them into the mad.
10713   //
10714   // Only do this if we are not trying to support denormals. v_mad_f32 does
10715   // not support denormals ever.
10716   SDValue LHS = N->getOperand(0);
10717   SDValue RHS = N->getOperand(1);
10718   if (LHS.getOpcode() == ISD::FADD) {
10719     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10720     SDValue A = LHS.getOperand(0);
10721     if (A == LHS.getOperand(1)) {
10722       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10723       if (FusedOp != 0){
10724         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10725         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10726 
10727         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10728       }
10729     }
10730   }
10731 
10732   if (RHS.getOpcode() == ISD::FADD) {
10733     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10734 
10735     SDValue A = RHS.getOperand(0);
10736     if (A == RHS.getOperand(1)) {
10737       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10738       if (FusedOp != 0){
10739         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10740         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10741       }
10742     }
10743   }
10744 
10745   return SDValue();
10746 }
10747 
10748 SDValue SITargetLowering::performFMACombine(SDNode *N,
10749                                             DAGCombinerInfo &DCI) const {
10750   SelectionDAG &DAG = DCI.DAG;
10751   EVT VT = N->getValueType(0);
10752   SDLoc SL(N);
10753 
10754   if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
10755     return SDValue();
10756 
10757   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10758   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10759   SDValue Op1 = N->getOperand(0);
10760   SDValue Op2 = N->getOperand(1);
10761   SDValue FMA = N->getOperand(2);
10762 
10763   if (FMA.getOpcode() != ISD::FMA ||
10764       Op1.getOpcode() != ISD::FP_EXTEND ||
10765       Op2.getOpcode() != ISD::FP_EXTEND)
10766     return SDValue();
10767 
10768   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10769   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10770   // is sufficient to allow generaing fdot2.
10771   const TargetOptions &Options = DAG.getTarget().Options;
10772   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10773       (N->getFlags().hasAllowContract() &&
10774        FMA->getFlags().hasAllowContract())) {
10775     Op1 = Op1.getOperand(0);
10776     Op2 = Op2.getOperand(0);
10777     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10778         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10779       return SDValue();
10780 
10781     SDValue Vec1 = Op1.getOperand(0);
10782     SDValue Idx1 = Op1.getOperand(1);
10783     SDValue Vec2 = Op2.getOperand(0);
10784 
10785     SDValue FMAOp1 = FMA.getOperand(0);
10786     SDValue FMAOp2 = FMA.getOperand(1);
10787     SDValue FMAAcc = FMA.getOperand(2);
10788 
10789     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10790         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10791       return SDValue();
10792 
10793     FMAOp1 = FMAOp1.getOperand(0);
10794     FMAOp2 = FMAOp2.getOperand(0);
10795     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10796         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10797       return SDValue();
10798 
10799     SDValue Vec3 = FMAOp1.getOperand(0);
10800     SDValue Vec4 = FMAOp2.getOperand(0);
10801     SDValue Idx2 = FMAOp1.getOperand(1);
10802 
10803     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10804         // Idx1 and Idx2 cannot be the same.
10805         Idx1 == Idx2)
10806       return SDValue();
10807 
10808     if (Vec1 == Vec2 || Vec3 == Vec4)
10809       return SDValue();
10810 
10811     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10812       return SDValue();
10813 
10814     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10815         (Vec1 == Vec4 && Vec2 == Vec3)) {
10816       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10817                          DAG.getTargetConstant(0, SL, MVT::i1));
10818     }
10819   }
10820   return SDValue();
10821 }
10822 
10823 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10824                                               DAGCombinerInfo &DCI) const {
10825   SelectionDAG &DAG = DCI.DAG;
10826   SDLoc SL(N);
10827 
10828   SDValue LHS = N->getOperand(0);
10829   SDValue RHS = N->getOperand(1);
10830   EVT VT = LHS.getValueType();
10831   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10832 
10833   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10834   if (!CRHS) {
10835     CRHS = dyn_cast<ConstantSDNode>(LHS);
10836     if (CRHS) {
10837       std::swap(LHS, RHS);
10838       CC = getSetCCSwappedOperands(CC);
10839     }
10840   }
10841 
10842   if (CRHS) {
10843     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10844         isBoolSGPR(LHS.getOperand(0))) {
10845       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10846       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10847       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10848       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10849       if ((CRHS->isAllOnes() &&
10850            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10851           (CRHS->isZero() &&
10852            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10853         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10854                            DAG.getConstant(-1, SL, MVT::i1));
10855       if ((CRHS->isAllOnes() &&
10856            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10857           (CRHS->isZero() &&
10858            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10859         return LHS.getOperand(0);
10860     }
10861 
10862     const APInt &CRHSVal = CRHS->getAPIntValue();
10863     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10864         LHS.getOpcode() == ISD::SELECT &&
10865         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10866         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10867         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10868         isBoolSGPR(LHS.getOperand(0))) {
10869       // Given CT != FT:
10870       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10871       // setcc (select cc, CT, CF), CF, ne => cc
10872       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10873       // setcc (select cc, CT, CF), CT, eq => cc
10874       const APInt &CT = LHS.getConstantOperandAPInt(1);
10875       const APInt &CF = LHS.getConstantOperandAPInt(2);
10876 
10877       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10878           (CT == CRHSVal && CC == ISD::SETNE))
10879         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10880                            DAG.getConstant(-1, SL, MVT::i1));
10881       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10882           (CT == CRHSVal && CC == ISD::SETEQ))
10883         return LHS.getOperand(0);
10884     }
10885   }
10886 
10887   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10888                                            VT != MVT::f16))
10889     return SDValue();
10890 
10891   // Match isinf/isfinite pattern
10892   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10893   // (fcmp one (fabs x), inf) -> (fp_class x,
10894   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10895   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10896     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10897     if (!CRHS)
10898       return SDValue();
10899 
10900     const APFloat &APF = CRHS->getValueAPF();
10901     if (APF.isInfinity() && !APF.isNegative()) {
10902       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10903                                  SIInstrFlags::N_INFINITY;
10904       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10905                                     SIInstrFlags::P_ZERO |
10906                                     SIInstrFlags::N_NORMAL |
10907                                     SIInstrFlags::P_NORMAL |
10908                                     SIInstrFlags::N_SUBNORMAL |
10909                                     SIInstrFlags::P_SUBNORMAL;
10910       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10911       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10912                          DAG.getConstant(Mask, SL, MVT::i32));
10913     }
10914   }
10915 
10916   return SDValue();
10917 }
10918 
10919 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10920                                                      DAGCombinerInfo &DCI) const {
10921   SelectionDAG &DAG = DCI.DAG;
10922   SDLoc SL(N);
10923   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10924 
10925   SDValue Src = N->getOperand(0);
10926   SDValue Shift = N->getOperand(0);
10927 
10928   // TODO: Extend type shouldn't matter (assuming legal types).
10929   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10930     Shift = Shift.getOperand(0);
10931 
10932   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10933     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10934     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10935     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10936     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10937     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10938     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10939       SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0),
10940                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10941 
10942       unsigned ShiftOffset = 8 * Offset;
10943       if (Shift.getOpcode() == ISD::SHL)
10944         ShiftOffset -= C->getZExtValue();
10945       else
10946         ShiftOffset += C->getZExtValue();
10947 
10948       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10949         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10950                            MVT::f32, Shifted);
10951       }
10952     }
10953   }
10954 
10955   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10956   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10957   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10958     // We simplified Src. If this node is not dead, visit it again so it is
10959     // folded properly.
10960     if (N->getOpcode() != ISD::DELETED_NODE)
10961       DCI.AddToWorklist(N);
10962     return SDValue(N, 0);
10963   }
10964 
10965   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10966   if (SDValue DemandedSrc =
10967           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10968     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10969 
10970   return SDValue();
10971 }
10972 
10973 SDValue SITargetLowering::performClampCombine(SDNode *N,
10974                                               DAGCombinerInfo &DCI) const {
10975   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10976   if (!CSrc)
10977     return SDValue();
10978 
10979   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10980   const APFloat &F = CSrc->getValueAPF();
10981   APFloat Zero = APFloat::getZero(F.getSemantics());
10982   if (F < Zero ||
10983       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10984     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10985   }
10986 
10987   APFloat One(F.getSemantics(), "1.0");
10988   if (F > One)
10989     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10990 
10991   return SDValue(CSrc, 0);
10992 }
10993 
10994 
10995 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10996                                             DAGCombinerInfo &DCI) const {
10997   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10998     return SDValue();
10999   switch (N->getOpcode()) {
11000   case ISD::ADD:
11001     return performAddCombine(N, DCI);
11002   case ISD::SUB:
11003     return performSubCombine(N, DCI);
11004   case ISD::ADDCARRY:
11005   case ISD::SUBCARRY:
11006     return performAddCarrySubCarryCombine(N, DCI);
11007   case ISD::FADD:
11008     return performFAddCombine(N, DCI);
11009   case ISD::FSUB:
11010     return performFSubCombine(N, DCI);
11011   case ISD::SETCC:
11012     return performSetCCCombine(N, DCI);
11013   case ISD::FMAXNUM:
11014   case ISD::FMINNUM:
11015   case ISD::FMAXNUM_IEEE:
11016   case ISD::FMINNUM_IEEE:
11017   case ISD::SMAX:
11018   case ISD::SMIN:
11019   case ISD::UMAX:
11020   case ISD::UMIN:
11021   case AMDGPUISD::FMIN_LEGACY:
11022   case AMDGPUISD::FMAX_LEGACY:
11023     return performMinMaxCombine(N, DCI);
11024   case ISD::FMA:
11025     return performFMACombine(N, DCI);
11026   case ISD::AND:
11027     return performAndCombine(N, DCI);
11028   case ISD::OR:
11029     return performOrCombine(N, DCI);
11030   case ISD::XOR:
11031     return performXorCombine(N, DCI);
11032   case ISD::ZERO_EXTEND:
11033     return performZeroExtendCombine(N, DCI);
11034   case ISD::SIGN_EXTEND_INREG:
11035     return performSignExtendInRegCombine(N , DCI);
11036   case AMDGPUISD::FP_CLASS:
11037     return performClassCombine(N, DCI);
11038   case ISD::FCANONICALIZE:
11039     return performFCanonicalizeCombine(N, DCI);
11040   case AMDGPUISD::RCP:
11041     return performRcpCombine(N, DCI);
11042   case AMDGPUISD::FRACT:
11043   case AMDGPUISD::RSQ:
11044   case AMDGPUISD::RCP_LEGACY:
11045   case AMDGPUISD::RCP_IFLAG:
11046   case AMDGPUISD::RSQ_CLAMP:
11047   case AMDGPUISD::LDEXP: {
11048     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
11049     SDValue Src = N->getOperand(0);
11050     if (Src.isUndef())
11051       return Src;
11052     break;
11053   }
11054   case ISD::SINT_TO_FP:
11055   case ISD::UINT_TO_FP:
11056     return performUCharToFloatCombine(N, DCI);
11057   case AMDGPUISD::CVT_F32_UBYTE0:
11058   case AMDGPUISD::CVT_F32_UBYTE1:
11059   case AMDGPUISD::CVT_F32_UBYTE2:
11060   case AMDGPUISD::CVT_F32_UBYTE3:
11061     return performCvtF32UByteNCombine(N, DCI);
11062   case AMDGPUISD::FMED3:
11063     return performFMed3Combine(N, DCI);
11064   case AMDGPUISD::CVT_PKRTZ_F16_F32:
11065     return performCvtPkRTZCombine(N, DCI);
11066   case AMDGPUISD::CLAMP:
11067     return performClampCombine(N, DCI);
11068   case ISD::SCALAR_TO_VECTOR: {
11069     SelectionDAG &DAG = DCI.DAG;
11070     EVT VT = N->getValueType(0);
11071 
11072     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
11073     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
11074       SDLoc SL(N);
11075       SDValue Src = N->getOperand(0);
11076       EVT EltVT = Src.getValueType();
11077       if (EltVT == MVT::f16)
11078         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
11079 
11080       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
11081       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
11082     }
11083 
11084     break;
11085   }
11086   case ISD::EXTRACT_VECTOR_ELT:
11087     return performExtractVectorEltCombine(N, DCI);
11088   case ISD::INSERT_VECTOR_ELT:
11089     return performInsertVectorEltCombine(N, DCI);
11090   case ISD::LOAD: {
11091     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
11092       return Widended;
11093     LLVM_FALLTHROUGH;
11094   }
11095   default: {
11096     if (!DCI.isBeforeLegalize()) {
11097       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
11098         return performMemSDNodeCombine(MemNode, DCI);
11099     }
11100 
11101     break;
11102   }
11103   }
11104 
11105   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
11106 }
11107 
11108 /// Helper function for adjustWritemask
11109 static unsigned SubIdx2Lane(unsigned Idx) {
11110   switch (Idx) {
11111   default: return ~0u;
11112   case AMDGPU::sub0: return 0;
11113   case AMDGPU::sub1: return 1;
11114   case AMDGPU::sub2: return 2;
11115   case AMDGPU::sub3: return 3;
11116   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
11117   }
11118 }
11119 
11120 /// Adjust the writemask of MIMG instructions
11121 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
11122                                           SelectionDAG &DAG) const {
11123   unsigned Opcode = Node->getMachineOpcode();
11124 
11125   // Subtract 1 because the vdata output is not a MachineSDNode operand.
11126   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
11127   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
11128     return Node; // not implemented for D16
11129 
11130   SDNode *Users[5] = { nullptr };
11131   unsigned Lane = 0;
11132   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
11133   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
11134   unsigned NewDmask = 0;
11135   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
11136   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
11137   bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
11138                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
11139   unsigned TFCLane = 0;
11140   bool HasChain = Node->getNumValues() > 1;
11141 
11142   if (OldDmask == 0) {
11143     // These are folded out, but on the chance it happens don't assert.
11144     return Node;
11145   }
11146 
11147   unsigned OldBitsSet = countPopulation(OldDmask);
11148   // Work out which is the TFE/LWE lane if that is enabled.
11149   if (UsesTFC) {
11150     TFCLane = OldBitsSet;
11151   }
11152 
11153   // Try to figure out the used register components
11154   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
11155        I != E; ++I) {
11156 
11157     // Don't look at users of the chain.
11158     if (I.getUse().getResNo() != 0)
11159       continue;
11160 
11161     // Abort if we can't understand the usage
11162     if (!I->isMachineOpcode() ||
11163         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
11164       return Node;
11165 
11166     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
11167     // Note that subregs are packed, i.e. Lane==0 is the first bit set
11168     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
11169     // set, etc.
11170     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
11171     if (Lane == ~0u)
11172       return Node;
11173 
11174     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
11175     if (UsesTFC && Lane == TFCLane) {
11176       Users[Lane] = *I;
11177     } else {
11178       // Set which texture component corresponds to the lane.
11179       unsigned Comp;
11180       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
11181         Comp = countTrailingZeros(Dmask);
11182         Dmask &= ~(1 << Comp);
11183       }
11184 
11185       // Abort if we have more than one user per component.
11186       if (Users[Lane])
11187         return Node;
11188 
11189       Users[Lane] = *I;
11190       NewDmask |= 1 << Comp;
11191     }
11192   }
11193 
11194   // Don't allow 0 dmask, as hardware assumes one channel enabled.
11195   bool NoChannels = !NewDmask;
11196   if (NoChannels) {
11197     if (!UsesTFC) {
11198       // No uses of the result and not using TFC. Then do nothing.
11199       return Node;
11200     }
11201     // If the original dmask has one channel - then nothing to do
11202     if (OldBitsSet == 1)
11203       return Node;
11204     // Use an arbitrary dmask - required for the instruction to work
11205     NewDmask = 1;
11206   }
11207   // Abort if there's no change
11208   if (NewDmask == OldDmask)
11209     return Node;
11210 
11211   unsigned BitsSet = countPopulation(NewDmask);
11212 
11213   // Check for TFE or LWE - increase the number of channels by one to account
11214   // for the extra return value
11215   // This will need adjustment for D16 if this is also included in
11216   // adjustWriteMask (this function) but at present D16 are excluded.
11217   unsigned NewChannels = BitsSet + UsesTFC;
11218 
11219   int NewOpcode =
11220       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
11221   assert(NewOpcode != -1 &&
11222          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
11223          "failed to find equivalent MIMG op");
11224 
11225   // Adjust the writemask in the node
11226   SmallVector<SDValue, 12> Ops;
11227   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
11228   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
11229   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11230 
11231   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11232 
11233   MVT ResultVT = NewChannels == 1 ?
11234     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11235                            NewChannels == 5 ? 8 : NewChannels);
11236   SDVTList NewVTList = HasChain ?
11237     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11238 
11239 
11240   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11241                                               NewVTList, Ops);
11242 
11243   if (HasChain) {
11244     // Update chain.
11245     DAG.setNodeMemRefs(NewNode, Node->memoperands());
11246     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11247   }
11248 
11249   if (NewChannels == 1) {
11250     assert(Node->hasNUsesOfValue(1, 0));
11251     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11252                                       SDLoc(Node), Users[Lane]->getValueType(0),
11253                                       SDValue(NewNode, 0));
11254     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11255     return nullptr;
11256   }
11257 
11258   // Update the users of the node with the new indices
11259   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11260     SDNode *User = Users[i];
11261     if (!User) {
11262       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11263       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11264       if (i || !NoChannels)
11265         continue;
11266     } else {
11267       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11268       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11269     }
11270 
11271     switch (Idx) {
11272     default: break;
11273     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11274     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11275     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11276     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11277     }
11278   }
11279 
11280   DAG.RemoveDeadNode(Node);
11281   return nullptr;
11282 }
11283 
11284 static bool isFrameIndexOp(SDValue Op) {
11285   if (Op.getOpcode() == ISD::AssertZext)
11286     Op = Op.getOperand(0);
11287 
11288   return isa<FrameIndexSDNode>(Op);
11289 }
11290 
11291 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11292 /// with frame index operands.
11293 /// LLVM assumes that inputs are to these instructions are registers.
11294 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11295                                                         SelectionDAG &DAG) const {
11296   if (Node->getOpcode() == ISD::CopyToReg) {
11297     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11298     SDValue SrcVal = Node->getOperand(2);
11299 
11300     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11301     // to try understanding copies to physical registers.
11302     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11303       SDLoc SL(Node);
11304       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11305       SDValue VReg = DAG.getRegister(
11306         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11307 
11308       SDNode *Glued = Node->getGluedNode();
11309       SDValue ToVReg
11310         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11311                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11312       SDValue ToResultReg
11313         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11314                            VReg, ToVReg.getValue(1));
11315       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11316       DAG.RemoveDeadNode(Node);
11317       return ToResultReg.getNode();
11318     }
11319   }
11320 
11321   SmallVector<SDValue, 8> Ops;
11322   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11323     if (!isFrameIndexOp(Node->getOperand(i))) {
11324       Ops.push_back(Node->getOperand(i));
11325       continue;
11326     }
11327 
11328     SDLoc DL(Node);
11329     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11330                                      Node->getOperand(i).getValueType(),
11331                                      Node->getOperand(i)), 0));
11332   }
11333 
11334   return DAG.UpdateNodeOperands(Node, Ops);
11335 }
11336 
11337 /// Fold the instructions after selecting them.
11338 /// Returns null if users were already updated.
11339 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11340                                           SelectionDAG &DAG) const {
11341   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11342   unsigned Opcode = Node->getMachineOpcode();
11343 
11344   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11345       !TII->isGather4(Opcode) &&
11346       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11347     return adjustWritemask(Node, DAG);
11348   }
11349 
11350   if (Opcode == AMDGPU::INSERT_SUBREG ||
11351       Opcode == AMDGPU::REG_SEQUENCE) {
11352     legalizeTargetIndependentNode(Node, DAG);
11353     return Node;
11354   }
11355 
11356   switch (Opcode) {
11357   case AMDGPU::V_DIV_SCALE_F32_e64:
11358   case AMDGPU::V_DIV_SCALE_F64_e64: {
11359     // Satisfy the operand register constraint when one of the inputs is
11360     // undefined. Ordinarily each undef value will have its own implicit_def of
11361     // a vreg, so force these to use a single register.
11362     SDValue Src0 = Node->getOperand(1);
11363     SDValue Src1 = Node->getOperand(3);
11364     SDValue Src2 = Node->getOperand(5);
11365 
11366     if ((Src0.isMachineOpcode() &&
11367          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11368         (Src0 == Src1 || Src0 == Src2))
11369       break;
11370 
11371     MVT VT = Src0.getValueType().getSimpleVT();
11372     const TargetRegisterClass *RC =
11373         getRegClassFor(VT, Src0.getNode()->isDivergent());
11374 
11375     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11376     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11377 
11378     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11379                                       UndefReg, Src0, SDValue());
11380 
11381     // src0 must be the same register as src1 or src2, even if the value is
11382     // undefined, so make sure we don't violate this constraint.
11383     if (Src0.isMachineOpcode() &&
11384         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11385       if (Src1.isMachineOpcode() &&
11386           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11387         Src0 = Src1;
11388       else if (Src2.isMachineOpcode() &&
11389                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11390         Src0 = Src2;
11391       else {
11392         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11393         Src0 = UndefReg;
11394         Src1 = UndefReg;
11395       }
11396     } else
11397       break;
11398 
11399     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11400     Ops[1] = Src0;
11401     Ops[3] = Src1;
11402     Ops[5] = Src2;
11403     Ops.push_back(ImpDef.getValue(1));
11404     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11405   }
11406   default:
11407     break;
11408   }
11409 
11410   return Node;
11411 }
11412 
11413 // Any MIMG instructions that use tfe or lwe require an initialization of the
11414 // result register that will be written in the case of a memory access failure.
11415 // The required code is also added to tie this init code to the result of the
11416 // img instruction.
11417 void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
11418   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11419   const SIRegisterInfo &TRI = TII->getRegisterInfo();
11420   MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11421   MachineBasicBlock &MBB = *MI.getParent();
11422 
11423   MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
11424   MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
11425   MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
11426 
11427   if (!TFE && !LWE) // intersect_ray
11428     return;
11429 
11430   unsigned TFEVal = TFE ? TFE->getImm() : 0;
11431   unsigned LWEVal = LWE->getImm();
11432   unsigned D16Val = D16 ? D16->getImm() : 0;
11433 
11434   if (!TFEVal && !LWEVal)
11435     return;
11436 
11437   // At least one of TFE or LWE are non-zero
11438   // We have to insert a suitable initialization of the result value and
11439   // tie this to the dest of the image instruction.
11440 
11441   const DebugLoc &DL = MI.getDebugLoc();
11442 
11443   int DstIdx =
11444       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
11445 
11446   // Calculate which dword we have to initialize to 0.
11447   MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
11448 
11449   // check that dmask operand is found.
11450   assert(MO_Dmask && "Expected dmask operand in instruction");
11451 
11452   unsigned dmask = MO_Dmask->getImm();
11453   // Determine the number of active lanes taking into account the
11454   // Gather4 special case
11455   unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask);
11456 
11457   bool Packed = !Subtarget->hasUnpackedD16VMem();
11458 
11459   unsigned InitIdx =
11460       D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
11461 
11462   // Abandon attempt if the dst size isn't large enough
11463   // - this is in fact an error but this is picked up elsewhere and
11464   // reported correctly.
11465   uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
11466   if (DstSize < InitIdx)
11467     return;
11468 
11469   // Create a register for the intialization value.
11470   Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11471   unsigned NewDst = 0; // Final initialized value will be in here
11472 
11473   // If PRTStrictNull feature is enabled (the default) then initialize
11474   // all the result registers to 0, otherwise just the error indication
11475   // register (VGPRn+1)
11476   unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
11477   unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
11478 
11479   BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
11480   for (; SizeLeft; SizeLeft--, CurrIdx++) {
11481     NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11482     // Initialize dword
11483     Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
11484     BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
11485       .addImm(0);
11486     // Insert into the super-reg
11487     BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
11488       .addReg(PrevDst)
11489       .addReg(SubReg)
11490       .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
11491 
11492     PrevDst = NewDst;
11493   }
11494 
11495   // Add as an implicit operand
11496   MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
11497 
11498   // Tie the just added implicit operand to the dst
11499   MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
11500 }
11501 
11502 /// Assign the register class depending on the number of
11503 /// bits set in the writemask
11504 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11505                                                      SDNode *Node) const {
11506   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11507 
11508   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11509 
11510   if (TII->isVOP3(MI.getOpcode())) {
11511     // Make sure constant bus requirements are respected.
11512     TII->legalizeOperandsVOP3(MRI, MI);
11513 
11514     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11515     // This saves a chain-copy of registers and better ballance register
11516     // use between vgpr and agpr as agpr tuples tend to be big.
11517     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
11518       unsigned Opc = MI.getOpcode();
11519       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11520       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11521                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11522         if (I == -1)
11523           break;
11524         MachineOperand &Op = MI.getOperand(I);
11525         if (!Op.isReg() || !Op.getReg().isVirtual())
11526           continue;
11527         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11528         if (!TRI->hasAGPRs(RC))
11529           continue;
11530         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11531         if (!Src || !Src->isCopy() ||
11532             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11533           continue;
11534         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11535         // All uses of agpr64 and agpr32 can also accept vgpr except for
11536         // v_accvgpr_read, but we do not produce agpr reads during selection,
11537         // so no use checks are needed.
11538         MRI.setRegClass(Op.getReg(), NewRC);
11539       }
11540     }
11541 
11542     return;
11543   }
11544 
11545   // Replace unused atomics with the no return version.
11546   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11547   if (NoRetAtomicOp != -1) {
11548     if (!Node->hasAnyUseOfValue(0)) {
11549       int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
11550                                                AMDGPU::OpName::cpol);
11551       if (CPolIdx != -1) {
11552         MachineOperand &CPol = MI.getOperand(CPolIdx);
11553         CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC);
11554       }
11555       MI.RemoveOperand(0);
11556       MI.setDesc(TII->get(NoRetAtomicOp));
11557       return;
11558     }
11559 
11560     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11561     // instruction, because the return type of these instructions is a vec2 of
11562     // the memory type, so it can be tied to the input operand.
11563     // This means these instructions always have a use, so we need to add a
11564     // special case to check if the atomic has only one extract_subreg use,
11565     // which itself has no uses.
11566     if ((Node->hasNUsesOfValue(1, 0) &&
11567          Node->use_begin()->isMachineOpcode() &&
11568          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11569          !Node->use_begin()->hasAnyUseOfValue(0))) {
11570       Register Def = MI.getOperand(0).getReg();
11571 
11572       // Change this into a noret atomic.
11573       MI.setDesc(TII->get(NoRetAtomicOp));
11574       MI.RemoveOperand(0);
11575 
11576       // If we only remove the def operand from the atomic instruction, the
11577       // extract_subreg will be left with a use of a vreg without a def.
11578       // So we need to insert an implicit_def to avoid machine verifier
11579       // errors.
11580       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11581               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11582     }
11583     return;
11584   }
11585 
11586   if (TII->isMIMG(MI) && !MI.mayStore())
11587     AddIMGInit(MI);
11588 }
11589 
11590 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11591                               uint64_t Val) {
11592   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11593   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11594 }
11595 
11596 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11597                                                 const SDLoc &DL,
11598                                                 SDValue Ptr) const {
11599   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11600 
11601   // Build the half of the subregister with the constants before building the
11602   // full 128-bit register. If we are building multiple resource descriptors,
11603   // this will allow CSEing of the 2-component register.
11604   const SDValue Ops0[] = {
11605     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11606     buildSMovImm32(DAG, DL, 0),
11607     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11608     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11609     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11610   };
11611 
11612   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11613                                                 MVT::v2i32, Ops0), 0);
11614 
11615   // Combine the constants and the pointer.
11616   const SDValue Ops1[] = {
11617     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11618     Ptr,
11619     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11620     SubRegHi,
11621     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11622   };
11623 
11624   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11625 }
11626 
11627 /// Return a resource descriptor with the 'Add TID' bit enabled
11628 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11629 ///        of the resource descriptor) to create an offset, which is added to
11630 ///        the resource pointer.
11631 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11632                                            SDValue Ptr, uint32_t RsrcDword1,
11633                                            uint64_t RsrcDword2And3) const {
11634   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11635   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11636   if (RsrcDword1) {
11637     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11638                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11639                     0);
11640   }
11641 
11642   SDValue DataLo = buildSMovImm32(DAG, DL,
11643                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11644   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11645 
11646   const SDValue Ops[] = {
11647     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11648     PtrLo,
11649     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11650     PtrHi,
11651     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11652     DataLo,
11653     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11654     DataHi,
11655     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11656   };
11657 
11658   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11659 }
11660 
11661 //===----------------------------------------------------------------------===//
11662 //                         SI Inline Assembly Support
11663 //===----------------------------------------------------------------------===//
11664 
11665 std::pair<unsigned, const TargetRegisterClass *>
11666 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
11667                                                StringRef Constraint,
11668                                                MVT VT) const {
11669   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
11670 
11671   const TargetRegisterClass *RC = nullptr;
11672   if (Constraint.size() == 1) {
11673     const unsigned BitWidth = VT.getSizeInBits();
11674     switch (Constraint[0]) {
11675     default:
11676       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11677     case 's':
11678     case 'r':
11679       switch (BitWidth) {
11680       case 16:
11681         RC = &AMDGPU::SReg_32RegClass;
11682         break;
11683       case 64:
11684         RC = &AMDGPU::SGPR_64RegClass;
11685         break;
11686       default:
11687         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11688         if (!RC)
11689           return std::make_pair(0U, nullptr);
11690         break;
11691       }
11692       break;
11693     case 'v':
11694       switch (BitWidth) {
11695       case 16:
11696         RC = &AMDGPU::VGPR_32RegClass;
11697         break;
11698       default:
11699         RC = TRI->getVGPRClassForBitWidth(BitWidth);
11700         if (!RC)
11701           return std::make_pair(0U, nullptr);
11702         break;
11703       }
11704       break;
11705     case 'a':
11706       if (!Subtarget->hasMAIInsts())
11707         break;
11708       switch (BitWidth) {
11709       case 16:
11710         RC = &AMDGPU::AGPR_32RegClass;
11711         break;
11712       default:
11713         RC = TRI->getAGPRClassForBitWidth(BitWidth);
11714         if (!RC)
11715           return std::make_pair(0U, nullptr);
11716         break;
11717       }
11718       break;
11719     }
11720     // We actually support i128, i16 and f16 as inline parameters
11721     // even if they are not reported as legal
11722     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11723                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11724       return std::make_pair(0U, RC);
11725   }
11726 
11727   if (Constraint.size() > 1) {
11728     if (Constraint[1] == 'v') {
11729       RC = &AMDGPU::VGPR_32RegClass;
11730     } else if (Constraint[1] == 's') {
11731       RC = &AMDGPU::SGPR_32RegClass;
11732     } else if (Constraint[1] == 'a') {
11733       RC = &AMDGPU::AGPR_32RegClass;
11734     }
11735 
11736     if (RC) {
11737       uint32_t Idx;
11738       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
11739       if (!Failed && Idx < RC->getNumRegs())
11740         return std::make_pair(RC->getRegister(Idx), RC);
11741     }
11742   }
11743 
11744   // FIXME: Returns VS_32 for physical SGPR constraints
11745   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11746 }
11747 
11748 static bool isImmConstraint(StringRef Constraint) {
11749   if (Constraint.size() == 1) {
11750     switch (Constraint[0]) {
11751     default: break;
11752     case 'I':
11753     case 'J':
11754     case 'A':
11755     case 'B':
11756     case 'C':
11757       return true;
11758     }
11759   } else if (Constraint == "DA" ||
11760              Constraint == "DB") {
11761     return true;
11762   }
11763   return false;
11764 }
11765 
11766 SITargetLowering::ConstraintType
11767 SITargetLowering::getConstraintType(StringRef Constraint) const {
11768   if (Constraint.size() == 1) {
11769     switch (Constraint[0]) {
11770     default: break;
11771     case 's':
11772     case 'v':
11773     case 'a':
11774       return C_RegisterClass;
11775     }
11776   }
11777   if (isImmConstraint(Constraint)) {
11778     return C_Other;
11779   }
11780   return TargetLowering::getConstraintType(Constraint);
11781 }
11782 
11783 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11784   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11785     Val = Val & maskTrailingOnes<uint64_t>(Size);
11786   }
11787   return Val;
11788 }
11789 
11790 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11791                                                     std::string &Constraint,
11792                                                     std::vector<SDValue> &Ops,
11793                                                     SelectionDAG &DAG) const {
11794   if (isImmConstraint(Constraint)) {
11795     uint64_t Val;
11796     if (getAsmOperandConstVal(Op, Val) &&
11797         checkAsmConstraintVal(Op, Constraint, Val)) {
11798       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11799       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11800     }
11801   } else {
11802     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11803   }
11804 }
11805 
11806 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11807   unsigned Size = Op.getScalarValueSizeInBits();
11808   if (Size > 64)
11809     return false;
11810 
11811   if (Size == 16 && !Subtarget->has16BitInsts())
11812     return false;
11813 
11814   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11815     Val = C->getSExtValue();
11816     return true;
11817   }
11818   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11819     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11820     return true;
11821   }
11822   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11823     if (Size != 16 || Op.getNumOperands() != 2)
11824       return false;
11825     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11826       return false;
11827     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11828       Val = C->getSExtValue();
11829       return true;
11830     }
11831     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11832       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11833       return true;
11834     }
11835   }
11836 
11837   return false;
11838 }
11839 
11840 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11841                                              const std::string &Constraint,
11842                                              uint64_t Val) const {
11843   if (Constraint.size() == 1) {
11844     switch (Constraint[0]) {
11845     case 'I':
11846       return AMDGPU::isInlinableIntLiteral(Val);
11847     case 'J':
11848       return isInt<16>(Val);
11849     case 'A':
11850       return checkAsmConstraintValA(Op, Val);
11851     case 'B':
11852       return isInt<32>(Val);
11853     case 'C':
11854       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11855              AMDGPU::isInlinableIntLiteral(Val);
11856     default:
11857       break;
11858     }
11859   } else if (Constraint.size() == 2) {
11860     if (Constraint == "DA") {
11861       int64_t HiBits = static_cast<int32_t>(Val >> 32);
11862       int64_t LoBits = static_cast<int32_t>(Val);
11863       return checkAsmConstraintValA(Op, HiBits, 32) &&
11864              checkAsmConstraintValA(Op, LoBits, 32);
11865     }
11866     if (Constraint == "DB") {
11867       return true;
11868     }
11869   }
11870   llvm_unreachable("Invalid asm constraint");
11871 }
11872 
11873 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
11874                                               uint64_t Val,
11875                                               unsigned MaxSize) const {
11876   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
11877   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11878   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11879       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11880       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11881     return true;
11882   }
11883   return false;
11884 }
11885 
11886 static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
11887   switch (UnalignedClassID) {
11888   case AMDGPU::VReg_64RegClassID:
11889     return AMDGPU::VReg_64_Align2RegClassID;
11890   case AMDGPU::VReg_96RegClassID:
11891     return AMDGPU::VReg_96_Align2RegClassID;
11892   case AMDGPU::VReg_128RegClassID:
11893     return AMDGPU::VReg_128_Align2RegClassID;
11894   case AMDGPU::VReg_160RegClassID:
11895     return AMDGPU::VReg_160_Align2RegClassID;
11896   case AMDGPU::VReg_192RegClassID:
11897     return AMDGPU::VReg_192_Align2RegClassID;
11898   case AMDGPU::VReg_224RegClassID:
11899     return AMDGPU::VReg_224_Align2RegClassID;
11900   case AMDGPU::VReg_256RegClassID:
11901     return AMDGPU::VReg_256_Align2RegClassID;
11902   case AMDGPU::VReg_512RegClassID:
11903     return AMDGPU::VReg_512_Align2RegClassID;
11904   case AMDGPU::VReg_1024RegClassID:
11905     return AMDGPU::VReg_1024_Align2RegClassID;
11906   case AMDGPU::AReg_64RegClassID:
11907     return AMDGPU::AReg_64_Align2RegClassID;
11908   case AMDGPU::AReg_96RegClassID:
11909     return AMDGPU::AReg_96_Align2RegClassID;
11910   case AMDGPU::AReg_128RegClassID:
11911     return AMDGPU::AReg_128_Align2RegClassID;
11912   case AMDGPU::AReg_160RegClassID:
11913     return AMDGPU::AReg_160_Align2RegClassID;
11914   case AMDGPU::AReg_192RegClassID:
11915     return AMDGPU::AReg_192_Align2RegClassID;
11916   case AMDGPU::AReg_256RegClassID:
11917     return AMDGPU::AReg_256_Align2RegClassID;
11918   case AMDGPU::AReg_512RegClassID:
11919     return AMDGPU::AReg_512_Align2RegClassID;
11920   case AMDGPU::AReg_1024RegClassID:
11921     return AMDGPU::AReg_1024_Align2RegClassID;
11922   default:
11923     return -1;
11924   }
11925 }
11926 
11927 // Figure out which registers should be reserved for stack access. Only after
11928 // the function is legalized do we know all of the non-spill stack objects or if
11929 // calls are present.
11930 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
11931   MachineRegisterInfo &MRI = MF.getRegInfo();
11932   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11933   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
11934   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11935   const SIInstrInfo *TII = ST.getInstrInfo();
11936 
11937   if (Info->isEntryFunction()) {
11938     // Callable functions have fixed registers used for stack access.
11939     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
11940   }
11941 
11942   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
11943                              Info->getStackPtrOffsetReg()));
11944   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
11945     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
11946 
11947   // We need to worry about replacing the default register with itself in case
11948   // of MIR testcases missing the MFI.
11949   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
11950     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
11951 
11952   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
11953     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
11954 
11955   Info->limitOccupancy(MF);
11956 
11957   if (ST.isWave32() && !MF.empty()) {
11958     for (auto &MBB : MF) {
11959       for (auto &MI : MBB) {
11960         TII->fixImplicitOperands(MI);
11961       }
11962     }
11963   }
11964 
11965   // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
11966   // classes if required. Ideally the register class constraints would differ
11967   // per-subtarget, but there's no easy way to achieve that right now. This is
11968   // not a problem for VGPRs because the correctly aligned VGPR class is implied
11969   // from using them as the register class for legal types.
11970   if (ST.needsAlignedVGPRs()) {
11971     for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
11972       const Register Reg = Register::index2VirtReg(I);
11973       const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
11974       if (!RC)
11975         continue;
11976       int NewClassID = getAlignedAGPRClassID(RC->getID());
11977       if (NewClassID != -1)
11978         MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
11979     }
11980   }
11981 
11982   TargetLoweringBase::finalizeLowering(MF);
11983 
11984   // Allocate a VGPR for future SGPR Spill if
11985   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
11986   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
11987   if (VGPRReserveforSGPRSpill && TRI->spillSGPRToVGPR() &&
11988       !Info->VGPRReservedForSGPRSpill && !Info->isEntryFunction())
11989     Info->reserveVGPRforSGPRSpills(MF);
11990 }
11991 
11992 void SITargetLowering::computeKnownBitsForFrameIndex(
11993   const int FI, KnownBits &Known, const MachineFunction &MF) const {
11994   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
11995 
11996   // Set the high bits to zero based on the maximum allowed scratch size per
11997   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
11998   // calculation won't overflow, so assume the sign bit is never set.
11999   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
12000 }
12001 
12002 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
12003                                    KnownBits &Known, unsigned Dim) {
12004   unsigned MaxValue =
12005       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
12006   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
12007 }
12008 
12009 void SITargetLowering::computeKnownBitsForTargetInstr(
12010     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
12011     const MachineRegisterInfo &MRI, unsigned Depth) const {
12012   const MachineInstr *MI = MRI.getVRegDef(R);
12013   switch (MI->getOpcode()) {
12014   case AMDGPU::G_INTRINSIC: {
12015     switch (MI->getIntrinsicID()) {
12016     case Intrinsic::amdgcn_workitem_id_x:
12017       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
12018       break;
12019     case Intrinsic::amdgcn_workitem_id_y:
12020       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
12021       break;
12022     case Intrinsic::amdgcn_workitem_id_z:
12023       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
12024       break;
12025     case Intrinsic::amdgcn_mbcnt_lo:
12026     case Intrinsic::amdgcn_mbcnt_hi: {
12027       // These return at most the wavefront size - 1.
12028       unsigned Size = MRI.getType(R).getSizeInBits();
12029       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
12030       break;
12031     }
12032     case Intrinsic::amdgcn_groupstaticsize: {
12033       // We can report everything over the maximum size as 0. We can't report
12034       // based on the actual size because we don't know if it's accurate or not
12035       // at any given point.
12036       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
12037       break;
12038     }
12039     }
12040     break;
12041   }
12042   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
12043     Known.Zero.setHighBits(24);
12044     break;
12045   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
12046     Known.Zero.setHighBits(16);
12047     break;
12048   }
12049 }
12050 
12051 Align SITargetLowering::computeKnownAlignForTargetInstr(
12052   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
12053   unsigned Depth) const {
12054   const MachineInstr *MI = MRI.getVRegDef(R);
12055   switch (MI->getOpcode()) {
12056   case AMDGPU::G_INTRINSIC:
12057   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
12058     // FIXME: Can this move to generic code? What about the case where the call
12059     // site specifies a lower alignment?
12060     Intrinsic::ID IID = MI->getIntrinsicID();
12061     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
12062     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
12063     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
12064       return *RetAlign;
12065     return Align(1);
12066   }
12067   default:
12068     return Align(1);
12069   }
12070 }
12071 
12072 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12073   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
12074   const Align CacheLineAlign = Align(64);
12075 
12076   // Pre-GFX10 target did not benefit from loop alignment
12077   if (!ML || DisableLoopAlignment ||
12078       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
12079       getSubtarget()->hasInstFwdPrefetchBug())
12080     return PrefAlign;
12081 
12082   // On GFX10 I$ is 4 x 64 bytes cache lines.
12083   // By default prefetcher keeps one cache line behind and reads two ahead.
12084   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
12085   // behind and one ahead.
12086   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
12087   // If loop fits 64 bytes it always spans no more than two cache lines and
12088   // does not need an alignment.
12089   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
12090   // Else if loop is less or equal 192 bytes we need two lines behind.
12091 
12092   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12093   const MachineBasicBlock *Header = ML->getHeader();
12094   if (Header->getAlignment() != PrefAlign)
12095     return Header->getAlignment(); // Already processed.
12096 
12097   unsigned LoopSize = 0;
12098   for (const MachineBasicBlock *MBB : ML->blocks()) {
12099     // If inner loop block is aligned assume in average half of the alignment
12100     // size to be added as nops.
12101     if (MBB != Header)
12102       LoopSize += MBB->getAlignment().value() / 2;
12103 
12104     for (const MachineInstr &MI : *MBB) {
12105       LoopSize += TII->getInstSizeInBytes(MI);
12106       if (LoopSize > 192)
12107         return PrefAlign;
12108     }
12109   }
12110 
12111   if (LoopSize <= 64)
12112     return PrefAlign;
12113 
12114   if (LoopSize <= 128)
12115     return CacheLineAlign;
12116 
12117   // If any of parent loops is surrounded by prefetch instructions do not
12118   // insert new for inner loop, which would reset parent's settings.
12119   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
12120     if (MachineBasicBlock *Exit = P->getExitBlock()) {
12121       auto I = Exit->getFirstNonDebugInstr();
12122       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
12123         return CacheLineAlign;
12124     }
12125   }
12126 
12127   MachineBasicBlock *Pre = ML->getLoopPreheader();
12128   MachineBasicBlock *Exit = ML->getExitBlock();
12129 
12130   if (Pre && Exit) {
12131     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
12132             TII->get(AMDGPU::S_INST_PREFETCH))
12133       .addImm(1); // prefetch 2 lines behind PC
12134 
12135     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
12136             TII->get(AMDGPU::S_INST_PREFETCH))
12137       .addImm(2); // prefetch 1 line behind PC
12138   }
12139 
12140   return CacheLineAlign;
12141 }
12142 
12143 LLVM_ATTRIBUTE_UNUSED
12144 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
12145   assert(N->getOpcode() == ISD::CopyFromReg);
12146   do {
12147     // Follow the chain until we find an INLINEASM node.
12148     N = N->getOperand(0).getNode();
12149     if (N->getOpcode() == ISD::INLINEASM ||
12150         N->getOpcode() == ISD::INLINEASM_BR)
12151       return true;
12152   } while (N->getOpcode() == ISD::CopyFromReg);
12153   return false;
12154 }
12155 
12156 bool SITargetLowering::isSDNodeSourceOfDivergence(
12157     const SDNode *N, FunctionLoweringInfo *FLI,
12158     LegacyDivergenceAnalysis *KDA) const {
12159   switch (N->getOpcode()) {
12160   case ISD::CopyFromReg: {
12161     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
12162     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
12163     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12164     Register Reg = R->getReg();
12165 
12166     // FIXME: Why does this need to consider isLiveIn?
12167     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
12168       return !TRI->isSGPRReg(MRI, Reg);
12169 
12170     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
12171       return KDA->isDivergent(V);
12172 
12173     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
12174     return !TRI->isSGPRReg(MRI, Reg);
12175   }
12176   case ISD::LOAD: {
12177     const LoadSDNode *L = cast<LoadSDNode>(N);
12178     unsigned AS = L->getAddressSpace();
12179     // A flat load may access private memory.
12180     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
12181   }
12182   case ISD::CALLSEQ_END:
12183     return true;
12184   case ISD::INTRINSIC_WO_CHAIN:
12185     return AMDGPU::isIntrinsicSourceOfDivergence(
12186         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
12187   case ISD::INTRINSIC_W_CHAIN:
12188     return AMDGPU::isIntrinsicSourceOfDivergence(
12189         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
12190   case AMDGPUISD::ATOMIC_CMP_SWAP:
12191   case AMDGPUISD::ATOMIC_INC:
12192   case AMDGPUISD::ATOMIC_DEC:
12193   case AMDGPUISD::ATOMIC_LOAD_FMIN:
12194   case AMDGPUISD::ATOMIC_LOAD_FMAX:
12195   case AMDGPUISD::BUFFER_ATOMIC_SWAP:
12196   case AMDGPUISD::BUFFER_ATOMIC_ADD:
12197   case AMDGPUISD::BUFFER_ATOMIC_SUB:
12198   case AMDGPUISD::BUFFER_ATOMIC_SMIN:
12199   case AMDGPUISD::BUFFER_ATOMIC_UMIN:
12200   case AMDGPUISD::BUFFER_ATOMIC_SMAX:
12201   case AMDGPUISD::BUFFER_ATOMIC_UMAX:
12202   case AMDGPUISD::BUFFER_ATOMIC_AND:
12203   case AMDGPUISD::BUFFER_ATOMIC_OR:
12204   case AMDGPUISD::BUFFER_ATOMIC_XOR:
12205   case AMDGPUISD::BUFFER_ATOMIC_INC:
12206   case AMDGPUISD::BUFFER_ATOMIC_DEC:
12207   case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
12208   case AMDGPUISD::BUFFER_ATOMIC_CSUB:
12209   case AMDGPUISD::BUFFER_ATOMIC_FADD:
12210   case AMDGPUISD::BUFFER_ATOMIC_FMIN:
12211   case AMDGPUISD::BUFFER_ATOMIC_FMAX:
12212     // Target-specific read-modify-write atomics are sources of divergence.
12213     return true;
12214   default:
12215     if (auto *A = dyn_cast<AtomicSDNode>(N)) {
12216       // Generic read-modify-write atomics are sources of divergence.
12217       return A->readMem() && A->writeMem();
12218     }
12219     return false;
12220   }
12221 }
12222 
12223 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
12224                                                EVT VT) const {
12225   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
12226   case MVT::f32:
12227     return hasFP32Denormals(DAG.getMachineFunction());
12228   case MVT::f64:
12229   case MVT::f16:
12230     return hasFP64FP16Denormals(DAG.getMachineFunction());
12231   default:
12232     return false;
12233   }
12234 }
12235 
12236 bool SITargetLowering::denormalsEnabledForType(LLT Ty,
12237                                                MachineFunction &MF) const {
12238   switch (Ty.getScalarSizeInBits()) {
12239   case 32:
12240     return hasFP32Denormals(MF);
12241   case 64:
12242   case 16:
12243     return hasFP64FP16Denormals(MF);
12244   default:
12245     return false;
12246   }
12247 }
12248 
12249 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
12250                                                     const SelectionDAG &DAG,
12251                                                     bool SNaN,
12252                                                     unsigned Depth) const {
12253   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
12254     const MachineFunction &MF = DAG.getMachineFunction();
12255     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12256 
12257     if (Info->getMode().DX10Clamp)
12258       return true; // Clamped to 0.
12259     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
12260   }
12261 
12262   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
12263                                                             SNaN, Depth);
12264 }
12265 
12266 // Global FP atomic instructions have a hardcoded FP mode and do not support
12267 // FP32 denormals, and only support v2f16 denormals.
12268 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
12269   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
12270   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
12271   if (&Flt == &APFloat::IEEEsingle())
12272     return DenormMode == DenormalMode::getPreserveSign();
12273   return DenormMode == DenormalMode::getIEEE();
12274 }
12275 
12276 TargetLowering::AtomicExpansionKind
12277 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
12278 
12279   auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) {
12280     OptimizationRemarkEmitter ORE(RMW->getFunction());
12281     LLVMContext &Ctx = RMW->getFunction()->getContext();
12282     SmallVector<StringRef> SSNs;
12283     Ctx.getSyncScopeNames(SSNs);
12284     auto MemScope = SSNs[RMW->getSyncScopeID()].empty()
12285                         ? "system"
12286                         : SSNs[RMW->getSyncScopeID()];
12287     ORE.emit([&]() {
12288       return OptimizationRemark(DEBUG_TYPE, "Passed", RMW)
12289              << "Hardware instruction generated for atomic "
12290              << RMW->getOperationName(RMW->getOperation())
12291              << " operation at memory scope " << MemScope
12292              << " due to an unsafe request.";
12293     });
12294     return Kind;
12295   };
12296 
12297   switch (RMW->getOperation()) {
12298   case AtomicRMWInst::FAdd: {
12299     Type *Ty = RMW->getType();
12300 
12301     // We don't have a way to support 16-bit atomics now, so just leave them
12302     // as-is.
12303     if (Ty->isHalfTy())
12304       return AtomicExpansionKind::None;
12305 
12306     if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
12307       return AtomicExpansionKind::CmpXChg;
12308 
12309     unsigned AS = RMW->getPointerAddressSpace();
12310 
12311     if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) &&
12312          Subtarget->hasAtomicFaddInsts()) {
12313       // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
12314       // floating point atomic instructions. May generate more efficient code,
12315       // but may not respect rounding and denormal modes, and may give incorrect
12316       // results for certain memory destinations.
12317       if (RMW->getFunction()
12318               ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12319               .getValueAsString() != "true")
12320         return AtomicExpansionKind::CmpXChg;
12321 
12322       if (Subtarget->hasGFX90AInsts()) {
12323         if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS)
12324           return AtomicExpansionKind::CmpXChg;
12325 
12326         auto SSID = RMW->getSyncScopeID();
12327         if (SSID == SyncScope::System ||
12328             SSID == RMW->getContext().getOrInsertSyncScopeID("one-as"))
12329           return AtomicExpansionKind::CmpXChg;
12330 
12331         return ReportUnsafeHWInst(AtomicExpansionKind::None);
12332       }
12333 
12334       if (AS == AMDGPUAS::FLAT_ADDRESS)
12335         return AtomicExpansionKind::CmpXChg;
12336 
12337       return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12338                               : AtomicExpansionKind::CmpXChg;
12339     }
12340 
12341     // DS FP atomics do repect the denormal mode, but the rounding mode is fixed
12342     // to round-to-nearest-even.
12343     // The only exception is DS_ADD_F64 which never flushes regardless of mode.
12344     if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) {
12345       if (!Ty->isDoubleTy())
12346         return AtomicExpansionKind::None;
12347 
12348       if (fpModeMatchesGlobalFPAtomicMode(RMW))
12349         return AtomicExpansionKind::None;
12350 
12351       return RMW->getFunction()
12352                          ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12353                          .getValueAsString() == "true"
12354                  ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12355                  : AtomicExpansionKind::CmpXChg;
12356     }
12357 
12358     return AtomicExpansionKind::CmpXChg;
12359   }
12360   default:
12361     break;
12362   }
12363 
12364   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
12365 }
12366 
12367 const TargetRegisterClass *
12368 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
12369   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
12370   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12371   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
12372     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
12373                                                : &AMDGPU::SReg_32RegClass;
12374   if (!TRI->isSGPRClass(RC) && !isDivergent)
12375     return TRI->getEquivalentSGPRClass(RC);
12376   else if (TRI->isSGPRClass(RC) && isDivergent)
12377     return TRI->getEquivalentVGPRClass(RC);
12378 
12379   return RC;
12380 }
12381 
12382 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
12383 // uniform values (as produced by the mask results of control flow intrinsics)
12384 // used outside of divergent blocks. The phi users need to also be treated as
12385 // always uniform.
12386 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
12387                       unsigned WaveSize) {
12388   // FIXME: We asssume we never cast the mask results of a control flow
12389   // intrinsic.
12390   // Early exit if the type won't be consistent as a compile time hack.
12391   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
12392   if (!IT || IT->getBitWidth() != WaveSize)
12393     return false;
12394 
12395   if (!isa<Instruction>(V))
12396     return false;
12397   if (!Visited.insert(V).second)
12398     return false;
12399   bool Result = false;
12400   for (auto U : V->users()) {
12401     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
12402       if (V == U->getOperand(1)) {
12403         switch (Intrinsic->getIntrinsicID()) {
12404         default:
12405           Result = false;
12406           break;
12407         case Intrinsic::amdgcn_if_break:
12408         case Intrinsic::amdgcn_if:
12409         case Intrinsic::amdgcn_else:
12410           Result = true;
12411           break;
12412         }
12413       }
12414       if (V == U->getOperand(0)) {
12415         switch (Intrinsic->getIntrinsicID()) {
12416         default:
12417           Result = false;
12418           break;
12419         case Intrinsic::amdgcn_end_cf:
12420         case Intrinsic::amdgcn_loop:
12421           Result = true;
12422           break;
12423         }
12424       }
12425     } else {
12426       Result = hasCFUser(U, Visited, WaveSize);
12427     }
12428     if (Result)
12429       break;
12430   }
12431   return Result;
12432 }
12433 
12434 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
12435                                                const Value *V) const {
12436   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
12437     if (CI->isInlineAsm()) {
12438       // FIXME: This cannot give a correct answer. This should only trigger in
12439       // the case where inline asm returns mixed SGPR and VGPR results, used
12440       // outside the defining block. We don't have a specific result to
12441       // consider, so this assumes if any value is SGPR, the overall register
12442       // also needs to be SGPR.
12443       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
12444       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
12445           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
12446       for (auto &TC : TargetConstraints) {
12447         if (TC.Type == InlineAsm::isOutput) {
12448           ComputeConstraintToUse(TC, SDValue());
12449           unsigned AssignedReg;
12450           const TargetRegisterClass *RC;
12451           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
12452               SIRI, TC.ConstraintCode, TC.ConstraintVT);
12453           if (RC) {
12454             MachineRegisterInfo &MRI = MF.getRegInfo();
12455             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
12456               return true;
12457             else if (SIRI->isSGPRClass(RC))
12458               return true;
12459           }
12460         }
12461       }
12462     }
12463   }
12464   SmallPtrSet<const Value *, 16> Visited;
12465   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
12466 }
12467 
12468 std::pair<InstructionCost, MVT>
12469 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
12470                                           Type *Ty) const {
12471   std::pair<InstructionCost, MVT> Cost =
12472       TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
12473   auto Size = DL.getTypeSizeInBits(Ty);
12474   // Maximum load or store can handle 8 dwords for scalar and 4 for
12475   // vector ALU. Let's assume anything above 8 dwords is expensive
12476   // even if legal.
12477   if (Size <= 256)
12478     return Cost;
12479 
12480   Cost.first = (Size + 255) / 256;
12481   return Cost;
12482 }
12483