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   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
813   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
814   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
815   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
816   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
817   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
818   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
819 
820   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
821   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
822   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom);
823   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom);
824   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
825   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
826   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
827   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
828   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
829   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
830   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
831 
832   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
833   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
834   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
835   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom);
836   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom);
837   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
838   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
839   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
840   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
841   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
842 
843   setTargetDAGCombine(ISD::ADD);
844   setTargetDAGCombine(ISD::ADDCARRY);
845   setTargetDAGCombine(ISD::SUB);
846   setTargetDAGCombine(ISD::SUBCARRY);
847   setTargetDAGCombine(ISD::FADD);
848   setTargetDAGCombine(ISD::FSUB);
849   setTargetDAGCombine(ISD::FMINNUM);
850   setTargetDAGCombine(ISD::FMAXNUM);
851   setTargetDAGCombine(ISD::FMINNUM_IEEE);
852   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
853   setTargetDAGCombine(ISD::FMA);
854   setTargetDAGCombine(ISD::SMIN);
855   setTargetDAGCombine(ISD::SMAX);
856   setTargetDAGCombine(ISD::UMIN);
857   setTargetDAGCombine(ISD::UMAX);
858   setTargetDAGCombine(ISD::SETCC);
859   setTargetDAGCombine(ISD::AND);
860   setTargetDAGCombine(ISD::OR);
861   setTargetDAGCombine(ISD::XOR);
862   setTargetDAGCombine(ISD::SINT_TO_FP);
863   setTargetDAGCombine(ISD::UINT_TO_FP);
864   setTargetDAGCombine(ISD::FCANONICALIZE);
865   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
866   setTargetDAGCombine(ISD::ZERO_EXTEND);
867   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
868   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
869   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
870 
871   // All memory operations. Some folding on the pointer operand is done to help
872   // matching the constant offsets in the addressing modes.
873   setTargetDAGCombine(ISD::LOAD);
874   setTargetDAGCombine(ISD::STORE);
875   setTargetDAGCombine(ISD::ATOMIC_LOAD);
876   setTargetDAGCombine(ISD::ATOMIC_STORE);
877   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
878   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
879   setTargetDAGCombine(ISD::ATOMIC_SWAP);
880   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
881   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
882   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
883   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
884   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
885   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
886   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
887   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
888   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
889   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
890   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
891   setTargetDAGCombine(ISD::INTRINSIC_VOID);
892   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
893 
894   // FIXME: In other contexts we pretend this is a per-function property.
895   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
896 
897   setSchedulingPreference(Sched::RegPressure);
898 }
899 
900 const GCNSubtarget *SITargetLowering::getSubtarget() const {
901   return Subtarget;
902 }
903 
904 //===----------------------------------------------------------------------===//
905 // TargetLowering queries
906 //===----------------------------------------------------------------------===//
907 
908 // v_mad_mix* support a conversion from f16 to f32.
909 //
910 // There is only one special case when denormals are enabled we don't currently,
911 // where this is OK to use.
912 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
913                                        EVT DestVT, EVT SrcVT) const {
914   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
915           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
916     DestVT.getScalarType() == MVT::f32 &&
917     SrcVT.getScalarType() == MVT::f16 &&
918     // TODO: This probably only requires no input flushing?
919     !hasFP32Denormals(DAG.getMachineFunction());
920 }
921 
922 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
923   // SI has some legal vector types, but no legal vector operations. Say no
924   // shuffles are legal in order to prefer scalarizing some vector operations.
925   return false;
926 }
927 
928 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
929                                                     CallingConv::ID CC,
930                                                     EVT VT) const {
931   if (CC == CallingConv::AMDGPU_KERNEL)
932     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
933 
934   if (VT.isVector()) {
935     EVT ScalarVT = VT.getScalarType();
936     unsigned Size = ScalarVT.getSizeInBits();
937     if (Size == 16) {
938       if (Subtarget->has16BitInsts())
939         return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
940       return VT.isInteger() ? MVT::i32 : MVT::f32;
941     }
942 
943     if (Size < 16)
944       return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
945     return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
946   }
947 
948   if (VT.getSizeInBits() > 32)
949     return MVT::i32;
950 
951   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
952 }
953 
954 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
955                                                          CallingConv::ID CC,
956                                                          EVT VT) const {
957   if (CC == CallingConv::AMDGPU_KERNEL)
958     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
959 
960   if (VT.isVector()) {
961     unsigned NumElts = VT.getVectorNumElements();
962     EVT ScalarVT = VT.getScalarType();
963     unsigned Size = ScalarVT.getSizeInBits();
964 
965     // FIXME: Should probably promote 8-bit vectors to i16.
966     if (Size == 16 && Subtarget->has16BitInsts())
967       return (NumElts + 1) / 2;
968 
969     if (Size <= 32)
970       return NumElts;
971 
972     if (Size > 32)
973       return NumElts * ((Size + 31) / 32);
974   } else if (VT.getSizeInBits() > 32)
975     return (VT.getSizeInBits() + 31) / 32;
976 
977   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
978 }
979 
980 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
981   LLVMContext &Context, CallingConv::ID CC,
982   EVT VT, EVT &IntermediateVT,
983   unsigned &NumIntermediates, MVT &RegisterVT) const {
984   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
985     unsigned NumElts = VT.getVectorNumElements();
986     EVT ScalarVT = VT.getScalarType();
987     unsigned Size = ScalarVT.getSizeInBits();
988     // FIXME: We should fix the ABI to be the same on targets without 16-bit
989     // support, but unless we can properly handle 3-vectors, it will be still be
990     // inconsistent.
991     if (Size == 16 && Subtarget->has16BitInsts()) {
992       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
993       IntermediateVT = RegisterVT;
994       NumIntermediates = (NumElts + 1) / 2;
995       return NumIntermediates;
996     }
997 
998     if (Size == 32) {
999       RegisterVT = ScalarVT.getSimpleVT();
1000       IntermediateVT = RegisterVT;
1001       NumIntermediates = NumElts;
1002       return NumIntermediates;
1003     }
1004 
1005     if (Size < 16 && Subtarget->has16BitInsts()) {
1006       // FIXME: Should probably form v2i16 pieces
1007       RegisterVT = MVT::i16;
1008       IntermediateVT = ScalarVT;
1009       NumIntermediates = NumElts;
1010       return NumIntermediates;
1011     }
1012 
1013 
1014     if (Size != 16 && Size <= 32) {
1015       RegisterVT = MVT::i32;
1016       IntermediateVT = ScalarVT;
1017       NumIntermediates = NumElts;
1018       return NumIntermediates;
1019     }
1020 
1021     if (Size > 32) {
1022       RegisterVT = MVT::i32;
1023       IntermediateVT = RegisterVT;
1024       NumIntermediates = NumElts * ((Size + 31) / 32);
1025       return NumIntermediates;
1026     }
1027   }
1028 
1029   return TargetLowering::getVectorTypeBreakdownForCallingConv(
1030     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
1031 }
1032 
1033 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
1034   assert(DMaskLanes != 0);
1035 
1036   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1037     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
1038     return EVT::getVectorVT(Ty->getContext(),
1039                             EVT::getEVT(VT->getElementType()),
1040                             NumElts);
1041   }
1042 
1043   return EVT::getEVT(Ty);
1044 }
1045 
1046 // Peek through TFE struct returns to only use the data size.
1047 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
1048   auto *ST = dyn_cast<StructType>(Ty);
1049   if (!ST)
1050     return memVTFromImageData(Ty, DMaskLanes);
1051 
1052   // Some intrinsics return an aggregate type - special case to work out the
1053   // correct memVT.
1054   //
1055   // Only limited forms of aggregate type currently expected.
1056   if (ST->getNumContainedTypes() != 2 ||
1057       !ST->getContainedType(1)->isIntegerTy(32))
1058     return EVT();
1059   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
1060 }
1061 
1062 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1063                                           const CallInst &CI,
1064                                           MachineFunction &MF,
1065                                           unsigned IntrID) const {
1066   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1067           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1068     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1069                                                   (Intrinsic::ID)IntrID);
1070     if (Attr.hasFnAttr(Attribute::ReadNone))
1071       return false;
1072 
1073     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1074 
1075     if (RsrcIntr->IsImage) {
1076       Info.ptrVal =
1077           MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1078       Info.align.reset();
1079     } else {
1080       Info.ptrVal =
1081           MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1082     }
1083 
1084     Info.flags = MachineMemOperand::MODereferenceable;
1085     if (Attr.hasFnAttr(Attribute::ReadOnly)) {
1086       unsigned DMaskLanes = 4;
1087 
1088       if (RsrcIntr->IsImage) {
1089         const AMDGPU::ImageDimIntrinsicInfo *Intr
1090           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1091         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1092           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1093 
1094         if (!BaseOpcode->Gather4) {
1095           // If this isn't a gather, we may have excess loaded elements in the
1096           // IR type. Check the dmask for the real number of elements loaded.
1097           unsigned DMask
1098             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1099           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1100         }
1101 
1102         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1103       } else
1104         Info.memVT = EVT::getEVT(CI.getType());
1105 
1106       // FIXME: What does alignment mean for an image?
1107       Info.opc = ISD::INTRINSIC_W_CHAIN;
1108       Info.flags |= MachineMemOperand::MOLoad;
1109     } else if (Attr.hasFnAttr(Attribute::WriteOnly)) {
1110       Info.opc = ISD::INTRINSIC_VOID;
1111 
1112       Type *DataTy = CI.getArgOperand(0)->getType();
1113       if (RsrcIntr->IsImage) {
1114         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1115         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1116         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1117       } else
1118         Info.memVT = EVT::getEVT(DataTy);
1119 
1120       Info.flags |= MachineMemOperand::MOStore;
1121     } else {
1122       // Atomic
1123       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1124                                             ISD::INTRINSIC_W_CHAIN;
1125       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1126       Info.flags = MachineMemOperand::MOLoad |
1127                    MachineMemOperand::MOStore |
1128                    MachineMemOperand::MODereferenceable;
1129 
1130       // XXX - Should this be volatile without known ordering?
1131       Info.flags |= MachineMemOperand::MOVolatile;
1132     }
1133     return true;
1134   }
1135 
1136   switch (IntrID) {
1137   case Intrinsic::amdgcn_atomic_inc:
1138   case Intrinsic::amdgcn_atomic_dec:
1139   case Intrinsic::amdgcn_ds_ordered_add:
1140   case Intrinsic::amdgcn_ds_ordered_swap:
1141   case Intrinsic::amdgcn_ds_fadd:
1142   case Intrinsic::amdgcn_ds_fmin:
1143   case Intrinsic::amdgcn_ds_fmax: {
1144     Info.opc = ISD::INTRINSIC_W_CHAIN;
1145     Info.memVT = MVT::getVT(CI.getType());
1146     Info.ptrVal = CI.getOperand(0);
1147     Info.align.reset();
1148     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1149 
1150     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1151     if (!Vol->isZero())
1152       Info.flags |= MachineMemOperand::MOVolatile;
1153 
1154     return true;
1155   }
1156   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1157     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1158 
1159     Info.opc = ISD::INTRINSIC_W_CHAIN;
1160     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1161     Info.ptrVal =
1162         MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1163     Info.align.reset();
1164     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1165 
1166     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1167     if (!Vol || !Vol->isZero())
1168       Info.flags |= MachineMemOperand::MOVolatile;
1169 
1170     return true;
1171   }
1172   case Intrinsic::amdgcn_ds_append:
1173   case Intrinsic::amdgcn_ds_consume: {
1174     Info.opc = ISD::INTRINSIC_W_CHAIN;
1175     Info.memVT = MVT::getVT(CI.getType());
1176     Info.ptrVal = CI.getOperand(0);
1177     Info.align.reset();
1178     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1179 
1180     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1181     if (!Vol->isZero())
1182       Info.flags |= MachineMemOperand::MOVolatile;
1183 
1184     return true;
1185   }
1186   case Intrinsic::amdgcn_global_atomic_csub: {
1187     Info.opc = ISD::INTRINSIC_W_CHAIN;
1188     Info.memVT = MVT::getVT(CI.getType());
1189     Info.ptrVal = CI.getOperand(0);
1190     Info.align.reset();
1191     Info.flags = MachineMemOperand::MOLoad |
1192                  MachineMemOperand::MOStore |
1193                  MachineMemOperand::MOVolatile;
1194     return true;
1195   }
1196   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1197     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1198     Info.opc = ISD::INTRINSIC_W_CHAIN;
1199     Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1200     Info.ptrVal =
1201         MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1202     Info.align.reset();
1203     Info.flags = MachineMemOperand::MOLoad |
1204                  MachineMemOperand::MODereferenceable;
1205     return true;
1206   }
1207   case Intrinsic::amdgcn_global_atomic_fadd:
1208   case Intrinsic::amdgcn_global_atomic_fmin:
1209   case Intrinsic::amdgcn_global_atomic_fmax:
1210   case Intrinsic::amdgcn_flat_atomic_fadd:
1211   case Intrinsic::amdgcn_flat_atomic_fmin:
1212   case Intrinsic::amdgcn_flat_atomic_fmax: {
1213     Info.opc = ISD::INTRINSIC_W_CHAIN;
1214     Info.memVT = MVT::getVT(CI.getType());
1215     Info.ptrVal = CI.getOperand(0);
1216     Info.align.reset();
1217     Info.flags = MachineMemOperand::MOLoad |
1218                  MachineMemOperand::MOStore |
1219                  MachineMemOperand::MODereferenceable |
1220                  MachineMemOperand::MOVolatile;
1221     return true;
1222   }
1223   case Intrinsic::amdgcn_ds_gws_init:
1224   case Intrinsic::amdgcn_ds_gws_barrier:
1225   case Intrinsic::amdgcn_ds_gws_sema_v:
1226   case Intrinsic::amdgcn_ds_gws_sema_br:
1227   case Intrinsic::amdgcn_ds_gws_sema_p:
1228   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1229     Info.opc = ISD::INTRINSIC_VOID;
1230 
1231     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1232     Info.ptrVal =
1233         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1234 
1235     // This is an abstract access, but we need to specify a type and size.
1236     Info.memVT = MVT::i32;
1237     Info.size = 4;
1238     Info.align = Align(4);
1239 
1240     Info.flags = MachineMemOperand::MOStore;
1241     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1242       Info.flags = MachineMemOperand::MOLoad;
1243     return true;
1244   }
1245   default:
1246     return false;
1247   }
1248 }
1249 
1250 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1251                                             SmallVectorImpl<Value*> &Ops,
1252                                             Type *&AccessTy) const {
1253   switch (II->getIntrinsicID()) {
1254   case Intrinsic::amdgcn_atomic_inc:
1255   case Intrinsic::amdgcn_atomic_dec:
1256   case Intrinsic::amdgcn_ds_ordered_add:
1257   case Intrinsic::amdgcn_ds_ordered_swap:
1258   case Intrinsic::amdgcn_ds_append:
1259   case Intrinsic::amdgcn_ds_consume:
1260   case Intrinsic::amdgcn_ds_fadd:
1261   case Intrinsic::amdgcn_ds_fmin:
1262   case Intrinsic::amdgcn_ds_fmax:
1263   case Intrinsic::amdgcn_global_atomic_fadd:
1264   case Intrinsic::amdgcn_flat_atomic_fadd:
1265   case Intrinsic::amdgcn_flat_atomic_fmin:
1266   case Intrinsic::amdgcn_flat_atomic_fmax:
1267   case Intrinsic::amdgcn_global_atomic_csub: {
1268     Value *Ptr = II->getArgOperand(0);
1269     AccessTy = II->getType();
1270     Ops.push_back(Ptr);
1271     return true;
1272   }
1273   default:
1274     return false;
1275   }
1276 }
1277 
1278 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1279   if (!Subtarget->hasFlatInstOffsets()) {
1280     // Flat instructions do not have offsets, and only have the register
1281     // address.
1282     return AM.BaseOffs == 0 && AM.Scale == 0;
1283   }
1284 
1285   return AM.Scale == 0 &&
1286          (AM.BaseOffs == 0 ||
1287           Subtarget->getInstrInfo()->isLegalFLATOffset(
1288               AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT));
1289 }
1290 
1291 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1292   if (Subtarget->hasFlatGlobalInsts())
1293     return AM.Scale == 0 &&
1294            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1295                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1296                                     SIInstrFlags::FlatGlobal));
1297 
1298   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1299       // Assume the we will use FLAT for all global memory accesses
1300       // on VI.
1301       // FIXME: This assumption is currently wrong.  On VI we still use
1302       // MUBUF instructions for the r + i addressing mode.  As currently
1303       // implemented, the MUBUF instructions only work on buffer < 4GB.
1304       // It may be possible to support > 4GB buffers with MUBUF instructions,
1305       // by setting the stride value in the resource descriptor which would
1306       // increase the size limit to (stride * 4GB).  However, this is risky,
1307       // because it has never been validated.
1308     return isLegalFlatAddressingMode(AM);
1309   }
1310 
1311   return isLegalMUBUFAddressingMode(AM);
1312 }
1313 
1314 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1315   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1316   // additionally can do r + r + i with addr64. 32-bit has more addressing
1317   // mode options. Depending on the resource constant, it can also do
1318   // (i64 r0) + (i32 r1) * (i14 i).
1319   //
1320   // Private arrays end up using a scratch buffer most of the time, so also
1321   // assume those use MUBUF instructions. Scratch loads / stores are currently
1322   // implemented as mubuf instructions with offen bit set, so slightly
1323   // different than the normal addr64.
1324   if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1325     return false;
1326 
1327   // FIXME: Since we can split immediate into soffset and immediate offset,
1328   // would it make sense to allow any immediate?
1329 
1330   switch (AM.Scale) {
1331   case 0: // r + i or just i, depending on HasBaseReg.
1332     return true;
1333   case 1:
1334     return true; // We have r + r or r + i.
1335   case 2:
1336     if (AM.HasBaseReg) {
1337       // Reject 2 * r + r.
1338       return false;
1339     }
1340 
1341     // Allow 2 * r as r + r
1342     // Or  2 * r + i is allowed as r + r + i.
1343     return true;
1344   default: // Don't allow n * r
1345     return false;
1346   }
1347 }
1348 
1349 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1350                                              const AddrMode &AM, Type *Ty,
1351                                              unsigned AS, Instruction *I) const {
1352   // No global is ever allowed as a base.
1353   if (AM.BaseGV)
1354     return false;
1355 
1356   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1357     return isLegalGlobalAddressingMode(AM);
1358 
1359   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1360       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1361       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1362     // If the offset isn't a multiple of 4, it probably isn't going to be
1363     // correctly aligned.
1364     // FIXME: Can we get the real alignment here?
1365     if (AM.BaseOffs % 4 != 0)
1366       return isLegalMUBUFAddressingMode(AM);
1367 
1368     // There are no SMRD extloads, so if we have to do a small type access we
1369     // will use a MUBUF load.
1370     // FIXME?: We also need to do this if unaligned, but we don't know the
1371     // alignment here.
1372     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1373       return isLegalGlobalAddressingMode(AM);
1374 
1375     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1376       // SMRD instructions have an 8-bit, dword offset on SI.
1377       if (!isUInt<8>(AM.BaseOffs / 4))
1378         return false;
1379     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1380       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1381       // in 8-bits, it can use a smaller encoding.
1382       if (!isUInt<32>(AM.BaseOffs / 4))
1383         return false;
1384     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1385       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1386       if (!isUInt<20>(AM.BaseOffs))
1387         return false;
1388     } else
1389       llvm_unreachable("unhandled generation");
1390 
1391     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1392       return true;
1393 
1394     if (AM.Scale == 1 && AM.HasBaseReg)
1395       return true;
1396 
1397     return false;
1398 
1399   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1400     return isLegalMUBUFAddressingMode(AM);
1401   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1402              AS == AMDGPUAS::REGION_ADDRESS) {
1403     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1404     // field.
1405     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1406     // an 8-bit dword offset but we don't know the alignment here.
1407     if (!isUInt<16>(AM.BaseOffs))
1408       return false;
1409 
1410     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1411       return true;
1412 
1413     if (AM.Scale == 1 && AM.HasBaseReg)
1414       return true;
1415 
1416     return false;
1417   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1418              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1419     // For an unknown address space, this usually means that this is for some
1420     // reason being used for pure arithmetic, and not based on some addressing
1421     // computation. We don't have instructions that compute pointers with any
1422     // addressing modes, so treat them as having no offset like flat
1423     // instructions.
1424     return isLegalFlatAddressingMode(AM);
1425   }
1426 
1427   // Assume a user alias of global for unknown address spaces.
1428   return isLegalGlobalAddressingMode(AM);
1429 }
1430 
1431 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1432                                         const MachineFunction &MF) const {
1433   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1434     return (MemVT.getSizeInBits() <= 4 * 32);
1435   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1436     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1437     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1438   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1439     return (MemVT.getSizeInBits() <= 2 * 32);
1440   }
1441   return true;
1442 }
1443 
1444 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1445     unsigned Size, unsigned AddrSpace, Align Alignment,
1446     MachineMemOperand::Flags Flags, bool *IsFast) const {
1447   if (IsFast)
1448     *IsFast = false;
1449 
1450   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1451       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1452     // Check if alignment requirements for ds_read/write instructions are
1453     // disabled.
1454     if (Subtarget->hasUnalignedDSAccessEnabled() &&
1455         !Subtarget->hasLDSMisalignedBug()) {
1456       if (IsFast)
1457         *IsFast = Alignment != Align(2);
1458       return true;
1459     }
1460 
1461     // Either, the alignment requirements are "enabled", or there is an
1462     // unaligned LDS access related hardware bug though alignment requirements
1463     // are "disabled". In either case, we need to check for proper alignment
1464     // requirements.
1465     //
1466     if (Size == 64) {
1467       // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
1468       // can do a 4 byte aligned, 8 byte access in a single operation using
1469       // ds_read2/write2_b32 with adjacent offsets.
1470       bool AlignedBy4 = Alignment >= Align(4);
1471       if (IsFast)
1472         *IsFast = AlignedBy4;
1473 
1474       return AlignedBy4;
1475     }
1476     if (Size == 96) {
1477       // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
1478       // gfx8 and older.
1479       bool AlignedBy16 = Alignment >= Align(16);
1480       if (IsFast)
1481         *IsFast = AlignedBy16;
1482 
1483       return AlignedBy16;
1484     }
1485     if (Size == 128) {
1486       // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
1487       // gfx8 and older, but  we can do a 8 byte aligned, 16 byte access in a
1488       // single operation using ds_read2/write2_b64.
1489       bool AlignedBy8 = Alignment >= Align(8);
1490       if (IsFast)
1491         *IsFast = AlignedBy8;
1492 
1493       return AlignedBy8;
1494     }
1495   }
1496 
1497   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1498     bool AlignedBy4 = Alignment >= Align(4);
1499     if (IsFast)
1500       *IsFast = AlignedBy4;
1501 
1502     return AlignedBy4 ||
1503            Subtarget->enableFlatScratch() ||
1504            Subtarget->hasUnalignedScratchAccess();
1505   }
1506 
1507   // FIXME: We have to be conservative here and assume that flat operations
1508   // will access scratch.  If we had access to the IR function, then we
1509   // could determine if any private memory was used in the function.
1510   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1511       !Subtarget->hasUnalignedScratchAccess()) {
1512     bool AlignedBy4 = Alignment >= Align(4);
1513     if (IsFast)
1514       *IsFast = AlignedBy4;
1515 
1516     return AlignedBy4;
1517   }
1518 
1519   if (Subtarget->hasUnalignedBufferAccessEnabled() &&
1520       !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1521         AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1522     // If we have an uniform constant load, it still requires using a slow
1523     // buffer instruction if unaligned.
1524     if (IsFast) {
1525       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1526       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1527       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1528                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1529         Alignment >= Align(4) : Alignment != Align(2);
1530     }
1531 
1532     return true;
1533   }
1534 
1535   // Smaller than dword value must be aligned.
1536   if (Size < 32)
1537     return false;
1538 
1539   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1540   // byte-address are ignored, thus forcing Dword alignment.
1541   // This applies to private, global, and constant memory.
1542   if (IsFast)
1543     *IsFast = true;
1544 
1545   return Size >= 32 && Alignment >= Align(4);
1546 }
1547 
1548 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1549     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1550     bool *IsFast) const {
1551   if (IsFast)
1552     *IsFast = false;
1553 
1554   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1555   // which isn't a simple VT.
1556   // Until MVT is extended to handle this, simply check for the size and
1557   // rely on the condition below: allow accesses if the size is a multiple of 4.
1558   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1559                            VT.getStoreSize() > 16)) {
1560     return false;
1561   }
1562 
1563   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1564                                             Alignment, Flags, IsFast);
1565 }
1566 
1567 EVT SITargetLowering::getOptimalMemOpType(
1568     const MemOp &Op, const AttributeList &FuncAttributes) const {
1569   // FIXME: Should account for address space here.
1570 
1571   // The default fallback uses the private pointer size as a guess for a type to
1572   // use. Make sure we switch these to 64-bit accesses.
1573 
1574   if (Op.size() >= 16 &&
1575       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1576     return MVT::v4i32;
1577 
1578   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1579     return MVT::v2i32;
1580 
1581   // Use the default.
1582   return MVT::Other;
1583 }
1584 
1585 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1586   const MemSDNode *MemNode = cast<MemSDNode>(N);
1587   const Value *Ptr = MemNode->getMemOperand()->getValue();
1588   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1589   return I && I->getMetadata("amdgpu.noclobber");
1590 }
1591 
1592 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1593   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1594          AS == AMDGPUAS::PRIVATE_ADDRESS;
1595 }
1596 
1597 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1598                                            unsigned DestAS) const {
1599   // Flat -> private/local is a simple truncate.
1600   // Flat -> global is no-op
1601   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1602     return true;
1603 
1604   const GCNTargetMachine &TM =
1605       static_cast<const GCNTargetMachine &>(getTargetMachine());
1606   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1607 }
1608 
1609 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1610   const MemSDNode *MemNode = cast<MemSDNode>(N);
1611 
1612   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1613 }
1614 
1615 TargetLoweringBase::LegalizeTypeAction
1616 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1617   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1618       VT.getScalarType().bitsLE(MVT::i16))
1619     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1620   return TargetLoweringBase::getPreferredVectorAction(VT);
1621 }
1622 
1623 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1624                                                          Type *Ty) const {
1625   // FIXME: Could be smarter if called for vector constants.
1626   return true;
1627 }
1628 
1629 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1630   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1631     switch (Op) {
1632     case ISD::LOAD:
1633     case ISD::STORE:
1634 
1635     // These operations are done with 32-bit instructions anyway.
1636     case ISD::AND:
1637     case ISD::OR:
1638     case ISD::XOR:
1639     case ISD::SELECT:
1640       // TODO: Extensions?
1641       return true;
1642     default:
1643       return false;
1644     }
1645   }
1646 
1647   // SimplifySetCC uses this function to determine whether or not it should
1648   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1649   if (VT == MVT::i1 && Op == ISD::SETCC)
1650     return false;
1651 
1652   return TargetLowering::isTypeDesirableForOp(Op, VT);
1653 }
1654 
1655 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1656                                                    const SDLoc &SL,
1657                                                    SDValue Chain,
1658                                                    uint64_t Offset) const {
1659   const DataLayout &DL = DAG.getDataLayout();
1660   MachineFunction &MF = DAG.getMachineFunction();
1661   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1662 
1663   const ArgDescriptor *InputPtrReg;
1664   const TargetRegisterClass *RC;
1665   LLT ArgTy;
1666 
1667   std::tie(InputPtrReg, RC, ArgTy) =
1668       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1669 
1670   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1671   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1672   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1673     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1674 
1675   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1676 }
1677 
1678 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1679                                             const SDLoc &SL) const {
1680   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1681                                                FIRST_IMPLICIT);
1682   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1683 }
1684 
1685 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1686                                          const SDLoc &SL, SDValue Val,
1687                                          bool Signed,
1688                                          const ISD::InputArg *Arg) const {
1689   // First, if it is a widened vector, narrow it.
1690   if (VT.isVector() &&
1691       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1692     EVT NarrowedVT =
1693         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1694                          VT.getVectorNumElements());
1695     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1696                       DAG.getConstant(0, SL, MVT::i32));
1697   }
1698 
1699   // Then convert the vector elements or scalar value.
1700   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1701       VT.bitsLT(MemVT)) {
1702     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1703     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1704   }
1705 
1706   if (MemVT.isFloatingPoint())
1707     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1708   else if (Signed)
1709     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1710   else
1711     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1712 
1713   return Val;
1714 }
1715 
1716 SDValue SITargetLowering::lowerKernargMemParameter(
1717     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1718     uint64_t Offset, Align Alignment, bool Signed,
1719     const ISD::InputArg *Arg) const {
1720   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1721 
1722   // Try to avoid using an extload by loading earlier than the argument address,
1723   // and extracting the relevant bits. The load should hopefully be merged with
1724   // the previous argument.
1725   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1726     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1727     int64_t AlignDownOffset = alignDown(Offset, 4);
1728     int64_t OffsetDiff = Offset - AlignDownOffset;
1729 
1730     EVT IntVT = MemVT.changeTypeToInteger();
1731 
1732     // TODO: If we passed in the base kernel offset we could have a better
1733     // alignment than 4, but we don't really need it.
1734     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1735     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1736                                MachineMemOperand::MODereferenceable |
1737                                    MachineMemOperand::MOInvariant);
1738 
1739     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1740     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1741 
1742     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1743     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1744     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1745 
1746 
1747     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1748   }
1749 
1750   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1751   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1752                              MachineMemOperand::MODereferenceable |
1753                                  MachineMemOperand::MOInvariant);
1754 
1755   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1756   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1757 }
1758 
1759 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1760                                               const SDLoc &SL, SDValue Chain,
1761                                               const ISD::InputArg &Arg) const {
1762   MachineFunction &MF = DAG.getMachineFunction();
1763   MachineFrameInfo &MFI = MF.getFrameInfo();
1764 
1765   if (Arg.Flags.isByVal()) {
1766     unsigned Size = Arg.Flags.getByValSize();
1767     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1768     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1769   }
1770 
1771   unsigned ArgOffset = VA.getLocMemOffset();
1772   unsigned ArgSize = VA.getValVT().getStoreSize();
1773 
1774   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1775 
1776   // Create load nodes to retrieve arguments from the stack.
1777   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1778   SDValue ArgValue;
1779 
1780   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1781   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1782   MVT MemVT = VA.getValVT();
1783 
1784   switch (VA.getLocInfo()) {
1785   default:
1786     break;
1787   case CCValAssign::BCvt:
1788     MemVT = VA.getLocVT();
1789     break;
1790   case CCValAssign::SExt:
1791     ExtType = ISD::SEXTLOAD;
1792     break;
1793   case CCValAssign::ZExt:
1794     ExtType = ISD::ZEXTLOAD;
1795     break;
1796   case CCValAssign::AExt:
1797     ExtType = ISD::EXTLOAD;
1798     break;
1799   }
1800 
1801   ArgValue = DAG.getExtLoad(
1802     ExtType, SL, VA.getLocVT(), Chain, FIN,
1803     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1804     MemVT);
1805   return ArgValue;
1806 }
1807 
1808 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1809   const SIMachineFunctionInfo &MFI,
1810   EVT VT,
1811   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1812   const ArgDescriptor *Reg;
1813   const TargetRegisterClass *RC;
1814   LLT Ty;
1815 
1816   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1817   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1818 }
1819 
1820 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1821                                CallingConv::ID CallConv,
1822                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1823                                FunctionType *FType,
1824                                SIMachineFunctionInfo *Info) {
1825   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1826     const ISD::InputArg *Arg = &Ins[I];
1827 
1828     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1829            "vector type argument should have been split");
1830 
1831     // First check if it's a PS input addr.
1832     if (CallConv == CallingConv::AMDGPU_PS &&
1833         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1834       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1835 
1836       // Inconveniently only the first part of the split is marked as isSplit,
1837       // so skip to the end. We only want to increment PSInputNum once for the
1838       // entire split argument.
1839       if (Arg->Flags.isSplit()) {
1840         while (!Arg->Flags.isSplitEnd()) {
1841           assert((!Arg->VT.isVector() ||
1842                   Arg->VT.getScalarSizeInBits() == 16) &&
1843                  "unexpected vector split in ps argument type");
1844           if (!SkipArg)
1845             Splits.push_back(*Arg);
1846           Arg = &Ins[++I];
1847         }
1848       }
1849 
1850       if (SkipArg) {
1851         // We can safely skip PS inputs.
1852         Skipped.set(Arg->getOrigArgIndex());
1853         ++PSInputNum;
1854         continue;
1855       }
1856 
1857       Info->markPSInputAllocated(PSInputNum);
1858       if (Arg->Used)
1859         Info->markPSInputEnabled(PSInputNum);
1860 
1861       ++PSInputNum;
1862     }
1863 
1864     Splits.push_back(*Arg);
1865   }
1866 }
1867 
1868 // Allocate special inputs passed in VGPRs.
1869 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1870                                                       MachineFunction &MF,
1871                                                       const SIRegisterInfo &TRI,
1872                                                       SIMachineFunctionInfo &Info) const {
1873   const LLT S32 = LLT::scalar(32);
1874   MachineRegisterInfo &MRI = MF.getRegInfo();
1875 
1876   if (Info.hasWorkItemIDX()) {
1877     Register Reg = AMDGPU::VGPR0;
1878     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1879 
1880     CCInfo.AllocateReg(Reg);
1881     unsigned Mask = (Subtarget->hasPackedTID() &&
1882                      Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
1883     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1884   }
1885 
1886   if (Info.hasWorkItemIDY()) {
1887     assert(Info.hasWorkItemIDX());
1888     if (Subtarget->hasPackedTID()) {
1889       Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1890                                                         0x3ff << 10));
1891     } else {
1892       unsigned Reg = AMDGPU::VGPR1;
1893       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1894 
1895       CCInfo.AllocateReg(Reg);
1896       Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1897     }
1898   }
1899 
1900   if (Info.hasWorkItemIDZ()) {
1901     assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
1902     if (Subtarget->hasPackedTID()) {
1903       Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1904                                                         0x3ff << 20));
1905     } else {
1906       unsigned Reg = AMDGPU::VGPR2;
1907       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1908 
1909       CCInfo.AllocateReg(Reg);
1910       Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1911     }
1912   }
1913 }
1914 
1915 // Try to allocate a VGPR at the end of the argument list, or if no argument
1916 // VGPRs are left allocating a stack slot.
1917 // If \p Mask is is given it indicates bitfield position in the register.
1918 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1919 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1920                                          ArgDescriptor Arg = ArgDescriptor()) {
1921   if (Arg.isSet())
1922     return ArgDescriptor::createArg(Arg, Mask);
1923 
1924   ArrayRef<MCPhysReg> ArgVGPRs
1925     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1926   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1927   if (RegIdx == ArgVGPRs.size()) {
1928     // Spill to stack required.
1929     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1930 
1931     return ArgDescriptor::createStack(Offset, Mask);
1932   }
1933 
1934   unsigned Reg = ArgVGPRs[RegIdx];
1935   Reg = CCInfo.AllocateReg(Reg);
1936   assert(Reg != AMDGPU::NoRegister);
1937 
1938   MachineFunction &MF = CCInfo.getMachineFunction();
1939   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1940   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1941   return ArgDescriptor::createRegister(Reg, Mask);
1942 }
1943 
1944 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1945                                              const TargetRegisterClass *RC,
1946                                              unsigned NumArgRegs) {
1947   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1948   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1949   if (RegIdx == ArgSGPRs.size())
1950     report_fatal_error("ran out of SGPRs for arguments");
1951 
1952   unsigned Reg = ArgSGPRs[RegIdx];
1953   Reg = CCInfo.AllocateReg(Reg);
1954   assert(Reg != AMDGPU::NoRegister);
1955 
1956   MachineFunction &MF = CCInfo.getMachineFunction();
1957   MF.addLiveIn(Reg, RC);
1958   return ArgDescriptor::createRegister(Reg);
1959 }
1960 
1961 // If this has a fixed position, we still should allocate the register in the
1962 // CCInfo state. Technically we could get away with this for values passed
1963 // outside of the normal argument range.
1964 static void allocateFixedSGPRInputImpl(CCState &CCInfo,
1965                                        const TargetRegisterClass *RC,
1966                                        MCRegister Reg) {
1967   Reg = CCInfo.AllocateReg(Reg);
1968   assert(Reg != AMDGPU::NoRegister);
1969   MachineFunction &MF = CCInfo.getMachineFunction();
1970   MF.addLiveIn(Reg, RC);
1971 }
1972 
1973 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
1974   if (Arg) {
1975     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
1976                                Arg.getRegister());
1977   } else
1978     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1979 }
1980 
1981 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
1982   if (Arg) {
1983     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
1984                                Arg.getRegister());
1985   } else
1986     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1987 }
1988 
1989 /// Allocate implicit function VGPR arguments at the end of allocated user
1990 /// arguments.
1991 void SITargetLowering::allocateSpecialInputVGPRs(
1992   CCState &CCInfo, MachineFunction &MF,
1993   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1994   const unsigned Mask = 0x3ff;
1995   ArgDescriptor Arg;
1996 
1997   if (Info.hasWorkItemIDX()) {
1998     Arg = allocateVGPR32Input(CCInfo, Mask);
1999     Info.setWorkItemIDX(Arg);
2000   }
2001 
2002   if (Info.hasWorkItemIDY()) {
2003     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
2004     Info.setWorkItemIDY(Arg);
2005   }
2006 
2007   if (Info.hasWorkItemIDZ())
2008     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
2009 }
2010 
2011 /// Allocate implicit function VGPR arguments in fixed registers.
2012 void SITargetLowering::allocateSpecialInputVGPRsFixed(
2013   CCState &CCInfo, MachineFunction &MF,
2014   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2015   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
2016   if (!Reg)
2017     report_fatal_error("failed to allocated VGPR for implicit arguments");
2018 
2019   const unsigned Mask = 0x3ff;
2020   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2021   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
2022   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
2023 }
2024 
2025 void SITargetLowering::allocateSpecialInputSGPRs(
2026   CCState &CCInfo,
2027   MachineFunction &MF,
2028   const SIRegisterInfo &TRI,
2029   SIMachineFunctionInfo &Info) const {
2030   auto &ArgInfo = Info.getArgInfo();
2031 
2032   // TODO: Unify handling with private memory pointers.
2033 
2034   if (Info.hasDispatchPtr())
2035     allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
2036 
2037   if (Info.hasQueuePtr())
2038     allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
2039 
2040   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
2041   // constant offset from the kernarg segment.
2042   if (Info.hasImplicitArgPtr())
2043     allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
2044 
2045   if (Info.hasDispatchID())
2046     allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2047 
2048   // flat_scratch_init is not applicable for non-kernel functions.
2049 
2050   if (Info.hasWorkGroupIDX())
2051     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2052 
2053   if (Info.hasWorkGroupIDY())
2054     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2055 
2056   if (Info.hasWorkGroupIDZ())
2057     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2058 }
2059 
2060 // Allocate special inputs passed in user SGPRs.
2061 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2062                                             MachineFunction &MF,
2063                                             const SIRegisterInfo &TRI,
2064                                             SIMachineFunctionInfo &Info) const {
2065   if (Info.hasImplicitBufferPtr()) {
2066     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2067     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2068     CCInfo.AllocateReg(ImplicitBufferPtrReg);
2069   }
2070 
2071   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2072   if (Info.hasPrivateSegmentBuffer()) {
2073     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2074     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2075     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2076   }
2077 
2078   if (Info.hasDispatchPtr()) {
2079     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2080     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2081     CCInfo.AllocateReg(DispatchPtrReg);
2082   }
2083 
2084   if (Info.hasQueuePtr()) {
2085     Register QueuePtrReg = Info.addQueuePtr(TRI);
2086     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2087     CCInfo.AllocateReg(QueuePtrReg);
2088   }
2089 
2090   if (Info.hasKernargSegmentPtr()) {
2091     MachineRegisterInfo &MRI = MF.getRegInfo();
2092     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2093     CCInfo.AllocateReg(InputPtrReg);
2094 
2095     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2096     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2097   }
2098 
2099   if (Info.hasDispatchID()) {
2100     Register DispatchIDReg = Info.addDispatchID(TRI);
2101     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2102     CCInfo.AllocateReg(DispatchIDReg);
2103   }
2104 
2105   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2106     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2107     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2108     CCInfo.AllocateReg(FlatScratchInitReg);
2109   }
2110 
2111   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2112   // these from the dispatch pointer.
2113 }
2114 
2115 // Allocate special input registers that are initialized per-wave.
2116 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2117                                            MachineFunction &MF,
2118                                            SIMachineFunctionInfo &Info,
2119                                            CallingConv::ID CallConv,
2120                                            bool IsShader) const {
2121   if (Info.hasWorkGroupIDX()) {
2122     Register Reg = Info.addWorkGroupIDX();
2123     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2124     CCInfo.AllocateReg(Reg);
2125   }
2126 
2127   if (Info.hasWorkGroupIDY()) {
2128     Register Reg = Info.addWorkGroupIDY();
2129     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2130     CCInfo.AllocateReg(Reg);
2131   }
2132 
2133   if (Info.hasWorkGroupIDZ()) {
2134     Register Reg = Info.addWorkGroupIDZ();
2135     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2136     CCInfo.AllocateReg(Reg);
2137   }
2138 
2139   if (Info.hasWorkGroupInfo()) {
2140     Register Reg = Info.addWorkGroupInfo();
2141     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2142     CCInfo.AllocateReg(Reg);
2143   }
2144 
2145   if (Info.hasPrivateSegmentWaveByteOffset()) {
2146     // Scratch wave offset passed in system SGPR.
2147     unsigned PrivateSegmentWaveByteOffsetReg;
2148 
2149     if (IsShader) {
2150       PrivateSegmentWaveByteOffsetReg =
2151         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2152 
2153       // This is true if the scratch wave byte offset doesn't have a fixed
2154       // location.
2155       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2156         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2157         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2158       }
2159     } else
2160       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2161 
2162     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2163     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2164   }
2165 }
2166 
2167 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2168                                      MachineFunction &MF,
2169                                      const SIRegisterInfo &TRI,
2170                                      SIMachineFunctionInfo &Info) {
2171   // Now that we've figured out where the scratch register inputs are, see if
2172   // should reserve the arguments and use them directly.
2173   MachineFrameInfo &MFI = MF.getFrameInfo();
2174   bool HasStackObjects = MFI.hasStackObjects();
2175   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2176 
2177   // Record that we know we have non-spill stack objects so we don't need to
2178   // check all stack objects later.
2179   if (HasStackObjects)
2180     Info.setHasNonSpillStackObjects(true);
2181 
2182   // Everything live out of a block is spilled with fast regalloc, so it's
2183   // almost certain that spilling will be required.
2184   if (TM.getOptLevel() == CodeGenOpt::None)
2185     HasStackObjects = true;
2186 
2187   // For now assume stack access is needed in any callee functions, so we need
2188   // the scratch registers to pass in.
2189   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2190 
2191   if (!ST.enableFlatScratch()) {
2192     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2193       // If we have stack objects, we unquestionably need the private buffer
2194       // resource. For the Code Object V2 ABI, this will be the first 4 user
2195       // SGPR inputs. We can reserve those and use them directly.
2196 
2197       Register PrivateSegmentBufferReg =
2198           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2199       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2200     } else {
2201       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2202       // We tentatively reserve the last registers (skipping the last registers
2203       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2204       // we'll replace these with the ones immediately after those which were
2205       // really allocated. In the prologue copies will be inserted from the
2206       // argument to these reserved registers.
2207 
2208       // Without HSA, relocations are used for the scratch pointer and the
2209       // buffer resource setup is always inserted in the prologue. Scratch wave
2210       // offset is still in an input SGPR.
2211       Info.setScratchRSrcReg(ReservedBufferReg);
2212     }
2213   }
2214 
2215   MachineRegisterInfo &MRI = MF.getRegInfo();
2216 
2217   // For entry functions we have to set up the stack pointer if we use it,
2218   // whereas non-entry functions get this "for free". This means there is no
2219   // intrinsic advantage to using S32 over S34 in cases where we do not have
2220   // calls but do need a frame pointer (i.e. if we are requested to have one
2221   // because frame pointer elimination is disabled). To keep things simple we
2222   // only ever use S32 as the call ABI stack pointer, and so using it does not
2223   // imply we need a separate frame pointer.
2224   //
2225   // Try to use s32 as the SP, but move it if it would interfere with input
2226   // arguments. This won't work with calls though.
2227   //
2228   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2229   // registers.
2230   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2231     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2232   } else {
2233     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2234 
2235     if (MFI.hasCalls())
2236       report_fatal_error("call in graphics shader with too many input SGPRs");
2237 
2238     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2239       if (!MRI.isLiveIn(Reg)) {
2240         Info.setStackPtrOffsetReg(Reg);
2241         break;
2242       }
2243     }
2244 
2245     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2246       report_fatal_error("failed to find register for SP");
2247   }
2248 
2249   // hasFP should be accurate for entry functions even before the frame is
2250   // finalized, because it does not rely on the known stack size, only
2251   // properties like whether variable sized objects are present.
2252   if (ST.getFrameLowering()->hasFP(MF)) {
2253     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2254   }
2255 }
2256 
2257 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2258   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2259   return !Info->isEntryFunction();
2260 }
2261 
2262 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2263 
2264 }
2265 
2266 void SITargetLowering::insertCopiesSplitCSR(
2267   MachineBasicBlock *Entry,
2268   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2269   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2270 
2271   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2272   if (!IStart)
2273     return;
2274 
2275   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2276   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2277   MachineBasicBlock::iterator MBBI = Entry->begin();
2278   for (const MCPhysReg *I = IStart; *I; ++I) {
2279     const TargetRegisterClass *RC = nullptr;
2280     if (AMDGPU::SReg_64RegClass.contains(*I))
2281       RC = &AMDGPU::SGPR_64RegClass;
2282     else if (AMDGPU::SReg_32RegClass.contains(*I))
2283       RC = &AMDGPU::SGPR_32RegClass;
2284     else
2285       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2286 
2287     Register NewVR = MRI->createVirtualRegister(RC);
2288     // Create copy from CSR to a virtual register.
2289     Entry->addLiveIn(*I);
2290     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2291       .addReg(*I);
2292 
2293     // Insert the copy-back instructions right before the terminator.
2294     for (auto *Exit : Exits)
2295       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2296               TII->get(TargetOpcode::COPY), *I)
2297         .addReg(NewVR);
2298   }
2299 }
2300 
2301 SDValue SITargetLowering::LowerFormalArguments(
2302     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2303     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2304     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2305   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2306 
2307   MachineFunction &MF = DAG.getMachineFunction();
2308   const Function &Fn = MF.getFunction();
2309   FunctionType *FType = MF.getFunction().getFunctionType();
2310   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2311 
2312   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2313     DiagnosticInfoUnsupported NoGraphicsHSA(
2314         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2315     DAG.getContext()->diagnose(NoGraphicsHSA);
2316     return DAG.getEntryNode();
2317   }
2318 
2319   Info->allocateModuleLDSGlobal(Fn.getParent());
2320 
2321   SmallVector<ISD::InputArg, 16> Splits;
2322   SmallVector<CCValAssign, 16> ArgLocs;
2323   BitVector Skipped(Ins.size());
2324   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2325                  *DAG.getContext());
2326 
2327   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2328   bool IsKernel = AMDGPU::isKernel(CallConv);
2329   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2330 
2331   if (IsGraphics) {
2332     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2333            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2334            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2335            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2336            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2337            !Info->hasWorkItemIDZ());
2338   }
2339 
2340   if (CallConv == CallingConv::AMDGPU_PS) {
2341     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2342 
2343     // At least one interpolation mode must be enabled or else the GPU will
2344     // hang.
2345     //
2346     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2347     // set PSInputAddr, the user wants to enable some bits after the compilation
2348     // based on run-time states. Since we can't know what the final PSInputEna
2349     // will look like, so we shouldn't do anything here and the user should take
2350     // responsibility for the correct programming.
2351     //
2352     // Otherwise, the following restrictions apply:
2353     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2354     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2355     //   enabled too.
2356     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2357         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2358       CCInfo.AllocateReg(AMDGPU::VGPR0);
2359       CCInfo.AllocateReg(AMDGPU::VGPR1);
2360       Info->markPSInputAllocated(0);
2361       Info->markPSInputEnabled(0);
2362     }
2363     if (Subtarget->isAmdPalOS()) {
2364       // For isAmdPalOS, the user does not enable some bits after compilation
2365       // based on run-time states; the register values being generated here are
2366       // the final ones set in hardware. Therefore we need to apply the
2367       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2368       // a bit is set in PSInputAddr but not PSInputEnable is where the
2369       // frontend set up an input arg for a particular interpolation mode, but
2370       // nothing uses that input arg. Really we should have an earlier pass
2371       // that removes such an arg.)
2372       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2373       if ((PsInputBits & 0x7F) == 0 ||
2374           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2375         Info->markPSInputEnabled(
2376             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2377     }
2378   } else if (IsKernel) {
2379     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2380   } else {
2381     Splits.append(Ins.begin(), Ins.end());
2382   }
2383 
2384   if (IsEntryFunc) {
2385     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2386     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2387   } else {
2388     // For the fixed ABI, pass workitem IDs in the last argument register.
2389     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2390       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2391   }
2392 
2393   if (IsKernel) {
2394     analyzeFormalArgumentsCompute(CCInfo, Ins);
2395   } else {
2396     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2397     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2398   }
2399 
2400   SmallVector<SDValue, 16> Chains;
2401 
2402   // FIXME: This is the minimum kernel argument alignment. We should improve
2403   // this to the maximum alignment of the arguments.
2404   //
2405   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2406   // kern arg offset.
2407   const Align KernelArgBaseAlign = Align(16);
2408 
2409   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2410     const ISD::InputArg &Arg = Ins[i];
2411     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2412       InVals.push_back(DAG.getUNDEF(Arg.VT));
2413       continue;
2414     }
2415 
2416     CCValAssign &VA = ArgLocs[ArgIdx++];
2417     MVT VT = VA.getLocVT();
2418 
2419     if (IsEntryFunc && VA.isMemLoc()) {
2420       VT = Ins[i].VT;
2421       EVT MemVT = VA.getLocVT();
2422 
2423       const uint64_t Offset = VA.getLocMemOffset();
2424       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2425 
2426       if (Arg.Flags.isByRef()) {
2427         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2428 
2429         const GCNTargetMachine &TM =
2430             static_cast<const GCNTargetMachine &>(getTargetMachine());
2431         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2432                                     Arg.Flags.getPointerAddrSpace())) {
2433           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2434                                      Arg.Flags.getPointerAddrSpace());
2435         }
2436 
2437         InVals.push_back(Ptr);
2438         continue;
2439       }
2440 
2441       SDValue Arg = lowerKernargMemParameter(
2442         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2443       Chains.push_back(Arg.getValue(1));
2444 
2445       auto *ParamTy =
2446         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2447       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2448           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2449                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2450         // On SI local pointers are just offsets into LDS, so they are always
2451         // less than 16-bits.  On CI and newer they could potentially be
2452         // real pointers, so we can't guarantee their size.
2453         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2454                           DAG.getValueType(MVT::i16));
2455       }
2456 
2457       InVals.push_back(Arg);
2458       continue;
2459     } else if (!IsEntryFunc && VA.isMemLoc()) {
2460       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2461       InVals.push_back(Val);
2462       if (!Arg.Flags.isByVal())
2463         Chains.push_back(Val.getValue(1));
2464       continue;
2465     }
2466 
2467     assert(VA.isRegLoc() && "Parameter must be in a register!");
2468 
2469     Register Reg = VA.getLocReg();
2470     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2471     EVT ValVT = VA.getValVT();
2472 
2473     Reg = MF.addLiveIn(Reg, RC);
2474     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2475 
2476     if (Arg.Flags.isSRet()) {
2477       // The return object should be reasonably addressable.
2478 
2479       // FIXME: This helps when the return is a real sret. If it is a
2480       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2481       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2482       unsigned NumBits
2483         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2484       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2485         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2486     }
2487 
2488     // If this is an 8 or 16-bit value, it is really passed promoted
2489     // to 32 bits. Insert an assert[sz]ext to capture this, then
2490     // truncate to the right size.
2491     switch (VA.getLocInfo()) {
2492     case CCValAssign::Full:
2493       break;
2494     case CCValAssign::BCvt:
2495       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2496       break;
2497     case CCValAssign::SExt:
2498       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2499                         DAG.getValueType(ValVT));
2500       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2501       break;
2502     case CCValAssign::ZExt:
2503       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2504                         DAG.getValueType(ValVT));
2505       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2506       break;
2507     case CCValAssign::AExt:
2508       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2509       break;
2510     default:
2511       llvm_unreachable("Unknown loc info!");
2512     }
2513 
2514     InVals.push_back(Val);
2515   }
2516 
2517   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2518     // Special inputs come after user arguments.
2519     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2520   }
2521 
2522   // Start adding system SGPRs.
2523   if (IsEntryFunc) {
2524     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2525   } else {
2526     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2527     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2528   }
2529 
2530   auto &ArgUsageInfo =
2531     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2532   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2533 
2534   unsigned StackArgSize = CCInfo.getNextStackOffset();
2535   Info->setBytesInStackArgArea(StackArgSize);
2536 
2537   return Chains.empty() ? Chain :
2538     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2539 }
2540 
2541 // TODO: If return values can't fit in registers, we should return as many as
2542 // possible in registers before passing on stack.
2543 bool SITargetLowering::CanLowerReturn(
2544   CallingConv::ID CallConv,
2545   MachineFunction &MF, bool IsVarArg,
2546   const SmallVectorImpl<ISD::OutputArg> &Outs,
2547   LLVMContext &Context) const {
2548   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2549   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2550   // for shaders. Vector types should be explicitly handled by CC.
2551   if (AMDGPU::isEntryFunctionCC(CallConv))
2552     return true;
2553 
2554   SmallVector<CCValAssign, 16> RVLocs;
2555   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2556   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2557 }
2558 
2559 SDValue
2560 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2561                               bool isVarArg,
2562                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2563                               const SmallVectorImpl<SDValue> &OutVals,
2564                               const SDLoc &DL, SelectionDAG &DAG) const {
2565   MachineFunction &MF = DAG.getMachineFunction();
2566   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2567 
2568   if (AMDGPU::isKernel(CallConv)) {
2569     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2570                                              OutVals, DL, DAG);
2571   }
2572 
2573   bool IsShader = AMDGPU::isShader(CallConv);
2574 
2575   Info->setIfReturnsVoid(Outs.empty());
2576   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2577 
2578   // CCValAssign - represent the assignment of the return value to a location.
2579   SmallVector<CCValAssign, 48> RVLocs;
2580   SmallVector<ISD::OutputArg, 48> Splits;
2581 
2582   // CCState - Info about the registers and stack slots.
2583   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2584                  *DAG.getContext());
2585 
2586   // Analyze outgoing return values.
2587   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2588 
2589   SDValue Flag;
2590   SmallVector<SDValue, 48> RetOps;
2591   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2592 
2593   // Add return address for callable functions.
2594   if (!Info->isEntryFunction()) {
2595     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2596     SDValue ReturnAddrReg = CreateLiveInRegister(
2597       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2598 
2599     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2600         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2601         MVT::i64);
2602     Chain =
2603         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2604     Flag = Chain.getValue(1);
2605     RetOps.push_back(ReturnAddrVirtualReg);
2606   }
2607 
2608   // Copy the result values into the output registers.
2609   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2610        ++I, ++RealRVLocIdx) {
2611     CCValAssign &VA = RVLocs[I];
2612     assert(VA.isRegLoc() && "Can only return in registers!");
2613     // TODO: Partially return in registers if return values don't fit.
2614     SDValue Arg = OutVals[RealRVLocIdx];
2615 
2616     // Copied from other backends.
2617     switch (VA.getLocInfo()) {
2618     case CCValAssign::Full:
2619       break;
2620     case CCValAssign::BCvt:
2621       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2622       break;
2623     case CCValAssign::SExt:
2624       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2625       break;
2626     case CCValAssign::ZExt:
2627       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2628       break;
2629     case CCValAssign::AExt:
2630       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2631       break;
2632     default:
2633       llvm_unreachable("Unknown loc info!");
2634     }
2635 
2636     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2637     Flag = Chain.getValue(1);
2638     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2639   }
2640 
2641   // FIXME: Does sret work properly?
2642   if (!Info->isEntryFunction()) {
2643     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2644     const MCPhysReg *I =
2645       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2646     if (I) {
2647       for (; *I; ++I) {
2648         if (AMDGPU::SReg_64RegClass.contains(*I))
2649           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2650         else if (AMDGPU::SReg_32RegClass.contains(*I))
2651           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2652         else
2653           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2654       }
2655     }
2656   }
2657 
2658   // Update chain and glue.
2659   RetOps[0] = Chain;
2660   if (Flag.getNode())
2661     RetOps.push_back(Flag);
2662 
2663   unsigned Opc = AMDGPUISD::ENDPGM;
2664   if (!IsWaveEnd)
2665     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2666   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2667 }
2668 
2669 SDValue SITargetLowering::LowerCallResult(
2670     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2671     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2672     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2673     SDValue ThisVal) const {
2674   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2675 
2676   // Assign locations to each value returned by this call.
2677   SmallVector<CCValAssign, 16> RVLocs;
2678   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2679                  *DAG.getContext());
2680   CCInfo.AnalyzeCallResult(Ins, RetCC);
2681 
2682   // Copy all of the result registers out of their specified physreg.
2683   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2684     CCValAssign VA = RVLocs[i];
2685     SDValue Val;
2686 
2687     if (VA.isRegLoc()) {
2688       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2689       Chain = Val.getValue(1);
2690       InFlag = Val.getValue(2);
2691     } else if (VA.isMemLoc()) {
2692       report_fatal_error("TODO: return values in memory");
2693     } else
2694       llvm_unreachable("unknown argument location type");
2695 
2696     switch (VA.getLocInfo()) {
2697     case CCValAssign::Full:
2698       break;
2699     case CCValAssign::BCvt:
2700       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2701       break;
2702     case CCValAssign::ZExt:
2703       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2704                         DAG.getValueType(VA.getValVT()));
2705       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2706       break;
2707     case CCValAssign::SExt:
2708       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2709                         DAG.getValueType(VA.getValVT()));
2710       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2711       break;
2712     case CCValAssign::AExt:
2713       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2714       break;
2715     default:
2716       llvm_unreachable("Unknown loc info!");
2717     }
2718 
2719     InVals.push_back(Val);
2720   }
2721 
2722   return Chain;
2723 }
2724 
2725 // Add code to pass special inputs required depending on used features separate
2726 // from the explicit user arguments present in the IR.
2727 void SITargetLowering::passSpecialInputs(
2728     CallLoweringInfo &CLI,
2729     CCState &CCInfo,
2730     const SIMachineFunctionInfo &Info,
2731     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2732     SmallVectorImpl<SDValue> &MemOpChains,
2733     SDValue Chain) const {
2734   // If we don't have a call site, this was a call inserted by
2735   // legalization. These can never use special inputs.
2736   if (!CLI.CB)
2737     return;
2738 
2739   SelectionDAG &DAG = CLI.DAG;
2740   const SDLoc &DL = CLI.DL;
2741 
2742   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2743   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2744 
2745   const AMDGPUFunctionArgInfo *CalleeArgInfo
2746     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2747   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2748     auto &ArgUsageInfo =
2749       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2750     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2751   }
2752 
2753   // TODO: Unify with private memory register handling. This is complicated by
2754   // the fact that at least in kernels, the input argument is not necessarily
2755   // in the same location as the input.
2756   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2757     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2758     AMDGPUFunctionArgInfo::QUEUE_PTR,
2759     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
2760     AMDGPUFunctionArgInfo::DISPATCH_ID,
2761     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2762     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2763     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
2764   };
2765 
2766   for (auto InputID : InputRegs) {
2767     const ArgDescriptor *OutgoingArg;
2768     const TargetRegisterClass *ArgRC;
2769     LLT ArgTy;
2770 
2771     std::tie(OutgoingArg, ArgRC, ArgTy) =
2772         CalleeArgInfo->getPreloadedValue(InputID);
2773     if (!OutgoingArg)
2774       continue;
2775 
2776     const ArgDescriptor *IncomingArg;
2777     const TargetRegisterClass *IncomingArgRC;
2778     LLT Ty;
2779     std::tie(IncomingArg, IncomingArgRC, Ty) =
2780         CallerArgInfo.getPreloadedValue(InputID);
2781     assert(IncomingArgRC == ArgRC);
2782 
2783     // All special arguments are ints for now.
2784     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2785     SDValue InputReg;
2786 
2787     if (IncomingArg) {
2788       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2789     } else {
2790       // The implicit arg ptr is special because it doesn't have a corresponding
2791       // input for kernels, and is computed from the kernarg segment pointer.
2792       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2793       InputReg = getImplicitArgPtr(DAG, DL);
2794     }
2795 
2796     if (OutgoingArg->isRegister()) {
2797       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2798       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2799         report_fatal_error("failed to allocate implicit input argument");
2800     } else {
2801       unsigned SpecialArgOffset =
2802           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2803       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2804                                               SpecialArgOffset);
2805       MemOpChains.push_back(ArgStore);
2806     }
2807   }
2808 
2809   // Pack workitem IDs into a single register or pass it as is if already
2810   // packed.
2811   const ArgDescriptor *OutgoingArg;
2812   const TargetRegisterClass *ArgRC;
2813   LLT Ty;
2814 
2815   std::tie(OutgoingArg, ArgRC, Ty) =
2816       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2817   if (!OutgoingArg)
2818     std::tie(OutgoingArg, ArgRC, Ty) =
2819         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2820   if (!OutgoingArg)
2821     std::tie(OutgoingArg, ArgRC, Ty) =
2822         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2823   if (!OutgoingArg)
2824     return;
2825 
2826   const ArgDescriptor *IncomingArgX = std::get<0>(
2827       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2828   const ArgDescriptor *IncomingArgY = std::get<0>(
2829       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2830   const ArgDescriptor *IncomingArgZ = std::get<0>(
2831       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2832 
2833   SDValue InputReg;
2834   SDLoc SL;
2835 
2836   // If incoming ids are not packed we need to pack them.
2837   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX)
2838     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2839 
2840   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
2841     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2842     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2843                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2844     InputReg = InputReg.getNode() ?
2845                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2846   }
2847 
2848   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
2849     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2850     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2851                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2852     InputReg = InputReg.getNode() ?
2853                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2854   }
2855 
2856   if (!InputReg.getNode()) {
2857     // Workitem ids are already packed, any of present incoming arguments
2858     // will carry all required fields.
2859     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2860       IncomingArgX ? *IncomingArgX :
2861       IncomingArgY ? *IncomingArgY :
2862                      *IncomingArgZ, ~0u);
2863     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2864   }
2865 
2866   if (OutgoingArg->isRegister()) {
2867     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2868     CCInfo.AllocateReg(OutgoingArg->getRegister());
2869   } else {
2870     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2871     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2872                                             SpecialArgOffset);
2873     MemOpChains.push_back(ArgStore);
2874   }
2875 }
2876 
2877 static bool canGuaranteeTCO(CallingConv::ID CC) {
2878   return CC == CallingConv::Fast;
2879 }
2880 
2881 /// Return true if we might ever do TCO for calls with this calling convention.
2882 static bool mayTailCallThisCC(CallingConv::ID CC) {
2883   switch (CC) {
2884   case CallingConv::C:
2885   case CallingConv::AMDGPU_Gfx:
2886     return true;
2887   default:
2888     return canGuaranteeTCO(CC);
2889   }
2890 }
2891 
2892 bool SITargetLowering::isEligibleForTailCallOptimization(
2893     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2894     const SmallVectorImpl<ISD::OutputArg> &Outs,
2895     const SmallVectorImpl<SDValue> &OutVals,
2896     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2897   if (!mayTailCallThisCC(CalleeCC))
2898     return false;
2899 
2900   // For a divergent call target, we need to do a waterfall loop over the
2901   // possible callees which precludes us from using a simple jump.
2902   if (Callee->isDivergent())
2903     return false;
2904 
2905   MachineFunction &MF = DAG.getMachineFunction();
2906   const Function &CallerF = MF.getFunction();
2907   CallingConv::ID CallerCC = CallerF.getCallingConv();
2908   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2909   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2910 
2911   // Kernels aren't callable, and don't have a live in return address so it
2912   // doesn't make sense to do a tail call with entry functions.
2913   if (!CallerPreserved)
2914     return false;
2915 
2916   bool CCMatch = CallerCC == CalleeCC;
2917 
2918   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2919     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2920       return true;
2921     return false;
2922   }
2923 
2924   // TODO: Can we handle var args?
2925   if (IsVarArg)
2926     return false;
2927 
2928   for (const Argument &Arg : CallerF.args()) {
2929     if (Arg.hasByValAttr())
2930       return false;
2931   }
2932 
2933   LLVMContext &Ctx = *DAG.getContext();
2934 
2935   // Check that the call results are passed in the same way.
2936   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2937                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2938                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2939     return false;
2940 
2941   // The callee has to preserve all registers the caller needs to preserve.
2942   if (!CCMatch) {
2943     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2944     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2945       return false;
2946   }
2947 
2948   // Nothing more to check if the callee is taking no arguments.
2949   if (Outs.empty())
2950     return true;
2951 
2952   SmallVector<CCValAssign, 16> ArgLocs;
2953   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2954 
2955   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2956 
2957   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2958   // If the stack arguments for this call do not fit into our own save area then
2959   // the call cannot be made tail.
2960   // TODO: Is this really necessary?
2961   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2962     return false;
2963 
2964   const MachineRegisterInfo &MRI = MF.getRegInfo();
2965   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2966 }
2967 
2968 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2969   if (!CI->isTailCall())
2970     return false;
2971 
2972   const Function *ParentFn = CI->getParent()->getParent();
2973   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2974     return false;
2975   return true;
2976 }
2977 
2978 // The wave scratch offset register is used as the global base pointer.
2979 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2980                                     SmallVectorImpl<SDValue> &InVals) const {
2981   SelectionDAG &DAG = CLI.DAG;
2982   const SDLoc &DL = CLI.DL;
2983   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2984   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2985   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2986   SDValue Chain = CLI.Chain;
2987   SDValue Callee = CLI.Callee;
2988   bool &IsTailCall = CLI.IsTailCall;
2989   CallingConv::ID CallConv = CLI.CallConv;
2990   bool IsVarArg = CLI.IsVarArg;
2991   bool IsSibCall = false;
2992   bool IsThisReturn = false;
2993   MachineFunction &MF = DAG.getMachineFunction();
2994 
2995   if (Callee.isUndef() || isNullConstant(Callee)) {
2996     if (!CLI.IsTailCall) {
2997       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2998         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2999     }
3000 
3001     return Chain;
3002   }
3003 
3004   if (IsVarArg) {
3005     return lowerUnhandledCall(CLI, InVals,
3006                               "unsupported call to variadic function ");
3007   }
3008 
3009   if (!CLI.CB)
3010     report_fatal_error("unsupported libcall legalization");
3011 
3012   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
3013     return lowerUnhandledCall(CLI, InVals,
3014                               "unsupported required tail call to function ");
3015   }
3016 
3017   if (AMDGPU::isShader(CallConv)) {
3018     // Note the issue is with the CC of the called function, not of the call
3019     // itself.
3020     return lowerUnhandledCall(CLI, InVals,
3021                               "unsupported call to a shader function ");
3022   }
3023 
3024   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
3025       CallConv != CallingConv::AMDGPU_Gfx) {
3026     // Only allow calls with specific calling conventions.
3027     return lowerUnhandledCall(CLI, InVals,
3028                               "unsupported calling convention for call from "
3029                               "graphics shader of function ");
3030   }
3031 
3032   if (IsTailCall) {
3033     IsTailCall = isEligibleForTailCallOptimization(
3034       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3035     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
3036       report_fatal_error("failed to perform tail call elimination on a call "
3037                          "site marked musttail");
3038     }
3039 
3040     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3041 
3042     // A sibling call is one where we're under the usual C ABI and not planning
3043     // to change that but can still do a tail call:
3044     if (!TailCallOpt && IsTailCall)
3045       IsSibCall = true;
3046 
3047     if (IsTailCall)
3048       ++NumTailCalls;
3049   }
3050 
3051   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3052   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3053   SmallVector<SDValue, 8> MemOpChains;
3054 
3055   // Analyze operands of the call, assigning locations to each operand.
3056   SmallVector<CCValAssign, 16> ArgLocs;
3057   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3058   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3059 
3060   if (AMDGPUTargetMachine::EnableFixedFunctionABI &&
3061       CallConv != CallingConv::AMDGPU_Gfx) {
3062     // With a fixed ABI, allocate fixed registers before user arguments.
3063     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3064   }
3065 
3066   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3067 
3068   // Get a count of how many bytes are to be pushed on the stack.
3069   unsigned NumBytes = CCInfo.getNextStackOffset();
3070 
3071   if (IsSibCall) {
3072     // Since we're not changing the ABI to make this a tail call, the memory
3073     // operands are already available in the caller's incoming argument space.
3074     NumBytes = 0;
3075   }
3076 
3077   // FPDiff is the byte offset of the call's argument area from the callee's.
3078   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3079   // by this amount for a tail call. In a sibling call it must be 0 because the
3080   // caller will deallocate the entire stack and the callee still expects its
3081   // arguments to begin at SP+0. Completely unused for non-tail calls.
3082   int32_t FPDiff = 0;
3083   MachineFrameInfo &MFI = MF.getFrameInfo();
3084 
3085   // Adjust the stack pointer for the new arguments...
3086   // These operations are automatically eliminated by the prolog/epilog pass
3087   if (!IsSibCall) {
3088     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3089 
3090     if (!Subtarget->enableFlatScratch()) {
3091       SmallVector<SDValue, 4> CopyFromChains;
3092 
3093       // In the HSA case, this should be an identity copy.
3094       SDValue ScratchRSrcReg
3095         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3096       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3097       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3098       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3099     }
3100   }
3101 
3102   MVT PtrVT = MVT::i32;
3103 
3104   // Walk the register/memloc assignments, inserting copies/loads.
3105   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3106     CCValAssign &VA = ArgLocs[i];
3107     SDValue Arg = OutVals[i];
3108 
3109     // Promote the value if needed.
3110     switch (VA.getLocInfo()) {
3111     case CCValAssign::Full:
3112       break;
3113     case CCValAssign::BCvt:
3114       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3115       break;
3116     case CCValAssign::ZExt:
3117       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3118       break;
3119     case CCValAssign::SExt:
3120       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3121       break;
3122     case CCValAssign::AExt:
3123       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3124       break;
3125     case CCValAssign::FPExt:
3126       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3127       break;
3128     default:
3129       llvm_unreachable("Unknown loc info!");
3130     }
3131 
3132     if (VA.isRegLoc()) {
3133       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3134     } else {
3135       assert(VA.isMemLoc());
3136 
3137       SDValue DstAddr;
3138       MachinePointerInfo DstInfo;
3139 
3140       unsigned LocMemOffset = VA.getLocMemOffset();
3141       int32_t Offset = LocMemOffset;
3142 
3143       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3144       MaybeAlign Alignment;
3145 
3146       if (IsTailCall) {
3147         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3148         unsigned OpSize = Flags.isByVal() ?
3149           Flags.getByValSize() : VA.getValVT().getStoreSize();
3150 
3151         // FIXME: We can have better than the minimum byval required alignment.
3152         Alignment =
3153             Flags.isByVal()
3154                 ? Flags.getNonZeroByValAlign()
3155                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3156 
3157         Offset = Offset + FPDiff;
3158         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3159 
3160         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3161         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3162 
3163         // Make sure any stack arguments overlapping with where we're storing
3164         // are loaded before this eventual operation. Otherwise they'll be
3165         // clobbered.
3166 
3167         // FIXME: Why is this really necessary? This seems to just result in a
3168         // lot of code to copy the stack and write them back to the same
3169         // locations, which are supposed to be immutable?
3170         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3171       } else {
3172         // Stores to the argument stack area are relative to the stack pointer.
3173         SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3174                                         MVT::i32);
3175         DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3176         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3177         Alignment =
3178             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3179       }
3180 
3181       if (Outs[i].Flags.isByVal()) {
3182         SDValue SizeNode =
3183             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3184         SDValue Cpy =
3185             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3186                           Outs[i].Flags.getNonZeroByValAlign(),
3187                           /*isVol = */ false, /*AlwaysInline = */ true,
3188                           /*isTailCall = */ false, DstInfo,
3189                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3190 
3191         MemOpChains.push_back(Cpy);
3192       } else {
3193         SDValue Store =
3194             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3195         MemOpChains.push_back(Store);
3196       }
3197     }
3198   }
3199 
3200   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
3201       CallConv != CallingConv::AMDGPU_Gfx) {
3202     // Copy special input registers after user input arguments.
3203     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3204   }
3205 
3206   if (!MemOpChains.empty())
3207     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3208 
3209   // Build a sequence of copy-to-reg nodes chained together with token chain
3210   // and flag operands which copy the outgoing args into the appropriate regs.
3211   SDValue InFlag;
3212   for (auto &RegToPass : RegsToPass) {
3213     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3214                              RegToPass.second, InFlag);
3215     InFlag = Chain.getValue(1);
3216   }
3217 
3218 
3219   SDValue PhysReturnAddrReg;
3220   if (IsTailCall) {
3221     // Since the return is being combined with the call, we need to pass on the
3222     // return address.
3223 
3224     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3225     SDValue ReturnAddrReg = CreateLiveInRegister(
3226       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3227 
3228     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3229                                         MVT::i64);
3230     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3231     InFlag = Chain.getValue(1);
3232   }
3233 
3234   // We don't usually want to end the call-sequence here because we would tidy
3235   // the frame up *after* the call, however in the ABI-changing tail-call case
3236   // we've carefully laid out the parameters so that when sp is reset they'll be
3237   // in the correct location.
3238   if (IsTailCall && !IsSibCall) {
3239     Chain = DAG.getCALLSEQ_END(Chain,
3240                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3241                                DAG.getTargetConstant(0, DL, MVT::i32),
3242                                InFlag, DL);
3243     InFlag = Chain.getValue(1);
3244   }
3245 
3246   std::vector<SDValue> Ops;
3247   Ops.push_back(Chain);
3248   Ops.push_back(Callee);
3249   // Add a redundant copy of the callee global which will not be legalized, as
3250   // we need direct access to the callee later.
3251   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3252     const GlobalValue *GV = GSD->getGlobal();
3253     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3254   } else {
3255     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3256   }
3257 
3258   if (IsTailCall) {
3259     // Each tail call may have to adjust the stack by a different amount, so
3260     // this information must travel along with the operation for eventual
3261     // consumption by emitEpilogue.
3262     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3263 
3264     Ops.push_back(PhysReturnAddrReg);
3265   }
3266 
3267   // Add argument registers to the end of the list so that they are known live
3268   // into the call.
3269   for (auto &RegToPass : RegsToPass) {
3270     Ops.push_back(DAG.getRegister(RegToPass.first,
3271                                   RegToPass.second.getValueType()));
3272   }
3273 
3274   // Add a register mask operand representing the call-preserved registers.
3275 
3276   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3277   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3278   assert(Mask && "Missing call preserved mask for calling convention");
3279   Ops.push_back(DAG.getRegisterMask(Mask));
3280 
3281   if (InFlag.getNode())
3282     Ops.push_back(InFlag);
3283 
3284   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3285 
3286   // If we're doing a tall call, use a TC_RETURN here rather than an
3287   // actual call instruction.
3288   if (IsTailCall) {
3289     MFI.setHasTailCall();
3290     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3291   }
3292 
3293   // Returns a chain and a flag for retval copy to use.
3294   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3295   Chain = Call.getValue(0);
3296   InFlag = Call.getValue(1);
3297 
3298   uint64_t CalleePopBytes = NumBytes;
3299   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3300                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3301                              InFlag, DL);
3302   if (!Ins.empty())
3303     InFlag = Chain.getValue(1);
3304 
3305   // Handle result values, copying them out of physregs into vregs that we
3306   // return.
3307   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3308                          InVals, IsThisReturn,
3309                          IsThisReturn ? OutVals[0] : SDValue());
3310 }
3311 
3312 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3313 // except for applying the wave size scale to the increment amount.
3314 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3315     SDValue Op, SelectionDAG &DAG) const {
3316   const MachineFunction &MF = DAG.getMachineFunction();
3317   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3318 
3319   SDLoc dl(Op);
3320   EVT VT = Op.getValueType();
3321   SDValue Tmp1 = Op;
3322   SDValue Tmp2 = Op.getValue(1);
3323   SDValue Tmp3 = Op.getOperand(2);
3324   SDValue Chain = Tmp1.getOperand(0);
3325 
3326   Register SPReg = Info->getStackPtrOffsetReg();
3327 
3328   // Chain the dynamic stack allocation so that it doesn't modify the stack
3329   // pointer when other instructions are using the stack.
3330   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3331 
3332   SDValue Size  = Tmp2.getOperand(1);
3333   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3334   Chain = SP.getValue(1);
3335   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3336   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3337   const TargetFrameLowering *TFL = ST.getFrameLowering();
3338   unsigned Opc =
3339     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3340     ISD::ADD : ISD::SUB;
3341 
3342   SDValue ScaledSize = DAG.getNode(
3343       ISD::SHL, dl, VT, Size,
3344       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3345 
3346   Align StackAlign = TFL->getStackAlign();
3347   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3348   if (Alignment && *Alignment > StackAlign) {
3349     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3350                        DAG.getConstant(-(uint64_t)Alignment->value()
3351                                            << ST.getWavefrontSizeLog2(),
3352                                        dl, VT));
3353   }
3354 
3355   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3356   Tmp2 = DAG.getCALLSEQ_END(
3357       Chain, DAG.getIntPtrConstant(0, dl, true),
3358       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3359 
3360   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3361 }
3362 
3363 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3364                                                   SelectionDAG &DAG) const {
3365   // We only handle constant sizes here to allow non-entry block, static sized
3366   // allocas. A truly dynamic value is more difficult to support because we
3367   // don't know if the size value is uniform or not. If the size isn't uniform,
3368   // we would need to do a wave reduction to get the maximum size to know how
3369   // much to increment the uniform stack pointer.
3370   SDValue Size = Op.getOperand(1);
3371   if (isa<ConstantSDNode>(Size))
3372       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3373 
3374   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3375 }
3376 
3377 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3378                                              const MachineFunction &MF) const {
3379   Register Reg = StringSwitch<Register>(RegName)
3380     .Case("m0", AMDGPU::M0)
3381     .Case("exec", AMDGPU::EXEC)
3382     .Case("exec_lo", AMDGPU::EXEC_LO)
3383     .Case("exec_hi", AMDGPU::EXEC_HI)
3384     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3385     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3386     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3387     .Default(Register());
3388 
3389   if (Reg == AMDGPU::NoRegister) {
3390     report_fatal_error(Twine("invalid register name \""
3391                              + StringRef(RegName)  + "\"."));
3392 
3393   }
3394 
3395   if (!Subtarget->hasFlatScrRegister() &&
3396        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3397     report_fatal_error(Twine("invalid register \""
3398                              + StringRef(RegName)  + "\" for subtarget."));
3399   }
3400 
3401   switch (Reg) {
3402   case AMDGPU::M0:
3403   case AMDGPU::EXEC_LO:
3404   case AMDGPU::EXEC_HI:
3405   case AMDGPU::FLAT_SCR_LO:
3406   case AMDGPU::FLAT_SCR_HI:
3407     if (VT.getSizeInBits() == 32)
3408       return Reg;
3409     break;
3410   case AMDGPU::EXEC:
3411   case AMDGPU::FLAT_SCR:
3412     if (VT.getSizeInBits() == 64)
3413       return Reg;
3414     break;
3415   default:
3416     llvm_unreachable("missing register type checking");
3417   }
3418 
3419   report_fatal_error(Twine("invalid type for register \""
3420                            + StringRef(RegName) + "\"."));
3421 }
3422 
3423 // If kill is not the last instruction, split the block so kill is always a
3424 // proper terminator.
3425 MachineBasicBlock *
3426 SITargetLowering::splitKillBlock(MachineInstr &MI,
3427                                  MachineBasicBlock *BB) const {
3428   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3429   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3430   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3431   return SplitBB;
3432 }
3433 
3434 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3435 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3436 // be the first instruction in the remainder block.
3437 //
3438 /// \returns { LoopBody, Remainder }
3439 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3440 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3441   MachineFunction *MF = MBB.getParent();
3442   MachineBasicBlock::iterator I(&MI);
3443 
3444   // To insert the loop we need to split the block. Move everything after this
3445   // point to a new block, and insert a new empty block between the two.
3446   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3447   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3448   MachineFunction::iterator MBBI(MBB);
3449   ++MBBI;
3450 
3451   MF->insert(MBBI, LoopBB);
3452   MF->insert(MBBI, RemainderBB);
3453 
3454   LoopBB->addSuccessor(LoopBB);
3455   LoopBB->addSuccessor(RemainderBB);
3456 
3457   // Move the rest of the block into a new block.
3458   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3459 
3460   if (InstInLoop) {
3461     auto Next = std::next(I);
3462 
3463     // Move instruction to loop body.
3464     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3465 
3466     // Move the rest of the block.
3467     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3468   } else {
3469     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3470   }
3471 
3472   MBB.addSuccessor(LoopBB);
3473 
3474   return std::make_pair(LoopBB, RemainderBB);
3475 }
3476 
3477 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3478 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3479   MachineBasicBlock *MBB = MI.getParent();
3480   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3481   auto I = MI.getIterator();
3482   auto E = std::next(I);
3483 
3484   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3485     .addImm(0);
3486 
3487   MIBundleBuilder Bundler(*MBB, I, E);
3488   finalizeBundle(*MBB, Bundler.begin());
3489 }
3490 
3491 MachineBasicBlock *
3492 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3493                                          MachineBasicBlock *BB) const {
3494   const DebugLoc &DL = MI.getDebugLoc();
3495 
3496   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3497 
3498   MachineBasicBlock *LoopBB;
3499   MachineBasicBlock *RemainderBB;
3500   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3501 
3502   // Apparently kill flags are only valid if the def is in the same block?
3503   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3504     Src->setIsKill(false);
3505 
3506   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3507 
3508   MachineBasicBlock::iterator I = LoopBB->end();
3509 
3510   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3511     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3512 
3513   // Clear TRAP_STS.MEM_VIOL
3514   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3515     .addImm(0)
3516     .addImm(EncodedReg);
3517 
3518   bundleInstWithWaitcnt(MI);
3519 
3520   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3521 
3522   // Load and check TRAP_STS.MEM_VIOL
3523   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3524     .addImm(EncodedReg);
3525 
3526   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3527   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3528     .addReg(Reg, RegState::Kill)
3529     .addImm(0);
3530   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3531     .addMBB(LoopBB);
3532 
3533   return RemainderBB;
3534 }
3535 
3536 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3537 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3538 // will only do one iteration. In the worst case, this will loop 64 times.
3539 //
3540 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3541 static MachineBasicBlock::iterator
3542 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3543                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3544                        const DebugLoc &DL, const MachineOperand &Idx,
3545                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3546                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3547                        Register &SGPRIdxReg) {
3548 
3549   MachineFunction *MF = OrigBB.getParent();
3550   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3551   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3552   MachineBasicBlock::iterator I = LoopBB.begin();
3553 
3554   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3555   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3556   Register NewExec = MRI.createVirtualRegister(BoolRC);
3557   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3558   Register CondReg = MRI.createVirtualRegister(BoolRC);
3559 
3560   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3561     .addReg(InitReg)
3562     .addMBB(&OrigBB)
3563     .addReg(ResultReg)
3564     .addMBB(&LoopBB);
3565 
3566   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3567     .addReg(InitSaveExecReg)
3568     .addMBB(&OrigBB)
3569     .addReg(NewExec)
3570     .addMBB(&LoopBB);
3571 
3572   // Read the next variant <- also loop target.
3573   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3574       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3575 
3576   // Compare the just read M0 value to all possible Idx values.
3577   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3578       .addReg(CurrentIdxReg)
3579       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3580 
3581   // Update EXEC, save the original EXEC value to VCC.
3582   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3583                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3584           NewExec)
3585     .addReg(CondReg, RegState::Kill);
3586 
3587   MRI.setSimpleHint(NewExec, CondReg);
3588 
3589   if (UseGPRIdxMode) {
3590     if (Offset == 0) {
3591       SGPRIdxReg = CurrentIdxReg;
3592     } else {
3593       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3594       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3595           .addReg(CurrentIdxReg, RegState::Kill)
3596           .addImm(Offset);
3597     }
3598   } else {
3599     // Move index from VCC into M0
3600     if (Offset == 0) {
3601       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3602         .addReg(CurrentIdxReg, RegState::Kill);
3603     } else {
3604       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3605         .addReg(CurrentIdxReg, RegState::Kill)
3606         .addImm(Offset);
3607     }
3608   }
3609 
3610   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3611   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3612   MachineInstr *InsertPt =
3613     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3614                                                   : AMDGPU::S_XOR_B64_term), Exec)
3615       .addReg(Exec)
3616       .addReg(NewExec);
3617 
3618   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3619   // s_cbranch_scc0?
3620 
3621   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3622   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3623     .addMBB(&LoopBB);
3624 
3625   return InsertPt->getIterator();
3626 }
3627 
3628 // This has slightly sub-optimal regalloc when the source vector is killed by
3629 // the read. The register allocator does not understand that the kill is
3630 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3631 // subregister from it, using 1 more VGPR than necessary. This was saved when
3632 // this was expanded after register allocation.
3633 static MachineBasicBlock::iterator
3634 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3635                unsigned InitResultReg, unsigned PhiReg, int Offset,
3636                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3637   MachineFunction *MF = MBB.getParent();
3638   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3639   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3640   MachineRegisterInfo &MRI = MF->getRegInfo();
3641   const DebugLoc &DL = MI.getDebugLoc();
3642   MachineBasicBlock::iterator I(&MI);
3643 
3644   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3645   Register DstReg = MI.getOperand(0).getReg();
3646   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3647   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3648   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3649   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3650 
3651   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3652 
3653   // Save the EXEC mask
3654   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3655     .addReg(Exec);
3656 
3657   MachineBasicBlock *LoopBB;
3658   MachineBasicBlock *RemainderBB;
3659   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3660 
3661   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3662 
3663   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3664                                       InitResultReg, DstReg, PhiReg, TmpExec,
3665                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3666 
3667   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3668   MachineFunction::iterator MBBI(LoopBB);
3669   ++MBBI;
3670   MF->insert(MBBI, LandingPad);
3671   LoopBB->removeSuccessor(RemainderBB);
3672   LandingPad->addSuccessor(RemainderBB);
3673   LoopBB->addSuccessor(LandingPad);
3674   MachineBasicBlock::iterator First = LandingPad->begin();
3675   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3676     .addReg(SaveExec);
3677 
3678   return InsPt;
3679 }
3680 
3681 // Returns subreg index, offset
3682 static std::pair<unsigned, int>
3683 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3684                             const TargetRegisterClass *SuperRC,
3685                             unsigned VecReg,
3686                             int Offset) {
3687   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3688 
3689   // Skip out of bounds offsets, or else we would end up using an undefined
3690   // register.
3691   if (Offset >= NumElts || Offset < 0)
3692     return std::make_pair(AMDGPU::sub0, Offset);
3693 
3694   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3695 }
3696 
3697 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3698                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3699                                  int Offset) {
3700   MachineBasicBlock *MBB = MI.getParent();
3701   const DebugLoc &DL = MI.getDebugLoc();
3702   MachineBasicBlock::iterator I(&MI);
3703 
3704   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3705 
3706   assert(Idx->getReg() != AMDGPU::NoRegister);
3707 
3708   if (Offset == 0) {
3709     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3710   } else {
3711     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3712         .add(*Idx)
3713         .addImm(Offset);
3714   }
3715 }
3716 
3717 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3718                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3719                                    int Offset) {
3720   MachineBasicBlock *MBB = MI.getParent();
3721   const DebugLoc &DL = MI.getDebugLoc();
3722   MachineBasicBlock::iterator I(&MI);
3723 
3724   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3725 
3726   if (Offset == 0)
3727     return Idx->getReg();
3728 
3729   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3730   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3731       .add(*Idx)
3732       .addImm(Offset);
3733   return Tmp;
3734 }
3735 
3736 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3737                                           MachineBasicBlock &MBB,
3738                                           const GCNSubtarget &ST) {
3739   const SIInstrInfo *TII = ST.getInstrInfo();
3740   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3741   MachineFunction *MF = MBB.getParent();
3742   MachineRegisterInfo &MRI = MF->getRegInfo();
3743 
3744   Register Dst = MI.getOperand(0).getReg();
3745   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3746   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3747   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3748 
3749   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3750   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3751 
3752   unsigned SubReg;
3753   std::tie(SubReg, Offset)
3754     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3755 
3756   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3757 
3758   // Check for a SGPR index.
3759   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3760     MachineBasicBlock::iterator I(&MI);
3761     const DebugLoc &DL = MI.getDebugLoc();
3762 
3763     if (UseGPRIdxMode) {
3764       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3765       // to avoid interfering with other uses, so probably requires a new
3766       // optimization pass.
3767       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3768 
3769       const MCInstrDesc &GPRIDXDesc =
3770           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3771       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3772           .addReg(SrcReg)
3773           .addReg(Idx)
3774           .addImm(SubReg);
3775     } else {
3776       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3777 
3778       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3779         .addReg(SrcReg, 0, SubReg)
3780         .addReg(SrcReg, RegState::Implicit);
3781     }
3782 
3783     MI.eraseFromParent();
3784 
3785     return &MBB;
3786   }
3787 
3788   // Control flow needs to be inserted if indexing with a VGPR.
3789   const DebugLoc &DL = MI.getDebugLoc();
3790   MachineBasicBlock::iterator I(&MI);
3791 
3792   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3793   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3794 
3795   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3796 
3797   Register SGPRIdxReg;
3798   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3799                               UseGPRIdxMode, SGPRIdxReg);
3800 
3801   MachineBasicBlock *LoopBB = InsPt->getParent();
3802 
3803   if (UseGPRIdxMode) {
3804     const MCInstrDesc &GPRIDXDesc =
3805         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3806 
3807     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3808         .addReg(SrcReg)
3809         .addReg(SGPRIdxReg)
3810         .addImm(SubReg);
3811   } else {
3812     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3813       .addReg(SrcReg, 0, SubReg)
3814       .addReg(SrcReg, RegState::Implicit);
3815   }
3816 
3817   MI.eraseFromParent();
3818 
3819   return LoopBB;
3820 }
3821 
3822 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3823                                           MachineBasicBlock &MBB,
3824                                           const GCNSubtarget &ST) {
3825   const SIInstrInfo *TII = ST.getInstrInfo();
3826   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3827   MachineFunction *MF = MBB.getParent();
3828   MachineRegisterInfo &MRI = MF->getRegInfo();
3829 
3830   Register Dst = MI.getOperand(0).getReg();
3831   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3832   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3833   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3834   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3835   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3836   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3837 
3838   // This can be an immediate, but will be folded later.
3839   assert(Val->getReg());
3840 
3841   unsigned SubReg;
3842   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3843                                                          SrcVec->getReg(),
3844                                                          Offset);
3845   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3846 
3847   if (Idx->getReg() == AMDGPU::NoRegister) {
3848     MachineBasicBlock::iterator I(&MI);
3849     const DebugLoc &DL = MI.getDebugLoc();
3850 
3851     assert(Offset == 0);
3852 
3853     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3854         .add(*SrcVec)
3855         .add(*Val)
3856         .addImm(SubReg);
3857 
3858     MI.eraseFromParent();
3859     return &MBB;
3860   }
3861 
3862   // Check for a SGPR index.
3863   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3864     MachineBasicBlock::iterator I(&MI);
3865     const DebugLoc &DL = MI.getDebugLoc();
3866 
3867     if (UseGPRIdxMode) {
3868       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3869 
3870       const MCInstrDesc &GPRIDXDesc =
3871           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3872       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3873           .addReg(SrcVec->getReg())
3874           .add(*Val)
3875           .addReg(Idx)
3876           .addImm(SubReg);
3877     } else {
3878       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3879 
3880       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3881           TRI.getRegSizeInBits(*VecRC), 32, false);
3882       BuildMI(MBB, I, DL, MovRelDesc, Dst)
3883           .addReg(SrcVec->getReg())
3884           .add(*Val)
3885           .addImm(SubReg);
3886     }
3887     MI.eraseFromParent();
3888     return &MBB;
3889   }
3890 
3891   // Control flow needs to be inserted if indexing with a VGPR.
3892   if (Val->isReg())
3893     MRI.clearKillFlags(Val->getReg());
3894 
3895   const DebugLoc &DL = MI.getDebugLoc();
3896 
3897   Register PhiReg = MRI.createVirtualRegister(VecRC);
3898 
3899   Register SGPRIdxReg;
3900   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
3901                               UseGPRIdxMode, SGPRIdxReg);
3902   MachineBasicBlock *LoopBB = InsPt->getParent();
3903 
3904   if (UseGPRIdxMode) {
3905     const MCInstrDesc &GPRIDXDesc =
3906         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3907 
3908     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3909         .addReg(PhiReg)
3910         .add(*Val)
3911         .addReg(SGPRIdxReg)
3912         .addImm(AMDGPU::sub0);
3913   } else {
3914     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3915         TRI.getRegSizeInBits(*VecRC), 32, false);
3916     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3917         .addReg(PhiReg)
3918         .add(*Val)
3919         .addImm(AMDGPU::sub0);
3920   }
3921 
3922   MI.eraseFromParent();
3923   return LoopBB;
3924 }
3925 
3926 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3927   MachineInstr &MI, MachineBasicBlock *BB) const {
3928 
3929   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3930   MachineFunction *MF = BB->getParent();
3931   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3932 
3933   switch (MI.getOpcode()) {
3934   case AMDGPU::S_UADDO_PSEUDO:
3935   case AMDGPU::S_USUBO_PSEUDO: {
3936     const DebugLoc &DL = MI.getDebugLoc();
3937     MachineOperand &Dest0 = MI.getOperand(0);
3938     MachineOperand &Dest1 = MI.getOperand(1);
3939     MachineOperand &Src0 = MI.getOperand(2);
3940     MachineOperand &Src1 = MI.getOperand(3);
3941 
3942     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3943                        ? AMDGPU::S_ADD_I32
3944                        : AMDGPU::S_SUB_I32;
3945     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3946 
3947     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3948         .addImm(1)
3949         .addImm(0);
3950 
3951     MI.eraseFromParent();
3952     return BB;
3953   }
3954   case AMDGPU::S_ADD_U64_PSEUDO:
3955   case AMDGPU::S_SUB_U64_PSEUDO: {
3956     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3957     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3958     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3959     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3960     const DebugLoc &DL = MI.getDebugLoc();
3961 
3962     MachineOperand &Dest = MI.getOperand(0);
3963     MachineOperand &Src0 = MI.getOperand(1);
3964     MachineOperand &Src1 = MI.getOperand(2);
3965 
3966     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3967     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3968 
3969     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3970         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3971     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3972         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3973 
3974     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3975         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3976     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3977         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3978 
3979     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3980 
3981     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3982     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3983     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3984     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3985     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3986         .addReg(DestSub0)
3987         .addImm(AMDGPU::sub0)
3988         .addReg(DestSub1)
3989         .addImm(AMDGPU::sub1);
3990     MI.eraseFromParent();
3991     return BB;
3992   }
3993   case AMDGPU::V_ADD_U64_PSEUDO:
3994   case AMDGPU::V_SUB_U64_PSEUDO: {
3995     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3996     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3997     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3998     const DebugLoc &DL = MI.getDebugLoc();
3999 
4000     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
4001 
4002     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4003 
4004     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4005     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4006 
4007     Register CarryReg = MRI.createVirtualRegister(CarryRC);
4008     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
4009 
4010     MachineOperand &Dest = MI.getOperand(0);
4011     MachineOperand &Src0 = MI.getOperand(1);
4012     MachineOperand &Src1 = MI.getOperand(2);
4013 
4014     const TargetRegisterClass *Src0RC = Src0.isReg()
4015                                             ? MRI.getRegClass(Src0.getReg())
4016                                             : &AMDGPU::VReg_64RegClass;
4017     const TargetRegisterClass *Src1RC = Src1.isReg()
4018                                             ? MRI.getRegClass(Src1.getReg())
4019                                             : &AMDGPU::VReg_64RegClass;
4020 
4021     const TargetRegisterClass *Src0SubRC =
4022         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
4023     const TargetRegisterClass *Src1SubRC =
4024         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
4025 
4026     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
4027         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
4028     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
4029         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
4030 
4031     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
4032         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
4033     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
4034         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
4035 
4036     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
4037     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
4038                                .addReg(CarryReg, RegState::Define)
4039                                .add(SrcReg0Sub0)
4040                                .add(SrcReg1Sub0)
4041                                .addImm(0); // clamp bit
4042 
4043     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
4044     MachineInstr *HiHalf =
4045         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4046             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4047             .add(SrcReg0Sub1)
4048             .add(SrcReg1Sub1)
4049             .addReg(CarryReg, RegState::Kill)
4050             .addImm(0); // clamp bit
4051 
4052     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4053         .addReg(DestSub0)
4054         .addImm(AMDGPU::sub0)
4055         .addReg(DestSub1)
4056         .addImm(AMDGPU::sub1);
4057     TII->legalizeOperands(*LoHalf);
4058     TII->legalizeOperands(*HiHalf);
4059     MI.eraseFromParent();
4060     return BB;
4061   }
4062   case AMDGPU::S_ADD_CO_PSEUDO:
4063   case AMDGPU::S_SUB_CO_PSEUDO: {
4064     // This pseudo has a chance to be selected
4065     // only from uniform add/subcarry node. All the VGPR operands
4066     // therefore assumed to be splat vectors.
4067     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4068     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4069     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4070     MachineBasicBlock::iterator MII = MI;
4071     const DebugLoc &DL = MI.getDebugLoc();
4072     MachineOperand &Dest = MI.getOperand(0);
4073     MachineOperand &CarryDest = MI.getOperand(1);
4074     MachineOperand &Src0 = MI.getOperand(2);
4075     MachineOperand &Src1 = MI.getOperand(3);
4076     MachineOperand &Src2 = MI.getOperand(4);
4077     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4078                        ? AMDGPU::S_ADDC_U32
4079                        : AMDGPU::S_SUBB_U32;
4080     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4081       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4082       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4083           .addReg(Src0.getReg());
4084       Src0.setReg(RegOp0);
4085     }
4086     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4087       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4088       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4089           .addReg(Src1.getReg());
4090       Src1.setReg(RegOp1);
4091     }
4092     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4093     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4094       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4095           .addReg(Src2.getReg());
4096       Src2.setReg(RegOp2);
4097     }
4098 
4099     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4100     if (TRI->getRegSizeInBits(*Src2RC) == 64) {
4101       if (ST.hasScalarCompareEq64()) {
4102         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4103             .addReg(Src2.getReg())
4104             .addImm(0);
4105       } else {
4106         const TargetRegisterClass *SubRC =
4107             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4108         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4109             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4110         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4111             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4112         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4113 
4114         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4115             .add(Src2Sub0)
4116             .add(Src2Sub1);
4117 
4118         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4119             .addReg(Src2_32, RegState::Kill)
4120             .addImm(0);
4121       }
4122     } else {
4123       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4124           .addReg(Src2.getReg())
4125           .addImm(0);
4126     }
4127 
4128     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4129 
4130     BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg())
4131       .addReg(AMDGPU::SCC);
4132     MI.eraseFromParent();
4133     return BB;
4134   }
4135   case AMDGPU::SI_INIT_M0: {
4136     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4137             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4138         .add(MI.getOperand(0));
4139     MI.eraseFromParent();
4140     return BB;
4141   }
4142   case AMDGPU::GET_GROUPSTATICSIZE: {
4143     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4144            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4145     DebugLoc DL = MI.getDebugLoc();
4146     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4147         .add(MI.getOperand(0))
4148         .addImm(MFI->getLDSSize());
4149     MI.eraseFromParent();
4150     return BB;
4151   }
4152   case AMDGPU::SI_INDIRECT_SRC_V1:
4153   case AMDGPU::SI_INDIRECT_SRC_V2:
4154   case AMDGPU::SI_INDIRECT_SRC_V4:
4155   case AMDGPU::SI_INDIRECT_SRC_V8:
4156   case AMDGPU::SI_INDIRECT_SRC_V16:
4157   case AMDGPU::SI_INDIRECT_SRC_V32:
4158     return emitIndirectSrc(MI, *BB, *getSubtarget());
4159   case AMDGPU::SI_INDIRECT_DST_V1:
4160   case AMDGPU::SI_INDIRECT_DST_V2:
4161   case AMDGPU::SI_INDIRECT_DST_V4:
4162   case AMDGPU::SI_INDIRECT_DST_V8:
4163   case AMDGPU::SI_INDIRECT_DST_V16:
4164   case AMDGPU::SI_INDIRECT_DST_V32:
4165     return emitIndirectDst(MI, *BB, *getSubtarget());
4166   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4167   case AMDGPU::SI_KILL_I1_PSEUDO:
4168     return splitKillBlock(MI, BB);
4169   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4170     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4171     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4172     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4173 
4174     Register Dst = MI.getOperand(0).getReg();
4175     Register Src0 = MI.getOperand(1).getReg();
4176     Register Src1 = MI.getOperand(2).getReg();
4177     const DebugLoc &DL = MI.getDebugLoc();
4178     Register SrcCond = MI.getOperand(3).getReg();
4179 
4180     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4181     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4182     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4183     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4184 
4185     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4186       .addReg(SrcCond);
4187     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4188       .addImm(0)
4189       .addReg(Src0, 0, AMDGPU::sub0)
4190       .addImm(0)
4191       .addReg(Src1, 0, AMDGPU::sub0)
4192       .addReg(SrcCondCopy);
4193     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4194       .addImm(0)
4195       .addReg(Src0, 0, AMDGPU::sub1)
4196       .addImm(0)
4197       .addReg(Src1, 0, AMDGPU::sub1)
4198       .addReg(SrcCondCopy);
4199 
4200     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4201       .addReg(DstLo)
4202       .addImm(AMDGPU::sub0)
4203       .addReg(DstHi)
4204       .addImm(AMDGPU::sub1);
4205     MI.eraseFromParent();
4206     return BB;
4207   }
4208   case AMDGPU::SI_BR_UNDEF: {
4209     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4210     const DebugLoc &DL = MI.getDebugLoc();
4211     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4212                            .add(MI.getOperand(0));
4213     Br->getOperand(1).setIsUndef(true); // read undef SCC
4214     MI.eraseFromParent();
4215     return BB;
4216   }
4217   case AMDGPU::ADJCALLSTACKUP:
4218   case AMDGPU::ADJCALLSTACKDOWN: {
4219     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4220     MachineInstrBuilder MIB(*MF, &MI);
4221     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4222        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4223     return BB;
4224   }
4225   case AMDGPU::SI_CALL_ISEL: {
4226     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4227     const DebugLoc &DL = MI.getDebugLoc();
4228 
4229     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4230 
4231     MachineInstrBuilder MIB;
4232     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4233 
4234     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
4235       MIB.add(MI.getOperand(I));
4236 
4237     MIB.cloneMemRefs(MI);
4238     MI.eraseFromParent();
4239     return BB;
4240   }
4241   case AMDGPU::V_ADD_CO_U32_e32:
4242   case AMDGPU::V_SUB_CO_U32_e32:
4243   case AMDGPU::V_SUBREV_CO_U32_e32: {
4244     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4245     const DebugLoc &DL = MI.getDebugLoc();
4246     unsigned Opc = MI.getOpcode();
4247 
4248     bool NeedClampOperand = false;
4249     if (TII->pseudoToMCOpcode(Opc) == -1) {
4250       Opc = AMDGPU::getVOPe64(Opc);
4251       NeedClampOperand = true;
4252     }
4253 
4254     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4255     if (TII->isVOP3(*I)) {
4256       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4257       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4258       I.addReg(TRI->getVCC(), RegState::Define);
4259     }
4260     I.add(MI.getOperand(1))
4261      .add(MI.getOperand(2));
4262     if (NeedClampOperand)
4263       I.addImm(0); // clamp bit for e64 encoding
4264 
4265     TII->legalizeOperands(*I);
4266 
4267     MI.eraseFromParent();
4268     return BB;
4269   }
4270   case AMDGPU::V_ADDC_U32_e32:
4271   case AMDGPU::V_SUBB_U32_e32:
4272   case AMDGPU::V_SUBBREV_U32_e32:
4273     // These instructions have an implicit use of vcc which counts towards the
4274     // constant bus limit.
4275     TII->legalizeOperands(MI);
4276     return BB;
4277   case AMDGPU::DS_GWS_INIT:
4278   case AMDGPU::DS_GWS_SEMA_BR:
4279   case AMDGPU::DS_GWS_BARRIER:
4280     if (Subtarget->needsAlignedVGPRs()) {
4281       // Add implicit aligned super-reg to force alignment on the data operand.
4282       const DebugLoc &DL = MI.getDebugLoc();
4283       MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4284       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
4285       MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0);
4286       Register DataReg = Op->getReg();
4287       bool IsAGPR = TRI->isAGPR(MRI, DataReg);
4288       Register Undef = MRI.createVirtualRegister(
4289           IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass);
4290       BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef);
4291       Register NewVR =
4292           MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass
4293                                            : &AMDGPU::VReg_64_Align2RegClass);
4294       BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR)
4295           .addReg(DataReg, 0, Op->getSubReg())
4296           .addImm(AMDGPU::sub0)
4297           .addReg(Undef)
4298           .addImm(AMDGPU::sub1);
4299       Op->setReg(NewVR);
4300       Op->setSubReg(AMDGPU::sub0);
4301       MI.addOperand(MachineOperand::CreateReg(NewVR, false, true));
4302     }
4303     LLVM_FALLTHROUGH;
4304   case AMDGPU::DS_GWS_SEMA_V:
4305   case AMDGPU::DS_GWS_SEMA_P:
4306   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4307     // A s_waitcnt 0 is required to be the instruction immediately following.
4308     if (getSubtarget()->hasGWSAutoReplay()) {
4309       bundleInstWithWaitcnt(MI);
4310       return BB;
4311     }
4312 
4313     return emitGWSMemViolTestLoop(MI, BB);
4314   case AMDGPU::S_SETREG_B32: {
4315     // Try to optimize cases that only set the denormal mode or rounding mode.
4316     //
4317     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4318     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4319     // instead.
4320     //
4321     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4322     // allow you to have a no side effect instruction in the output of a
4323     // sideeffecting pattern.
4324     unsigned ID, Offset, Width;
4325     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4326     if (ID != AMDGPU::Hwreg::ID_MODE)
4327       return BB;
4328 
4329     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4330     const unsigned SetMask = WidthMask << Offset;
4331 
4332     if (getSubtarget()->hasDenormModeInst()) {
4333       unsigned SetDenormOp = 0;
4334       unsigned SetRoundOp = 0;
4335 
4336       // The dedicated instructions can only set the whole denorm or round mode
4337       // at once, not a subset of bits in either.
4338       if (SetMask ==
4339           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4340         // If this fully sets both the round and denorm mode, emit the two
4341         // dedicated instructions for these.
4342         SetRoundOp = AMDGPU::S_ROUND_MODE;
4343         SetDenormOp = AMDGPU::S_DENORM_MODE;
4344       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4345         SetRoundOp = AMDGPU::S_ROUND_MODE;
4346       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4347         SetDenormOp = AMDGPU::S_DENORM_MODE;
4348       }
4349 
4350       if (SetRoundOp || SetDenormOp) {
4351         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4352         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4353         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4354           unsigned ImmVal = Def->getOperand(1).getImm();
4355           if (SetRoundOp) {
4356             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4357                 .addImm(ImmVal & 0xf);
4358 
4359             // If we also have the denorm mode, get just the denorm mode bits.
4360             ImmVal >>= 4;
4361           }
4362 
4363           if (SetDenormOp) {
4364             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4365                 .addImm(ImmVal & 0xf);
4366           }
4367 
4368           MI.eraseFromParent();
4369           return BB;
4370         }
4371       }
4372     }
4373 
4374     // If only FP bits are touched, used the no side effects pseudo.
4375     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4376                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4377       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4378 
4379     return BB;
4380   }
4381   default:
4382     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4383   }
4384 }
4385 
4386 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4387   return isTypeLegal(VT.getScalarType());
4388 }
4389 
4390 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4391   // This currently forces unfolding various combinations of fsub into fma with
4392   // free fneg'd operands. As long as we have fast FMA (controlled by
4393   // isFMAFasterThanFMulAndFAdd), we should perform these.
4394 
4395   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4396   // most of these combines appear to be cycle neutral but save on instruction
4397   // count / code size.
4398   return true;
4399 }
4400 
4401 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4402                                          EVT VT) const {
4403   if (!VT.isVector()) {
4404     return MVT::i1;
4405   }
4406   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4407 }
4408 
4409 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4410   // TODO: Should i16 be used always if legal? For now it would force VALU
4411   // shifts.
4412   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4413 }
4414 
4415 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4416   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4417              ? Ty.changeElementSize(16)
4418              : Ty.changeElementSize(32);
4419 }
4420 
4421 // Answering this is somewhat tricky and depends on the specific device which
4422 // have different rates for fma or all f64 operations.
4423 //
4424 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4425 // regardless of which device (although the number of cycles differs between
4426 // devices), so it is always profitable for f64.
4427 //
4428 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4429 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4430 // which we can always do even without fused FP ops since it returns the same
4431 // result as the separate operations and since it is always full
4432 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4433 // however does not support denormals, so we do report fma as faster if we have
4434 // a fast fma device and require denormals.
4435 //
4436 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4437                                                   EVT VT) const {
4438   VT = VT.getScalarType();
4439 
4440   switch (VT.getSimpleVT().SimpleTy) {
4441   case MVT::f32: {
4442     // If mad is not available this depends only on if f32 fma is full rate.
4443     if (!Subtarget->hasMadMacF32Insts())
4444       return Subtarget->hasFastFMAF32();
4445 
4446     // Otherwise f32 mad is always full rate and returns the same result as
4447     // the separate operations so should be preferred over fma.
4448     // However does not support denomals.
4449     if (hasFP32Denormals(MF))
4450       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4451 
4452     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4453     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4454   }
4455   case MVT::f64:
4456     return true;
4457   case MVT::f16:
4458     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4459   default:
4460     break;
4461   }
4462 
4463   return false;
4464 }
4465 
4466 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4467                                    const SDNode *N) const {
4468   // TODO: Check future ftz flag
4469   // v_mad_f32/v_mac_f32 do not support denormals.
4470   EVT VT = N->getValueType(0);
4471   if (VT == MVT::f32)
4472     return Subtarget->hasMadMacF32Insts() &&
4473            !hasFP32Denormals(DAG.getMachineFunction());
4474   if (VT == MVT::f16) {
4475     return Subtarget->hasMadF16() &&
4476            !hasFP64FP16Denormals(DAG.getMachineFunction());
4477   }
4478 
4479   return false;
4480 }
4481 
4482 //===----------------------------------------------------------------------===//
4483 // Custom DAG Lowering Operations
4484 //===----------------------------------------------------------------------===//
4485 
4486 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4487 // wider vector type is legal.
4488 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4489                                              SelectionDAG &DAG) const {
4490   unsigned Opc = Op.getOpcode();
4491   EVT VT = Op.getValueType();
4492   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4493 
4494   SDValue Lo, Hi;
4495   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4496 
4497   SDLoc SL(Op);
4498   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4499                              Op->getFlags());
4500   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4501                              Op->getFlags());
4502 
4503   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4504 }
4505 
4506 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4507 // wider vector type is legal.
4508 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4509                                               SelectionDAG &DAG) const {
4510   unsigned Opc = Op.getOpcode();
4511   EVT VT = Op.getValueType();
4512   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4513          VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32);
4514 
4515   SDValue Lo0, Hi0;
4516   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4517   SDValue Lo1, Hi1;
4518   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4519 
4520   SDLoc SL(Op);
4521 
4522   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4523                              Op->getFlags());
4524   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4525                              Op->getFlags());
4526 
4527   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4528 }
4529 
4530 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4531                                               SelectionDAG &DAG) const {
4532   unsigned Opc = Op.getOpcode();
4533   EVT VT = Op.getValueType();
4534   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4535          VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32);
4536 
4537   SDValue Lo0, Hi0;
4538   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4539   SDValue Lo1, Hi1;
4540   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4541   SDValue Lo2, Hi2;
4542   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4543 
4544   SDLoc SL(Op);
4545 
4546   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4547                              Op->getFlags());
4548   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4549                              Op->getFlags());
4550 
4551   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4552 }
4553 
4554 
4555 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4556   switch (Op.getOpcode()) {
4557   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4558   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4559   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4560   case ISD::LOAD: {
4561     SDValue Result = LowerLOAD(Op, DAG);
4562     assert((!Result.getNode() ||
4563             Result.getNode()->getNumValues() == 2) &&
4564            "Load should return a value and a chain");
4565     return Result;
4566   }
4567 
4568   case ISD::FSIN:
4569   case ISD::FCOS:
4570     return LowerTrig(Op, DAG);
4571   case ISD::SELECT: return LowerSELECT(Op, DAG);
4572   case ISD::FDIV: return LowerFDIV(Op, DAG);
4573   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4574   case ISD::STORE: return LowerSTORE(Op, DAG);
4575   case ISD::GlobalAddress: {
4576     MachineFunction &MF = DAG.getMachineFunction();
4577     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4578     return LowerGlobalAddress(MFI, Op, DAG);
4579   }
4580   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4581   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4582   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4583   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4584   case ISD::INSERT_SUBVECTOR:
4585     return lowerINSERT_SUBVECTOR(Op, DAG);
4586   case ISD::INSERT_VECTOR_ELT:
4587     return lowerINSERT_VECTOR_ELT(Op, DAG);
4588   case ISD::EXTRACT_VECTOR_ELT:
4589     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4590   case ISD::VECTOR_SHUFFLE:
4591     return lowerVECTOR_SHUFFLE(Op, DAG);
4592   case ISD::BUILD_VECTOR:
4593     return lowerBUILD_VECTOR(Op, DAG);
4594   case ISD::FP_ROUND:
4595     return lowerFP_ROUND(Op, DAG);
4596   case ISD::TRAP:
4597     return lowerTRAP(Op, DAG);
4598   case ISD::DEBUGTRAP:
4599     return lowerDEBUGTRAP(Op, DAG);
4600   case ISD::FABS:
4601   case ISD::FNEG:
4602   case ISD::FCANONICALIZE:
4603   case ISD::BSWAP:
4604     return splitUnaryVectorOp(Op, DAG);
4605   case ISD::FMINNUM:
4606   case ISD::FMAXNUM:
4607     return lowerFMINNUM_FMAXNUM(Op, DAG);
4608   case ISD::FMA:
4609     return splitTernaryVectorOp(Op, DAG);
4610   case ISD::FP_TO_SINT:
4611   case ISD::FP_TO_UINT:
4612     return LowerFP_TO_INT(Op, DAG);
4613   case ISD::SHL:
4614   case ISD::SRA:
4615   case ISD::SRL:
4616   case ISD::ADD:
4617   case ISD::SUB:
4618   case ISD::MUL:
4619   case ISD::SMIN:
4620   case ISD::SMAX:
4621   case ISD::UMIN:
4622   case ISD::UMAX:
4623   case ISD::FADD:
4624   case ISD::FMUL:
4625   case ISD::FMINNUM_IEEE:
4626   case ISD::FMAXNUM_IEEE:
4627   case ISD::UADDSAT:
4628   case ISD::USUBSAT:
4629   case ISD::SADDSAT:
4630   case ISD::SSUBSAT:
4631     return splitBinaryVectorOp(Op, DAG);
4632   case ISD::SMULO:
4633   case ISD::UMULO:
4634     return lowerXMULO(Op, DAG);
4635   case ISD::DYNAMIC_STACKALLOC:
4636     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4637   }
4638   return SDValue();
4639 }
4640 
4641 // Used for D16: Casts the result of an instruction into the right vector,
4642 // packs values if loads return unpacked values.
4643 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4644                                        const SDLoc &DL,
4645                                        SelectionDAG &DAG, bool Unpacked) {
4646   if (!LoadVT.isVector())
4647     return Result;
4648 
4649   // Cast back to the original packed type or to a larger type that is a
4650   // multiple of 32 bit for D16. Widening the return type is a required for
4651   // legalization.
4652   EVT FittingLoadVT = LoadVT;
4653   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4654     FittingLoadVT =
4655         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4656                          LoadVT.getVectorNumElements() + 1);
4657   }
4658 
4659   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4660     // Truncate to v2i16/v4i16.
4661     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4662 
4663     // Workaround legalizer not scalarizing truncate after vector op
4664     // legalization but not creating intermediate vector trunc.
4665     SmallVector<SDValue, 4> Elts;
4666     DAG.ExtractVectorElements(Result, Elts);
4667     for (SDValue &Elt : Elts)
4668       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4669 
4670     // Pad illegal v1i16/v3fi6 to v4i16
4671     if ((LoadVT.getVectorNumElements() % 2) == 1)
4672       Elts.push_back(DAG.getUNDEF(MVT::i16));
4673 
4674     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4675 
4676     // Bitcast to original type (v2f16/v4f16).
4677     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4678   }
4679 
4680   // Cast back to the original packed type.
4681   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4682 }
4683 
4684 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4685                                               MemSDNode *M,
4686                                               SelectionDAG &DAG,
4687                                               ArrayRef<SDValue> Ops,
4688                                               bool IsIntrinsic) const {
4689   SDLoc DL(M);
4690 
4691   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4692   EVT LoadVT = M->getValueType(0);
4693 
4694   EVT EquivLoadVT = LoadVT;
4695   if (LoadVT.isVector()) {
4696     if (Unpacked) {
4697       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4698                                      LoadVT.getVectorNumElements());
4699     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4700       // Widen v3f16 to legal type
4701       EquivLoadVT =
4702           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4703                            LoadVT.getVectorNumElements() + 1);
4704     }
4705   }
4706 
4707   // Change from v4f16/v2f16 to EquivLoadVT.
4708   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4709 
4710   SDValue Load
4711     = DAG.getMemIntrinsicNode(
4712       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4713       VTList, Ops, M->getMemoryVT(),
4714       M->getMemOperand());
4715 
4716   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4717 
4718   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4719 }
4720 
4721 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4722                                              SelectionDAG &DAG,
4723                                              ArrayRef<SDValue> Ops) const {
4724   SDLoc DL(M);
4725   EVT LoadVT = M->getValueType(0);
4726   EVT EltType = LoadVT.getScalarType();
4727   EVT IntVT = LoadVT.changeTypeToInteger();
4728 
4729   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4730 
4731   unsigned Opc =
4732       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4733 
4734   if (IsD16) {
4735     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4736   }
4737 
4738   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4739   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4740     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4741 
4742   if (isTypeLegal(LoadVT)) {
4743     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4744                                M->getMemOperand(), DAG);
4745   }
4746 
4747   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4748   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4749   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4750                                         M->getMemOperand(), DAG);
4751   return DAG.getMergeValues(
4752       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4753       DL);
4754 }
4755 
4756 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4757                                   SDNode *N, SelectionDAG &DAG) {
4758   EVT VT = N->getValueType(0);
4759   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4760   unsigned CondCode = CD->getZExtValue();
4761   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4762     return DAG.getUNDEF(VT);
4763 
4764   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4765 
4766   SDValue LHS = N->getOperand(1);
4767   SDValue RHS = N->getOperand(2);
4768 
4769   SDLoc DL(N);
4770 
4771   EVT CmpVT = LHS.getValueType();
4772   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4773     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4774       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4775     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4776     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4777   }
4778 
4779   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4780 
4781   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4782   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4783 
4784   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4785                               DAG.getCondCode(CCOpcode));
4786   if (VT.bitsEq(CCVT))
4787     return SetCC;
4788   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4789 }
4790 
4791 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4792                                   SDNode *N, SelectionDAG &DAG) {
4793   EVT VT = N->getValueType(0);
4794   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4795 
4796   unsigned CondCode = CD->getZExtValue();
4797   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4798     return DAG.getUNDEF(VT);
4799 
4800   SDValue Src0 = N->getOperand(1);
4801   SDValue Src1 = N->getOperand(2);
4802   EVT CmpVT = Src0.getValueType();
4803   SDLoc SL(N);
4804 
4805   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4806     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4807     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4808   }
4809 
4810   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4811   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4812   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4813   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4814   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4815                               Src1, DAG.getCondCode(CCOpcode));
4816   if (VT.bitsEq(CCVT))
4817     return SetCC;
4818   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4819 }
4820 
4821 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4822                                     SelectionDAG &DAG) {
4823   EVT VT = N->getValueType(0);
4824   SDValue Src = N->getOperand(1);
4825   SDLoc SL(N);
4826 
4827   if (Src.getOpcode() == ISD::SETCC) {
4828     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4829     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4830                        Src.getOperand(1), Src.getOperand(2));
4831   }
4832   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4833     // (ballot 0) -> 0
4834     if (Arg->isNullValue())
4835       return DAG.getConstant(0, SL, VT);
4836 
4837     // (ballot 1) -> EXEC/EXEC_LO
4838     if (Arg->isOne()) {
4839       Register Exec;
4840       if (VT.getScalarSizeInBits() == 32)
4841         Exec = AMDGPU::EXEC_LO;
4842       else if (VT.getScalarSizeInBits() == 64)
4843         Exec = AMDGPU::EXEC;
4844       else
4845         return SDValue();
4846 
4847       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4848     }
4849   }
4850 
4851   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4852   // ISD::SETNE)
4853   return DAG.getNode(
4854       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4855       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4856 }
4857 
4858 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4859                                           SmallVectorImpl<SDValue> &Results,
4860                                           SelectionDAG &DAG) const {
4861   switch (N->getOpcode()) {
4862   case ISD::INSERT_VECTOR_ELT: {
4863     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4864       Results.push_back(Res);
4865     return;
4866   }
4867   case ISD::EXTRACT_VECTOR_ELT: {
4868     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4869       Results.push_back(Res);
4870     return;
4871   }
4872   case ISD::INTRINSIC_WO_CHAIN: {
4873     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4874     switch (IID) {
4875     case Intrinsic::amdgcn_cvt_pkrtz: {
4876       SDValue Src0 = N->getOperand(1);
4877       SDValue Src1 = N->getOperand(2);
4878       SDLoc SL(N);
4879       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4880                                 Src0, Src1);
4881       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4882       return;
4883     }
4884     case Intrinsic::amdgcn_cvt_pknorm_i16:
4885     case Intrinsic::amdgcn_cvt_pknorm_u16:
4886     case Intrinsic::amdgcn_cvt_pk_i16:
4887     case Intrinsic::amdgcn_cvt_pk_u16: {
4888       SDValue Src0 = N->getOperand(1);
4889       SDValue Src1 = N->getOperand(2);
4890       SDLoc SL(N);
4891       unsigned Opcode;
4892 
4893       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4894         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4895       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4896         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4897       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4898         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4899       else
4900         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4901 
4902       EVT VT = N->getValueType(0);
4903       if (isTypeLegal(VT))
4904         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4905       else {
4906         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4907         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4908       }
4909       return;
4910     }
4911     }
4912     break;
4913   }
4914   case ISD::INTRINSIC_W_CHAIN: {
4915     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4916       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4917         // FIXME: Hacky
4918         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
4919           Results.push_back(Res.getOperand(I));
4920         }
4921       } else {
4922         Results.push_back(Res);
4923         Results.push_back(Res.getValue(1));
4924       }
4925       return;
4926     }
4927 
4928     break;
4929   }
4930   case ISD::SELECT: {
4931     SDLoc SL(N);
4932     EVT VT = N->getValueType(0);
4933     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4934     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4935     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4936 
4937     EVT SelectVT = NewVT;
4938     if (NewVT.bitsLT(MVT::i32)) {
4939       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4940       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4941       SelectVT = MVT::i32;
4942     }
4943 
4944     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4945                                     N->getOperand(0), LHS, RHS);
4946 
4947     if (NewVT != SelectVT)
4948       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4949     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4950     return;
4951   }
4952   case ISD::FNEG: {
4953     if (N->getValueType(0) != MVT::v2f16)
4954       break;
4955 
4956     SDLoc SL(N);
4957     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4958 
4959     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4960                              BC,
4961                              DAG.getConstant(0x80008000, SL, MVT::i32));
4962     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4963     return;
4964   }
4965   case ISD::FABS: {
4966     if (N->getValueType(0) != MVT::v2f16)
4967       break;
4968 
4969     SDLoc SL(N);
4970     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4971 
4972     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4973                              BC,
4974                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4975     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4976     return;
4977   }
4978   default:
4979     break;
4980   }
4981 }
4982 
4983 /// Helper function for LowerBRCOND
4984 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4985 
4986   SDNode *Parent = Value.getNode();
4987   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4988        I != E; ++I) {
4989 
4990     if (I.getUse().get() != Value)
4991       continue;
4992 
4993     if (I->getOpcode() == Opcode)
4994       return *I;
4995   }
4996   return nullptr;
4997 }
4998 
4999 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
5000   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
5001     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
5002     case Intrinsic::amdgcn_if:
5003       return AMDGPUISD::IF;
5004     case Intrinsic::amdgcn_else:
5005       return AMDGPUISD::ELSE;
5006     case Intrinsic::amdgcn_loop:
5007       return AMDGPUISD::LOOP;
5008     case Intrinsic::amdgcn_end_cf:
5009       llvm_unreachable("should not occur");
5010     default:
5011       return 0;
5012     }
5013   }
5014 
5015   // break, if_break, else_break are all only used as inputs to loop, not
5016   // directly as branch conditions.
5017   return 0;
5018 }
5019 
5020 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
5021   const Triple &TT = getTargetMachine().getTargetTriple();
5022   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5023           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5024          AMDGPU::shouldEmitConstantsToTextSection(TT);
5025 }
5026 
5027 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
5028   // FIXME: Either avoid relying on address space here or change the default
5029   // address space for functions to avoid the explicit check.
5030   return (GV->getValueType()->isFunctionTy() ||
5031           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
5032          !shouldEmitFixup(GV) &&
5033          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
5034 }
5035 
5036 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
5037   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
5038 }
5039 
5040 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
5041   if (!GV->hasExternalLinkage())
5042     return true;
5043 
5044   const auto OS = getTargetMachine().getTargetTriple().getOS();
5045   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
5046 }
5047 
5048 /// This transforms the control flow intrinsics to get the branch destination as
5049 /// last parameter, also switches branch target with BR if the need arise
5050 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
5051                                       SelectionDAG &DAG) const {
5052   SDLoc DL(BRCOND);
5053 
5054   SDNode *Intr = BRCOND.getOperand(1).getNode();
5055   SDValue Target = BRCOND.getOperand(2);
5056   SDNode *BR = nullptr;
5057   SDNode *SetCC = nullptr;
5058 
5059   if (Intr->getOpcode() == ISD::SETCC) {
5060     // As long as we negate the condition everything is fine
5061     SetCC = Intr;
5062     Intr = SetCC->getOperand(0).getNode();
5063 
5064   } else {
5065     // Get the target from BR if we don't negate the condition
5066     BR = findUser(BRCOND, ISD::BR);
5067     assert(BR && "brcond missing unconditional branch user");
5068     Target = BR->getOperand(1);
5069   }
5070 
5071   unsigned CFNode = isCFIntrinsic(Intr);
5072   if (CFNode == 0) {
5073     // This is a uniform branch so we don't need to legalize.
5074     return BRCOND;
5075   }
5076 
5077   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5078                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5079 
5080   assert(!SetCC ||
5081         (SetCC->getConstantOperandVal(1) == 1 &&
5082          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5083                                                              ISD::SETNE));
5084 
5085   // operands of the new intrinsic call
5086   SmallVector<SDValue, 4> Ops;
5087   if (HaveChain)
5088     Ops.push_back(BRCOND.getOperand(0));
5089 
5090   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5091   Ops.push_back(Target);
5092 
5093   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5094 
5095   // build the new intrinsic call
5096   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5097 
5098   if (!HaveChain) {
5099     SDValue Ops[] =  {
5100       SDValue(Result, 0),
5101       BRCOND.getOperand(0)
5102     };
5103 
5104     Result = DAG.getMergeValues(Ops, DL).getNode();
5105   }
5106 
5107   if (BR) {
5108     // Give the branch instruction our target
5109     SDValue Ops[] = {
5110       BR->getOperand(0),
5111       BRCOND.getOperand(2)
5112     };
5113     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5114     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5115   }
5116 
5117   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5118 
5119   // Copy the intrinsic results to registers
5120   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5121     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5122     if (!CopyToReg)
5123       continue;
5124 
5125     Chain = DAG.getCopyToReg(
5126       Chain, DL,
5127       CopyToReg->getOperand(1),
5128       SDValue(Result, i - 1),
5129       SDValue());
5130 
5131     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5132   }
5133 
5134   // Remove the old intrinsic from the chain
5135   DAG.ReplaceAllUsesOfValueWith(
5136     SDValue(Intr, Intr->getNumValues() - 1),
5137     Intr->getOperand(0));
5138 
5139   return Chain;
5140 }
5141 
5142 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5143                                           SelectionDAG &DAG) const {
5144   MVT VT = Op.getSimpleValueType();
5145   SDLoc DL(Op);
5146   // Checking the depth
5147   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5148     return DAG.getConstant(0, DL, VT);
5149 
5150   MachineFunction &MF = DAG.getMachineFunction();
5151   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5152   // Check for kernel and shader functions
5153   if (Info->isEntryFunction())
5154     return DAG.getConstant(0, DL, VT);
5155 
5156   MachineFrameInfo &MFI = MF.getFrameInfo();
5157   // There is a call to @llvm.returnaddress in this function
5158   MFI.setReturnAddressIsTaken(true);
5159 
5160   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5161   // Get the return address reg and mark it as an implicit live-in
5162   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5163 
5164   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5165 }
5166 
5167 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5168                                             SDValue Op,
5169                                             const SDLoc &DL,
5170                                             EVT VT) const {
5171   return Op.getValueType().bitsLE(VT) ?
5172       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5173     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5174                 DAG.getTargetConstant(0, DL, MVT::i32));
5175 }
5176 
5177 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5178   assert(Op.getValueType() == MVT::f16 &&
5179          "Do not know how to custom lower FP_ROUND for non-f16 type");
5180 
5181   SDValue Src = Op.getOperand(0);
5182   EVT SrcVT = Src.getValueType();
5183   if (SrcVT != MVT::f64)
5184     return Op;
5185 
5186   SDLoc DL(Op);
5187 
5188   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5189   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5190   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5191 }
5192 
5193 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5194                                                SelectionDAG &DAG) const {
5195   EVT VT = Op.getValueType();
5196   const MachineFunction &MF = DAG.getMachineFunction();
5197   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5198   bool IsIEEEMode = Info->getMode().IEEE;
5199 
5200   // FIXME: Assert during selection that this is only selected for
5201   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5202   // mode functions, but this happens to be OK since it's only done in cases
5203   // where there is known no sNaN.
5204   if (IsIEEEMode)
5205     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5206 
5207   if (VT == MVT::v4f16)
5208     return splitBinaryVectorOp(Op, DAG);
5209   return Op;
5210 }
5211 
5212 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5213   EVT VT = Op.getValueType();
5214   SDLoc SL(Op);
5215   SDValue LHS = Op.getOperand(0);
5216   SDValue RHS = Op.getOperand(1);
5217   bool isSigned = Op.getOpcode() == ISD::SMULO;
5218 
5219   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5220     const APInt &C = RHSC->getAPIntValue();
5221     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5222     if (C.isPowerOf2()) {
5223       // smulo(x, signed_min) is same as umulo(x, signed_min).
5224       bool UseArithShift = isSigned && !C.isMinSignedValue();
5225       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5226       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5227       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5228           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5229                       SL, VT, Result, ShiftAmt),
5230           LHS, ISD::SETNE);
5231       return DAG.getMergeValues({ Result, Overflow }, SL);
5232     }
5233   }
5234 
5235   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5236   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5237                             SL, VT, LHS, RHS);
5238 
5239   SDValue Sign = isSigned
5240     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5241                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5242     : DAG.getConstant(0, SL, VT);
5243   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5244 
5245   return DAG.getMergeValues({ Result, Overflow }, SL);
5246 }
5247 
5248 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5249   if (!Subtarget->isTrapHandlerEnabled() ||
5250       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5251     return lowerTrapEndpgm(Op, DAG);
5252 
5253   if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) {
5254     switch (*HsaAbiVer) {
5255     case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
5256     case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
5257       return lowerTrapHsaQueuePtr(Op, DAG);
5258     case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
5259       return Subtarget->supportsGetDoorbellID() ?
5260           lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG);
5261     }
5262   }
5263 
5264   llvm_unreachable("Unknown trap handler");
5265 }
5266 
5267 SDValue SITargetLowering::lowerTrapEndpgm(
5268     SDValue Op, SelectionDAG &DAG) const {
5269   SDLoc SL(Op);
5270   SDValue Chain = Op.getOperand(0);
5271   return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5272 }
5273 
5274 SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5275     SDValue Op, SelectionDAG &DAG) const {
5276   SDLoc SL(Op);
5277   SDValue Chain = Op.getOperand(0);
5278 
5279   MachineFunction &MF = DAG.getMachineFunction();
5280   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5281   Register UserSGPR = Info->getQueuePtrUserSGPR();
5282   assert(UserSGPR != AMDGPU::NoRegister);
5283   SDValue QueuePtr = CreateLiveInRegister(
5284     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5285   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5286   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5287                                    QueuePtr, SDValue());
5288 
5289   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5290   SDValue Ops[] = {
5291     ToReg,
5292     DAG.getTargetConstant(TrapID, SL, MVT::i16),
5293     SGPR01,
5294     ToReg.getValue(1)
5295   };
5296   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5297 }
5298 
5299 SDValue SITargetLowering::lowerTrapHsa(
5300     SDValue Op, SelectionDAG &DAG) const {
5301   SDLoc SL(Op);
5302   SDValue Chain = Op.getOperand(0);
5303 
5304   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5305   SDValue Ops[] = {
5306     Chain,
5307     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5308   };
5309   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5310 }
5311 
5312 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5313   SDLoc SL(Op);
5314   SDValue Chain = Op.getOperand(0);
5315   MachineFunction &MF = DAG.getMachineFunction();
5316 
5317   if (!Subtarget->isTrapHandlerEnabled() ||
5318       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5319     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5320                                      "debugtrap handler not supported",
5321                                      Op.getDebugLoc(),
5322                                      DS_Warning);
5323     LLVMContext &Ctx = MF.getFunction().getContext();
5324     Ctx.diagnose(NoTrap);
5325     return Chain;
5326   }
5327 
5328   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5329   SDValue Ops[] = {
5330     Chain,
5331     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5332   };
5333   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5334 }
5335 
5336 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5337                                              SelectionDAG &DAG) const {
5338   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5339   if (Subtarget->hasApertureRegs()) {
5340     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5341         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5342         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5343     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5344         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5345         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5346     unsigned Encoding =
5347         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5348         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5349         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5350 
5351     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5352     SDValue ApertureReg = SDValue(
5353         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5354     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5355     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5356   }
5357 
5358   MachineFunction &MF = DAG.getMachineFunction();
5359   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5360   Register UserSGPR = Info->getQueuePtrUserSGPR();
5361   assert(UserSGPR != AMDGPU::NoRegister);
5362 
5363   SDValue QueuePtr = CreateLiveInRegister(
5364     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5365 
5366   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5367   // private_segment_aperture_base_hi.
5368   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5369 
5370   SDValue Ptr =
5371       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5372 
5373   // TODO: Use custom target PseudoSourceValue.
5374   // TODO: We should use the value from the IR intrinsic call, but it might not
5375   // be available and how do we get it?
5376   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5377   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5378                      commonAlignment(Align(64), StructOffset),
5379                      MachineMemOperand::MODereferenceable |
5380                          MachineMemOperand::MOInvariant);
5381 }
5382 
5383 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5384                                              SelectionDAG &DAG) const {
5385   SDLoc SL(Op);
5386   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5387 
5388   SDValue Src = ASC->getOperand(0);
5389   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5390 
5391   const AMDGPUTargetMachine &TM =
5392     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5393 
5394   // flat -> local/private
5395   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5396     unsigned DestAS = ASC->getDestAddressSpace();
5397 
5398     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5399         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5400       unsigned NullVal = TM.getNullPointerValue(DestAS);
5401       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5402       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5403       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5404 
5405       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
5406                          NonNull, Ptr, SegmentNullPtr);
5407     }
5408   }
5409 
5410   // local/private -> flat
5411   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5412     unsigned SrcAS = ASC->getSrcAddressSpace();
5413 
5414     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5415         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5416       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5417       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5418 
5419       SDValue NonNull
5420         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5421 
5422       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5423       SDValue CvtPtr
5424         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5425 
5426       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5427                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5428                          FlatNullPtr);
5429     }
5430   }
5431 
5432   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5433       Src.getValueType() == MVT::i64)
5434     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5435 
5436   // global <-> flat are no-ops and never emitted.
5437 
5438   const MachineFunction &MF = DAG.getMachineFunction();
5439   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5440     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5441   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5442 
5443   return DAG.getUNDEF(ASC->getValueType(0));
5444 }
5445 
5446 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5447 // the small vector and inserting them into the big vector. That is better than
5448 // the default expansion of doing it via a stack slot. Even though the use of
5449 // the stack slot would be optimized away afterwards, the stack slot itself
5450 // remains.
5451 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5452                                                 SelectionDAG &DAG) const {
5453   SDValue Vec = Op.getOperand(0);
5454   SDValue Ins = Op.getOperand(1);
5455   SDValue Idx = Op.getOperand(2);
5456   EVT VecVT = Vec.getValueType();
5457   EVT InsVT = Ins.getValueType();
5458   EVT EltVT = VecVT.getVectorElementType();
5459   unsigned InsNumElts = InsVT.getVectorNumElements();
5460   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5461   SDLoc SL(Op);
5462 
5463   for (unsigned I = 0; I != InsNumElts; ++I) {
5464     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5465                               DAG.getConstant(I, SL, MVT::i32));
5466     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5467                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5468   }
5469   return Vec;
5470 }
5471 
5472 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5473                                                  SelectionDAG &DAG) const {
5474   SDValue Vec = Op.getOperand(0);
5475   SDValue InsVal = Op.getOperand(1);
5476   SDValue Idx = Op.getOperand(2);
5477   EVT VecVT = Vec.getValueType();
5478   EVT EltVT = VecVT.getVectorElementType();
5479   unsigned VecSize = VecVT.getSizeInBits();
5480   unsigned EltSize = EltVT.getSizeInBits();
5481 
5482 
5483   assert(VecSize <= 64);
5484 
5485   unsigned NumElts = VecVT.getVectorNumElements();
5486   SDLoc SL(Op);
5487   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5488 
5489   if (NumElts == 4 && EltSize == 16 && KIdx) {
5490     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5491 
5492     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5493                                  DAG.getConstant(0, SL, MVT::i32));
5494     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5495                                  DAG.getConstant(1, SL, MVT::i32));
5496 
5497     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5498     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5499 
5500     unsigned Idx = KIdx->getZExtValue();
5501     bool InsertLo = Idx < 2;
5502     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5503       InsertLo ? LoVec : HiVec,
5504       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5505       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5506 
5507     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5508 
5509     SDValue Concat = InsertLo ?
5510       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5511       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5512 
5513     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5514   }
5515 
5516   if (isa<ConstantSDNode>(Idx))
5517     return SDValue();
5518 
5519   MVT IntVT = MVT::getIntegerVT(VecSize);
5520 
5521   // Avoid stack access for dynamic indexing.
5522   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5523 
5524   // Create a congruent vector with the target value in each element so that
5525   // the required element can be masked and ORed into the target vector.
5526   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5527                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5528 
5529   assert(isPowerOf2_32(EltSize));
5530   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5531 
5532   // Convert vector index to bit-index.
5533   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5534 
5535   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5536   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5537                             DAG.getConstant(0xffff, SL, IntVT),
5538                             ScaledIdx);
5539 
5540   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5541   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5542                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5543 
5544   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5545   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5546 }
5547 
5548 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5549                                                   SelectionDAG &DAG) const {
5550   SDLoc SL(Op);
5551 
5552   EVT ResultVT = Op.getValueType();
5553   SDValue Vec = Op.getOperand(0);
5554   SDValue Idx = Op.getOperand(1);
5555   EVT VecVT = Vec.getValueType();
5556   unsigned VecSize = VecVT.getSizeInBits();
5557   EVT EltVT = VecVT.getVectorElementType();
5558   assert(VecSize <= 64);
5559 
5560   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5561 
5562   // Make sure we do any optimizations that will make it easier to fold
5563   // source modifiers before obscuring it with bit operations.
5564 
5565   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5566   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5567     return Combined;
5568 
5569   unsigned EltSize = EltVT.getSizeInBits();
5570   assert(isPowerOf2_32(EltSize));
5571 
5572   MVT IntVT = MVT::getIntegerVT(VecSize);
5573   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5574 
5575   // Convert vector index to bit-index (* EltSize)
5576   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5577 
5578   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5579   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5580 
5581   if (ResultVT == MVT::f16) {
5582     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5583     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5584   }
5585 
5586   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5587 }
5588 
5589 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5590   assert(Elt % 2 == 0);
5591   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5592 }
5593 
5594 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5595                                               SelectionDAG &DAG) const {
5596   SDLoc SL(Op);
5597   EVT ResultVT = Op.getValueType();
5598   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5599 
5600   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5601   EVT EltVT = PackVT.getVectorElementType();
5602   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5603 
5604   // vector_shuffle <0,1,6,7> lhs, rhs
5605   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5606   //
5607   // vector_shuffle <6,7,2,3> lhs, rhs
5608   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5609   //
5610   // vector_shuffle <6,7,0,1> lhs, rhs
5611   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5612 
5613   // Avoid scalarizing when both halves are reading from consecutive elements.
5614   SmallVector<SDValue, 4> Pieces;
5615   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5616     if (elementPairIsContiguous(SVN->getMask(), I)) {
5617       const int Idx = SVN->getMaskElt(I);
5618       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5619       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5620       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5621                                     PackVT, SVN->getOperand(VecIdx),
5622                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5623       Pieces.push_back(SubVec);
5624     } else {
5625       const int Idx0 = SVN->getMaskElt(I);
5626       const int Idx1 = SVN->getMaskElt(I + 1);
5627       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5628       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5629       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5630       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5631 
5632       SDValue Vec0 = SVN->getOperand(VecIdx0);
5633       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5634                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5635 
5636       SDValue Vec1 = SVN->getOperand(VecIdx1);
5637       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5638                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5639       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5640     }
5641   }
5642 
5643   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5644 }
5645 
5646 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5647                                             SelectionDAG &DAG) const {
5648   SDLoc SL(Op);
5649   EVT VT = Op.getValueType();
5650 
5651   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5652     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5653 
5654     // Turn into pair of packed build_vectors.
5655     // TODO: Special case for constants that can be materialized with s_mov_b64.
5656     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5657                                     { Op.getOperand(0), Op.getOperand(1) });
5658     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5659                                     { Op.getOperand(2), Op.getOperand(3) });
5660 
5661     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5662     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5663 
5664     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5665     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5666   }
5667 
5668   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5669   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5670 
5671   SDValue Lo = Op.getOperand(0);
5672   SDValue Hi = Op.getOperand(1);
5673 
5674   // Avoid adding defined bits with the zero_extend.
5675   if (Hi.isUndef()) {
5676     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5677     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5678     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5679   }
5680 
5681   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5682   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5683 
5684   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5685                               DAG.getConstant(16, SL, MVT::i32));
5686   if (Lo.isUndef())
5687     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5688 
5689   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5690   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5691 
5692   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5693   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5694 }
5695 
5696 bool
5697 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5698   // We can fold offsets for anything that doesn't require a GOT relocation.
5699   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5700           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5701           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5702          !shouldEmitGOTReloc(GA->getGlobal());
5703 }
5704 
5705 static SDValue
5706 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5707                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5708                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5709   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5710   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5711   // lowered to the following code sequence:
5712   //
5713   // For constant address space:
5714   //   s_getpc_b64 s[0:1]
5715   //   s_add_u32 s0, s0, $symbol
5716   //   s_addc_u32 s1, s1, 0
5717   //
5718   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5719   //   a fixup or relocation is emitted to replace $symbol with a literal
5720   //   constant, which is a pc-relative offset from the encoding of the $symbol
5721   //   operand to the global variable.
5722   //
5723   // For global address space:
5724   //   s_getpc_b64 s[0:1]
5725   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5726   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5727   //
5728   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5729   //   fixups or relocations are emitted to replace $symbol@*@lo and
5730   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5731   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5732   //   operand to the global variable.
5733   //
5734   // What we want here is an offset from the value returned by s_getpc
5735   // (which is the address of the s_add_u32 instruction) to the global
5736   // variable, but since the encoding of $symbol starts 4 bytes after the start
5737   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5738   // small. This requires us to add 4 to the global variable offset in order to
5739   // compute the correct address. Similarly for the s_addc_u32 instruction, the
5740   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
5741   // instruction.
5742   SDValue PtrLo =
5743       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5744   SDValue PtrHi;
5745   if (GAFlags == SIInstrInfo::MO_NONE) {
5746     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5747   } else {
5748     PtrHi =
5749         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
5750   }
5751   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5752 }
5753 
5754 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5755                                              SDValue Op,
5756                                              SelectionDAG &DAG) const {
5757   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5758   SDLoc DL(GSD);
5759   EVT PtrVT = Op.getValueType();
5760 
5761   const GlobalValue *GV = GSD->getGlobal();
5762   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5763        shouldUseLDSConstAddress(GV)) ||
5764       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5765       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
5766     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5767         GV->hasExternalLinkage()) {
5768       Type *Ty = GV->getValueType();
5769       // HIP uses an unsized array `extern __shared__ T s[]` or similar
5770       // zero-sized type in other languages to declare the dynamic shared
5771       // memory which size is not known at the compile time. They will be
5772       // allocated by the runtime and placed directly after the static
5773       // allocated ones. They all share the same offset.
5774       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
5775         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
5776         // Adjust alignment for that dynamic shared memory array.
5777         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
5778         return SDValue(
5779             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
5780       }
5781     }
5782     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5783   }
5784 
5785   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5786     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5787                                             SIInstrInfo::MO_ABS32_LO);
5788     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5789   }
5790 
5791   if (shouldEmitFixup(GV))
5792     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5793   else if (shouldEmitPCReloc(GV))
5794     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5795                                    SIInstrInfo::MO_REL32);
5796 
5797   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5798                                             SIInstrInfo::MO_GOTPCREL32);
5799 
5800   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5801   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5802   const DataLayout &DataLayout = DAG.getDataLayout();
5803   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
5804   MachinePointerInfo PtrInfo
5805     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5806 
5807   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
5808                      MachineMemOperand::MODereferenceable |
5809                          MachineMemOperand::MOInvariant);
5810 }
5811 
5812 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5813                                    const SDLoc &DL, SDValue V) const {
5814   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5815   // the destination register.
5816   //
5817   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5818   // so we will end up with redundant moves to m0.
5819   //
5820   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5821 
5822   // A Null SDValue creates a glue result.
5823   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5824                                   V, Chain);
5825   return SDValue(M0, 0);
5826 }
5827 
5828 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5829                                                  SDValue Op,
5830                                                  MVT VT,
5831                                                  unsigned Offset) const {
5832   SDLoc SL(Op);
5833   SDValue Param = lowerKernargMemParameter(
5834       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
5835   // The local size values will have the hi 16-bits as zero.
5836   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5837                      DAG.getValueType(VT));
5838 }
5839 
5840 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5841                                         EVT VT) {
5842   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5843                                       "non-hsa intrinsic with hsa target",
5844                                       DL.getDebugLoc());
5845   DAG.getContext()->diagnose(BadIntrin);
5846   return DAG.getUNDEF(VT);
5847 }
5848 
5849 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5850                                          EVT VT) {
5851   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5852                                       "intrinsic not supported on subtarget",
5853                                       DL.getDebugLoc());
5854   DAG.getContext()->diagnose(BadIntrin);
5855   return DAG.getUNDEF(VT);
5856 }
5857 
5858 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5859                                     ArrayRef<SDValue> Elts) {
5860   assert(!Elts.empty());
5861   MVT Type;
5862   unsigned NumElts = Elts.size();
5863 
5864   if (NumElts <= 8) {
5865     Type = MVT::getVectorVT(MVT::f32, NumElts);
5866   } else {
5867     assert(Elts.size() <= 16);
5868     Type = MVT::v16f32;
5869     NumElts = 16;
5870   }
5871 
5872   SmallVector<SDValue, 16> VecElts(NumElts);
5873   for (unsigned i = 0; i < Elts.size(); ++i) {
5874     SDValue Elt = Elts[i];
5875     if (Elt.getValueType() != MVT::f32)
5876       Elt = DAG.getBitcast(MVT::f32, Elt);
5877     VecElts[i] = Elt;
5878   }
5879   for (unsigned i = Elts.size(); i < NumElts; ++i)
5880     VecElts[i] = DAG.getUNDEF(MVT::f32);
5881 
5882   if (NumElts == 1)
5883     return VecElts[0];
5884   return DAG.getBuildVector(Type, DL, VecElts);
5885 }
5886 
5887 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5888                               SDValue Src, int ExtraElts) {
5889   EVT SrcVT = Src.getValueType();
5890 
5891   SmallVector<SDValue, 8> Elts;
5892 
5893   if (SrcVT.isVector())
5894     DAG.ExtractVectorElements(Src, Elts);
5895   else
5896     Elts.push_back(Src);
5897 
5898   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5899   while (ExtraElts--)
5900     Elts.push_back(Undef);
5901 
5902   return DAG.getBuildVector(CastVT, DL, Elts);
5903 }
5904 
5905 // Re-construct the required return value for a image load intrinsic.
5906 // This is more complicated due to the optional use TexFailCtrl which means the required
5907 // return type is an aggregate
5908 static SDValue constructRetValue(SelectionDAG &DAG,
5909                                  MachineSDNode *Result,
5910                                  ArrayRef<EVT> ResultTypes,
5911                                  bool IsTexFail, bool Unpacked, bool IsD16,
5912                                  int DMaskPop, int NumVDataDwords,
5913                                  const SDLoc &DL) {
5914   // Determine the required return type. This is the same regardless of IsTexFail flag
5915   EVT ReqRetVT = ResultTypes[0];
5916   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5917   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5918     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5919 
5920   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5921     DMaskPop : (DMaskPop + 1) / 2;
5922 
5923   MVT DataDwordVT = NumDataDwords == 1 ?
5924     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5925 
5926   MVT MaskPopVT = MaskPopDwords == 1 ?
5927     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5928 
5929   SDValue Data(Result, 0);
5930   SDValue TexFail;
5931 
5932   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
5933     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5934     if (MaskPopVT.isVector()) {
5935       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5936                          SDValue(Result, 0), ZeroIdx);
5937     } else {
5938       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5939                          SDValue(Result, 0), ZeroIdx);
5940     }
5941   }
5942 
5943   if (DataDwordVT.isVector())
5944     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5945                           NumDataDwords - MaskPopDwords);
5946 
5947   if (IsD16)
5948     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5949 
5950   EVT LegalReqRetVT = ReqRetVT;
5951   if (!ReqRetVT.isVector()) {
5952     if (!Data.getValueType().isInteger())
5953       Data = DAG.getNode(ISD::BITCAST, DL,
5954                          Data.getValueType().changeTypeToInteger(), Data);
5955     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5956   } else {
5957     // We need to widen the return vector to a legal type
5958     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
5959         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
5960       LegalReqRetVT =
5961           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
5962                            ReqRetVT.getVectorNumElements() + 1);
5963     }
5964   }
5965   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
5966 
5967   if (IsTexFail) {
5968     TexFail =
5969         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
5970                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5971 
5972     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5973   }
5974 
5975   if (Result->getNumValues() == 1)
5976     return Data;
5977 
5978   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5979 }
5980 
5981 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5982                          SDValue *LWE, bool &IsTexFail) {
5983   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5984 
5985   uint64_t Value = TexFailCtrlConst->getZExtValue();
5986   if (Value) {
5987     IsTexFail = true;
5988   }
5989 
5990   SDLoc DL(TexFailCtrlConst);
5991   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5992   Value &= ~(uint64_t)0x1;
5993   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5994   Value &= ~(uint64_t)0x2;
5995 
5996   return Value == 0;
5997 }
5998 
5999 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
6000                                       MVT PackVectorVT,
6001                                       SmallVectorImpl<SDValue> &PackedAddrs,
6002                                       unsigned DimIdx, unsigned EndIdx,
6003                                       unsigned NumGradients) {
6004   SDLoc DL(Op);
6005   for (unsigned I = DimIdx; I < EndIdx; I++) {
6006     SDValue Addr = Op.getOperand(I);
6007 
6008     // Gradients are packed with undef for each coordinate.
6009     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
6010     // 1D: undef,dx/dh; undef,dx/dv
6011     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
6012     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
6013     if (((I + 1) >= EndIdx) ||
6014         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
6015                                          I == DimIdx + NumGradients - 1))) {
6016       if (Addr.getValueType() != MVT::i16)
6017         Addr = DAG.getBitcast(MVT::i16, Addr);
6018       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
6019     } else {
6020       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
6021       I++;
6022     }
6023     Addr = DAG.getBitcast(MVT::f32, Addr);
6024     PackedAddrs.push_back(Addr);
6025   }
6026 }
6027 
6028 SDValue SITargetLowering::lowerImage(SDValue Op,
6029                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
6030                                      SelectionDAG &DAG, bool WithChain) const {
6031   SDLoc DL(Op);
6032   MachineFunction &MF = DAG.getMachineFunction();
6033   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
6034   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
6035       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
6036   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
6037   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
6038       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
6039   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
6040       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
6041   unsigned IntrOpcode = Intr->BaseOpcode;
6042   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6043 
6044   SmallVector<EVT, 3> ResultTypes(Op->values());
6045   SmallVector<EVT, 3> OrigResultTypes(Op->values());
6046   bool IsD16 = false;
6047   bool IsG16 = false;
6048   bool IsA16 = false;
6049   SDValue VData;
6050   int NumVDataDwords;
6051   bool AdjustRetType = false;
6052 
6053   // Offset of intrinsic arguments
6054   const unsigned ArgOffset = WithChain ? 2 : 1;
6055 
6056   unsigned DMask;
6057   unsigned DMaskLanes = 0;
6058 
6059   if (BaseOpcode->Atomic) {
6060     VData = Op.getOperand(2);
6061 
6062     bool Is64Bit = VData.getValueType() == MVT::i64;
6063     if (BaseOpcode->AtomicX2) {
6064       SDValue VData2 = Op.getOperand(3);
6065       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6066                                  {VData, VData2});
6067       if (Is64Bit)
6068         VData = DAG.getBitcast(MVT::v4i32, VData);
6069 
6070       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6071       DMask = Is64Bit ? 0xf : 0x3;
6072       NumVDataDwords = Is64Bit ? 4 : 2;
6073     } else {
6074       DMask = Is64Bit ? 0x3 : 0x1;
6075       NumVDataDwords = Is64Bit ? 2 : 1;
6076     }
6077   } else {
6078     auto *DMaskConst =
6079         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6080     DMask = DMaskConst->getZExtValue();
6081     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6082 
6083     if (BaseOpcode->Store) {
6084       VData = Op.getOperand(2);
6085 
6086       MVT StoreVT = VData.getSimpleValueType();
6087       if (StoreVT.getScalarType() == MVT::f16) {
6088         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6089           return Op; // D16 is unsupported for this instruction
6090 
6091         IsD16 = true;
6092         VData = handleD16VData(VData, DAG, true);
6093       }
6094 
6095       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6096     } else {
6097       // Work out the num dwords based on the dmask popcount and underlying type
6098       // and whether packing is supported.
6099       MVT LoadVT = ResultTypes[0].getSimpleVT();
6100       if (LoadVT.getScalarType() == MVT::f16) {
6101         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6102           return Op; // D16 is unsupported for this instruction
6103 
6104         IsD16 = true;
6105       }
6106 
6107       // Confirm that the return type is large enough for the dmask specified
6108       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6109           (!LoadVT.isVector() && DMaskLanes > 1))
6110           return Op;
6111 
6112       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6113       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6114       // instructions.
6115       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6116           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6117         NumVDataDwords = (DMaskLanes + 1) / 2;
6118       else
6119         NumVDataDwords = DMaskLanes;
6120 
6121       AdjustRetType = true;
6122     }
6123   }
6124 
6125   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6126   SmallVector<SDValue, 4> VAddrs;
6127 
6128   // Optimize _L to _LZ when _L is zero
6129   if (LZMappingInfo) {
6130     if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>(
6131             Op.getOperand(ArgOffset + Intr->LodIndex))) {
6132       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
6133         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
6134         VAddrEnd--;                      // remove 'lod'
6135       }
6136     }
6137   }
6138 
6139   // Optimize _mip away, when 'lod' is zero
6140   if (MIPMappingInfo) {
6141     if (auto *ConstantLod = dyn_cast<ConstantSDNode>(
6142             Op.getOperand(ArgOffset + Intr->MipIndex))) {
6143       if (ConstantLod->isNullValue()) {
6144         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
6145         VAddrEnd--;                           // remove 'mip'
6146       }
6147     }
6148   }
6149 
6150   // Push back extra arguments.
6151   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++)
6152     VAddrs.push_back(Op.getOperand(ArgOffset + I));
6153 
6154   // Check for 16 bit addresses or derivatives and pack if true.
6155   MVT VAddrVT =
6156       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6157   MVT VAddrScalarVT = VAddrVT.getScalarType();
6158   MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6159   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6160 
6161   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6162   VAddrScalarVT = VAddrVT.getScalarType();
6163   MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6164   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6165 
6166   if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
6167     // 16 bit gradients are supported, but are tied to the A16 control
6168     // so both gradients and addresses must be 16 bit
6169     LLVM_DEBUG(
6170         dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6171                   "require 16 bit args for both gradients and addresses");
6172     return Op;
6173   }
6174 
6175   if (IsA16) {
6176     if (!ST->hasA16()) {
6177       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6178                            "support 16 bit addresses\n");
6179       return Op;
6180     }
6181   }
6182 
6183   // We've dealt with incorrect input so we know that if IsA16, IsG16
6184   // are set then we have to compress/pack operands (either address,
6185   // gradient or both)
6186   // In the case where a16 and gradients are tied (no G16 support) then we
6187   // have already verified that both IsA16 and IsG16 are true
6188   if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
6189     // Activate g16
6190     const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6191         AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6192     IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6193   }
6194 
6195   // Add gradients (packed or unpacked)
6196   if (IsG16) {
6197     // Pack the gradients
6198     // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6199     packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
6200                               ArgOffset + Intr->GradientStart,
6201                               ArgOffset + Intr->CoordStart, Intr->NumGradients);
6202   } else {
6203     for (unsigned I = ArgOffset + Intr->GradientStart;
6204          I < ArgOffset + Intr->CoordStart; I++)
6205       VAddrs.push_back(Op.getOperand(I));
6206   }
6207 
6208   // Add addresses (packed or unpacked)
6209   if (IsA16) {
6210     packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
6211                               ArgOffset + Intr->CoordStart, VAddrEnd,
6212                               0 /* No gradients */);
6213   } else {
6214     // Add uncompressed address
6215     for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6216       VAddrs.push_back(Op.getOperand(I));
6217   }
6218 
6219   // If the register allocator cannot place the address registers contiguously
6220   // without introducing moves, then using the non-sequential address encoding
6221   // is always preferable, since it saves VALU instructions and is usually a
6222   // wash in terms of code size or even better.
6223   //
6224   // However, we currently have no way of hinting to the register allocator that
6225   // MIMG addresses should be placed contiguously when it is possible to do so,
6226   // so force non-NSA for the common 2-address case as a heuristic.
6227   //
6228   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6229   // allocation when possible.
6230   bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) &&
6231                 VAddrs.size() >= 3 &&
6232                 VAddrs.size() <= (unsigned)ST->getNSAMaxSize();
6233   SDValue VAddr;
6234   if (!UseNSA)
6235     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6236 
6237   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6238   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6239   SDValue Unorm;
6240   if (!BaseOpcode->Sampler) {
6241     Unorm = True;
6242   } else {
6243     auto UnormConst =
6244         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6245 
6246     Unorm = UnormConst->getZExtValue() ? True : False;
6247   }
6248 
6249   SDValue TFE;
6250   SDValue LWE;
6251   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6252   bool IsTexFail = false;
6253   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6254     return Op;
6255 
6256   if (IsTexFail) {
6257     if (!DMaskLanes) {
6258       // Expecting to get an error flag since TFC is on - and dmask is 0
6259       // Force dmask to be at least 1 otherwise the instruction will fail
6260       DMask = 0x1;
6261       DMaskLanes = 1;
6262       NumVDataDwords = 1;
6263     }
6264     NumVDataDwords += 1;
6265     AdjustRetType = true;
6266   }
6267 
6268   // Has something earlier tagged that the return type needs adjusting
6269   // This happens if the instruction is a load or has set TexFailCtrl flags
6270   if (AdjustRetType) {
6271     // NumVDataDwords reflects the true number of dwords required in the return type
6272     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6273       // This is a no-op load. This can be eliminated
6274       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6275       if (isa<MemSDNode>(Op))
6276         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6277       return Undef;
6278     }
6279 
6280     EVT NewVT = NumVDataDwords > 1 ?
6281                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6282                 : MVT::i32;
6283 
6284     ResultTypes[0] = NewVT;
6285     if (ResultTypes.size() == 3) {
6286       // Original result was aggregate type used for TexFailCtrl results
6287       // The actual instruction returns as a vector type which has now been
6288       // created. Remove the aggregate result.
6289       ResultTypes.erase(&ResultTypes[1]);
6290     }
6291   }
6292 
6293   unsigned CPol = cast<ConstantSDNode>(
6294       Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6295   if (BaseOpcode->Atomic)
6296     CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6297   if (CPol & ~AMDGPU::CPol::ALL)
6298     return Op;
6299 
6300   SmallVector<SDValue, 26> Ops;
6301   if (BaseOpcode->Store || BaseOpcode->Atomic)
6302     Ops.push_back(VData); // vdata
6303   if (UseNSA)
6304     append_range(Ops, VAddrs);
6305   else
6306     Ops.push_back(VAddr);
6307   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6308   if (BaseOpcode->Sampler)
6309     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6310   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6311   if (IsGFX10Plus)
6312     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6313   Ops.push_back(Unorm);
6314   Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6315   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6316                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6317   if (IsGFX10Plus)
6318     Ops.push_back(IsA16 ? True : False);
6319   if (!Subtarget->hasGFX90AInsts()) {
6320     Ops.push_back(TFE); //tfe
6321   } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6322     report_fatal_error("TFE is not supported on this GPU");
6323   }
6324   Ops.push_back(LWE); // lwe
6325   if (!IsGFX10Plus)
6326     Ops.push_back(DimInfo->DA ? True : False);
6327   if (BaseOpcode->HasD16)
6328     Ops.push_back(IsD16 ? True : False);
6329   if (isa<MemSDNode>(Op))
6330     Ops.push_back(Op.getOperand(0)); // chain
6331 
6332   int NumVAddrDwords =
6333       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6334   int Opcode = -1;
6335 
6336   if (IsGFX10Plus) {
6337     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6338                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6339                                           : AMDGPU::MIMGEncGfx10Default,
6340                                    NumVDataDwords, NumVAddrDwords);
6341   } else {
6342     if (Subtarget->hasGFX90AInsts()) {
6343       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6344                                      NumVDataDwords, NumVAddrDwords);
6345       if (Opcode == -1)
6346         report_fatal_error(
6347             "requested image instruction is not supported on this GPU");
6348     }
6349     if (Opcode == -1 &&
6350         Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6351       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6352                                      NumVDataDwords, NumVAddrDwords);
6353     if (Opcode == -1)
6354       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6355                                      NumVDataDwords, NumVAddrDwords);
6356   }
6357   assert(Opcode != -1);
6358 
6359   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6360   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6361     MachineMemOperand *MemRef = MemOp->getMemOperand();
6362     DAG.setNodeMemRefs(NewNode, {MemRef});
6363   }
6364 
6365   if (BaseOpcode->AtomicX2) {
6366     SmallVector<SDValue, 1> Elt;
6367     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6368     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6369   }
6370   if (BaseOpcode->Store)
6371     return SDValue(NewNode, 0);
6372   return constructRetValue(DAG, NewNode,
6373                            OrigResultTypes, IsTexFail,
6374                            Subtarget->hasUnpackedD16VMem(), IsD16,
6375                            DMaskLanes, NumVDataDwords, DL);
6376 }
6377 
6378 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6379                                        SDValue Offset, SDValue CachePolicy,
6380                                        SelectionDAG &DAG) const {
6381   MachineFunction &MF = DAG.getMachineFunction();
6382 
6383   const DataLayout &DataLayout = DAG.getDataLayout();
6384   Align Alignment =
6385       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6386 
6387   MachineMemOperand *MMO = MF.getMachineMemOperand(
6388       MachinePointerInfo(),
6389       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6390           MachineMemOperand::MOInvariant,
6391       VT.getStoreSize(), Alignment);
6392 
6393   if (!Offset->isDivergent()) {
6394     SDValue Ops[] = {
6395         Rsrc,
6396         Offset, // Offset
6397         CachePolicy
6398     };
6399 
6400     // Widen vec3 load to vec4.
6401     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6402       EVT WidenedVT =
6403           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6404       auto WidenedOp = DAG.getMemIntrinsicNode(
6405           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6406           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6407       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6408                                    DAG.getVectorIdxConstant(0, DL));
6409       return Subvector;
6410     }
6411 
6412     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6413                                    DAG.getVTList(VT), Ops, VT, MMO);
6414   }
6415 
6416   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6417   // assume that the buffer is unswizzled.
6418   SmallVector<SDValue, 4> Loads;
6419   unsigned NumLoads = 1;
6420   MVT LoadVT = VT.getSimpleVT();
6421   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6422   assert((LoadVT.getScalarType() == MVT::i32 ||
6423           LoadVT.getScalarType() == MVT::f32));
6424 
6425   if (NumElts == 8 || NumElts == 16) {
6426     NumLoads = NumElts / 4;
6427     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6428   }
6429 
6430   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6431   SDValue Ops[] = {
6432       DAG.getEntryNode(),                               // Chain
6433       Rsrc,                                             // rsrc
6434       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6435       {},                                               // voffset
6436       {},                                               // soffset
6437       {},                                               // offset
6438       CachePolicy,                                      // cachepolicy
6439       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6440   };
6441 
6442   // Use the alignment to ensure that the required offsets will fit into the
6443   // immediate offsets.
6444   setBufferOffsets(Offset, DAG, &Ops[3],
6445                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6446 
6447   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6448   for (unsigned i = 0; i < NumLoads; ++i) {
6449     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6450     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6451                                         LoadVT, MMO, DAG));
6452   }
6453 
6454   if (NumElts == 8 || NumElts == 16)
6455     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6456 
6457   return Loads[0];
6458 }
6459 
6460 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6461                                                   SelectionDAG &DAG) const {
6462   MachineFunction &MF = DAG.getMachineFunction();
6463   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6464 
6465   EVT VT = Op.getValueType();
6466   SDLoc DL(Op);
6467   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6468 
6469   // TODO: Should this propagate fast-math-flags?
6470 
6471   switch (IntrinsicID) {
6472   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6473     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6474       return emitNonHSAIntrinsicError(DAG, DL, VT);
6475     return getPreloadedValue(DAG, *MFI, VT,
6476                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6477   }
6478   case Intrinsic::amdgcn_dispatch_ptr:
6479   case Intrinsic::amdgcn_queue_ptr: {
6480     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6481       DiagnosticInfoUnsupported BadIntrin(
6482           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6483           DL.getDebugLoc());
6484       DAG.getContext()->diagnose(BadIntrin);
6485       return DAG.getUNDEF(VT);
6486     }
6487 
6488     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6489       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6490     return getPreloadedValue(DAG, *MFI, VT, RegID);
6491   }
6492   case Intrinsic::amdgcn_implicitarg_ptr: {
6493     if (MFI->isEntryFunction())
6494       return getImplicitArgPtr(DAG, DL);
6495     return getPreloadedValue(DAG, *MFI, VT,
6496                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6497   }
6498   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6499     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6500       // This only makes sense to call in a kernel, so just lower to null.
6501       return DAG.getConstant(0, DL, VT);
6502     }
6503 
6504     return getPreloadedValue(DAG, *MFI, VT,
6505                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6506   }
6507   case Intrinsic::amdgcn_dispatch_id: {
6508     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6509   }
6510   case Intrinsic::amdgcn_rcp:
6511     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6512   case Intrinsic::amdgcn_rsq:
6513     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6514   case Intrinsic::amdgcn_rsq_legacy:
6515     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6516       return emitRemovedIntrinsicError(DAG, DL, VT);
6517     return SDValue();
6518   case Intrinsic::amdgcn_rcp_legacy:
6519     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6520       return emitRemovedIntrinsicError(DAG, DL, VT);
6521     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6522   case Intrinsic::amdgcn_rsq_clamp: {
6523     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6524       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6525 
6526     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6527     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6528     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6529 
6530     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6531     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6532                               DAG.getConstantFP(Max, DL, VT));
6533     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6534                        DAG.getConstantFP(Min, DL, VT));
6535   }
6536   case Intrinsic::r600_read_ngroups_x:
6537     if (Subtarget->isAmdHsaOS())
6538       return emitNonHSAIntrinsicError(DAG, DL, VT);
6539 
6540     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6541                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6542                                     false);
6543   case Intrinsic::r600_read_ngroups_y:
6544     if (Subtarget->isAmdHsaOS())
6545       return emitNonHSAIntrinsicError(DAG, DL, VT);
6546 
6547     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6548                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6549                                     false);
6550   case Intrinsic::r600_read_ngroups_z:
6551     if (Subtarget->isAmdHsaOS())
6552       return emitNonHSAIntrinsicError(DAG, DL, VT);
6553 
6554     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6555                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6556                                     false);
6557   case Intrinsic::r600_read_global_size_x:
6558     if (Subtarget->isAmdHsaOS())
6559       return emitNonHSAIntrinsicError(DAG, DL, VT);
6560 
6561     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6562                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6563                                     Align(4), false);
6564   case Intrinsic::r600_read_global_size_y:
6565     if (Subtarget->isAmdHsaOS())
6566       return emitNonHSAIntrinsicError(DAG, DL, VT);
6567 
6568     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6569                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6570                                     Align(4), false);
6571   case Intrinsic::r600_read_global_size_z:
6572     if (Subtarget->isAmdHsaOS())
6573       return emitNonHSAIntrinsicError(DAG, DL, VT);
6574 
6575     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6576                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6577                                     Align(4), false);
6578   case Intrinsic::r600_read_local_size_x:
6579     if (Subtarget->isAmdHsaOS())
6580       return emitNonHSAIntrinsicError(DAG, DL, VT);
6581 
6582     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6583                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6584   case Intrinsic::r600_read_local_size_y:
6585     if (Subtarget->isAmdHsaOS())
6586       return emitNonHSAIntrinsicError(DAG, DL, VT);
6587 
6588     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6589                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6590   case Intrinsic::r600_read_local_size_z:
6591     if (Subtarget->isAmdHsaOS())
6592       return emitNonHSAIntrinsicError(DAG, DL, VT);
6593 
6594     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6595                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6596   case Intrinsic::amdgcn_workgroup_id_x:
6597     return getPreloadedValue(DAG, *MFI, VT,
6598                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6599   case Intrinsic::amdgcn_workgroup_id_y:
6600     return getPreloadedValue(DAG, *MFI, VT,
6601                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6602   case Intrinsic::amdgcn_workgroup_id_z:
6603     return getPreloadedValue(DAG, *MFI, VT,
6604                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6605   case Intrinsic::amdgcn_workitem_id_x:
6606     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6607                           SDLoc(DAG.getEntryNode()),
6608                           MFI->getArgInfo().WorkItemIDX);
6609   case Intrinsic::amdgcn_workitem_id_y:
6610     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6611                           SDLoc(DAG.getEntryNode()),
6612                           MFI->getArgInfo().WorkItemIDY);
6613   case Intrinsic::amdgcn_workitem_id_z:
6614     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6615                           SDLoc(DAG.getEntryNode()),
6616                           MFI->getArgInfo().WorkItemIDZ);
6617   case Intrinsic::amdgcn_wavefrontsize:
6618     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6619                            SDLoc(Op), MVT::i32);
6620   case Intrinsic::amdgcn_s_buffer_load: {
6621     unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6622     if (CPol & ~AMDGPU::CPol::ALL)
6623       return Op;
6624     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6625                         DAG);
6626   }
6627   case Intrinsic::amdgcn_fdiv_fast:
6628     return lowerFDIV_FAST(Op, DAG);
6629   case Intrinsic::amdgcn_sin:
6630     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6631 
6632   case Intrinsic::amdgcn_cos:
6633     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6634 
6635   case Intrinsic::amdgcn_mul_u24:
6636     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6637   case Intrinsic::amdgcn_mul_i24:
6638     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6639 
6640   case Intrinsic::amdgcn_log_clamp: {
6641     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6642       return SDValue();
6643 
6644     return emitRemovedIntrinsicError(DAG, DL, VT);
6645   }
6646   case Intrinsic::amdgcn_ldexp:
6647     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6648                        Op.getOperand(1), Op.getOperand(2));
6649 
6650   case Intrinsic::amdgcn_fract:
6651     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6652 
6653   case Intrinsic::amdgcn_class:
6654     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6655                        Op.getOperand(1), Op.getOperand(2));
6656   case Intrinsic::amdgcn_div_fmas:
6657     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6658                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6659                        Op.getOperand(4));
6660 
6661   case Intrinsic::amdgcn_div_fixup:
6662     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6663                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6664 
6665   case Intrinsic::amdgcn_div_scale: {
6666     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6667 
6668     // Translate to the operands expected by the machine instruction. The
6669     // first parameter must be the same as the first instruction.
6670     SDValue Numerator = Op.getOperand(1);
6671     SDValue Denominator = Op.getOperand(2);
6672 
6673     // Note this order is opposite of the machine instruction's operations,
6674     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6675     // intrinsic has the numerator as the first operand to match a normal
6676     // division operation.
6677 
6678     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6679 
6680     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6681                        Denominator, Numerator);
6682   }
6683   case Intrinsic::amdgcn_icmp: {
6684     // There is a Pat that handles this variant, so return it as-is.
6685     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6686         Op.getConstantOperandVal(2) == 0 &&
6687         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6688       return Op;
6689     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6690   }
6691   case Intrinsic::amdgcn_fcmp: {
6692     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6693   }
6694   case Intrinsic::amdgcn_ballot:
6695     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6696   case Intrinsic::amdgcn_fmed3:
6697     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6698                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6699   case Intrinsic::amdgcn_fdot2:
6700     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6701                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6702                        Op.getOperand(4));
6703   case Intrinsic::amdgcn_fmul_legacy:
6704     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6705                        Op.getOperand(1), Op.getOperand(2));
6706   case Intrinsic::amdgcn_sffbh:
6707     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6708   case Intrinsic::amdgcn_sbfe:
6709     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6710                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6711   case Intrinsic::amdgcn_ubfe:
6712     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6713                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6714   case Intrinsic::amdgcn_cvt_pkrtz:
6715   case Intrinsic::amdgcn_cvt_pknorm_i16:
6716   case Intrinsic::amdgcn_cvt_pknorm_u16:
6717   case Intrinsic::amdgcn_cvt_pk_i16:
6718   case Intrinsic::amdgcn_cvt_pk_u16: {
6719     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6720     EVT VT = Op.getValueType();
6721     unsigned Opcode;
6722 
6723     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6724       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6725     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6726       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6727     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6728       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6729     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6730       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6731     else
6732       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6733 
6734     if (isTypeLegal(VT))
6735       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6736 
6737     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6738                                Op.getOperand(1), Op.getOperand(2));
6739     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6740   }
6741   case Intrinsic::amdgcn_fmad_ftz:
6742     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6743                        Op.getOperand(2), Op.getOperand(3));
6744 
6745   case Intrinsic::amdgcn_if_break:
6746     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6747                                       Op->getOperand(1), Op->getOperand(2)), 0);
6748 
6749   case Intrinsic::amdgcn_groupstaticsize: {
6750     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6751     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6752       return Op;
6753 
6754     const Module *M = MF.getFunction().getParent();
6755     const GlobalValue *GV =
6756         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6757     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6758                                             SIInstrInfo::MO_ABS32_LO);
6759     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6760   }
6761   case Intrinsic::amdgcn_is_shared:
6762   case Intrinsic::amdgcn_is_private: {
6763     SDLoc SL(Op);
6764     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6765       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6766     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6767     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6768                                  Op.getOperand(1));
6769 
6770     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6771                                 DAG.getConstant(1, SL, MVT::i32));
6772     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6773   }
6774   case Intrinsic::amdgcn_alignbit:
6775     return DAG.getNode(ISD::FSHR, DL, VT,
6776                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6777   case Intrinsic::amdgcn_perm:
6778     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
6779                        Op.getOperand(2), Op.getOperand(3));
6780   case Intrinsic::amdgcn_reloc_constant: {
6781     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6782     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6783     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6784     auto RelocSymbol = cast<GlobalVariable>(
6785         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6786     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6787                                             SIInstrInfo::MO_ABS32_LO);
6788     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6789   }
6790   default:
6791     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6792             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6793       return lowerImage(Op, ImageDimIntr, DAG, false);
6794 
6795     return Op;
6796   }
6797 }
6798 
6799 /// Update \p MMO based on the offset inputs to an intrinsic.
6800 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset,
6801                             SDValue SOffset, SDValue Offset,
6802                             SDValue VIndex = SDValue()) {
6803   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6804       !isa<ConstantSDNode>(Offset)) {
6805     // The combined offset is not known to be constant, so we cannot represent
6806     // it in the MMO. Give up.
6807     MMO->setValue((Value *)nullptr);
6808     return;
6809   }
6810 
6811   if (VIndex && (!isa<ConstantSDNode>(VIndex) ||
6812                  !cast<ConstantSDNode>(VIndex)->isNullValue())) {
6813     // The strided index component of the address is not known to be zero, so we
6814     // cannot represent it in the MMO. Give up.
6815     MMO->setValue((Value *)nullptr);
6816     return;
6817   }
6818 
6819   MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() +
6820                  cast<ConstantSDNode>(SOffset)->getSExtValue() +
6821                  cast<ConstantSDNode>(Offset)->getSExtValue());
6822 }
6823 
6824 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
6825                                                      SelectionDAG &DAG,
6826                                                      unsigned NewOpcode) const {
6827   SDLoc DL(Op);
6828 
6829   SDValue VData = Op.getOperand(2);
6830   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6831   SDValue Ops[] = {
6832     Op.getOperand(0), // Chain
6833     VData,            // vdata
6834     Op.getOperand(3), // rsrc
6835     DAG.getConstant(0, DL, MVT::i32), // vindex
6836     Offsets.first,    // voffset
6837     Op.getOperand(5), // soffset
6838     Offsets.second,   // offset
6839     Op.getOperand(6), // cachepolicy
6840     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6841   };
6842 
6843   auto *M = cast<MemSDNode>(Op);
6844   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
6845 
6846   EVT MemVT = VData.getValueType();
6847   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6848                                  M->getMemOperand());
6849 }
6850 
6851 // Return a value to use for the idxen operand by examining the vindex operand.
6852 static unsigned getIdxEn(SDValue VIndex) {
6853   if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex))
6854     // No need to set idxen if vindex is known to be zero.
6855     return VIndexC->getZExtValue() != 0;
6856   return 1;
6857 }
6858 
6859 SDValue
6860 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
6861                                                 unsigned NewOpcode) const {
6862   SDLoc DL(Op);
6863 
6864   SDValue VData = Op.getOperand(2);
6865   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6866   SDValue Ops[] = {
6867     Op.getOperand(0), // Chain
6868     VData,            // vdata
6869     Op.getOperand(3), // rsrc
6870     Op.getOperand(4), // vindex
6871     Offsets.first,    // voffset
6872     Op.getOperand(6), // soffset
6873     Offsets.second,   // offset
6874     Op.getOperand(7), // cachepolicy
6875     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6876   };
6877 
6878   auto *M = cast<MemSDNode>(Op);
6879   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
6880 
6881   EVT MemVT = VData.getValueType();
6882   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6883                                  M->getMemOperand());
6884 }
6885 
6886 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6887                                                  SelectionDAG &DAG) const {
6888   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6889   SDLoc DL(Op);
6890 
6891   switch (IntrID) {
6892   case Intrinsic::amdgcn_ds_ordered_add:
6893   case Intrinsic::amdgcn_ds_ordered_swap: {
6894     MemSDNode *M = cast<MemSDNode>(Op);
6895     SDValue Chain = M->getOperand(0);
6896     SDValue M0 = M->getOperand(2);
6897     SDValue Value = M->getOperand(3);
6898     unsigned IndexOperand = M->getConstantOperandVal(7);
6899     unsigned WaveRelease = M->getConstantOperandVal(8);
6900     unsigned WaveDone = M->getConstantOperandVal(9);
6901 
6902     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6903     IndexOperand &= ~0x3f;
6904     unsigned CountDw = 0;
6905 
6906     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6907       CountDw = (IndexOperand >> 24) & 0xf;
6908       IndexOperand &= ~(0xf << 24);
6909 
6910       if (CountDw < 1 || CountDw > 4) {
6911         report_fatal_error(
6912             "ds_ordered_count: dword count must be between 1 and 4");
6913       }
6914     }
6915 
6916     if (IndexOperand)
6917       report_fatal_error("ds_ordered_count: bad index operand");
6918 
6919     if (WaveDone && !WaveRelease)
6920       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6921 
6922     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6923     unsigned ShaderType =
6924         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
6925     unsigned Offset0 = OrderedCountIndex << 2;
6926     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6927                        (Instruction << 4);
6928 
6929     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6930       Offset1 |= (CountDw - 1) << 6;
6931 
6932     unsigned Offset = Offset0 | (Offset1 << 8);
6933 
6934     SDValue Ops[] = {
6935       Chain,
6936       Value,
6937       DAG.getTargetConstant(Offset, DL, MVT::i16),
6938       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6939     };
6940     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6941                                    M->getVTList(), Ops, M->getMemoryVT(),
6942                                    M->getMemOperand());
6943   }
6944   case Intrinsic::amdgcn_ds_fadd: {
6945     MemSDNode *M = cast<MemSDNode>(Op);
6946     unsigned Opc;
6947     switch (IntrID) {
6948     case Intrinsic::amdgcn_ds_fadd:
6949       Opc = ISD::ATOMIC_LOAD_FADD;
6950       break;
6951     }
6952 
6953     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6954                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6955                          M->getMemOperand());
6956   }
6957   case Intrinsic::amdgcn_atomic_inc:
6958   case Intrinsic::amdgcn_atomic_dec:
6959   case Intrinsic::amdgcn_ds_fmin:
6960   case Intrinsic::amdgcn_ds_fmax: {
6961     MemSDNode *M = cast<MemSDNode>(Op);
6962     unsigned Opc;
6963     switch (IntrID) {
6964     case Intrinsic::amdgcn_atomic_inc:
6965       Opc = AMDGPUISD::ATOMIC_INC;
6966       break;
6967     case Intrinsic::amdgcn_atomic_dec:
6968       Opc = AMDGPUISD::ATOMIC_DEC;
6969       break;
6970     case Intrinsic::amdgcn_ds_fmin:
6971       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6972       break;
6973     case Intrinsic::amdgcn_ds_fmax:
6974       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6975       break;
6976     default:
6977       llvm_unreachable("Unknown intrinsic!");
6978     }
6979     SDValue Ops[] = {
6980       M->getOperand(0), // Chain
6981       M->getOperand(2), // Ptr
6982       M->getOperand(3)  // Value
6983     };
6984 
6985     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6986                                    M->getMemoryVT(), M->getMemOperand());
6987   }
6988   case Intrinsic::amdgcn_buffer_load:
6989   case Intrinsic::amdgcn_buffer_load_format: {
6990     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6991     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6992     unsigned IdxEn = getIdxEn(Op.getOperand(3));
6993     SDValue Ops[] = {
6994       Op.getOperand(0), // Chain
6995       Op.getOperand(2), // rsrc
6996       Op.getOperand(3), // vindex
6997       SDValue(),        // voffset -- will be set by setBufferOffsets
6998       SDValue(),        // soffset -- will be set by setBufferOffsets
6999       SDValue(),        // offset -- will be set by setBufferOffsets
7000       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7001       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7002     };
7003     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
7004 
7005     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
7006         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
7007 
7008     EVT VT = Op.getValueType();
7009     EVT IntVT = VT.changeTypeToInteger();
7010     auto *M = cast<MemSDNode>(Op);
7011     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7012     EVT LoadVT = Op.getValueType();
7013 
7014     if (LoadVT.getScalarType() == MVT::f16)
7015       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
7016                                  M, DAG, Ops);
7017 
7018     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
7019     if (LoadVT.getScalarType() == MVT::i8 ||
7020         LoadVT.getScalarType() == MVT::i16)
7021       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
7022 
7023     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
7024                                M->getMemOperand(), DAG);
7025   }
7026   case Intrinsic::amdgcn_raw_buffer_load:
7027   case Intrinsic::amdgcn_raw_buffer_load_format: {
7028     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
7029 
7030     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7031     SDValue Ops[] = {
7032       Op.getOperand(0), // Chain
7033       Op.getOperand(2), // rsrc
7034       DAG.getConstant(0, DL, MVT::i32), // vindex
7035       Offsets.first,    // voffset
7036       Op.getOperand(4), // soffset
7037       Offsets.second,   // offset
7038       Op.getOperand(5), // cachepolicy, swizzled buffer
7039       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7040     };
7041 
7042     auto *M = cast<MemSDNode>(Op);
7043     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]);
7044     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
7045   }
7046   case Intrinsic::amdgcn_struct_buffer_load:
7047   case Intrinsic::amdgcn_struct_buffer_load_format: {
7048     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
7049 
7050     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7051     SDValue Ops[] = {
7052       Op.getOperand(0), // Chain
7053       Op.getOperand(2), // rsrc
7054       Op.getOperand(3), // vindex
7055       Offsets.first,    // voffset
7056       Op.getOperand(5), // soffset
7057       Offsets.second,   // offset
7058       Op.getOperand(6), // cachepolicy, swizzled buffer
7059       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7060     };
7061 
7062     auto *M = cast<MemSDNode>(Op);
7063     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7064     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7065   }
7066   case Intrinsic::amdgcn_tbuffer_load: {
7067     MemSDNode *M = cast<MemSDNode>(Op);
7068     EVT LoadVT = Op.getValueType();
7069 
7070     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7071     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7072     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7073     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7074     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7075     SDValue Ops[] = {
7076       Op.getOperand(0),  // Chain
7077       Op.getOperand(2),  // rsrc
7078       Op.getOperand(3),  // vindex
7079       Op.getOperand(4),  // voffset
7080       Op.getOperand(5),  // soffset
7081       Op.getOperand(6),  // offset
7082       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7083       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7084       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7085     };
7086 
7087     if (LoadVT.getScalarType() == MVT::f16)
7088       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7089                                  M, DAG, Ops);
7090     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7091                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7092                                DAG);
7093   }
7094   case Intrinsic::amdgcn_raw_tbuffer_load: {
7095     MemSDNode *M = cast<MemSDNode>(Op);
7096     EVT LoadVT = Op.getValueType();
7097     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7098 
7099     SDValue Ops[] = {
7100       Op.getOperand(0),  // Chain
7101       Op.getOperand(2),  // rsrc
7102       DAG.getConstant(0, DL, MVT::i32), // vindex
7103       Offsets.first,     // voffset
7104       Op.getOperand(4),  // soffset
7105       Offsets.second,    // offset
7106       Op.getOperand(5),  // format
7107       Op.getOperand(6),  // cachepolicy, swizzled buffer
7108       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7109     };
7110 
7111     if (LoadVT.getScalarType() == MVT::f16)
7112       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7113                                  M, DAG, Ops);
7114     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7115                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7116                                DAG);
7117   }
7118   case Intrinsic::amdgcn_struct_tbuffer_load: {
7119     MemSDNode *M = cast<MemSDNode>(Op);
7120     EVT LoadVT = Op.getValueType();
7121     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7122 
7123     SDValue Ops[] = {
7124       Op.getOperand(0),  // Chain
7125       Op.getOperand(2),  // rsrc
7126       Op.getOperand(3),  // vindex
7127       Offsets.first,     // voffset
7128       Op.getOperand(5),  // soffset
7129       Offsets.second,    // offset
7130       Op.getOperand(6),  // format
7131       Op.getOperand(7),  // cachepolicy, swizzled buffer
7132       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7133     };
7134 
7135     if (LoadVT.getScalarType() == MVT::f16)
7136       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7137                                  M, DAG, Ops);
7138     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7139                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7140                                DAG);
7141   }
7142   case Intrinsic::amdgcn_buffer_atomic_swap:
7143   case Intrinsic::amdgcn_buffer_atomic_add:
7144   case Intrinsic::amdgcn_buffer_atomic_sub:
7145   case Intrinsic::amdgcn_buffer_atomic_csub:
7146   case Intrinsic::amdgcn_buffer_atomic_smin:
7147   case Intrinsic::amdgcn_buffer_atomic_umin:
7148   case Intrinsic::amdgcn_buffer_atomic_smax:
7149   case Intrinsic::amdgcn_buffer_atomic_umax:
7150   case Intrinsic::amdgcn_buffer_atomic_and:
7151   case Intrinsic::amdgcn_buffer_atomic_or:
7152   case Intrinsic::amdgcn_buffer_atomic_xor:
7153   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7154     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7155     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7156     SDValue Ops[] = {
7157       Op.getOperand(0), // Chain
7158       Op.getOperand(2), // vdata
7159       Op.getOperand(3), // rsrc
7160       Op.getOperand(4), // vindex
7161       SDValue(),        // voffset -- will be set by setBufferOffsets
7162       SDValue(),        // soffset -- will be set by setBufferOffsets
7163       SDValue(),        // offset -- will be set by setBufferOffsets
7164       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7165       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7166     };
7167     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7168 
7169     EVT VT = Op.getValueType();
7170 
7171     auto *M = cast<MemSDNode>(Op);
7172     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7173     unsigned Opcode = 0;
7174 
7175     switch (IntrID) {
7176     case Intrinsic::amdgcn_buffer_atomic_swap:
7177       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7178       break;
7179     case Intrinsic::amdgcn_buffer_atomic_add:
7180       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7181       break;
7182     case Intrinsic::amdgcn_buffer_atomic_sub:
7183       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7184       break;
7185     case Intrinsic::amdgcn_buffer_atomic_csub:
7186       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7187       break;
7188     case Intrinsic::amdgcn_buffer_atomic_smin:
7189       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7190       break;
7191     case Intrinsic::amdgcn_buffer_atomic_umin:
7192       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7193       break;
7194     case Intrinsic::amdgcn_buffer_atomic_smax:
7195       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7196       break;
7197     case Intrinsic::amdgcn_buffer_atomic_umax:
7198       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7199       break;
7200     case Intrinsic::amdgcn_buffer_atomic_and:
7201       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7202       break;
7203     case Intrinsic::amdgcn_buffer_atomic_or:
7204       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7205       break;
7206     case Intrinsic::amdgcn_buffer_atomic_xor:
7207       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7208       break;
7209     case Intrinsic::amdgcn_buffer_atomic_fadd:
7210       if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7211         DiagnosticInfoUnsupported
7212           NoFpRet(DAG.getMachineFunction().getFunction(),
7213                   "return versions of fp atomics not supported",
7214                   DL.getDebugLoc(), DS_Error);
7215         DAG.getContext()->diagnose(NoFpRet);
7216         return SDValue();
7217       }
7218       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7219       break;
7220     default:
7221       llvm_unreachable("unhandled atomic opcode");
7222     }
7223 
7224     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7225                                    M->getMemOperand());
7226   }
7227   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7228     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7229   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7230     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7231   case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7232     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7233   case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7234     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7235   case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7236     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7237   case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7238     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7239   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7240     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7241   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7242     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7243   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7244     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7245   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7246     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7247   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7248     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7249   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7250     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7251   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7252     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7253   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7254     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7255   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7256     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7257   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7258     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7259   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7260     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7261   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7262     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7263   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7264     return lowerStructBufferAtomicIntrin(Op, DAG,
7265                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7266   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7267     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7268   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7269     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7270   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7271     return lowerStructBufferAtomicIntrin(Op, DAG,
7272                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7273   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7274     return lowerStructBufferAtomicIntrin(Op, DAG,
7275                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7276   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7277     return lowerStructBufferAtomicIntrin(Op, DAG,
7278                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7279   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7280     return lowerStructBufferAtomicIntrin(Op, DAG,
7281                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7282   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7283     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7284   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7285     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7286   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7287     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7288   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7289     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7290   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7291     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7292 
7293   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7294     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7295     unsigned IdxEn = getIdxEn(Op.getOperand(5));
7296     SDValue Ops[] = {
7297       Op.getOperand(0), // Chain
7298       Op.getOperand(2), // src
7299       Op.getOperand(3), // cmp
7300       Op.getOperand(4), // rsrc
7301       Op.getOperand(5), // vindex
7302       SDValue(),        // voffset -- will be set by setBufferOffsets
7303       SDValue(),        // soffset -- will be set by setBufferOffsets
7304       SDValue(),        // offset -- will be set by setBufferOffsets
7305       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7306       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7307     };
7308     setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7309 
7310     EVT VT = Op.getValueType();
7311     auto *M = cast<MemSDNode>(Op);
7312     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7313 
7314     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7315                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7316   }
7317   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7318     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7319     SDValue Ops[] = {
7320       Op.getOperand(0), // Chain
7321       Op.getOperand(2), // src
7322       Op.getOperand(3), // cmp
7323       Op.getOperand(4), // rsrc
7324       DAG.getConstant(0, DL, MVT::i32), // vindex
7325       Offsets.first,    // voffset
7326       Op.getOperand(6), // soffset
7327       Offsets.second,   // offset
7328       Op.getOperand(7), // cachepolicy
7329       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7330     };
7331     EVT VT = Op.getValueType();
7332     auto *M = cast<MemSDNode>(Op);
7333     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]);
7334 
7335     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7336                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7337   }
7338   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7339     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7340     SDValue Ops[] = {
7341       Op.getOperand(0), // Chain
7342       Op.getOperand(2), // src
7343       Op.getOperand(3), // cmp
7344       Op.getOperand(4), // rsrc
7345       Op.getOperand(5), // vindex
7346       Offsets.first,    // voffset
7347       Op.getOperand(7), // soffset
7348       Offsets.second,   // offset
7349       Op.getOperand(8), // cachepolicy
7350       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7351     };
7352     EVT VT = Op.getValueType();
7353     auto *M = cast<MemSDNode>(Op);
7354     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7355 
7356     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7357                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7358   }
7359   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7360     MemSDNode *M = cast<MemSDNode>(Op);
7361     SDValue NodePtr = M->getOperand(2);
7362     SDValue RayExtent = M->getOperand(3);
7363     SDValue RayOrigin = M->getOperand(4);
7364     SDValue RayDir = M->getOperand(5);
7365     SDValue RayInvDir = M->getOperand(6);
7366     SDValue TDescr = M->getOperand(7);
7367 
7368     assert(NodePtr.getValueType() == MVT::i32 ||
7369            NodePtr.getValueType() == MVT::i64);
7370     assert(RayDir.getValueType() == MVT::v4f16 ||
7371            RayDir.getValueType() == MVT::v4f32);
7372 
7373     if (!Subtarget->hasGFX10_AEncoding()) {
7374       emitRemovedIntrinsicError(DAG, DL, Op.getValueType());
7375       return SDValue();
7376     }
7377 
7378     const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7379     const bool Is64 = NodePtr.getValueType() == MVT::i64;
7380     const unsigned NumVDataDwords = 4;
7381     const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
7382     const bool UseNSA = Subtarget->hasNSAEncoding() &&
7383                         NumVAddrDwords <= Subtarget->getNSAMaxSize();
7384     const unsigned BaseOpcodes[2][2] = {
7385         {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
7386         {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
7387          AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
7388     int Opcode;
7389     if (UseNSA) {
7390       Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7391                                      AMDGPU::MIMGEncGfx10NSA, NumVDataDwords,
7392                                      NumVAddrDwords);
7393     } else {
7394       Opcode = AMDGPU::getMIMGOpcode(
7395           BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords,
7396           PowerOf2Ceil(NumVAddrDwords));
7397     }
7398     assert(Opcode != -1);
7399 
7400     SmallVector<SDValue, 16> Ops;
7401 
7402     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7403       SmallVector<SDValue, 3> Lanes;
7404       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7405       if (Lanes[0].getValueSizeInBits() == 32) {
7406         for (unsigned I = 0; I < 3; ++I)
7407           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7408       } else {
7409         if (IsAligned) {
7410           Ops.push_back(
7411             DAG.getBitcast(MVT::i32,
7412                            DAG.getBuildVector(MVT::v2f16, DL,
7413                                               { Lanes[0], Lanes[1] })));
7414           Ops.push_back(Lanes[2]);
7415         } else {
7416           SDValue Elt0 = Ops.pop_back_val();
7417           Ops.push_back(
7418             DAG.getBitcast(MVT::i32,
7419                            DAG.getBuildVector(MVT::v2f16, DL,
7420                                               { Elt0, Lanes[0] })));
7421           Ops.push_back(
7422             DAG.getBitcast(MVT::i32,
7423                            DAG.getBuildVector(MVT::v2f16, DL,
7424                                               { Lanes[1], Lanes[2] })));
7425         }
7426       }
7427     };
7428 
7429     if (Is64)
7430       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7431     else
7432       Ops.push_back(NodePtr);
7433 
7434     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7435     packLanes(RayOrigin, true);
7436     packLanes(RayDir, true);
7437     packLanes(RayInvDir, false);
7438 
7439     if (!UseNSA) {
7440       // Build a single vector containing all the operands so far prepared.
7441       if (NumVAddrDwords > 8) {
7442         SDValue Undef = DAG.getUNDEF(MVT::i32);
7443         Ops.append(16 - Ops.size(), Undef);
7444       }
7445       assert(Ops.size() == 8 || Ops.size() == 16);
7446       SDValue MergedOps = DAG.getBuildVector(
7447           Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops);
7448       Ops.clear();
7449       Ops.push_back(MergedOps);
7450     }
7451 
7452     Ops.push_back(TDescr);
7453     if (IsA16)
7454       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7455     Ops.push_back(M->getChain());
7456 
7457     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7458     MachineMemOperand *MemRef = M->getMemOperand();
7459     DAG.setNodeMemRefs(NewNode, {MemRef});
7460     return SDValue(NewNode, 0);
7461   }
7462   case Intrinsic::amdgcn_global_atomic_fadd:
7463     if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7464       DiagnosticInfoUnsupported
7465         NoFpRet(DAG.getMachineFunction().getFunction(),
7466                 "return versions of fp atomics not supported",
7467                 DL.getDebugLoc(), DS_Error);
7468       DAG.getContext()->diagnose(NoFpRet);
7469       return SDValue();
7470     }
7471     LLVM_FALLTHROUGH;
7472   case Intrinsic::amdgcn_global_atomic_fmin:
7473   case Intrinsic::amdgcn_global_atomic_fmax:
7474   case Intrinsic::amdgcn_flat_atomic_fadd:
7475   case Intrinsic::amdgcn_flat_atomic_fmin:
7476   case Intrinsic::amdgcn_flat_atomic_fmax: {
7477     MemSDNode *M = cast<MemSDNode>(Op);
7478     SDValue Ops[] = {
7479       M->getOperand(0), // Chain
7480       M->getOperand(2), // Ptr
7481       M->getOperand(3)  // Value
7482     };
7483     unsigned Opcode = 0;
7484     switch (IntrID) {
7485     case Intrinsic::amdgcn_global_atomic_fadd:
7486     case Intrinsic::amdgcn_flat_atomic_fadd: {
7487       EVT VT = Op.getOperand(3).getValueType();
7488       return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7489                            DAG.getVTList(VT, MVT::Other), Ops,
7490                            M->getMemOperand());
7491     }
7492     case Intrinsic::amdgcn_global_atomic_fmin:
7493     case Intrinsic::amdgcn_flat_atomic_fmin: {
7494       Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7495       break;
7496     }
7497     case Intrinsic::amdgcn_global_atomic_fmax:
7498     case Intrinsic::amdgcn_flat_atomic_fmax: {
7499       Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7500       break;
7501     }
7502     default:
7503       llvm_unreachable("unhandled atomic opcode");
7504     }
7505     return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7506                                    M->getVTList(), Ops, M->getMemoryVT(),
7507                                    M->getMemOperand());
7508   }
7509   default:
7510 
7511     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7512             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7513       return lowerImage(Op, ImageDimIntr, DAG, true);
7514 
7515     return SDValue();
7516   }
7517 }
7518 
7519 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7520 // dwordx4 if on SI.
7521 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7522                                               SDVTList VTList,
7523                                               ArrayRef<SDValue> Ops, EVT MemVT,
7524                                               MachineMemOperand *MMO,
7525                                               SelectionDAG &DAG) const {
7526   EVT VT = VTList.VTs[0];
7527   EVT WidenedVT = VT;
7528   EVT WidenedMemVT = MemVT;
7529   if (!Subtarget->hasDwordx3LoadStores() &&
7530       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7531     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7532                                  WidenedVT.getVectorElementType(), 4);
7533     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7534                                     WidenedMemVT.getVectorElementType(), 4);
7535     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7536   }
7537 
7538   assert(VTList.NumVTs == 2);
7539   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7540 
7541   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7542                                        WidenedMemVT, MMO);
7543   if (WidenedVT != VT) {
7544     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7545                                DAG.getVectorIdxConstant(0, DL));
7546     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7547   }
7548   return NewOp;
7549 }
7550 
7551 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7552                                          bool ImageStore) const {
7553   EVT StoreVT = VData.getValueType();
7554 
7555   // No change for f16 and legal vector D16 types.
7556   if (!StoreVT.isVector())
7557     return VData;
7558 
7559   SDLoc DL(VData);
7560   unsigned NumElements = StoreVT.getVectorNumElements();
7561 
7562   if (Subtarget->hasUnpackedD16VMem()) {
7563     // We need to unpack the packed data to store.
7564     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7565     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7566 
7567     EVT EquivStoreVT =
7568         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7569     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7570     return DAG.UnrollVectorOp(ZExt.getNode());
7571   }
7572 
7573   // The sq block of gfx8.1 does not estimate register use correctly for d16
7574   // image store instructions. The data operand is computed as if it were not a
7575   // d16 image instruction.
7576   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7577     // Bitcast to i16
7578     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7579     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7580 
7581     // Decompose into scalars
7582     SmallVector<SDValue, 4> Elts;
7583     DAG.ExtractVectorElements(IntVData, Elts);
7584 
7585     // Group pairs of i16 into v2i16 and bitcast to i32
7586     SmallVector<SDValue, 4> PackedElts;
7587     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7588       SDValue Pair =
7589           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7590       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7591       PackedElts.push_back(IntPair);
7592     }
7593     if ((NumElements % 2) == 1) {
7594       // Handle v3i16
7595       unsigned I = Elts.size() / 2;
7596       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7597                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7598       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7599       PackedElts.push_back(IntPair);
7600     }
7601 
7602     // Pad using UNDEF
7603     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7604 
7605     // Build final vector
7606     EVT VecVT =
7607         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7608     return DAG.getBuildVector(VecVT, DL, PackedElts);
7609   }
7610 
7611   if (NumElements == 3) {
7612     EVT IntStoreVT =
7613         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7614     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7615 
7616     EVT WidenedStoreVT = EVT::getVectorVT(
7617         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7618     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7619                                          WidenedStoreVT.getStoreSizeInBits());
7620     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7621     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7622   }
7623 
7624   assert(isTypeLegal(StoreVT));
7625   return VData;
7626 }
7627 
7628 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7629                                               SelectionDAG &DAG) const {
7630   SDLoc DL(Op);
7631   SDValue Chain = Op.getOperand(0);
7632   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7633   MachineFunction &MF = DAG.getMachineFunction();
7634 
7635   switch (IntrinsicID) {
7636   case Intrinsic::amdgcn_exp_compr: {
7637     SDValue Src0 = Op.getOperand(4);
7638     SDValue Src1 = Op.getOperand(5);
7639     // Hack around illegal type on SI by directly selecting it.
7640     if (isTypeLegal(Src0.getValueType()))
7641       return SDValue();
7642 
7643     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7644     SDValue Undef = DAG.getUNDEF(MVT::f32);
7645     const SDValue Ops[] = {
7646       Op.getOperand(2), // tgt
7647       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7648       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7649       Undef, // src2
7650       Undef, // src3
7651       Op.getOperand(7), // vm
7652       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7653       Op.getOperand(3), // en
7654       Op.getOperand(0) // Chain
7655     };
7656 
7657     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7658     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7659   }
7660   case Intrinsic::amdgcn_s_barrier: {
7661     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7662       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7663       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7664       if (WGSize <= ST.getWavefrontSize())
7665         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7666                                           Op.getOperand(0)), 0);
7667     }
7668     return SDValue();
7669   };
7670   case Intrinsic::amdgcn_tbuffer_store: {
7671     SDValue VData = Op.getOperand(2);
7672     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7673     if (IsD16)
7674       VData = handleD16VData(VData, DAG);
7675     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7676     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7677     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7678     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7679     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7680     SDValue Ops[] = {
7681       Chain,
7682       VData,             // vdata
7683       Op.getOperand(3),  // rsrc
7684       Op.getOperand(4),  // vindex
7685       Op.getOperand(5),  // voffset
7686       Op.getOperand(6),  // soffset
7687       Op.getOperand(7),  // offset
7688       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7689       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7690       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7691     };
7692     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7693                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7694     MemSDNode *M = cast<MemSDNode>(Op);
7695     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7696                                    M->getMemoryVT(), M->getMemOperand());
7697   }
7698 
7699   case Intrinsic::amdgcn_struct_tbuffer_store: {
7700     SDValue VData = Op.getOperand(2);
7701     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7702     if (IsD16)
7703       VData = handleD16VData(VData, DAG);
7704     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7705     SDValue Ops[] = {
7706       Chain,
7707       VData,             // vdata
7708       Op.getOperand(3),  // rsrc
7709       Op.getOperand(4),  // vindex
7710       Offsets.first,     // voffset
7711       Op.getOperand(6),  // soffset
7712       Offsets.second,    // offset
7713       Op.getOperand(7),  // format
7714       Op.getOperand(8),  // cachepolicy, swizzled buffer
7715       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7716     };
7717     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7718                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7719     MemSDNode *M = cast<MemSDNode>(Op);
7720     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7721                                    M->getMemoryVT(), M->getMemOperand());
7722   }
7723 
7724   case Intrinsic::amdgcn_raw_tbuffer_store: {
7725     SDValue VData = Op.getOperand(2);
7726     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7727     if (IsD16)
7728       VData = handleD16VData(VData, DAG);
7729     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7730     SDValue Ops[] = {
7731       Chain,
7732       VData,             // vdata
7733       Op.getOperand(3),  // rsrc
7734       DAG.getConstant(0, DL, MVT::i32), // vindex
7735       Offsets.first,     // voffset
7736       Op.getOperand(5),  // soffset
7737       Offsets.second,    // offset
7738       Op.getOperand(6),  // format
7739       Op.getOperand(7),  // cachepolicy, swizzled buffer
7740       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7741     };
7742     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7743                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7744     MemSDNode *M = cast<MemSDNode>(Op);
7745     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7746                                    M->getMemoryVT(), M->getMemOperand());
7747   }
7748 
7749   case Intrinsic::amdgcn_buffer_store:
7750   case Intrinsic::amdgcn_buffer_store_format: {
7751     SDValue VData = Op.getOperand(2);
7752     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7753     if (IsD16)
7754       VData = handleD16VData(VData, DAG);
7755     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7756     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7757     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7758     SDValue Ops[] = {
7759       Chain,
7760       VData,
7761       Op.getOperand(3), // rsrc
7762       Op.getOperand(4), // vindex
7763       SDValue(), // voffset -- will be set by setBufferOffsets
7764       SDValue(), // soffset -- will be set by setBufferOffsets
7765       SDValue(), // offset -- will be set by setBufferOffsets
7766       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7767       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7768     };
7769     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7770 
7771     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7772                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7773     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7774     MemSDNode *M = cast<MemSDNode>(Op);
7775     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7776 
7777     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7778     EVT VDataType = VData.getValueType().getScalarType();
7779     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7780       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7781 
7782     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7783                                    M->getMemoryVT(), M->getMemOperand());
7784   }
7785 
7786   case Intrinsic::amdgcn_raw_buffer_store:
7787   case Intrinsic::amdgcn_raw_buffer_store_format: {
7788     const bool IsFormat =
7789         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7790 
7791     SDValue VData = Op.getOperand(2);
7792     EVT VDataVT = VData.getValueType();
7793     EVT EltType = VDataVT.getScalarType();
7794     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7795     if (IsD16) {
7796       VData = handleD16VData(VData, DAG);
7797       VDataVT = VData.getValueType();
7798     }
7799 
7800     if (!isTypeLegal(VDataVT)) {
7801       VData =
7802           DAG.getNode(ISD::BITCAST, DL,
7803                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7804     }
7805 
7806     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7807     SDValue Ops[] = {
7808       Chain,
7809       VData,
7810       Op.getOperand(3), // rsrc
7811       DAG.getConstant(0, DL, MVT::i32), // vindex
7812       Offsets.first,    // voffset
7813       Op.getOperand(5), // soffset
7814       Offsets.second,   // offset
7815       Op.getOperand(6), // cachepolicy, swizzled buffer
7816       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7817     };
7818     unsigned Opc =
7819         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7820     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7821     MemSDNode *M = cast<MemSDNode>(Op);
7822     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
7823 
7824     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7825     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7826       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7827 
7828     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7829                                    M->getMemoryVT(), M->getMemOperand());
7830   }
7831 
7832   case Intrinsic::amdgcn_struct_buffer_store:
7833   case Intrinsic::amdgcn_struct_buffer_store_format: {
7834     const bool IsFormat =
7835         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7836 
7837     SDValue VData = Op.getOperand(2);
7838     EVT VDataVT = VData.getValueType();
7839     EVT EltType = VDataVT.getScalarType();
7840     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7841 
7842     if (IsD16) {
7843       VData = handleD16VData(VData, DAG);
7844       VDataVT = VData.getValueType();
7845     }
7846 
7847     if (!isTypeLegal(VDataVT)) {
7848       VData =
7849           DAG.getNode(ISD::BITCAST, DL,
7850                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7851     }
7852 
7853     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7854     SDValue Ops[] = {
7855       Chain,
7856       VData,
7857       Op.getOperand(3), // rsrc
7858       Op.getOperand(4), // vindex
7859       Offsets.first,    // voffset
7860       Op.getOperand(6), // soffset
7861       Offsets.second,   // offset
7862       Op.getOperand(7), // cachepolicy, swizzled buffer
7863       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7864     };
7865     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7866                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7867     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7868     MemSDNode *M = cast<MemSDNode>(Op);
7869     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7870 
7871     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7872     EVT VDataType = VData.getValueType().getScalarType();
7873     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7874       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7875 
7876     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7877                                    M->getMemoryVT(), M->getMemOperand());
7878   }
7879   case Intrinsic::amdgcn_end_cf:
7880     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7881                                       Op->getOperand(2), Chain), 0);
7882 
7883   default: {
7884     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7885             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7886       return lowerImage(Op, ImageDimIntr, DAG, true);
7887 
7888     return Op;
7889   }
7890   }
7891 }
7892 
7893 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7894 // offset (the offset that is included in bounds checking and swizzling, to be
7895 // split between the instruction's voffset and immoffset fields) and soffset
7896 // (the offset that is excluded from bounds checking and swizzling, to go in
7897 // the instruction's soffset field).  This function takes the first kind of
7898 // offset and figures out how to split it between voffset and immoffset.
7899 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7900     SDValue Offset, SelectionDAG &DAG) const {
7901   SDLoc DL(Offset);
7902   const unsigned MaxImm = 4095;
7903   SDValue N0 = Offset;
7904   ConstantSDNode *C1 = nullptr;
7905 
7906   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7907     N0 = SDValue();
7908   else if (DAG.isBaseWithConstantOffset(N0)) {
7909     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7910     N0 = N0.getOperand(0);
7911   }
7912 
7913   if (C1) {
7914     unsigned ImmOffset = C1->getZExtValue();
7915     // If the immediate value is too big for the immoffset field, put the value
7916     // and -4096 into the immoffset field so that the value that is copied/added
7917     // for the voffset field is a multiple of 4096, and it stands more chance
7918     // of being CSEd with the copy/add for another similar load/store.
7919     // However, do not do that rounding down to a multiple of 4096 if that is a
7920     // negative number, as it appears to be illegal to have a negative offset
7921     // in the vgpr, even if adding the immediate offset makes it positive.
7922     unsigned Overflow = ImmOffset & ~MaxImm;
7923     ImmOffset -= Overflow;
7924     if ((int32_t)Overflow < 0) {
7925       Overflow += ImmOffset;
7926       ImmOffset = 0;
7927     }
7928     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7929     if (Overflow) {
7930       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7931       if (!N0)
7932         N0 = OverflowVal;
7933       else {
7934         SDValue Ops[] = { N0, OverflowVal };
7935         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7936       }
7937     }
7938   }
7939   if (!N0)
7940     N0 = DAG.getConstant(0, DL, MVT::i32);
7941   if (!C1)
7942     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7943   return {N0, SDValue(C1, 0)};
7944 }
7945 
7946 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7947 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7948 // pointed to by Offsets.
7949 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7950                                         SelectionDAG &DAG, SDValue *Offsets,
7951                                         Align Alignment) const {
7952   SDLoc DL(CombinedOffset);
7953   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7954     uint32_t Imm = C->getZExtValue();
7955     uint32_t SOffset, ImmOffset;
7956     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
7957                                  Alignment)) {
7958       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7959       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7960       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7961       return;
7962     }
7963   }
7964   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7965     SDValue N0 = CombinedOffset.getOperand(0);
7966     SDValue N1 = CombinedOffset.getOperand(1);
7967     uint32_t SOffset, ImmOffset;
7968     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7969     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7970                                                 Subtarget, Alignment)) {
7971       Offsets[0] = N0;
7972       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7973       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7974       return;
7975     }
7976   }
7977   Offsets[0] = CombinedOffset;
7978   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7979   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7980 }
7981 
7982 // Handle 8 bit and 16 bit buffer loads
7983 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7984                                                      EVT LoadVT, SDLoc DL,
7985                                                      ArrayRef<SDValue> Ops,
7986                                                      MemSDNode *M) const {
7987   EVT IntVT = LoadVT.changeTypeToInteger();
7988   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7989          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7990 
7991   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7992   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7993                                                Ops, IntVT,
7994                                                M->getMemOperand());
7995   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7996   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7997 
7998   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7999 }
8000 
8001 // Handle 8 bit and 16 bit buffer stores
8002 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
8003                                                       EVT VDataType, SDLoc DL,
8004                                                       SDValue Ops[],
8005                                                       MemSDNode *M) const {
8006   if (VDataType == MVT::f16)
8007     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
8008 
8009   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
8010   Ops[1] = BufferStoreExt;
8011   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
8012                                  AMDGPUISD::BUFFER_STORE_SHORT;
8013   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
8014   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
8015                                      M->getMemOperand());
8016 }
8017 
8018 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
8019                                  ISD::LoadExtType ExtType, SDValue Op,
8020                                  const SDLoc &SL, EVT VT) {
8021   if (VT.bitsLT(Op.getValueType()))
8022     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
8023 
8024   switch (ExtType) {
8025   case ISD::SEXTLOAD:
8026     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
8027   case ISD::ZEXTLOAD:
8028     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
8029   case ISD::EXTLOAD:
8030     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
8031   case ISD::NON_EXTLOAD:
8032     return Op;
8033   }
8034 
8035   llvm_unreachable("invalid ext type");
8036 }
8037 
8038 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
8039   SelectionDAG &DAG = DCI.DAG;
8040   if (Ld->getAlignment() < 4 || Ld->isDivergent())
8041     return SDValue();
8042 
8043   // FIXME: Constant loads should all be marked invariant.
8044   unsigned AS = Ld->getAddressSpace();
8045   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
8046       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
8047       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
8048     return SDValue();
8049 
8050   // Don't do this early, since it may interfere with adjacent load merging for
8051   // illegal types. We can avoid losing alignment information for exotic types
8052   // pre-legalize.
8053   EVT MemVT = Ld->getMemoryVT();
8054   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
8055       MemVT.getSizeInBits() >= 32)
8056     return SDValue();
8057 
8058   SDLoc SL(Ld);
8059 
8060   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
8061          "unexpected vector extload");
8062 
8063   // TODO: Drop only high part of range.
8064   SDValue Ptr = Ld->getBasePtr();
8065   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
8066                                 MVT::i32, SL, Ld->getChain(), Ptr,
8067                                 Ld->getOffset(),
8068                                 Ld->getPointerInfo(), MVT::i32,
8069                                 Ld->getAlignment(),
8070                                 Ld->getMemOperand()->getFlags(),
8071                                 Ld->getAAInfo(),
8072                                 nullptr); // Drop ranges
8073 
8074   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
8075   if (MemVT.isFloatingPoint()) {
8076     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
8077            "unexpected fp extload");
8078     TruncVT = MemVT.changeTypeToInteger();
8079   }
8080 
8081   SDValue Cvt = NewLoad;
8082   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
8083     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
8084                       DAG.getValueType(TruncVT));
8085   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
8086              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
8087     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
8088   } else {
8089     assert(Ld->getExtensionType() == ISD::EXTLOAD);
8090   }
8091 
8092   EVT VT = Ld->getValueType(0);
8093   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8094 
8095   DCI.AddToWorklist(Cvt.getNode());
8096 
8097   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
8098   // the appropriate extension from the 32-bit load.
8099   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
8100   DCI.AddToWorklist(Cvt.getNode());
8101 
8102   // Handle conversion back to floating point if necessary.
8103   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8104 
8105   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8106 }
8107 
8108 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8109   SDLoc DL(Op);
8110   LoadSDNode *Load = cast<LoadSDNode>(Op);
8111   ISD::LoadExtType ExtType = Load->getExtensionType();
8112   EVT MemVT = Load->getMemoryVT();
8113 
8114   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8115     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8116       return SDValue();
8117 
8118     // FIXME: Copied from PPC
8119     // First, load into 32 bits, then truncate to 1 bit.
8120 
8121     SDValue Chain = Load->getChain();
8122     SDValue BasePtr = Load->getBasePtr();
8123     MachineMemOperand *MMO = Load->getMemOperand();
8124 
8125     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8126 
8127     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8128                                    BasePtr, RealMemVT, MMO);
8129 
8130     if (!MemVT.isVector()) {
8131       SDValue Ops[] = {
8132         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8133         NewLD.getValue(1)
8134       };
8135 
8136       return DAG.getMergeValues(Ops, DL);
8137     }
8138 
8139     SmallVector<SDValue, 3> Elts;
8140     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8141       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8142                                 DAG.getConstant(I, DL, MVT::i32));
8143 
8144       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8145     }
8146 
8147     SDValue Ops[] = {
8148       DAG.getBuildVector(MemVT, DL, Elts),
8149       NewLD.getValue(1)
8150     };
8151 
8152     return DAG.getMergeValues(Ops, DL);
8153   }
8154 
8155   if (!MemVT.isVector())
8156     return SDValue();
8157 
8158   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8159          "Custom lowering for non-i32 vectors hasn't been implemented.");
8160 
8161   unsigned Alignment = Load->getAlignment();
8162   unsigned AS = Load->getAddressSpace();
8163   if (Subtarget->hasLDSMisalignedBug() &&
8164       AS == AMDGPUAS::FLAT_ADDRESS &&
8165       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8166     return SplitVectorLoad(Op, DAG);
8167   }
8168 
8169   MachineFunction &MF = DAG.getMachineFunction();
8170   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8171   // If there is a possibilty that flat instruction access scratch memory
8172   // then we need to use the same legalization rules we use for private.
8173   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8174       !Subtarget->hasMultiDwordFlatScratchAddressing())
8175     AS = MFI->hasFlatScratchInit() ?
8176          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8177 
8178   unsigned NumElements = MemVT.getVectorNumElements();
8179 
8180   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8181       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8182     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8183       if (MemVT.isPow2VectorType())
8184         return SDValue();
8185       return WidenOrSplitVectorLoad(Op, DAG);
8186     }
8187     // Non-uniform loads will be selected to MUBUF instructions, so they
8188     // have the same legalization requirements as global and private
8189     // loads.
8190     //
8191   }
8192 
8193   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8194       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8195       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8196     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8197         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8198         Alignment >= 4 && NumElements < 32) {
8199       if (MemVT.isPow2VectorType())
8200         return SDValue();
8201       return WidenOrSplitVectorLoad(Op, DAG);
8202     }
8203     // Non-uniform loads will be selected to MUBUF instructions, so they
8204     // have the same legalization requirements as global and private
8205     // loads.
8206     //
8207   }
8208   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8209       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8210       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8211       AS == AMDGPUAS::FLAT_ADDRESS) {
8212     if (NumElements > 4)
8213       return SplitVectorLoad(Op, DAG);
8214     // v3 loads not supported on SI.
8215     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8216       return WidenOrSplitVectorLoad(Op, DAG);
8217 
8218     // v3 and v4 loads are supported for private and global memory.
8219     return SDValue();
8220   }
8221   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8222     // Depending on the setting of the private_element_size field in the
8223     // resource descriptor, we can only make private accesses up to a certain
8224     // size.
8225     switch (Subtarget->getMaxPrivateElementSize()) {
8226     case 4: {
8227       SDValue Ops[2];
8228       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8229       return DAG.getMergeValues(Ops, DL);
8230     }
8231     case 8:
8232       if (NumElements > 2)
8233         return SplitVectorLoad(Op, DAG);
8234       return SDValue();
8235     case 16:
8236       // Same as global/flat
8237       if (NumElements > 4)
8238         return SplitVectorLoad(Op, DAG);
8239       // v3 loads not supported on SI.
8240       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8241         return WidenOrSplitVectorLoad(Op, DAG);
8242 
8243       return SDValue();
8244     default:
8245       llvm_unreachable("unsupported private_element_size");
8246     }
8247   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8248     // Use ds_read_b128 or ds_read_b96 when possible.
8249     if (Subtarget->hasDS96AndDS128() &&
8250         ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) ||
8251          MemVT.getStoreSize() == 12) &&
8252         allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8253                                            Load->getAlign()))
8254       return SDValue();
8255 
8256     if (NumElements > 2)
8257       return SplitVectorLoad(Op, DAG);
8258 
8259     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8260     // address is negative, then the instruction is incorrectly treated as
8261     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8262     // loads here to avoid emitting ds_read2_b32. We may re-combine the
8263     // load later in the SILoadStoreOptimizer.
8264     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
8265         NumElements == 2 && MemVT.getStoreSize() == 8 &&
8266         Load->getAlignment() < 8) {
8267       return SplitVectorLoad(Op, DAG);
8268     }
8269   }
8270 
8271   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8272                                       MemVT, *Load->getMemOperand())) {
8273     SDValue Ops[2];
8274     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8275     return DAG.getMergeValues(Ops, DL);
8276   }
8277 
8278   return SDValue();
8279 }
8280 
8281 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8282   EVT VT = Op.getValueType();
8283   assert(VT.getSizeInBits() == 64);
8284 
8285   SDLoc DL(Op);
8286   SDValue Cond = Op.getOperand(0);
8287 
8288   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8289   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8290 
8291   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8292   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8293 
8294   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8295   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8296 
8297   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8298 
8299   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8300   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8301 
8302   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8303 
8304   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8305   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8306 }
8307 
8308 // Catch division cases where we can use shortcuts with rcp and rsq
8309 // instructions.
8310 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8311                                               SelectionDAG &DAG) const {
8312   SDLoc SL(Op);
8313   SDValue LHS = Op.getOperand(0);
8314   SDValue RHS = Op.getOperand(1);
8315   EVT VT = Op.getValueType();
8316   const SDNodeFlags Flags = Op->getFlags();
8317 
8318   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8319 
8320   // Without !fpmath accuracy information, we can't do more because we don't
8321   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8322   if (!AllowInaccurateRcp)
8323     return SDValue();
8324 
8325   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8326     if (CLHS->isExactlyValue(1.0)) {
8327       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8328       // the CI documentation has a worst case error of 1 ulp.
8329       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8330       // use it as long as we aren't trying to use denormals.
8331       //
8332       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8333 
8334       // 1.0 / sqrt(x) -> rsq(x)
8335 
8336       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8337       // error seems really high at 2^29 ULP.
8338       if (RHS.getOpcode() == ISD::FSQRT)
8339         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8340 
8341       // 1.0 / x -> rcp(x)
8342       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8343     }
8344 
8345     // Same as for 1.0, but expand the sign out of the constant.
8346     if (CLHS->isExactlyValue(-1.0)) {
8347       // -1.0 / x -> rcp (fneg x)
8348       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8349       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8350     }
8351   }
8352 
8353   // Turn into multiply by the reciprocal.
8354   // x / y -> x * (1.0 / y)
8355   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8356   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8357 }
8358 
8359 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8360                                                 SelectionDAG &DAG) const {
8361   SDLoc SL(Op);
8362   SDValue X = Op.getOperand(0);
8363   SDValue Y = Op.getOperand(1);
8364   EVT VT = Op.getValueType();
8365   const SDNodeFlags Flags = Op->getFlags();
8366 
8367   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8368                             DAG.getTarget().Options.UnsafeFPMath;
8369   if (!AllowInaccurateDiv)
8370     return SDValue();
8371 
8372   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8373   SDValue One = DAG.getConstantFP(1.0, SL, VT);
8374 
8375   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8376   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8377 
8378   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8379   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8380   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8381   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8382   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8383   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8384 }
8385 
8386 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8387                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8388                           SDNodeFlags Flags) {
8389   if (GlueChain->getNumValues() <= 1) {
8390     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8391   }
8392 
8393   assert(GlueChain->getNumValues() == 3);
8394 
8395   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8396   switch (Opcode) {
8397   default: llvm_unreachable("no chain equivalent for opcode");
8398   case ISD::FMUL:
8399     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8400     break;
8401   }
8402 
8403   return DAG.getNode(Opcode, SL, VTList,
8404                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8405                      Flags);
8406 }
8407 
8408 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8409                            EVT VT, SDValue A, SDValue B, SDValue C,
8410                            SDValue GlueChain, SDNodeFlags Flags) {
8411   if (GlueChain->getNumValues() <= 1) {
8412     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8413   }
8414 
8415   assert(GlueChain->getNumValues() == 3);
8416 
8417   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8418   switch (Opcode) {
8419   default: llvm_unreachable("no chain equivalent for opcode");
8420   case ISD::FMA:
8421     Opcode = AMDGPUISD::FMA_W_CHAIN;
8422     break;
8423   }
8424 
8425   return DAG.getNode(Opcode, SL, VTList,
8426                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8427                      Flags);
8428 }
8429 
8430 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8431   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8432     return FastLowered;
8433 
8434   SDLoc SL(Op);
8435   SDValue Src0 = Op.getOperand(0);
8436   SDValue Src1 = Op.getOperand(1);
8437 
8438   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8439   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8440 
8441   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8442   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8443 
8444   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8445   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8446 
8447   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8448 }
8449 
8450 // Faster 2.5 ULP division that does not support denormals.
8451 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8452   SDLoc SL(Op);
8453   SDValue LHS = Op.getOperand(1);
8454   SDValue RHS = Op.getOperand(2);
8455 
8456   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8457 
8458   const APFloat K0Val(BitsToFloat(0x6f800000));
8459   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8460 
8461   const APFloat K1Val(BitsToFloat(0x2f800000));
8462   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8463 
8464   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8465 
8466   EVT SetCCVT =
8467     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8468 
8469   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8470 
8471   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8472 
8473   // TODO: Should this propagate fast-math-flags?
8474   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8475 
8476   // rcp does not support denormals.
8477   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8478 
8479   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8480 
8481   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8482 }
8483 
8484 // Returns immediate value for setting the F32 denorm mode when using the
8485 // S_DENORM_MODE instruction.
8486 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8487                                     const SDLoc &SL, const GCNSubtarget *ST) {
8488   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8489   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8490                                 ? FP_DENORM_FLUSH_NONE
8491                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8492 
8493   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8494   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8495 }
8496 
8497 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8498   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8499     return FastLowered;
8500 
8501   // The selection matcher assumes anything with a chain selecting to a
8502   // mayRaiseFPException machine instruction. Since we're introducing a chain
8503   // here, we need to explicitly report nofpexcept for the regular fdiv
8504   // lowering.
8505   SDNodeFlags Flags = Op->getFlags();
8506   Flags.setNoFPExcept(true);
8507 
8508   SDLoc SL(Op);
8509   SDValue LHS = Op.getOperand(0);
8510   SDValue RHS = Op.getOperand(1);
8511 
8512   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8513 
8514   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8515 
8516   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8517                                           {RHS, RHS, LHS}, Flags);
8518   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8519                                         {LHS, RHS, LHS}, Flags);
8520 
8521   // Denominator is scaled to not be denormal, so using rcp is ok.
8522   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8523                                   DenominatorScaled, Flags);
8524   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8525                                      DenominatorScaled, Flags);
8526 
8527   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8528                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8529                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8530   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8531 
8532   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8533 
8534   if (!HasFP32Denormals) {
8535     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8536     // lowering. The chain dependence is insufficient, and we need glue. We do
8537     // not need the glue variants in a strictfp function.
8538 
8539     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8540 
8541     SDNode *EnableDenorm;
8542     if (Subtarget->hasDenormModeInst()) {
8543       const SDValue EnableDenormValue =
8544           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8545 
8546       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8547                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8548     } else {
8549       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8550                                                         SL, MVT::i32);
8551       EnableDenorm =
8552           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8553                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8554     }
8555 
8556     SDValue Ops[3] = {
8557       NegDivScale0,
8558       SDValue(EnableDenorm, 0),
8559       SDValue(EnableDenorm, 1)
8560     };
8561 
8562     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8563   }
8564 
8565   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8566                              ApproxRcp, One, NegDivScale0, Flags);
8567 
8568   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8569                              ApproxRcp, Fma0, Flags);
8570 
8571   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8572                            Fma1, Fma1, Flags);
8573 
8574   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8575                              NumeratorScaled, Mul, Flags);
8576 
8577   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8578                              Fma2, Fma1, Mul, Fma2, Flags);
8579 
8580   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8581                              NumeratorScaled, Fma3, Flags);
8582 
8583   if (!HasFP32Denormals) {
8584     SDNode *DisableDenorm;
8585     if (Subtarget->hasDenormModeInst()) {
8586       const SDValue DisableDenormValue =
8587           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8588 
8589       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8590                                   Fma4.getValue(1), DisableDenormValue,
8591                                   Fma4.getValue(2)).getNode();
8592     } else {
8593       const SDValue DisableDenormValue =
8594           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8595 
8596       DisableDenorm = DAG.getMachineNode(
8597           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8598           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8599     }
8600 
8601     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8602                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8603     DAG.setRoot(OutputChain);
8604   }
8605 
8606   SDValue Scale = NumeratorScaled.getValue(1);
8607   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8608                              {Fma4, Fma1, Fma3, Scale}, Flags);
8609 
8610   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8611 }
8612 
8613 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8614   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
8615     return FastLowered;
8616 
8617   SDLoc SL(Op);
8618   SDValue X = Op.getOperand(0);
8619   SDValue Y = Op.getOperand(1);
8620 
8621   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8622 
8623   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8624 
8625   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8626 
8627   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8628 
8629   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8630 
8631   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8632 
8633   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8634 
8635   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8636 
8637   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8638 
8639   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8640   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8641 
8642   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8643                              NegDivScale0, Mul, DivScale1);
8644 
8645   SDValue Scale;
8646 
8647   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8648     // Workaround a hardware bug on SI where the condition output from div_scale
8649     // is not usable.
8650 
8651     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8652 
8653     // Figure out if the scale to use for div_fmas.
8654     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8655     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8656     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8657     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8658 
8659     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8660     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8661 
8662     SDValue Scale0Hi
8663       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8664     SDValue Scale1Hi
8665       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8666 
8667     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8668     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8669     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8670   } else {
8671     Scale = DivScale1.getValue(1);
8672   }
8673 
8674   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8675                              Fma4, Fma3, Mul, Scale);
8676 
8677   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8678 }
8679 
8680 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8681   EVT VT = Op.getValueType();
8682 
8683   if (VT == MVT::f32)
8684     return LowerFDIV32(Op, DAG);
8685 
8686   if (VT == MVT::f64)
8687     return LowerFDIV64(Op, DAG);
8688 
8689   if (VT == MVT::f16)
8690     return LowerFDIV16(Op, DAG);
8691 
8692   llvm_unreachable("Unexpected type for fdiv");
8693 }
8694 
8695 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8696   SDLoc DL(Op);
8697   StoreSDNode *Store = cast<StoreSDNode>(Op);
8698   EVT VT = Store->getMemoryVT();
8699 
8700   if (VT == MVT::i1) {
8701     return DAG.getTruncStore(Store->getChain(), DL,
8702        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8703        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8704   }
8705 
8706   assert(VT.isVector() &&
8707          Store->getValue().getValueType().getScalarType() == MVT::i32);
8708 
8709   unsigned AS = Store->getAddressSpace();
8710   if (Subtarget->hasLDSMisalignedBug() &&
8711       AS == AMDGPUAS::FLAT_ADDRESS &&
8712       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8713     return SplitVectorStore(Op, DAG);
8714   }
8715 
8716   MachineFunction &MF = DAG.getMachineFunction();
8717   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8718   // If there is a possibilty that flat instruction access scratch memory
8719   // then we need to use the same legalization rules we use for private.
8720   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8721       !Subtarget->hasMultiDwordFlatScratchAddressing())
8722     AS = MFI->hasFlatScratchInit() ?
8723          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8724 
8725   unsigned NumElements = VT.getVectorNumElements();
8726   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8727       AS == AMDGPUAS::FLAT_ADDRESS) {
8728     if (NumElements > 4)
8729       return SplitVectorStore(Op, DAG);
8730     // v3 stores not supported on SI.
8731     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8732       return SplitVectorStore(Op, DAG);
8733 
8734     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8735                                         VT, *Store->getMemOperand()))
8736       return expandUnalignedStore(Store, DAG);
8737 
8738     return SDValue();
8739   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8740     switch (Subtarget->getMaxPrivateElementSize()) {
8741     case 4:
8742       return scalarizeVectorStore(Store, DAG);
8743     case 8:
8744       if (NumElements > 2)
8745         return SplitVectorStore(Op, DAG);
8746       return SDValue();
8747     case 16:
8748       if (NumElements > 4 ||
8749           (NumElements == 3 && !Subtarget->enableFlatScratch()))
8750         return SplitVectorStore(Op, DAG);
8751       return SDValue();
8752     default:
8753       llvm_unreachable("unsupported private_element_size");
8754     }
8755   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8756     // Use ds_write_b128 or ds_write_b96 when possible.
8757     if (Subtarget->hasDS96AndDS128() &&
8758         ((Subtarget->useDS128() && VT.getStoreSize() == 16) ||
8759          (VT.getStoreSize() == 12)) &&
8760         allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
8761                                            Store->getAlign()))
8762       return SDValue();
8763 
8764     if (NumElements > 2)
8765       return SplitVectorStore(Op, DAG);
8766 
8767     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8768     // address is negative, then the instruction is incorrectly treated as
8769     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8770     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8771     // store later in the SILoadStoreOptimizer.
8772     if (!Subtarget->hasUsableDSOffset() &&
8773         NumElements == 2 && VT.getStoreSize() == 8 &&
8774         Store->getAlignment() < 8) {
8775       return SplitVectorStore(Op, DAG);
8776     }
8777 
8778     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8779                                         VT, *Store->getMemOperand())) {
8780       if (VT.isVector())
8781         return SplitVectorStore(Op, DAG);
8782       return expandUnalignedStore(Store, DAG);
8783     }
8784 
8785     return SDValue();
8786   } else {
8787     llvm_unreachable("unhandled address space");
8788   }
8789 }
8790 
8791 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8792   SDLoc DL(Op);
8793   EVT VT = Op.getValueType();
8794   SDValue Arg = Op.getOperand(0);
8795   SDValue TrigVal;
8796 
8797   // Propagate fast-math flags so that the multiply we introduce can be folded
8798   // if Arg is already the result of a multiply by constant.
8799   auto Flags = Op->getFlags();
8800 
8801   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
8802 
8803   if (Subtarget->hasTrigReducedRange()) {
8804     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8805     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
8806   } else {
8807     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8808   }
8809 
8810   switch (Op.getOpcode()) {
8811   case ISD::FCOS:
8812     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
8813   case ISD::FSIN:
8814     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
8815   default:
8816     llvm_unreachable("Wrong trig opcode");
8817   }
8818 }
8819 
8820 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8821   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8822   assert(AtomicNode->isCompareAndSwap());
8823   unsigned AS = AtomicNode->getAddressSpace();
8824 
8825   // No custom lowering required for local address space
8826   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
8827     return Op;
8828 
8829   // Non-local address space requires custom lowering for atomic compare
8830   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8831   SDLoc DL(Op);
8832   SDValue ChainIn = Op.getOperand(0);
8833   SDValue Addr = Op.getOperand(1);
8834   SDValue Old = Op.getOperand(2);
8835   SDValue New = Op.getOperand(3);
8836   EVT VT = Op.getValueType();
8837   MVT SimpleVT = VT.getSimpleVT();
8838   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8839 
8840   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8841   SDValue Ops[] = { ChainIn, Addr, NewOld };
8842 
8843   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8844                                  Ops, VT, AtomicNode->getMemOperand());
8845 }
8846 
8847 //===----------------------------------------------------------------------===//
8848 // Custom DAG optimizations
8849 //===----------------------------------------------------------------------===//
8850 
8851 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8852                                                      DAGCombinerInfo &DCI) const {
8853   EVT VT = N->getValueType(0);
8854   EVT ScalarVT = VT.getScalarType();
8855   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8856     return SDValue();
8857 
8858   SelectionDAG &DAG = DCI.DAG;
8859   SDLoc DL(N);
8860 
8861   SDValue Src = N->getOperand(0);
8862   EVT SrcVT = Src.getValueType();
8863 
8864   // TODO: We could try to match extracting the higher bytes, which would be
8865   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8866   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8867   // about in practice.
8868   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8869     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8870       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8871       DCI.AddToWorklist(Cvt.getNode());
8872 
8873       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8874       if (ScalarVT != MVT::f32) {
8875         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8876                           DAG.getTargetConstant(0, DL, MVT::i32));
8877       }
8878       return Cvt;
8879     }
8880   }
8881 
8882   return SDValue();
8883 }
8884 
8885 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8886 
8887 // This is a variant of
8888 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8889 //
8890 // The normal DAG combiner will do this, but only if the add has one use since
8891 // that would increase the number of instructions.
8892 //
8893 // This prevents us from seeing a constant offset that can be folded into a
8894 // memory instruction's addressing mode. If we know the resulting add offset of
8895 // a pointer can be folded into an addressing offset, we can replace the pointer
8896 // operand with the add of new constant offset. This eliminates one of the uses,
8897 // and may allow the remaining use to also be simplified.
8898 //
8899 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8900                                                unsigned AddrSpace,
8901                                                EVT MemVT,
8902                                                DAGCombinerInfo &DCI) const {
8903   SDValue N0 = N->getOperand(0);
8904   SDValue N1 = N->getOperand(1);
8905 
8906   // We only do this to handle cases where it's profitable when there are
8907   // multiple uses of the add, so defer to the standard combine.
8908   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8909       N0->hasOneUse())
8910     return SDValue();
8911 
8912   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8913   if (!CN1)
8914     return SDValue();
8915 
8916   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8917   if (!CAdd)
8918     return SDValue();
8919 
8920   // If the resulting offset is too large, we can't fold it into the addressing
8921   // mode offset.
8922   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8923   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8924 
8925   AddrMode AM;
8926   AM.HasBaseReg = true;
8927   AM.BaseOffs = Offset.getSExtValue();
8928   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8929     return SDValue();
8930 
8931   SelectionDAG &DAG = DCI.DAG;
8932   SDLoc SL(N);
8933   EVT VT = N->getValueType(0);
8934 
8935   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8936   SDValue COffset = DAG.getConstant(Offset, SL, VT);
8937 
8938   SDNodeFlags Flags;
8939   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8940                           (N0.getOpcode() == ISD::OR ||
8941                            N0->getFlags().hasNoUnsignedWrap()));
8942 
8943   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8944 }
8945 
8946 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
8947 /// by the chain and intrinsic ID. Theoretically we would also need to check the
8948 /// specific intrinsic, but they all place the pointer operand first.
8949 static unsigned getBasePtrIndex(const MemSDNode *N) {
8950   switch (N->getOpcode()) {
8951   case ISD::STORE:
8952   case ISD::INTRINSIC_W_CHAIN:
8953   case ISD::INTRINSIC_VOID:
8954     return 2;
8955   default:
8956     return 1;
8957   }
8958 }
8959 
8960 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8961                                                   DAGCombinerInfo &DCI) const {
8962   SelectionDAG &DAG = DCI.DAG;
8963   SDLoc SL(N);
8964 
8965   unsigned PtrIdx = getBasePtrIndex(N);
8966   SDValue Ptr = N->getOperand(PtrIdx);
8967 
8968   // TODO: We could also do this for multiplies.
8969   if (Ptr.getOpcode() == ISD::SHL) {
8970     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8971                                           N->getMemoryVT(), DCI);
8972     if (NewPtr) {
8973       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8974 
8975       NewOps[PtrIdx] = NewPtr;
8976       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8977     }
8978   }
8979 
8980   return SDValue();
8981 }
8982 
8983 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8984   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8985          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8986          (Opc == ISD::XOR && Val == 0);
8987 }
8988 
8989 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8990 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8991 // integer combine opportunities since most 64-bit operations are decomposed
8992 // this way.  TODO: We won't want this for SALU especially if it is an inline
8993 // immediate.
8994 SDValue SITargetLowering::splitBinaryBitConstantOp(
8995   DAGCombinerInfo &DCI,
8996   const SDLoc &SL,
8997   unsigned Opc, SDValue LHS,
8998   const ConstantSDNode *CRHS) const {
8999   uint64_t Val = CRHS->getZExtValue();
9000   uint32_t ValLo = Lo_32(Val);
9001   uint32_t ValHi = Hi_32(Val);
9002   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9003 
9004     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
9005          bitOpWithConstantIsReducible(Opc, ValHi)) ||
9006         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
9007     // If we need to materialize a 64-bit immediate, it will be split up later
9008     // anyway. Avoid creating the harder to understand 64-bit immediate
9009     // materialization.
9010     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
9011   }
9012 
9013   return SDValue();
9014 }
9015 
9016 // Returns true if argument is a boolean value which is not serialized into
9017 // memory or argument and does not require v_cndmask_b32 to be deserialized.
9018 static bool isBoolSGPR(SDValue V) {
9019   if (V.getValueType() != MVT::i1)
9020     return false;
9021   switch (V.getOpcode()) {
9022   default:
9023     break;
9024   case ISD::SETCC:
9025   case AMDGPUISD::FP_CLASS:
9026     return true;
9027   case ISD::AND:
9028   case ISD::OR:
9029   case ISD::XOR:
9030     return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
9031   }
9032   return false;
9033 }
9034 
9035 // If a constant has all zeroes or all ones within each byte return it.
9036 // Otherwise return 0.
9037 static uint32_t getConstantPermuteMask(uint32_t C) {
9038   // 0xff for any zero byte in the mask
9039   uint32_t ZeroByteMask = 0;
9040   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
9041   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
9042   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
9043   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
9044   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
9045   if ((NonZeroByteMask & C) != NonZeroByteMask)
9046     return 0; // Partial bytes selected.
9047   return C;
9048 }
9049 
9050 // Check if a node selects whole bytes from its operand 0 starting at a byte
9051 // boundary while masking the rest. Returns select mask as in the v_perm_b32
9052 // or -1 if not succeeded.
9053 // Note byte select encoding:
9054 // value 0-3 selects corresponding source byte;
9055 // value 0xc selects zero;
9056 // value 0xff selects 0xff.
9057 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
9058   assert(V.getValueSizeInBits() == 32);
9059 
9060   if (V.getNumOperands() != 2)
9061     return ~0;
9062 
9063   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
9064   if (!N1)
9065     return ~0;
9066 
9067   uint32_t C = N1->getZExtValue();
9068 
9069   switch (V.getOpcode()) {
9070   default:
9071     break;
9072   case ISD::AND:
9073     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9074       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
9075     }
9076     break;
9077 
9078   case ISD::OR:
9079     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9080       return (0x03020100 & ~ConstMask) | ConstMask;
9081     }
9082     break;
9083 
9084   case ISD::SHL:
9085     if (C % 8)
9086       return ~0;
9087 
9088     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
9089 
9090   case ISD::SRL:
9091     if (C % 8)
9092       return ~0;
9093 
9094     return uint32_t(0x0c0c0c0c03020100ull >> C);
9095   }
9096 
9097   return ~0;
9098 }
9099 
9100 SDValue SITargetLowering::performAndCombine(SDNode *N,
9101                                             DAGCombinerInfo &DCI) const {
9102   if (DCI.isBeforeLegalize())
9103     return SDValue();
9104 
9105   SelectionDAG &DAG = DCI.DAG;
9106   EVT VT = N->getValueType(0);
9107   SDValue LHS = N->getOperand(0);
9108   SDValue RHS = N->getOperand(1);
9109 
9110 
9111   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9112   if (VT == MVT::i64 && CRHS) {
9113     if (SDValue Split
9114         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9115       return Split;
9116   }
9117 
9118   if (CRHS && VT == MVT::i32) {
9119     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9120     // nb = number of trailing zeroes in mask
9121     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9122     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9123     uint64_t Mask = CRHS->getZExtValue();
9124     unsigned Bits = countPopulation(Mask);
9125     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9126         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9127       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9128         unsigned Shift = CShift->getZExtValue();
9129         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9130         unsigned Offset = NB + Shift;
9131         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9132           SDLoc SL(N);
9133           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9134                                     LHS->getOperand(0),
9135                                     DAG.getConstant(Offset, SL, MVT::i32),
9136                                     DAG.getConstant(Bits, SL, MVT::i32));
9137           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9138           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9139                                     DAG.getValueType(NarrowVT));
9140           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9141                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9142           return Shl;
9143         }
9144       }
9145     }
9146 
9147     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9148     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9149         isa<ConstantSDNode>(LHS.getOperand(2))) {
9150       uint32_t Sel = getConstantPermuteMask(Mask);
9151       if (!Sel)
9152         return SDValue();
9153 
9154       // Select 0xc for all zero bytes
9155       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9156       SDLoc DL(N);
9157       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9158                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9159     }
9160   }
9161 
9162   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9163   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9164   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9165     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9166     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9167 
9168     SDValue X = LHS.getOperand(0);
9169     SDValue Y = RHS.getOperand(0);
9170     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9171       return SDValue();
9172 
9173     if (LCC == ISD::SETO) {
9174       if (X != LHS.getOperand(1))
9175         return SDValue();
9176 
9177       if (RCC == ISD::SETUNE) {
9178         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9179         if (!C1 || !C1->isInfinity() || C1->isNegative())
9180           return SDValue();
9181 
9182         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9183                               SIInstrFlags::N_SUBNORMAL |
9184                               SIInstrFlags::N_ZERO |
9185                               SIInstrFlags::P_ZERO |
9186                               SIInstrFlags::P_SUBNORMAL |
9187                               SIInstrFlags::P_NORMAL;
9188 
9189         static_assert(((~(SIInstrFlags::S_NAN |
9190                           SIInstrFlags::Q_NAN |
9191                           SIInstrFlags::N_INFINITY |
9192                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9193                       "mask not equal");
9194 
9195         SDLoc DL(N);
9196         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9197                            X, DAG.getConstant(Mask, DL, MVT::i32));
9198       }
9199     }
9200   }
9201 
9202   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9203     std::swap(LHS, RHS);
9204 
9205   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9206       RHS.hasOneUse()) {
9207     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9208     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9209     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9210     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9211     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9212         (RHS.getOperand(0) == LHS.getOperand(0) &&
9213          LHS.getOperand(0) == LHS.getOperand(1))) {
9214       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9215       unsigned NewMask = LCC == ISD::SETO ?
9216         Mask->getZExtValue() & ~OrdMask :
9217         Mask->getZExtValue() & OrdMask;
9218 
9219       SDLoc DL(N);
9220       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9221                          DAG.getConstant(NewMask, DL, MVT::i32));
9222     }
9223   }
9224 
9225   if (VT == MVT::i32 &&
9226       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9227     // and x, (sext cc from i1) => select cc, x, 0
9228     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9229       std::swap(LHS, RHS);
9230     if (isBoolSGPR(RHS.getOperand(0)))
9231       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9232                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9233   }
9234 
9235   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9236   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9237   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9238       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9239     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9240     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9241     if (LHSMask != ~0u && RHSMask != ~0u) {
9242       // Canonicalize the expression in an attempt to have fewer unique masks
9243       // and therefore fewer registers used to hold the masks.
9244       if (LHSMask > RHSMask) {
9245         std::swap(LHSMask, RHSMask);
9246         std::swap(LHS, RHS);
9247       }
9248 
9249       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9250       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9251       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9252       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9253 
9254       // Check of we need to combine values from two sources within a byte.
9255       if (!(LHSUsedLanes & RHSUsedLanes) &&
9256           // If we select high and lower word keep it for SDWA.
9257           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9258           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9259         // Each byte in each mask is either selector mask 0-3, or has higher
9260         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9261         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9262         // mask which is not 0xff wins. By anding both masks we have a correct
9263         // result except that 0x0c shall be corrected to give 0x0c only.
9264         uint32_t Mask = LHSMask & RHSMask;
9265         for (unsigned I = 0; I < 32; I += 8) {
9266           uint32_t ByteSel = 0xff << I;
9267           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9268             Mask &= (0x0c << I) & 0xffffffff;
9269         }
9270 
9271         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9272         // or 0x0c.
9273         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9274         SDLoc DL(N);
9275 
9276         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9277                            LHS.getOperand(0), RHS.getOperand(0),
9278                            DAG.getConstant(Sel, DL, MVT::i32));
9279       }
9280     }
9281   }
9282 
9283   return SDValue();
9284 }
9285 
9286 SDValue SITargetLowering::performOrCombine(SDNode *N,
9287                                            DAGCombinerInfo &DCI) const {
9288   SelectionDAG &DAG = DCI.DAG;
9289   SDValue LHS = N->getOperand(0);
9290   SDValue RHS = N->getOperand(1);
9291 
9292   EVT VT = N->getValueType(0);
9293   if (VT == MVT::i1) {
9294     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9295     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9296         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9297       SDValue Src = LHS.getOperand(0);
9298       if (Src != RHS.getOperand(0))
9299         return SDValue();
9300 
9301       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9302       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9303       if (!CLHS || !CRHS)
9304         return SDValue();
9305 
9306       // Only 10 bits are used.
9307       static const uint32_t MaxMask = 0x3ff;
9308 
9309       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9310       SDLoc DL(N);
9311       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9312                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9313     }
9314 
9315     return SDValue();
9316   }
9317 
9318   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9319   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9320       LHS.getOpcode() == AMDGPUISD::PERM &&
9321       isa<ConstantSDNode>(LHS.getOperand(2))) {
9322     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9323     if (!Sel)
9324       return SDValue();
9325 
9326     Sel |= LHS.getConstantOperandVal(2);
9327     SDLoc DL(N);
9328     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9329                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9330   }
9331 
9332   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9333   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9334   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9335       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9336     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9337     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9338     if (LHSMask != ~0u && RHSMask != ~0u) {
9339       // Canonicalize the expression in an attempt to have fewer unique masks
9340       // and therefore fewer registers used to hold the masks.
9341       if (LHSMask > RHSMask) {
9342         std::swap(LHSMask, RHSMask);
9343         std::swap(LHS, RHS);
9344       }
9345 
9346       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9347       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9348       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9349       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9350 
9351       // Check of we need to combine values from two sources within a byte.
9352       if (!(LHSUsedLanes & RHSUsedLanes) &&
9353           // If we select high and lower word keep it for SDWA.
9354           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9355           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9356         // Kill zero bytes selected by other mask. Zero value is 0xc.
9357         LHSMask &= ~RHSUsedLanes;
9358         RHSMask &= ~LHSUsedLanes;
9359         // Add 4 to each active LHS lane
9360         LHSMask |= LHSUsedLanes & 0x04040404;
9361         // Combine masks
9362         uint32_t Sel = LHSMask | RHSMask;
9363         SDLoc DL(N);
9364 
9365         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9366                            LHS.getOperand(0), RHS.getOperand(0),
9367                            DAG.getConstant(Sel, DL, MVT::i32));
9368       }
9369     }
9370   }
9371 
9372   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9373     return SDValue();
9374 
9375   // TODO: This could be a generic combine with a predicate for extracting the
9376   // high half of an integer being free.
9377 
9378   // (or i64:x, (zero_extend i32:y)) ->
9379   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9380   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9381       RHS.getOpcode() != ISD::ZERO_EXTEND)
9382     std::swap(LHS, RHS);
9383 
9384   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9385     SDValue ExtSrc = RHS.getOperand(0);
9386     EVT SrcVT = ExtSrc.getValueType();
9387     if (SrcVT == MVT::i32) {
9388       SDLoc SL(N);
9389       SDValue LowLHS, HiBits;
9390       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9391       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9392 
9393       DCI.AddToWorklist(LowOr.getNode());
9394       DCI.AddToWorklist(HiBits.getNode());
9395 
9396       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9397                                 LowOr, HiBits);
9398       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9399     }
9400   }
9401 
9402   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9403   if (CRHS) {
9404     if (SDValue Split
9405           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
9406       return Split;
9407   }
9408 
9409   return SDValue();
9410 }
9411 
9412 SDValue SITargetLowering::performXorCombine(SDNode *N,
9413                                             DAGCombinerInfo &DCI) const {
9414   EVT VT = N->getValueType(0);
9415   if (VT != MVT::i64)
9416     return SDValue();
9417 
9418   SDValue LHS = N->getOperand(0);
9419   SDValue RHS = N->getOperand(1);
9420 
9421   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9422   if (CRHS) {
9423     if (SDValue Split
9424           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9425       return Split;
9426   }
9427 
9428   return SDValue();
9429 }
9430 
9431 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9432                                                    DAGCombinerInfo &DCI) const {
9433   if (!Subtarget->has16BitInsts() ||
9434       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9435     return SDValue();
9436 
9437   EVT VT = N->getValueType(0);
9438   if (VT != MVT::i32)
9439     return SDValue();
9440 
9441   SDValue Src = N->getOperand(0);
9442   if (Src.getValueType() != MVT::i16)
9443     return SDValue();
9444 
9445   return SDValue();
9446 }
9447 
9448 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9449                                                         DAGCombinerInfo &DCI)
9450                                                         const {
9451   SDValue Src = N->getOperand(0);
9452   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9453 
9454   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9455       VTSign->getVT() == MVT::i8) ||
9456       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9457       VTSign->getVT() == MVT::i16)) &&
9458       Src.hasOneUse()) {
9459     auto *M = cast<MemSDNode>(Src);
9460     SDValue Ops[] = {
9461       Src.getOperand(0), // Chain
9462       Src.getOperand(1), // rsrc
9463       Src.getOperand(2), // vindex
9464       Src.getOperand(3), // voffset
9465       Src.getOperand(4), // soffset
9466       Src.getOperand(5), // offset
9467       Src.getOperand(6),
9468       Src.getOperand(7)
9469     };
9470     // replace with BUFFER_LOAD_BYTE/SHORT
9471     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9472                                          Src.getOperand(0).getValueType());
9473     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9474                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9475     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9476                                                           ResList,
9477                                                           Ops, M->getMemoryVT(),
9478                                                           M->getMemOperand());
9479     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9480                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9481   }
9482   return SDValue();
9483 }
9484 
9485 SDValue SITargetLowering::performClassCombine(SDNode *N,
9486                                               DAGCombinerInfo &DCI) const {
9487   SelectionDAG &DAG = DCI.DAG;
9488   SDValue Mask = N->getOperand(1);
9489 
9490   // fp_class x, 0 -> false
9491   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9492     if (CMask->isNullValue())
9493       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9494   }
9495 
9496   if (N->getOperand(0).isUndef())
9497     return DAG.getUNDEF(MVT::i1);
9498 
9499   return SDValue();
9500 }
9501 
9502 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9503                                             DAGCombinerInfo &DCI) const {
9504   EVT VT = N->getValueType(0);
9505   SDValue N0 = N->getOperand(0);
9506 
9507   if (N0.isUndef())
9508     return N0;
9509 
9510   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9511                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9512     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9513                            N->getFlags());
9514   }
9515 
9516   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9517     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9518                            N0.getOperand(0), N->getFlags());
9519   }
9520 
9521   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9522 }
9523 
9524 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9525                                        unsigned MaxDepth) const {
9526   unsigned Opcode = Op.getOpcode();
9527   if (Opcode == ISD::FCANONICALIZE)
9528     return true;
9529 
9530   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9531     auto F = CFP->getValueAPF();
9532     if (F.isNaN() && F.isSignaling())
9533       return false;
9534     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9535   }
9536 
9537   // If source is a result of another standard FP operation it is already in
9538   // canonical form.
9539   if (MaxDepth == 0)
9540     return false;
9541 
9542   switch (Opcode) {
9543   // These will flush denorms if required.
9544   case ISD::FADD:
9545   case ISD::FSUB:
9546   case ISD::FMUL:
9547   case ISD::FCEIL:
9548   case ISD::FFLOOR:
9549   case ISD::FMA:
9550   case ISD::FMAD:
9551   case ISD::FSQRT:
9552   case ISD::FDIV:
9553   case ISD::FREM:
9554   case ISD::FP_ROUND:
9555   case ISD::FP_EXTEND:
9556   case AMDGPUISD::FMUL_LEGACY:
9557   case AMDGPUISD::FMAD_FTZ:
9558   case AMDGPUISD::RCP:
9559   case AMDGPUISD::RSQ:
9560   case AMDGPUISD::RSQ_CLAMP:
9561   case AMDGPUISD::RCP_LEGACY:
9562   case AMDGPUISD::RCP_IFLAG:
9563   case AMDGPUISD::DIV_SCALE:
9564   case AMDGPUISD::DIV_FMAS:
9565   case AMDGPUISD::DIV_FIXUP:
9566   case AMDGPUISD::FRACT:
9567   case AMDGPUISD::LDEXP:
9568   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9569   case AMDGPUISD::CVT_F32_UBYTE0:
9570   case AMDGPUISD::CVT_F32_UBYTE1:
9571   case AMDGPUISD::CVT_F32_UBYTE2:
9572   case AMDGPUISD::CVT_F32_UBYTE3:
9573     return true;
9574 
9575   // It can/will be lowered or combined as a bit operation.
9576   // Need to check their input recursively to handle.
9577   case ISD::FNEG:
9578   case ISD::FABS:
9579   case ISD::FCOPYSIGN:
9580     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9581 
9582   case ISD::FSIN:
9583   case ISD::FCOS:
9584   case ISD::FSINCOS:
9585     return Op.getValueType().getScalarType() != MVT::f16;
9586 
9587   case ISD::FMINNUM:
9588   case ISD::FMAXNUM:
9589   case ISD::FMINNUM_IEEE:
9590   case ISD::FMAXNUM_IEEE:
9591   case AMDGPUISD::CLAMP:
9592   case AMDGPUISD::FMED3:
9593   case AMDGPUISD::FMAX3:
9594   case AMDGPUISD::FMIN3: {
9595     // FIXME: Shouldn't treat the generic operations different based these.
9596     // However, we aren't really required to flush the result from
9597     // minnum/maxnum..
9598 
9599     // snans will be quieted, so we only need to worry about denormals.
9600     if (Subtarget->supportsMinMaxDenormModes() ||
9601         denormalsEnabledForType(DAG, Op.getValueType()))
9602       return true;
9603 
9604     // Flushing may be required.
9605     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9606     // targets need to check their input recursively.
9607 
9608     // FIXME: Does this apply with clamp? It's implemented with max.
9609     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9610       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9611         return false;
9612     }
9613 
9614     return true;
9615   }
9616   case ISD::SELECT: {
9617     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9618            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9619   }
9620   case ISD::BUILD_VECTOR: {
9621     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9622       SDValue SrcOp = Op.getOperand(i);
9623       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9624         return false;
9625     }
9626 
9627     return true;
9628   }
9629   case ISD::EXTRACT_VECTOR_ELT:
9630   case ISD::EXTRACT_SUBVECTOR: {
9631     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9632   }
9633   case ISD::INSERT_VECTOR_ELT: {
9634     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9635            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9636   }
9637   case ISD::UNDEF:
9638     // Could be anything.
9639     return false;
9640 
9641   case ISD::BITCAST:
9642     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9643   case ISD::TRUNCATE: {
9644     // Hack round the mess we make when legalizing extract_vector_elt
9645     if (Op.getValueType() == MVT::i16) {
9646       SDValue TruncSrc = Op.getOperand(0);
9647       if (TruncSrc.getValueType() == MVT::i32 &&
9648           TruncSrc.getOpcode() == ISD::BITCAST &&
9649           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9650         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9651       }
9652     }
9653     return false;
9654   }
9655   case ISD::INTRINSIC_WO_CHAIN: {
9656     unsigned IntrinsicID
9657       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9658     // TODO: Handle more intrinsics
9659     switch (IntrinsicID) {
9660     case Intrinsic::amdgcn_cvt_pkrtz:
9661     case Intrinsic::amdgcn_cubeid:
9662     case Intrinsic::amdgcn_frexp_mant:
9663     case Intrinsic::amdgcn_fdot2:
9664     case Intrinsic::amdgcn_rcp:
9665     case Intrinsic::amdgcn_rsq:
9666     case Intrinsic::amdgcn_rsq_clamp:
9667     case Intrinsic::amdgcn_rcp_legacy:
9668     case Intrinsic::amdgcn_rsq_legacy:
9669     case Intrinsic::amdgcn_trig_preop:
9670       return true;
9671     default:
9672       break;
9673     }
9674 
9675     LLVM_FALLTHROUGH;
9676   }
9677   default:
9678     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9679            DAG.isKnownNeverSNaN(Op);
9680   }
9681 
9682   llvm_unreachable("invalid operation");
9683 }
9684 
9685 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
9686                                        unsigned MaxDepth) const {
9687   MachineRegisterInfo &MRI = MF.getRegInfo();
9688   MachineInstr *MI = MRI.getVRegDef(Reg);
9689   unsigned Opcode = MI->getOpcode();
9690 
9691   if (Opcode == AMDGPU::G_FCANONICALIZE)
9692     return true;
9693 
9694   if (Opcode == AMDGPU::G_FCONSTANT) {
9695     auto F = MI->getOperand(1).getFPImm()->getValueAPF();
9696     if (F.isNaN() && F.isSignaling())
9697       return false;
9698     return !F.isDenormal() || denormalsEnabledForType(MRI.getType(Reg), MF);
9699   }
9700 
9701   if (MaxDepth == 0)
9702     return false;
9703 
9704   switch (Opcode) {
9705   case AMDGPU::G_FMINNUM_IEEE:
9706   case AMDGPU::G_FMAXNUM_IEEE: {
9707     if (Subtarget->supportsMinMaxDenormModes() ||
9708         denormalsEnabledForType(MRI.getType(Reg), MF))
9709       return true;
9710     for (unsigned I = 1, E = MI->getNumOperands(); I != E; ++I) {
9711       if (!isCanonicalized(MI->getOperand(I).getReg(), MF, MaxDepth - 1))
9712         return false;
9713     }
9714     return true;
9715   }
9716   default:
9717     return denormalsEnabledForType(MRI.getType(Reg), MF) &&
9718            isKnownNeverSNaN(Reg, MRI);
9719   }
9720 
9721   llvm_unreachable("invalid operation");
9722 }
9723 
9724 // Constant fold canonicalize.
9725 SDValue SITargetLowering::getCanonicalConstantFP(
9726   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9727   // Flush denormals to 0 if not enabled.
9728   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9729     return DAG.getConstantFP(0.0, SL, VT);
9730 
9731   if (C.isNaN()) {
9732     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9733     if (C.isSignaling()) {
9734       // Quiet a signaling NaN.
9735       // FIXME: Is this supposed to preserve payload bits?
9736       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9737     }
9738 
9739     // Make sure it is the canonical NaN bitpattern.
9740     //
9741     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9742     // immediate?
9743     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9744       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9745   }
9746 
9747   // Already canonical.
9748   return DAG.getConstantFP(C, SL, VT);
9749 }
9750 
9751 static bool vectorEltWillFoldAway(SDValue Op) {
9752   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9753 }
9754 
9755 SDValue SITargetLowering::performFCanonicalizeCombine(
9756   SDNode *N,
9757   DAGCombinerInfo &DCI) const {
9758   SelectionDAG &DAG = DCI.DAG;
9759   SDValue N0 = N->getOperand(0);
9760   EVT VT = N->getValueType(0);
9761 
9762   // fcanonicalize undef -> qnan
9763   if (N0.isUndef()) {
9764     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9765     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9766   }
9767 
9768   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9769     EVT VT = N->getValueType(0);
9770     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9771   }
9772 
9773   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9774   //                                                   (fcanonicalize k)
9775   //
9776   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9777 
9778   // TODO: This could be better with wider vectors that will be split to v2f16,
9779   // and to consider uses since there aren't that many packed operations.
9780   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9781       isTypeLegal(MVT::v2f16)) {
9782     SDLoc SL(N);
9783     SDValue NewElts[2];
9784     SDValue Lo = N0.getOperand(0);
9785     SDValue Hi = N0.getOperand(1);
9786     EVT EltVT = Lo.getValueType();
9787 
9788     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9789       for (unsigned I = 0; I != 2; ++I) {
9790         SDValue Op = N0.getOperand(I);
9791         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9792           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9793                                               CFP->getValueAPF());
9794         } else if (Op.isUndef()) {
9795           // Handled below based on what the other operand is.
9796           NewElts[I] = Op;
9797         } else {
9798           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9799         }
9800       }
9801 
9802       // If one half is undef, and one is constant, perfer a splat vector rather
9803       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9804       // cheaper to use and may be free with a packed operation.
9805       if (NewElts[0].isUndef()) {
9806         if (isa<ConstantFPSDNode>(NewElts[1]))
9807           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9808             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9809       }
9810 
9811       if (NewElts[1].isUndef()) {
9812         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9813           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9814       }
9815 
9816       return DAG.getBuildVector(VT, SL, NewElts);
9817     }
9818   }
9819 
9820   unsigned SrcOpc = N0.getOpcode();
9821 
9822   // If it's free to do so, push canonicalizes further up the source, which may
9823   // find a canonical source.
9824   //
9825   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9826   // sNaNs.
9827   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9828     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9829     if (CRHS && N0.hasOneUse()) {
9830       SDLoc SL(N);
9831       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9832                                    N0.getOperand(0));
9833       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9834       DCI.AddToWorklist(Canon0.getNode());
9835 
9836       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9837     }
9838   }
9839 
9840   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9841 }
9842 
9843 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9844   switch (Opc) {
9845   case ISD::FMAXNUM:
9846   case ISD::FMAXNUM_IEEE:
9847     return AMDGPUISD::FMAX3;
9848   case ISD::SMAX:
9849     return AMDGPUISD::SMAX3;
9850   case ISD::UMAX:
9851     return AMDGPUISD::UMAX3;
9852   case ISD::FMINNUM:
9853   case ISD::FMINNUM_IEEE:
9854     return AMDGPUISD::FMIN3;
9855   case ISD::SMIN:
9856     return AMDGPUISD::SMIN3;
9857   case ISD::UMIN:
9858     return AMDGPUISD::UMIN3;
9859   default:
9860     llvm_unreachable("Not a min/max opcode");
9861   }
9862 }
9863 
9864 SDValue SITargetLowering::performIntMed3ImmCombine(
9865   SelectionDAG &DAG, const SDLoc &SL,
9866   SDValue Op0, SDValue Op1, bool Signed) const {
9867   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9868   if (!K1)
9869     return SDValue();
9870 
9871   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9872   if (!K0)
9873     return SDValue();
9874 
9875   if (Signed) {
9876     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9877       return SDValue();
9878   } else {
9879     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9880       return SDValue();
9881   }
9882 
9883   EVT VT = K0->getValueType(0);
9884   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9885   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9886     return DAG.getNode(Med3Opc, SL, VT,
9887                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9888   }
9889 
9890   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9891   if (VT == MVT::i16) {
9892     MVT NVT = MVT::i32;
9893     unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9894 
9895     SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9896     SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9897     SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9898 
9899     SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9900     return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9901   }
9902 
9903   return SDValue();
9904 }
9905 
9906 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9907   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9908     return C;
9909 
9910   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9911     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9912       return C;
9913   }
9914 
9915   return nullptr;
9916 }
9917 
9918 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9919                                                   const SDLoc &SL,
9920                                                   SDValue Op0,
9921                                                   SDValue Op1) const {
9922   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9923   if (!K1)
9924     return SDValue();
9925 
9926   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9927   if (!K0)
9928     return SDValue();
9929 
9930   // Ordered >= (although NaN inputs should have folded away by now).
9931   if (K0->getValueAPF() > K1->getValueAPF())
9932     return SDValue();
9933 
9934   const MachineFunction &MF = DAG.getMachineFunction();
9935   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9936 
9937   // TODO: Check IEEE bit enabled?
9938   EVT VT = Op0.getValueType();
9939   if (Info->getMode().DX10Clamp) {
9940     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9941     // hardware fmed3 behavior converting to a min.
9942     // FIXME: Should this be allowing -0.0?
9943     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9944       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9945   }
9946 
9947   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9948   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9949     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9950     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9951     // then give the other result, which is different from med3 with a NaN
9952     // input.
9953     SDValue Var = Op0.getOperand(0);
9954     if (!DAG.isKnownNeverSNaN(Var))
9955       return SDValue();
9956 
9957     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9958 
9959     if ((!K0->hasOneUse() ||
9960          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9961         (!K1->hasOneUse() ||
9962          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9963       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9964                          Var, SDValue(K0, 0), SDValue(K1, 0));
9965     }
9966   }
9967 
9968   return SDValue();
9969 }
9970 
9971 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9972                                                DAGCombinerInfo &DCI) const {
9973   SelectionDAG &DAG = DCI.DAG;
9974 
9975   EVT VT = N->getValueType(0);
9976   unsigned Opc = N->getOpcode();
9977   SDValue Op0 = N->getOperand(0);
9978   SDValue Op1 = N->getOperand(1);
9979 
9980   // Only do this if the inner op has one use since this will just increases
9981   // register pressure for no benefit.
9982 
9983   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9984       !VT.isVector() &&
9985       (VT == MVT::i32 || VT == MVT::f32 ||
9986        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9987     // max(max(a, b), c) -> max3(a, b, c)
9988     // min(min(a, b), c) -> min3(a, b, c)
9989     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9990       SDLoc DL(N);
9991       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9992                          DL,
9993                          N->getValueType(0),
9994                          Op0.getOperand(0),
9995                          Op0.getOperand(1),
9996                          Op1);
9997     }
9998 
9999     // Try commuted.
10000     // max(a, max(b, c)) -> max3(a, b, c)
10001     // min(a, min(b, c)) -> min3(a, b, c)
10002     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
10003       SDLoc DL(N);
10004       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10005                          DL,
10006                          N->getValueType(0),
10007                          Op0,
10008                          Op1.getOperand(0),
10009                          Op1.getOperand(1));
10010     }
10011   }
10012 
10013   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
10014   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
10015     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
10016       return Med3;
10017   }
10018 
10019   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
10020     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
10021       return Med3;
10022   }
10023 
10024   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
10025   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
10026        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
10027        (Opc == AMDGPUISD::FMIN_LEGACY &&
10028         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
10029       (VT == MVT::f32 || VT == MVT::f64 ||
10030        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
10031        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
10032       Op0.hasOneUse()) {
10033     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
10034       return Res;
10035   }
10036 
10037   return SDValue();
10038 }
10039 
10040 static bool isClampZeroToOne(SDValue A, SDValue B) {
10041   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
10042     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
10043       // FIXME: Should this be allowing -0.0?
10044       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
10045              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
10046     }
10047   }
10048 
10049   return false;
10050 }
10051 
10052 // FIXME: Should only worry about snans for version with chain.
10053 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
10054                                               DAGCombinerInfo &DCI) const {
10055   EVT VT = N->getValueType(0);
10056   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
10057   // NaNs. With a NaN input, the order of the operands may change the result.
10058 
10059   SelectionDAG &DAG = DCI.DAG;
10060   SDLoc SL(N);
10061 
10062   SDValue Src0 = N->getOperand(0);
10063   SDValue Src1 = N->getOperand(1);
10064   SDValue Src2 = N->getOperand(2);
10065 
10066   if (isClampZeroToOne(Src0, Src1)) {
10067     // const_a, const_b, x -> clamp is safe in all cases including signaling
10068     // nans.
10069     // FIXME: Should this be allowing -0.0?
10070     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
10071   }
10072 
10073   const MachineFunction &MF = DAG.getMachineFunction();
10074   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10075 
10076   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
10077   // handling no dx10-clamp?
10078   if (Info->getMode().DX10Clamp) {
10079     // If NaNs is clamped to 0, we are free to reorder the inputs.
10080 
10081     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10082       std::swap(Src0, Src1);
10083 
10084     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10085       std::swap(Src1, Src2);
10086 
10087     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10088       std::swap(Src0, Src1);
10089 
10090     if (isClampZeroToOne(Src1, Src2))
10091       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10092   }
10093 
10094   return SDValue();
10095 }
10096 
10097 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10098                                                  DAGCombinerInfo &DCI) const {
10099   SDValue Src0 = N->getOperand(0);
10100   SDValue Src1 = N->getOperand(1);
10101   if (Src0.isUndef() && Src1.isUndef())
10102     return DCI.DAG.getUNDEF(N->getValueType(0));
10103   return SDValue();
10104 }
10105 
10106 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10107 // expanded into a set of cmp/select instructions.
10108 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10109                                                 unsigned NumElem,
10110                                                 bool IsDivergentIdx) {
10111   if (UseDivergentRegisterIndexing)
10112     return false;
10113 
10114   unsigned VecSize = EltSize * NumElem;
10115 
10116   // Sub-dword vectors of size 2 dword or less have better implementation.
10117   if (VecSize <= 64 && EltSize < 32)
10118     return false;
10119 
10120   // Always expand the rest of sub-dword instructions, otherwise it will be
10121   // lowered via memory.
10122   if (EltSize < 32)
10123     return true;
10124 
10125   // Always do this if var-idx is divergent, otherwise it will become a loop.
10126   if (IsDivergentIdx)
10127     return true;
10128 
10129   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10130   unsigned NumInsts = NumElem /* Number of compares */ +
10131                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10132   return NumInsts <= 16;
10133 }
10134 
10135 static bool shouldExpandVectorDynExt(SDNode *N) {
10136   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10137   if (isa<ConstantSDNode>(Idx))
10138     return false;
10139 
10140   SDValue Vec = N->getOperand(0);
10141   EVT VecVT = Vec.getValueType();
10142   EVT EltVT = VecVT.getVectorElementType();
10143   unsigned EltSize = EltVT.getSizeInBits();
10144   unsigned NumElem = VecVT.getVectorNumElements();
10145 
10146   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
10147                                                     Idx->isDivergent());
10148 }
10149 
10150 SDValue SITargetLowering::performExtractVectorEltCombine(
10151   SDNode *N, DAGCombinerInfo &DCI) const {
10152   SDValue Vec = N->getOperand(0);
10153   SelectionDAG &DAG = DCI.DAG;
10154 
10155   EVT VecVT = Vec.getValueType();
10156   EVT EltVT = VecVT.getVectorElementType();
10157 
10158   if ((Vec.getOpcode() == ISD::FNEG ||
10159        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10160     SDLoc SL(N);
10161     EVT EltVT = N->getValueType(0);
10162     SDValue Idx = N->getOperand(1);
10163     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10164                               Vec.getOperand(0), Idx);
10165     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10166   }
10167 
10168   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10169   //    =>
10170   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10171   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10172   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10173   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10174     SDLoc SL(N);
10175     EVT EltVT = N->getValueType(0);
10176     SDValue Idx = N->getOperand(1);
10177     unsigned Opc = Vec.getOpcode();
10178 
10179     switch(Opc) {
10180     default:
10181       break;
10182       // TODO: Support other binary operations.
10183     case ISD::FADD:
10184     case ISD::FSUB:
10185     case ISD::FMUL:
10186     case ISD::ADD:
10187     case ISD::UMIN:
10188     case ISD::UMAX:
10189     case ISD::SMIN:
10190     case ISD::SMAX:
10191     case ISD::FMAXNUM:
10192     case ISD::FMINNUM:
10193     case ISD::FMAXNUM_IEEE:
10194     case ISD::FMINNUM_IEEE: {
10195       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10196                                  Vec.getOperand(0), Idx);
10197       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10198                                  Vec.getOperand(1), Idx);
10199 
10200       DCI.AddToWorklist(Elt0.getNode());
10201       DCI.AddToWorklist(Elt1.getNode());
10202       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10203     }
10204     }
10205   }
10206 
10207   unsigned VecSize = VecVT.getSizeInBits();
10208   unsigned EltSize = EltVT.getSizeInBits();
10209 
10210   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10211   if (::shouldExpandVectorDynExt(N)) {
10212     SDLoc SL(N);
10213     SDValue Idx = N->getOperand(1);
10214     SDValue V;
10215     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10216       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10217       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10218       if (I == 0)
10219         V = Elt;
10220       else
10221         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10222     }
10223     return V;
10224   }
10225 
10226   if (!DCI.isBeforeLegalize())
10227     return SDValue();
10228 
10229   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10230   // elements. This exposes more load reduction opportunities by replacing
10231   // multiple small extract_vector_elements with a single 32-bit extract.
10232   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10233   if (isa<MemSDNode>(Vec) &&
10234       EltSize <= 16 &&
10235       EltVT.isByteSized() &&
10236       VecSize > 32 &&
10237       VecSize % 32 == 0 &&
10238       Idx) {
10239     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10240 
10241     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10242     unsigned EltIdx = BitIndex / 32;
10243     unsigned LeftoverBitIdx = BitIndex % 32;
10244     SDLoc SL(N);
10245 
10246     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10247     DCI.AddToWorklist(Cast.getNode());
10248 
10249     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10250                               DAG.getConstant(EltIdx, SL, MVT::i32));
10251     DCI.AddToWorklist(Elt.getNode());
10252     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10253                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10254     DCI.AddToWorklist(Srl.getNode());
10255 
10256     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10257     DCI.AddToWorklist(Trunc.getNode());
10258     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10259   }
10260 
10261   return SDValue();
10262 }
10263 
10264 SDValue
10265 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10266                                                 DAGCombinerInfo &DCI) const {
10267   SDValue Vec = N->getOperand(0);
10268   SDValue Idx = N->getOperand(2);
10269   EVT VecVT = Vec.getValueType();
10270   EVT EltVT = VecVT.getVectorElementType();
10271 
10272   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10273   // => BUILD_VECTOR n x select (e, const-idx)
10274   if (!::shouldExpandVectorDynExt(N))
10275     return SDValue();
10276 
10277   SelectionDAG &DAG = DCI.DAG;
10278   SDLoc SL(N);
10279   SDValue Ins = N->getOperand(1);
10280   EVT IdxVT = Idx.getValueType();
10281 
10282   SmallVector<SDValue, 16> Ops;
10283   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10284     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10285     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10286     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10287     Ops.push_back(V);
10288   }
10289 
10290   return DAG.getBuildVector(VecVT, SL, Ops);
10291 }
10292 
10293 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10294                                           const SDNode *N0,
10295                                           const SDNode *N1) const {
10296   EVT VT = N0->getValueType(0);
10297 
10298   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10299   // support denormals ever.
10300   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10301        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10302         getSubtarget()->hasMadF16())) &&
10303        isOperationLegal(ISD::FMAD, VT))
10304     return ISD::FMAD;
10305 
10306   const TargetOptions &Options = DAG.getTarget().Options;
10307   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10308        (N0->getFlags().hasAllowContract() &&
10309         N1->getFlags().hasAllowContract())) &&
10310       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10311     return ISD::FMA;
10312   }
10313 
10314   return 0;
10315 }
10316 
10317 // For a reassociatable opcode perform:
10318 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10319 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10320                                                SelectionDAG &DAG) const {
10321   EVT VT = N->getValueType(0);
10322   if (VT != MVT::i32 && VT != MVT::i64)
10323     return SDValue();
10324 
10325   unsigned Opc = N->getOpcode();
10326   SDValue Op0 = N->getOperand(0);
10327   SDValue Op1 = N->getOperand(1);
10328 
10329   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10330     return SDValue();
10331 
10332   if (Op0->isDivergent())
10333     std::swap(Op0, Op1);
10334 
10335   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10336     return SDValue();
10337 
10338   SDValue Op2 = Op1.getOperand(1);
10339   Op1 = Op1.getOperand(0);
10340   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10341     return SDValue();
10342 
10343   if (Op1->isDivergent())
10344     std::swap(Op1, Op2);
10345 
10346   // If either operand is constant this will conflict with
10347   // DAGCombiner::ReassociateOps().
10348   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
10349       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
10350     return SDValue();
10351 
10352   SDLoc SL(N);
10353   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10354   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10355 }
10356 
10357 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10358                            EVT VT,
10359                            SDValue N0, SDValue N1, SDValue N2,
10360                            bool Signed) {
10361   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10362   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10363   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10364   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10365 }
10366 
10367 SDValue SITargetLowering::performAddCombine(SDNode *N,
10368                                             DAGCombinerInfo &DCI) const {
10369   SelectionDAG &DAG = DCI.DAG;
10370   EVT VT = N->getValueType(0);
10371   SDLoc SL(N);
10372   SDValue LHS = N->getOperand(0);
10373   SDValue RHS = N->getOperand(1);
10374 
10375   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10376       && Subtarget->hasMad64_32() &&
10377       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10378       VT.getScalarSizeInBits() <= 64) {
10379     if (LHS.getOpcode() != ISD::MUL)
10380       std::swap(LHS, RHS);
10381 
10382     SDValue MulLHS = LHS.getOperand(0);
10383     SDValue MulRHS = LHS.getOperand(1);
10384     SDValue AddRHS = RHS;
10385 
10386     // TODO: Maybe restrict if SGPR inputs.
10387     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10388         numBitsUnsigned(MulRHS, DAG) <= 32) {
10389       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10390       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10391       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10392       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10393     }
10394 
10395     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
10396       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10397       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10398       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10399       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10400     }
10401 
10402     return SDValue();
10403   }
10404 
10405   if (SDValue V = reassociateScalarOps(N, DAG)) {
10406     return V;
10407   }
10408 
10409   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10410     return SDValue();
10411 
10412   // add x, zext (setcc) => addcarry x, 0, setcc
10413   // add x, sext (setcc) => subcarry x, 0, setcc
10414   unsigned Opc = LHS.getOpcode();
10415   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10416       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10417     std::swap(RHS, LHS);
10418 
10419   Opc = RHS.getOpcode();
10420   switch (Opc) {
10421   default: break;
10422   case ISD::ZERO_EXTEND:
10423   case ISD::SIGN_EXTEND:
10424   case ISD::ANY_EXTEND: {
10425     auto Cond = RHS.getOperand(0);
10426     // If this won't be a real VOPC output, we would still need to insert an
10427     // extra instruction anyway.
10428     if (!isBoolSGPR(Cond))
10429       break;
10430     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10431     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10432     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10433     return DAG.getNode(Opc, SL, VTList, Args);
10434   }
10435   case ISD::ADDCARRY: {
10436     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10437     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10438     if (!C || C->getZExtValue() != 0) break;
10439     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10440     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10441   }
10442   }
10443   return SDValue();
10444 }
10445 
10446 SDValue SITargetLowering::performSubCombine(SDNode *N,
10447                                             DAGCombinerInfo &DCI) const {
10448   SelectionDAG &DAG = DCI.DAG;
10449   EVT VT = N->getValueType(0);
10450 
10451   if (VT != MVT::i32)
10452     return SDValue();
10453 
10454   SDLoc SL(N);
10455   SDValue LHS = N->getOperand(0);
10456   SDValue RHS = N->getOperand(1);
10457 
10458   // sub x, zext (setcc) => subcarry x, 0, setcc
10459   // sub x, sext (setcc) => addcarry x, 0, setcc
10460   unsigned Opc = RHS.getOpcode();
10461   switch (Opc) {
10462   default: break;
10463   case ISD::ZERO_EXTEND:
10464   case ISD::SIGN_EXTEND:
10465   case ISD::ANY_EXTEND: {
10466     auto Cond = RHS.getOperand(0);
10467     // If this won't be a real VOPC output, we would still need to insert an
10468     // extra instruction anyway.
10469     if (!isBoolSGPR(Cond))
10470       break;
10471     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10472     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10473     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10474     return DAG.getNode(Opc, SL, VTList, Args);
10475   }
10476   }
10477 
10478   if (LHS.getOpcode() == ISD::SUBCARRY) {
10479     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10480     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10481     if (!C || !C->isNullValue())
10482       return SDValue();
10483     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10484     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10485   }
10486   return SDValue();
10487 }
10488 
10489 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10490   DAGCombinerInfo &DCI) const {
10491 
10492   if (N->getValueType(0) != MVT::i32)
10493     return SDValue();
10494 
10495   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10496   if (!C || C->getZExtValue() != 0)
10497     return SDValue();
10498 
10499   SelectionDAG &DAG = DCI.DAG;
10500   SDValue LHS = N->getOperand(0);
10501 
10502   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10503   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10504   unsigned LHSOpc = LHS.getOpcode();
10505   unsigned Opc = N->getOpcode();
10506   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10507       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10508     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10509     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10510   }
10511   return SDValue();
10512 }
10513 
10514 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10515                                              DAGCombinerInfo &DCI) const {
10516   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10517     return SDValue();
10518 
10519   SelectionDAG &DAG = DCI.DAG;
10520   EVT VT = N->getValueType(0);
10521 
10522   SDLoc SL(N);
10523   SDValue LHS = N->getOperand(0);
10524   SDValue RHS = N->getOperand(1);
10525 
10526   // These should really be instruction patterns, but writing patterns with
10527   // source modiifiers is a pain.
10528 
10529   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10530   if (LHS.getOpcode() == ISD::FADD) {
10531     SDValue A = LHS.getOperand(0);
10532     if (A == LHS.getOperand(1)) {
10533       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10534       if (FusedOp != 0) {
10535         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10536         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10537       }
10538     }
10539   }
10540 
10541   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10542   if (RHS.getOpcode() == ISD::FADD) {
10543     SDValue A = RHS.getOperand(0);
10544     if (A == RHS.getOperand(1)) {
10545       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10546       if (FusedOp != 0) {
10547         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10548         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10549       }
10550     }
10551   }
10552 
10553   return SDValue();
10554 }
10555 
10556 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10557                                              DAGCombinerInfo &DCI) const {
10558   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10559     return SDValue();
10560 
10561   SelectionDAG &DAG = DCI.DAG;
10562   SDLoc SL(N);
10563   EVT VT = N->getValueType(0);
10564   assert(!VT.isVector());
10565 
10566   // Try to get the fneg to fold into the source modifier. This undoes generic
10567   // DAG combines and folds them into the mad.
10568   //
10569   // Only do this if we are not trying to support denormals. v_mad_f32 does
10570   // not support denormals ever.
10571   SDValue LHS = N->getOperand(0);
10572   SDValue RHS = N->getOperand(1);
10573   if (LHS.getOpcode() == ISD::FADD) {
10574     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10575     SDValue A = LHS.getOperand(0);
10576     if (A == LHS.getOperand(1)) {
10577       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10578       if (FusedOp != 0){
10579         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10580         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10581 
10582         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10583       }
10584     }
10585   }
10586 
10587   if (RHS.getOpcode() == ISD::FADD) {
10588     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10589 
10590     SDValue A = RHS.getOperand(0);
10591     if (A == RHS.getOperand(1)) {
10592       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10593       if (FusedOp != 0){
10594         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10595         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10596       }
10597     }
10598   }
10599 
10600   return SDValue();
10601 }
10602 
10603 SDValue SITargetLowering::performFMACombine(SDNode *N,
10604                                             DAGCombinerInfo &DCI) const {
10605   SelectionDAG &DAG = DCI.DAG;
10606   EVT VT = N->getValueType(0);
10607   SDLoc SL(N);
10608 
10609   if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
10610     return SDValue();
10611 
10612   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10613   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10614   SDValue Op1 = N->getOperand(0);
10615   SDValue Op2 = N->getOperand(1);
10616   SDValue FMA = N->getOperand(2);
10617 
10618   if (FMA.getOpcode() != ISD::FMA ||
10619       Op1.getOpcode() != ISD::FP_EXTEND ||
10620       Op2.getOpcode() != ISD::FP_EXTEND)
10621     return SDValue();
10622 
10623   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10624   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10625   // is sufficient to allow generaing fdot2.
10626   const TargetOptions &Options = DAG.getTarget().Options;
10627   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10628       (N->getFlags().hasAllowContract() &&
10629        FMA->getFlags().hasAllowContract())) {
10630     Op1 = Op1.getOperand(0);
10631     Op2 = Op2.getOperand(0);
10632     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10633         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10634       return SDValue();
10635 
10636     SDValue Vec1 = Op1.getOperand(0);
10637     SDValue Idx1 = Op1.getOperand(1);
10638     SDValue Vec2 = Op2.getOperand(0);
10639 
10640     SDValue FMAOp1 = FMA.getOperand(0);
10641     SDValue FMAOp2 = FMA.getOperand(1);
10642     SDValue FMAAcc = FMA.getOperand(2);
10643 
10644     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10645         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10646       return SDValue();
10647 
10648     FMAOp1 = FMAOp1.getOperand(0);
10649     FMAOp2 = FMAOp2.getOperand(0);
10650     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10651         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10652       return SDValue();
10653 
10654     SDValue Vec3 = FMAOp1.getOperand(0);
10655     SDValue Vec4 = FMAOp2.getOperand(0);
10656     SDValue Idx2 = FMAOp1.getOperand(1);
10657 
10658     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10659         // Idx1 and Idx2 cannot be the same.
10660         Idx1 == Idx2)
10661       return SDValue();
10662 
10663     if (Vec1 == Vec2 || Vec3 == Vec4)
10664       return SDValue();
10665 
10666     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10667       return SDValue();
10668 
10669     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10670         (Vec1 == Vec4 && Vec2 == Vec3)) {
10671       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10672                          DAG.getTargetConstant(0, SL, MVT::i1));
10673     }
10674   }
10675   return SDValue();
10676 }
10677 
10678 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10679                                               DAGCombinerInfo &DCI) const {
10680   SelectionDAG &DAG = DCI.DAG;
10681   SDLoc SL(N);
10682 
10683   SDValue LHS = N->getOperand(0);
10684   SDValue RHS = N->getOperand(1);
10685   EVT VT = LHS.getValueType();
10686   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10687 
10688   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10689   if (!CRHS) {
10690     CRHS = dyn_cast<ConstantSDNode>(LHS);
10691     if (CRHS) {
10692       std::swap(LHS, RHS);
10693       CC = getSetCCSwappedOperands(CC);
10694     }
10695   }
10696 
10697   if (CRHS) {
10698     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10699         isBoolSGPR(LHS.getOperand(0))) {
10700       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10701       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10702       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10703       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10704       if ((CRHS->isAllOnesValue() &&
10705            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10706           (CRHS->isNullValue() &&
10707            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10708         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10709                            DAG.getConstant(-1, SL, MVT::i1));
10710       if ((CRHS->isAllOnesValue() &&
10711            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10712           (CRHS->isNullValue() &&
10713            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10714         return LHS.getOperand(0);
10715     }
10716 
10717     uint64_t CRHSVal = CRHS->getZExtValue();
10718     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10719         LHS.getOpcode() == ISD::SELECT &&
10720         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10721         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10722         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10723         isBoolSGPR(LHS.getOperand(0))) {
10724       // Given CT != FT:
10725       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10726       // setcc (select cc, CT, CF), CF, ne => cc
10727       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10728       // setcc (select cc, CT, CF), CT, eq => cc
10729       uint64_t CT = LHS.getConstantOperandVal(1);
10730       uint64_t CF = LHS.getConstantOperandVal(2);
10731 
10732       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10733           (CT == CRHSVal && CC == ISD::SETNE))
10734         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10735                            DAG.getConstant(-1, SL, MVT::i1));
10736       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10737           (CT == CRHSVal && CC == ISD::SETEQ))
10738         return LHS.getOperand(0);
10739     }
10740   }
10741 
10742   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10743                                            VT != MVT::f16))
10744     return SDValue();
10745 
10746   // Match isinf/isfinite pattern
10747   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10748   // (fcmp one (fabs x), inf) -> (fp_class x,
10749   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10750   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10751     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10752     if (!CRHS)
10753       return SDValue();
10754 
10755     const APFloat &APF = CRHS->getValueAPF();
10756     if (APF.isInfinity() && !APF.isNegative()) {
10757       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10758                                  SIInstrFlags::N_INFINITY;
10759       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10760                                     SIInstrFlags::P_ZERO |
10761                                     SIInstrFlags::N_NORMAL |
10762                                     SIInstrFlags::P_NORMAL |
10763                                     SIInstrFlags::N_SUBNORMAL |
10764                                     SIInstrFlags::P_SUBNORMAL;
10765       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10766       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10767                          DAG.getConstant(Mask, SL, MVT::i32));
10768     }
10769   }
10770 
10771   return SDValue();
10772 }
10773 
10774 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10775                                                      DAGCombinerInfo &DCI) const {
10776   SelectionDAG &DAG = DCI.DAG;
10777   SDLoc SL(N);
10778   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10779 
10780   SDValue Src = N->getOperand(0);
10781   SDValue Shift = N->getOperand(0);
10782 
10783   // TODO: Extend type shouldn't matter (assuming legal types).
10784   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10785     Shift = Shift.getOperand(0);
10786 
10787   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10788     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10789     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10790     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10791     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10792     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10793     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10794       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
10795                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10796 
10797       unsigned ShiftOffset = 8 * Offset;
10798       if (Shift.getOpcode() == ISD::SHL)
10799         ShiftOffset -= C->getZExtValue();
10800       else
10801         ShiftOffset += C->getZExtValue();
10802 
10803       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10804         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10805                            MVT::f32, Shift);
10806       }
10807     }
10808   }
10809 
10810   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10811   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10812   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10813     // We simplified Src. If this node is not dead, visit it again so it is
10814     // folded properly.
10815     if (N->getOpcode() != ISD::DELETED_NODE)
10816       DCI.AddToWorklist(N);
10817     return SDValue(N, 0);
10818   }
10819 
10820   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10821   if (SDValue DemandedSrc =
10822           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10823     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10824 
10825   return SDValue();
10826 }
10827 
10828 SDValue SITargetLowering::performClampCombine(SDNode *N,
10829                                               DAGCombinerInfo &DCI) const {
10830   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10831   if (!CSrc)
10832     return SDValue();
10833 
10834   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10835   const APFloat &F = CSrc->getValueAPF();
10836   APFloat Zero = APFloat::getZero(F.getSemantics());
10837   if (F < Zero ||
10838       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10839     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10840   }
10841 
10842   APFloat One(F.getSemantics(), "1.0");
10843   if (F > One)
10844     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10845 
10846   return SDValue(CSrc, 0);
10847 }
10848 
10849 
10850 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10851                                             DAGCombinerInfo &DCI) const {
10852   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10853     return SDValue();
10854   switch (N->getOpcode()) {
10855   case ISD::ADD:
10856     return performAddCombine(N, DCI);
10857   case ISD::SUB:
10858     return performSubCombine(N, DCI);
10859   case ISD::ADDCARRY:
10860   case ISD::SUBCARRY:
10861     return performAddCarrySubCarryCombine(N, DCI);
10862   case ISD::FADD:
10863     return performFAddCombine(N, DCI);
10864   case ISD::FSUB:
10865     return performFSubCombine(N, DCI);
10866   case ISD::SETCC:
10867     return performSetCCCombine(N, DCI);
10868   case ISD::FMAXNUM:
10869   case ISD::FMINNUM:
10870   case ISD::FMAXNUM_IEEE:
10871   case ISD::FMINNUM_IEEE:
10872   case ISD::SMAX:
10873   case ISD::SMIN:
10874   case ISD::UMAX:
10875   case ISD::UMIN:
10876   case AMDGPUISD::FMIN_LEGACY:
10877   case AMDGPUISD::FMAX_LEGACY:
10878     return performMinMaxCombine(N, DCI);
10879   case ISD::FMA:
10880     return performFMACombine(N, DCI);
10881   case ISD::AND:
10882     return performAndCombine(N, DCI);
10883   case ISD::OR:
10884     return performOrCombine(N, DCI);
10885   case ISD::XOR:
10886     return performXorCombine(N, DCI);
10887   case ISD::ZERO_EXTEND:
10888     return performZeroExtendCombine(N, DCI);
10889   case ISD::SIGN_EXTEND_INREG:
10890     return performSignExtendInRegCombine(N , DCI);
10891   case AMDGPUISD::FP_CLASS:
10892     return performClassCombine(N, DCI);
10893   case ISD::FCANONICALIZE:
10894     return performFCanonicalizeCombine(N, DCI);
10895   case AMDGPUISD::RCP:
10896     return performRcpCombine(N, DCI);
10897   case AMDGPUISD::FRACT:
10898   case AMDGPUISD::RSQ:
10899   case AMDGPUISD::RCP_LEGACY:
10900   case AMDGPUISD::RCP_IFLAG:
10901   case AMDGPUISD::RSQ_CLAMP:
10902   case AMDGPUISD::LDEXP: {
10903     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10904     SDValue Src = N->getOperand(0);
10905     if (Src.isUndef())
10906       return Src;
10907     break;
10908   }
10909   case ISD::SINT_TO_FP:
10910   case ISD::UINT_TO_FP:
10911     return performUCharToFloatCombine(N, DCI);
10912   case AMDGPUISD::CVT_F32_UBYTE0:
10913   case AMDGPUISD::CVT_F32_UBYTE1:
10914   case AMDGPUISD::CVT_F32_UBYTE2:
10915   case AMDGPUISD::CVT_F32_UBYTE3:
10916     return performCvtF32UByteNCombine(N, DCI);
10917   case AMDGPUISD::FMED3:
10918     return performFMed3Combine(N, DCI);
10919   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10920     return performCvtPkRTZCombine(N, DCI);
10921   case AMDGPUISD::CLAMP:
10922     return performClampCombine(N, DCI);
10923   case ISD::SCALAR_TO_VECTOR: {
10924     SelectionDAG &DAG = DCI.DAG;
10925     EVT VT = N->getValueType(0);
10926 
10927     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10928     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10929       SDLoc SL(N);
10930       SDValue Src = N->getOperand(0);
10931       EVT EltVT = Src.getValueType();
10932       if (EltVT == MVT::f16)
10933         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10934 
10935       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10936       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10937     }
10938 
10939     break;
10940   }
10941   case ISD::EXTRACT_VECTOR_ELT:
10942     return performExtractVectorEltCombine(N, DCI);
10943   case ISD::INSERT_VECTOR_ELT:
10944     return performInsertVectorEltCombine(N, DCI);
10945   case ISD::LOAD: {
10946     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10947       return Widended;
10948     LLVM_FALLTHROUGH;
10949   }
10950   default: {
10951     if (!DCI.isBeforeLegalize()) {
10952       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
10953         return performMemSDNodeCombine(MemNode, DCI);
10954     }
10955 
10956     break;
10957   }
10958   }
10959 
10960   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10961 }
10962 
10963 /// Helper function for adjustWritemask
10964 static unsigned SubIdx2Lane(unsigned Idx) {
10965   switch (Idx) {
10966   default: return ~0u;
10967   case AMDGPU::sub0: return 0;
10968   case AMDGPU::sub1: return 1;
10969   case AMDGPU::sub2: return 2;
10970   case AMDGPU::sub3: return 3;
10971   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10972   }
10973 }
10974 
10975 /// Adjust the writemask of MIMG instructions
10976 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10977                                           SelectionDAG &DAG) const {
10978   unsigned Opcode = Node->getMachineOpcode();
10979 
10980   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10981   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10982   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10983     return Node; // not implemented for D16
10984 
10985   SDNode *Users[5] = { nullptr };
10986   unsigned Lane = 0;
10987   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10988   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10989   unsigned NewDmask = 0;
10990   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10991   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10992   bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
10993                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10994   unsigned TFCLane = 0;
10995   bool HasChain = Node->getNumValues() > 1;
10996 
10997   if (OldDmask == 0) {
10998     // These are folded out, but on the chance it happens don't assert.
10999     return Node;
11000   }
11001 
11002   unsigned OldBitsSet = countPopulation(OldDmask);
11003   // Work out which is the TFE/LWE lane if that is enabled.
11004   if (UsesTFC) {
11005     TFCLane = OldBitsSet;
11006   }
11007 
11008   // Try to figure out the used register components
11009   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
11010        I != E; ++I) {
11011 
11012     // Don't look at users of the chain.
11013     if (I.getUse().getResNo() != 0)
11014       continue;
11015 
11016     // Abort if we can't understand the usage
11017     if (!I->isMachineOpcode() ||
11018         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
11019       return Node;
11020 
11021     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
11022     // Note that subregs are packed, i.e. Lane==0 is the first bit set
11023     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
11024     // set, etc.
11025     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
11026     if (Lane == ~0u)
11027       return Node;
11028 
11029     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
11030     if (UsesTFC && Lane == TFCLane) {
11031       Users[Lane] = *I;
11032     } else {
11033       // Set which texture component corresponds to the lane.
11034       unsigned Comp;
11035       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
11036         Comp = countTrailingZeros(Dmask);
11037         Dmask &= ~(1 << Comp);
11038       }
11039 
11040       // Abort if we have more than one user per component.
11041       if (Users[Lane])
11042         return Node;
11043 
11044       Users[Lane] = *I;
11045       NewDmask |= 1 << Comp;
11046     }
11047   }
11048 
11049   // Don't allow 0 dmask, as hardware assumes one channel enabled.
11050   bool NoChannels = !NewDmask;
11051   if (NoChannels) {
11052     if (!UsesTFC) {
11053       // No uses of the result and not using TFC. Then do nothing.
11054       return Node;
11055     }
11056     // If the original dmask has one channel - then nothing to do
11057     if (OldBitsSet == 1)
11058       return Node;
11059     // Use an arbitrary dmask - required for the instruction to work
11060     NewDmask = 1;
11061   }
11062   // Abort if there's no change
11063   if (NewDmask == OldDmask)
11064     return Node;
11065 
11066   unsigned BitsSet = countPopulation(NewDmask);
11067 
11068   // Check for TFE or LWE - increase the number of channels by one to account
11069   // for the extra return value
11070   // This will need adjustment for D16 if this is also included in
11071   // adjustWriteMask (this function) but at present D16 are excluded.
11072   unsigned NewChannels = BitsSet + UsesTFC;
11073 
11074   int NewOpcode =
11075       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
11076   assert(NewOpcode != -1 &&
11077          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
11078          "failed to find equivalent MIMG op");
11079 
11080   // Adjust the writemask in the node
11081   SmallVector<SDValue, 12> Ops;
11082   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
11083   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
11084   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11085 
11086   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11087 
11088   MVT ResultVT = NewChannels == 1 ?
11089     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11090                            NewChannels == 5 ? 8 : NewChannels);
11091   SDVTList NewVTList = HasChain ?
11092     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11093 
11094 
11095   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11096                                               NewVTList, Ops);
11097 
11098   if (HasChain) {
11099     // Update chain.
11100     DAG.setNodeMemRefs(NewNode, Node->memoperands());
11101     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11102   }
11103 
11104   if (NewChannels == 1) {
11105     assert(Node->hasNUsesOfValue(1, 0));
11106     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11107                                       SDLoc(Node), Users[Lane]->getValueType(0),
11108                                       SDValue(NewNode, 0));
11109     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11110     return nullptr;
11111   }
11112 
11113   // Update the users of the node with the new indices
11114   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11115     SDNode *User = Users[i];
11116     if (!User) {
11117       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11118       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11119       if (i || !NoChannels)
11120         continue;
11121     } else {
11122       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11123       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11124     }
11125 
11126     switch (Idx) {
11127     default: break;
11128     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11129     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11130     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11131     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11132     }
11133   }
11134 
11135   DAG.RemoveDeadNode(Node);
11136   return nullptr;
11137 }
11138 
11139 static bool isFrameIndexOp(SDValue Op) {
11140   if (Op.getOpcode() == ISD::AssertZext)
11141     Op = Op.getOperand(0);
11142 
11143   return isa<FrameIndexSDNode>(Op);
11144 }
11145 
11146 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11147 /// with frame index operands.
11148 /// LLVM assumes that inputs are to these instructions are registers.
11149 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11150                                                         SelectionDAG &DAG) const {
11151   if (Node->getOpcode() == ISD::CopyToReg) {
11152     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11153     SDValue SrcVal = Node->getOperand(2);
11154 
11155     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11156     // to try understanding copies to physical registers.
11157     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11158       SDLoc SL(Node);
11159       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11160       SDValue VReg = DAG.getRegister(
11161         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11162 
11163       SDNode *Glued = Node->getGluedNode();
11164       SDValue ToVReg
11165         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11166                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11167       SDValue ToResultReg
11168         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11169                            VReg, ToVReg.getValue(1));
11170       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11171       DAG.RemoveDeadNode(Node);
11172       return ToResultReg.getNode();
11173     }
11174   }
11175 
11176   SmallVector<SDValue, 8> Ops;
11177   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11178     if (!isFrameIndexOp(Node->getOperand(i))) {
11179       Ops.push_back(Node->getOperand(i));
11180       continue;
11181     }
11182 
11183     SDLoc DL(Node);
11184     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11185                                      Node->getOperand(i).getValueType(),
11186                                      Node->getOperand(i)), 0));
11187   }
11188 
11189   return DAG.UpdateNodeOperands(Node, Ops);
11190 }
11191 
11192 /// Fold the instructions after selecting them.
11193 /// Returns null if users were already updated.
11194 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11195                                           SelectionDAG &DAG) const {
11196   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11197   unsigned Opcode = Node->getMachineOpcode();
11198 
11199   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11200       !TII->isGather4(Opcode) &&
11201       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11202     return adjustWritemask(Node, DAG);
11203   }
11204 
11205   if (Opcode == AMDGPU::INSERT_SUBREG ||
11206       Opcode == AMDGPU::REG_SEQUENCE) {
11207     legalizeTargetIndependentNode(Node, DAG);
11208     return Node;
11209   }
11210 
11211   switch (Opcode) {
11212   case AMDGPU::V_DIV_SCALE_F32_e64:
11213   case AMDGPU::V_DIV_SCALE_F64_e64: {
11214     // Satisfy the operand register constraint when one of the inputs is
11215     // undefined. Ordinarily each undef value will have its own implicit_def of
11216     // a vreg, so force these to use a single register.
11217     SDValue Src0 = Node->getOperand(1);
11218     SDValue Src1 = Node->getOperand(3);
11219     SDValue Src2 = Node->getOperand(5);
11220 
11221     if ((Src0.isMachineOpcode() &&
11222          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11223         (Src0 == Src1 || Src0 == Src2))
11224       break;
11225 
11226     MVT VT = Src0.getValueType().getSimpleVT();
11227     const TargetRegisterClass *RC =
11228         getRegClassFor(VT, Src0.getNode()->isDivergent());
11229 
11230     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11231     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11232 
11233     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11234                                       UndefReg, Src0, SDValue());
11235 
11236     // src0 must be the same register as src1 or src2, even if the value is
11237     // undefined, so make sure we don't violate this constraint.
11238     if (Src0.isMachineOpcode() &&
11239         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11240       if (Src1.isMachineOpcode() &&
11241           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11242         Src0 = Src1;
11243       else if (Src2.isMachineOpcode() &&
11244                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11245         Src0 = Src2;
11246       else {
11247         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11248         Src0 = UndefReg;
11249         Src1 = UndefReg;
11250       }
11251     } else
11252       break;
11253 
11254     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11255     Ops[1] = Src0;
11256     Ops[3] = Src1;
11257     Ops[5] = Src2;
11258     Ops.push_back(ImpDef.getValue(1));
11259     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11260   }
11261   default:
11262     break;
11263   }
11264 
11265   return Node;
11266 }
11267 
11268 // Any MIMG instructions that use tfe or lwe require an initialization of the
11269 // result register that will be written in the case of a memory access failure.
11270 // The required code is also added to tie this init code to the result of the
11271 // img instruction.
11272 void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
11273   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11274   const SIRegisterInfo &TRI = TII->getRegisterInfo();
11275   MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11276   MachineBasicBlock &MBB = *MI.getParent();
11277 
11278   MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
11279   MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
11280   MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
11281 
11282   if (!TFE && !LWE) // intersect_ray
11283     return;
11284 
11285   unsigned TFEVal = TFE ? TFE->getImm() : 0;
11286   unsigned LWEVal = LWE->getImm();
11287   unsigned D16Val = D16 ? D16->getImm() : 0;
11288 
11289   if (!TFEVal && !LWEVal)
11290     return;
11291 
11292   // At least one of TFE or LWE are non-zero
11293   // We have to insert a suitable initialization of the result value and
11294   // tie this to the dest of the image instruction.
11295 
11296   const DebugLoc &DL = MI.getDebugLoc();
11297 
11298   int DstIdx =
11299       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
11300 
11301   // Calculate which dword we have to initialize to 0.
11302   MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
11303 
11304   // check that dmask operand is found.
11305   assert(MO_Dmask && "Expected dmask operand in instruction");
11306 
11307   unsigned dmask = MO_Dmask->getImm();
11308   // Determine the number of active lanes taking into account the
11309   // Gather4 special case
11310   unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask);
11311 
11312   bool Packed = !Subtarget->hasUnpackedD16VMem();
11313 
11314   unsigned InitIdx =
11315       D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
11316 
11317   // Abandon attempt if the dst size isn't large enough
11318   // - this is in fact an error but this is picked up elsewhere and
11319   // reported correctly.
11320   uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
11321   if (DstSize < InitIdx)
11322     return;
11323 
11324   // Create a register for the intialization value.
11325   Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11326   unsigned NewDst = 0; // Final initialized value will be in here
11327 
11328   // If PRTStrictNull feature is enabled (the default) then initialize
11329   // all the result registers to 0, otherwise just the error indication
11330   // register (VGPRn+1)
11331   unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
11332   unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
11333 
11334   BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
11335   for (; SizeLeft; SizeLeft--, CurrIdx++) {
11336     NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11337     // Initialize dword
11338     Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
11339     BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
11340       .addImm(0);
11341     // Insert into the super-reg
11342     BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
11343       .addReg(PrevDst)
11344       .addReg(SubReg)
11345       .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
11346 
11347     PrevDst = NewDst;
11348   }
11349 
11350   // Add as an implicit operand
11351   MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
11352 
11353   // Tie the just added implicit operand to the dst
11354   MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
11355 }
11356 
11357 /// Assign the register class depending on the number of
11358 /// bits set in the writemask
11359 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11360                                                      SDNode *Node) const {
11361   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11362 
11363   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11364 
11365   if (TII->isVOP3(MI.getOpcode())) {
11366     // Make sure constant bus requirements are respected.
11367     TII->legalizeOperandsVOP3(MRI, MI);
11368 
11369     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11370     // This saves a chain-copy of registers and better ballance register
11371     // use between vgpr and agpr as agpr tuples tend to be big.
11372     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
11373       unsigned Opc = MI.getOpcode();
11374       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11375       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11376                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11377         if (I == -1)
11378           break;
11379         MachineOperand &Op = MI.getOperand(I);
11380         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
11381              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
11382             !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg()))
11383           continue;
11384         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11385         if (!Src || !Src->isCopy() ||
11386             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11387           continue;
11388         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11389         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11390         // All uses of agpr64 and agpr32 can also accept vgpr except for
11391         // v_accvgpr_read, but we do not produce agpr reads during selection,
11392         // so no use checks are needed.
11393         MRI.setRegClass(Op.getReg(), NewRC);
11394       }
11395     }
11396 
11397     return;
11398   }
11399 
11400   // Replace unused atomics with the no return version.
11401   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11402   if (NoRetAtomicOp != -1) {
11403     if (!Node->hasAnyUseOfValue(0)) {
11404       int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
11405                                                AMDGPU::OpName::cpol);
11406       if (CPolIdx != -1) {
11407         MachineOperand &CPol = MI.getOperand(CPolIdx);
11408         CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC);
11409       }
11410       MI.RemoveOperand(0);
11411       MI.setDesc(TII->get(NoRetAtomicOp));
11412       return;
11413     }
11414 
11415     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11416     // instruction, because the return type of these instructions is a vec2 of
11417     // the memory type, so it can be tied to the input operand.
11418     // This means these instructions always have a use, so we need to add a
11419     // special case to check if the atomic has only one extract_subreg use,
11420     // which itself has no uses.
11421     if ((Node->hasNUsesOfValue(1, 0) &&
11422          Node->use_begin()->isMachineOpcode() &&
11423          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11424          !Node->use_begin()->hasAnyUseOfValue(0))) {
11425       Register Def = MI.getOperand(0).getReg();
11426 
11427       // Change this into a noret atomic.
11428       MI.setDesc(TII->get(NoRetAtomicOp));
11429       MI.RemoveOperand(0);
11430 
11431       // If we only remove the def operand from the atomic instruction, the
11432       // extract_subreg will be left with a use of a vreg without a def.
11433       // So we need to insert an implicit_def to avoid machine verifier
11434       // errors.
11435       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11436               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11437     }
11438     return;
11439   }
11440 
11441   if (TII->isMIMG(MI) && !MI.mayStore())
11442     AddIMGInit(MI);
11443 }
11444 
11445 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11446                               uint64_t Val) {
11447   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11448   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11449 }
11450 
11451 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11452                                                 const SDLoc &DL,
11453                                                 SDValue Ptr) const {
11454   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11455 
11456   // Build the half of the subregister with the constants before building the
11457   // full 128-bit register. If we are building multiple resource descriptors,
11458   // this will allow CSEing of the 2-component register.
11459   const SDValue Ops0[] = {
11460     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11461     buildSMovImm32(DAG, DL, 0),
11462     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11463     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11464     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11465   };
11466 
11467   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11468                                                 MVT::v2i32, Ops0), 0);
11469 
11470   // Combine the constants and the pointer.
11471   const SDValue Ops1[] = {
11472     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11473     Ptr,
11474     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11475     SubRegHi,
11476     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11477   };
11478 
11479   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11480 }
11481 
11482 /// Return a resource descriptor with the 'Add TID' bit enabled
11483 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11484 ///        of the resource descriptor) to create an offset, which is added to
11485 ///        the resource pointer.
11486 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11487                                            SDValue Ptr, uint32_t RsrcDword1,
11488                                            uint64_t RsrcDword2And3) const {
11489   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11490   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11491   if (RsrcDword1) {
11492     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11493                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11494                     0);
11495   }
11496 
11497   SDValue DataLo = buildSMovImm32(DAG, DL,
11498                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11499   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11500 
11501   const SDValue Ops[] = {
11502     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11503     PtrLo,
11504     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11505     PtrHi,
11506     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11507     DataLo,
11508     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11509     DataHi,
11510     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11511   };
11512 
11513   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11514 }
11515 
11516 //===----------------------------------------------------------------------===//
11517 //                         SI Inline Assembly Support
11518 //===----------------------------------------------------------------------===//
11519 
11520 std::pair<unsigned, const TargetRegisterClass *>
11521 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
11522                                                StringRef Constraint,
11523                                                MVT VT) const {
11524   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
11525 
11526   const TargetRegisterClass *RC = nullptr;
11527   if (Constraint.size() == 1) {
11528     const unsigned BitWidth = VT.getSizeInBits();
11529     switch (Constraint[0]) {
11530     default:
11531       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11532     case 's':
11533     case 'r':
11534       switch (BitWidth) {
11535       case 16:
11536         RC = &AMDGPU::SReg_32RegClass;
11537         break;
11538       case 64:
11539         RC = &AMDGPU::SGPR_64RegClass;
11540         break;
11541       default:
11542         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11543         if (!RC)
11544           return std::make_pair(0U, nullptr);
11545         break;
11546       }
11547       break;
11548     case 'v':
11549       switch (BitWidth) {
11550       case 16:
11551         RC = &AMDGPU::VGPR_32RegClass;
11552         break;
11553       default:
11554         RC = TRI->getVGPRClassForBitWidth(BitWidth);
11555         if (!RC)
11556           return std::make_pair(0U, nullptr);
11557         break;
11558       }
11559       break;
11560     case 'a':
11561       if (!Subtarget->hasMAIInsts())
11562         break;
11563       switch (BitWidth) {
11564       case 16:
11565         RC = &AMDGPU::AGPR_32RegClass;
11566         break;
11567       default:
11568         RC = TRI->getAGPRClassForBitWidth(BitWidth);
11569         if (!RC)
11570           return std::make_pair(0U, nullptr);
11571         break;
11572       }
11573       break;
11574     }
11575     // We actually support i128, i16 and f16 as inline parameters
11576     // even if they are not reported as legal
11577     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11578                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11579       return std::make_pair(0U, RC);
11580   }
11581 
11582   if (Constraint.size() > 1) {
11583     if (Constraint[1] == 'v') {
11584       RC = &AMDGPU::VGPR_32RegClass;
11585     } else if (Constraint[1] == 's') {
11586       RC = &AMDGPU::SGPR_32RegClass;
11587     } else if (Constraint[1] == 'a') {
11588       RC = &AMDGPU::AGPR_32RegClass;
11589     }
11590 
11591     if (RC) {
11592       uint32_t Idx;
11593       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
11594       if (!Failed && Idx < RC->getNumRegs())
11595         return std::make_pair(RC->getRegister(Idx), RC);
11596     }
11597   }
11598 
11599   // FIXME: Returns VS_32 for physical SGPR constraints
11600   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11601 }
11602 
11603 static bool isImmConstraint(StringRef Constraint) {
11604   if (Constraint.size() == 1) {
11605     switch (Constraint[0]) {
11606     default: break;
11607     case 'I':
11608     case 'J':
11609     case 'A':
11610     case 'B':
11611     case 'C':
11612       return true;
11613     }
11614   } else if (Constraint == "DA" ||
11615              Constraint == "DB") {
11616     return true;
11617   }
11618   return false;
11619 }
11620 
11621 SITargetLowering::ConstraintType
11622 SITargetLowering::getConstraintType(StringRef Constraint) const {
11623   if (Constraint.size() == 1) {
11624     switch (Constraint[0]) {
11625     default: break;
11626     case 's':
11627     case 'v':
11628     case 'a':
11629       return C_RegisterClass;
11630     }
11631   }
11632   if (isImmConstraint(Constraint)) {
11633     return C_Other;
11634   }
11635   return TargetLowering::getConstraintType(Constraint);
11636 }
11637 
11638 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11639   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11640     Val = Val & maskTrailingOnes<uint64_t>(Size);
11641   }
11642   return Val;
11643 }
11644 
11645 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11646                                                     std::string &Constraint,
11647                                                     std::vector<SDValue> &Ops,
11648                                                     SelectionDAG &DAG) const {
11649   if (isImmConstraint(Constraint)) {
11650     uint64_t Val;
11651     if (getAsmOperandConstVal(Op, Val) &&
11652         checkAsmConstraintVal(Op, Constraint, Val)) {
11653       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11654       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11655     }
11656   } else {
11657     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11658   }
11659 }
11660 
11661 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11662   unsigned Size = Op.getScalarValueSizeInBits();
11663   if (Size > 64)
11664     return false;
11665 
11666   if (Size == 16 && !Subtarget->has16BitInsts())
11667     return false;
11668 
11669   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11670     Val = C->getSExtValue();
11671     return true;
11672   }
11673   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11674     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11675     return true;
11676   }
11677   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11678     if (Size != 16 || Op.getNumOperands() != 2)
11679       return false;
11680     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11681       return false;
11682     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11683       Val = C->getSExtValue();
11684       return true;
11685     }
11686     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11687       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11688       return true;
11689     }
11690   }
11691 
11692   return false;
11693 }
11694 
11695 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11696                                              const std::string &Constraint,
11697                                              uint64_t Val) const {
11698   if (Constraint.size() == 1) {
11699     switch (Constraint[0]) {
11700     case 'I':
11701       return AMDGPU::isInlinableIntLiteral(Val);
11702     case 'J':
11703       return isInt<16>(Val);
11704     case 'A':
11705       return checkAsmConstraintValA(Op, Val);
11706     case 'B':
11707       return isInt<32>(Val);
11708     case 'C':
11709       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11710              AMDGPU::isInlinableIntLiteral(Val);
11711     default:
11712       break;
11713     }
11714   } else if (Constraint.size() == 2) {
11715     if (Constraint == "DA") {
11716       int64_t HiBits = static_cast<int32_t>(Val >> 32);
11717       int64_t LoBits = static_cast<int32_t>(Val);
11718       return checkAsmConstraintValA(Op, HiBits, 32) &&
11719              checkAsmConstraintValA(Op, LoBits, 32);
11720     }
11721     if (Constraint == "DB") {
11722       return true;
11723     }
11724   }
11725   llvm_unreachable("Invalid asm constraint");
11726 }
11727 
11728 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
11729                                               uint64_t Val,
11730                                               unsigned MaxSize) const {
11731   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
11732   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11733   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11734       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11735       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11736     return true;
11737   }
11738   return false;
11739 }
11740 
11741 static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
11742   switch (UnalignedClassID) {
11743   case AMDGPU::VReg_64RegClassID:
11744     return AMDGPU::VReg_64_Align2RegClassID;
11745   case AMDGPU::VReg_96RegClassID:
11746     return AMDGPU::VReg_96_Align2RegClassID;
11747   case AMDGPU::VReg_128RegClassID:
11748     return AMDGPU::VReg_128_Align2RegClassID;
11749   case AMDGPU::VReg_160RegClassID:
11750     return AMDGPU::VReg_160_Align2RegClassID;
11751   case AMDGPU::VReg_192RegClassID:
11752     return AMDGPU::VReg_192_Align2RegClassID;
11753   case AMDGPU::VReg_224RegClassID:
11754     return AMDGPU::VReg_224_Align2RegClassID;
11755   case AMDGPU::VReg_256RegClassID:
11756     return AMDGPU::VReg_256_Align2RegClassID;
11757   case AMDGPU::VReg_512RegClassID:
11758     return AMDGPU::VReg_512_Align2RegClassID;
11759   case AMDGPU::VReg_1024RegClassID:
11760     return AMDGPU::VReg_1024_Align2RegClassID;
11761   case AMDGPU::AReg_64RegClassID:
11762     return AMDGPU::AReg_64_Align2RegClassID;
11763   case AMDGPU::AReg_96RegClassID:
11764     return AMDGPU::AReg_96_Align2RegClassID;
11765   case AMDGPU::AReg_128RegClassID:
11766     return AMDGPU::AReg_128_Align2RegClassID;
11767   case AMDGPU::AReg_160RegClassID:
11768     return AMDGPU::AReg_160_Align2RegClassID;
11769   case AMDGPU::AReg_192RegClassID:
11770     return AMDGPU::AReg_192_Align2RegClassID;
11771   case AMDGPU::AReg_256RegClassID:
11772     return AMDGPU::AReg_256_Align2RegClassID;
11773   case AMDGPU::AReg_512RegClassID:
11774     return AMDGPU::AReg_512_Align2RegClassID;
11775   case AMDGPU::AReg_1024RegClassID:
11776     return AMDGPU::AReg_1024_Align2RegClassID;
11777   default:
11778     return -1;
11779   }
11780 }
11781 
11782 // Figure out which registers should be reserved for stack access. Only after
11783 // the function is legalized do we know all of the non-spill stack objects or if
11784 // calls are present.
11785 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
11786   MachineRegisterInfo &MRI = MF.getRegInfo();
11787   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11788   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
11789   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11790   const SIInstrInfo *TII = ST.getInstrInfo();
11791 
11792   if (Info->isEntryFunction()) {
11793     // Callable functions have fixed registers used for stack access.
11794     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
11795   }
11796 
11797   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
11798                              Info->getStackPtrOffsetReg()));
11799   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
11800     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
11801 
11802   // We need to worry about replacing the default register with itself in case
11803   // of MIR testcases missing the MFI.
11804   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
11805     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
11806 
11807   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
11808     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
11809 
11810   Info->limitOccupancy(MF);
11811 
11812   if (ST.isWave32() && !MF.empty()) {
11813     for (auto &MBB : MF) {
11814       for (auto &MI : MBB) {
11815         TII->fixImplicitOperands(MI);
11816       }
11817     }
11818   }
11819 
11820   // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
11821   // classes if required. Ideally the register class constraints would differ
11822   // per-subtarget, but there's no easy way to achieve that right now. This is
11823   // not a problem for VGPRs because the correctly aligned VGPR class is implied
11824   // from using them as the register class for legal types.
11825   if (ST.needsAlignedVGPRs()) {
11826     for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
11827       const Register Reg = Register::index2VirtReg(I);
11828       const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
11829       if (!RC)
11830         continue;
11831       int NewClassID = getAlignedAGPRClassID(RC->getID());
11832       if (NewClassID != -1)
11833         MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
11834     }
11835   }
11836 
11837   TargetLoweringBase::finalizeLowering(MF);
11838 
11839   // Allocate a VGPR for future SGPR Spill if
11840   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
11841   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
11842   if (VGPRReserveforSGPRSpill && TRI->spillSGPRToVGPR() &&
11843       !Info->VGPRReservedForSGPRSpill && !Info->isEntryFunction())
11844     Info->reserveVGPRforSGPRSpills(MF);
11845 }
11846 
11847 void SITargetLowering::computeKnownBitsForFrameIndex(
11848   const int FI, KnownBits &Known, const MachineFunction &MF) const {
11849   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
11850 
11851   // Set the high bits to zero based on the maximum allowed scratch size per
11852   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
11853   // calculation won't overflow, so assume the sign bit is never set.
11854   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
11855 }
11856 
11857 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
11858                                    KnownBits &Known, unsigned Dim) {
11859   unsigned MaxValue =
11860       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
11861   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
11862 }
11863 
11864 void SITargetLowering::computeKnownBitsForTargetInstr(
11865     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
11866     const MachineRegisterInfo &MRI, unsigned Depth) const {
11867   const MachineInstr *MI = MRI.getVRegDef(R);
11868   switch (MI->getOpcode()) {
11869   case AMDGPU::G_INTRINSIC: {
11870     switch (MI->getIntrinsicID()) {
11871     case Intrinsic::amdgcn_workitem_id_x:
11872       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
11873       break;
11874     case Intrinsic::amdgcn_workitem_id_y:
11875       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
11876       break;
11877     case Intrinsic::amdgcn_workitem_id_z:
11878       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
11879       break;
11880     case Intrinsic::amdgcn_mbcnt_lo:
11881     case Intrinsic::amdgcn_mbcnt_hi: {
11882       // These return at most the wavefront size - 1.
11883       unsigned Size = MRI.getType(R).getSizeInBits();
11884       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
11885       break;
11886     }
11887     case Intrinsic::amdgcn_groupstaticsize: {
11888       // We can report everything over the maximum size as 0. We can't report
11889       // based on the actual size because we don't know if it's accurate or not
11890       // at any given point.
11891       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
11892       break;
11893     }
11894     }
11895     break;
11896   }
11897   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
11898     Known.Zero.setHighBits(24);
11899     break;
11900   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
11901     Known.Zero.setHighBits(16);
11902     break;
11903   }
11904 }
11905 
11906 Align SITargetLowering::computeKnownAlignForTargetInstr(
11907   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
11908   unsigned Depth) const {
11909   const MachineInstr *MI = MRI.getVRegDef(R);
11910   switch (MI->getOpcode()) {
11911   case AMDGPU::G_INTRINSIC:
11912   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
11913     // FIXME: Can this move to generic code? What about the case where the call
11914     // site specifies a lower alignment?
11915     Intrinsic::ID IID = MI->getIntrinsicID();
11916     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
11917     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
11918     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
11919       return *RetAlign;
11920     return Align(1);
11921   }
11922   default:
11923     return Align(1);
11924   }
11925 }
11926 
11927 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11928   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
11929   const Align CacheLineAlign = Align(64);
11930 
11931   // Pre-GFX10 target did not benefit from loop alignment
11932   if (!ML || DisableLoopAlignment ||
11933       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
11934       getSubtarget()->hasInstFwdPrefetchBug())
11935     return PrefAlign;
11936 
11937   // On GFX10 I$ is 4 x 64 bytes cache lines.
11938   // By default prefetcher keeps one cache line behind and reads two ahead.
11939   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
11940   // behind and one ahead.
11941   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
11942   // If loop fits 64 bytes it always spans no more than two cache lines and
11943   // does not need an alignment.
11944   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
11945   // Else if loop is less or equal 192 bytes we need two lines behind.
11946 
11947   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11948   const MachineBasicBlock *Header = ML->getHeader();
11949   if (Header->getAlignment() != PrefAlign)
11950     return Header->getAlignment(); // Already processed.
11951 
11952   unsigned LoopSize = 0;
11953   for (const MachineBasicBlock *MBB : ML->blocks()) {
11954     // If inner loop block is aligned assume in average half of the alignment
11955     // size to be added as nops.
11956     if (MBB != Header)
11957       LoopSize += MBB->getAlignment().value() / 2;
11958 
11959     for (const MachineInstr &MI : *MBB) {
11960       LoopSize += TII->getInstSizeInBytes(MI);
11961       if (LoopSize > 192)
11962         return PrefAlign;
11963     }
11964   }
11965 
11966   if (LoopSize <= 64)
11967     return PrefAlign;
11968 
11969   if (LoopSize <= 128)
11970     return CacheLineAlign;
11971 
11972   // If any of parent loops is surrounded by prefetch instructions do not
11973   // insert new for inner loop, which would reset parent's settings.
11974   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
11975     if (MachineBasicBlock *Exit = P->getExitBlock()) {
11976       auto I = Exit->getFirstNonDebugInstr();
11977       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
11978         return CacheLineAlign;
11979     }
11980   }
11981 
11982   MachineBasicBlock *Pre = ML->getLoopPreheader();
11983   MachineBasicBlock *Exit = ML->getExitBlock();
11984 
11985   if (Pre && Exit) {
11986     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
11987             TII->get(AMDGPU::S_INST_PREFETCH))
11988       .addImm(1); // prefetch 2 lines behind PC
11989 
11990     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
11991             TII->get(AMDGPU::S_INST_PREFETCH))
11992       .addImm(2); // prefetch 1 line behind PC
11993   }
11994 
11995   return CacheLineAlign;
11996 }
11997 
11998 LLVM_ATTRIBUTE_UNUSED
11999 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
12000   assert(N->getOpcode() == ISD::CopyFromReg);
12001   do {
12002     // Follow the chain until we find an INLINEASM node.
12003     N = N->getOperand(0).getNode();
12004     if (N->getOpcode() == ISD::INLINEASM ||
12005         N->getOpcode() == ISD::INLINEASM_BR)
12006       return true;
12007   } while (N->getOpcode() == ISD::CopyFromReg);
12008   return false;
12009 }
12010 
12011 bool SITargetLowering::isSDNodeSourceOfDivergence(
12012     const SDNode *N, FunctionLoweringInfo *FLI,
12013     LegacyDivergenceAnalysis *KDA) const {
12014   switch (N->getOpcode()) {
12015   case ISD::CopyFromReg: {
12016     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
12017     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
12018     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12019     Register Reg = R->getReg();
12020 
12021     // FIXME: Why does this need to consider isLiveIn?
12022     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
12023       return !TRI->isSGPRReg(MRI, Reg);
12024 
12025     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
12026       return KDA->isDivergent(V);
12027 
12028     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
12029     return !TRI->isSGPRReg(MRI, Reg);
12030   }
12031   case ISD::LOAD: {
12032     const LoadSDNode *L = cast<LoadSDNode>(N);
12033     unsigned AS = L->getAddressSpace();
12034     // A flat load may access private memory.
12035     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
12036   }
12037   case ISD::CALLSEQ_END:
12038     return true;
12039   case ISD::INTRINSIC_WO_CHAIN:
12040     return AMDGPU::isIntrinsicSourceOfDivergence(
12041         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
12042   case ISD::INTRINSIC_W_CHAIN:
12043     return AMDGPU::isIntrinsicSourceOfDivergence(
12044         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
12045   case AMDGPUISD::ATOMIC_CMP_SWAP:
12046   case AMDGPUISD::ATOMIC_INC:
12047   case AMDGPUISD::ATOMIC_DEC:
12048   case AMDGPUISD::ATOMIC_LOAD_FMIN:
12049   case AMDGPUISD::ATOMIC_LOAD_FMAX:
12050   case AMDGPUISD::BUFFER_ATOMIC_SWAP:
12051   case AMDGPUISD::BUFFER_ATOMIC_ADD:
12052   case AMDGPUISD::BUFFER_ATOMIC_SUB:
12053   case AMDGPUISD::BUFFER_ATOMIC_SMIN:
12054   case AMDGPUISD::BUFFER_ATOMIC_UMIN:
12055   case AMDGPUISD::BUFFER_ATOMIC_SMAX:
12056   case AMDGPUISD::BUFFER_ATOMIC_UMAX:
12057   case AMDGPUISD::BUFFER_ATOMIC_AND:
12058   case AMDGPUISD::BUFFER_ATOMIC_OR:
12059   case AMDGPUISD::BUFFER_ATOMIC_XOR:
12060   case AMDGPUISD::BUFFER_ATOMIC_INC:
12061   case AMDGPUISD::BUFFER_ATOMIC_DEC:
12062   case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
12063   case AMDGPUISD::BUFFER_ATOMIC_CSUB:
12064   case AMDGPUISD::BUFFER_ATOMIC_FADD:
12065   case AMDGPUISD::BUFFER_ATOMIC_FMIN:
12066   case AMDGPUISD::BUFFER_ATOMIC_FMAX:
12067     // Target-specific read-modify-write atomics are sources of divergence.
12068     return true;
12069   default:
12070     if (auto *A = dyn_cast<AtomicSDNode>(N)) {
12071       // Generic read-modify-write atomics are sources of divergence.
12072       return A->readMem() && A->writeMem();
12073     }
12074     return false;
12075   }
12076 }
12077 
12078 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
12079                                                EVT VT) const {
12080   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
12081   case MVT::f32:
12082     return hasFP32Denormals(DAG.getMachineFunction());
12083   case MVT::f64:
12084   case MVT::f16:
12085     return hasFP64FP16Denormals(DAG.getMachineFunction());
12086   default:
12087     return false;
12088   }
12089 }
12090 
12091 bool SITargetLowering::denormalsEnabledForType(LLT Ty,
12092                                                MachineFunction &MF) const {
12093   switch (Ty.getScalarSizeInBits()) {
12094   case 32:
12095     return hasFP32Denormals(MF);
12096   case 64:
12097   case 16:
12098     return hasFP64FP16Denormals(MF);
12099   default:
12100     return false;
12101   }
12102 }
12103 
12104 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
12105                                                     const SelectionDAG &DAG,
12106                                                     bool SNaN,
12107                                                     unsigned Depth) const {
12108   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
12109     const MachineFunction &MF = DAG.getMachineFunction();
12110     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12111 
12112     if (Info->getMode().DX10Clamp)
12113       return true; // Clamped to 0.
12114     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
12115   }
12116 
12117   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
12118                                                             SNaN, Depth);
12119 }
12120 
12121 // Global FP atomic instructions have a hardcoded FP mode and do not support
12122 // FP32 denormals, and only support v2f16 denormals.
12123 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
12124   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
12125   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
12126   if (&Flt == &APFloat::IEEEsingle())
12127     return DenormMode == DenormalMode::getPreserveSign();
12128   return DenormMode == DenormalMode::getIEEE();
12129 }
12130 
12131 TargetLowering::AtomicExpansionKind
12132 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
12133 
12134   auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) {
12135     OptimizationRemarkEmitter ORE(RMW->getFunction());
12136     LLVMContext &Ctx = RMW->getFunction()->getContext();
12137     SmallVector<StringRef> SSNs;
12138     Ctx.getSyncScopeNames(SSNs);
12139     auto MemScope = SSNs[RMW->getSyncScopeID()].empty()
12140                         ? "system"
12141                         : SSNs[RMW->getSyncScopeID()];
12142     ORE.emit([&]() {
12143       return OptimizationRemark(DEBUG_TYPE, "Passed", RMW)
12144              << "Hardware instruction generated for atomic "
12145              << RMW->getOperationName(RMW->getOperation())
12146              << " operation at memory scope " << MemScope
12147              << " due to an unsafe request.";
12148     });
12149     return Kind;
12150   };
12151 
12152   switch (RMW->getOperation()) {
12153   case AtomicRMWInst::FAdd: {
12154     Type *Ty = RMW->getType();
12155 
12156     // We don't have a way to support 16-bit atomics now, so just leave them
12157     // as-is.
12158     if (Ty->isHalfTy())
12159       return AtomicExpansionKind::None;
12160 
12161     if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
12162       return AtomicExpansionKind::CmpXChg;
12163 
12164     unsigned AS = RMW->getPointerAddressSpace();
12165 
12166     if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) &&
12167          Subtarget->hasAtomicFaddInsts()) {
12168       // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
12169       // floating point atomic instructions. May generate more efficient code,
12170       // but may not respect rounding and denormal modes, and may give incorrect
12171       // results for certain memory destinations.
12172       if (RMW->getFunction()
12173               ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12174               .getValueAsString() != "true")
12175         return AtomicExpansionKind::CmpXChg;
12176 
12177       if (Subtarget->hasGFX90AInsts()) {
12178         if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS)
12179           return AtomicExpansionKind::CmpXChg;
12180 
12181         auto SSID = RMW->getSyncScopeID();
12182         if (SSID == SyncScope::System ||
12183             SSID == RMW->getContext().getOrInsertSyncScopeID("one-as"))
12184           return AtomicExpansionKind::CmpXChg;
12185 
12186         return ReportUnsafeHWInst(AtomicExpansionKind::None);
12187       }
12188 
12189       if (AS == AMDGPUAS::FLAT_ADDRESS)
12190         return AtomicExpansionKind::CmpXChg;
12191 
12192       return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12193                               : AtomicExpansionKind::CmpXChg;
12194     }
12195 
12196     // DS FP atomics do repect the denormal mode, but the rounding mode is fixed
12197     // to round-to-nearest-even.
12198     // The only exception is DS_ADD_F64 which never flushes regardless of mode.
12199     if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) {
12200       if (!Ty->isDoubleTy())
12201         return AtomicExpansionKind::None;
12202 
12203       if (fpModeMatchesGlobalFPAtomicMode(RMW))
12204         return AtomicExpansionKind::None;
12205 
12206       return RMW->getFunction()
12207                          ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12208                          .getValueAsString() == "true"
12209                  ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12210                  : AtomicExpansionKind::CmpXChg;
12211     }
12212 
12213     return AtomicExpansionKind::CmpXChg;
12214   }
12215   default:
12216     break;
12217   }
12218 
12219   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
12220 }
12221 
12222 const TargetRegisterClass *
12223 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
12224   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
12225   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12226   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
12227     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
12228                                                : &AMDGPU::SReg_32RegClass;
12229   if (!TRI->isSGPRClass(RC) && !isDivergent)
12230     return TRI->getEquivalentSGPRClass(RC);
12231   else if (TRI->isSGPRClass(RC) && isDivergent)
12232     return TRI->getEquivalentVGPRClass(RC);
12233 
12234   return RC;
12235 }
12236 
12237 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
12238 // uniform values (as produced by the mask results of control flow intrinsics)
12239 // used outside of divergent blocks. The phi users need to also be treated as
12240 // always uniform.
12241 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
12242                       unsigned WaveSize) {
12243   // FIXME: We asssume we never cast the mask results of a control flow
12244   // intrinsic.
12245   // Early exit if the type won't be consistent as a compile time hack.
12246   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
12247   if (!IT || IT->getBitWidth() != WaveSize)
12248     return false;
12249 
12250   if (!isa<Instruction>(V))
12251     return false;
12252   if (!Visited.insert(V).second)
12253     return false;
12254   bool Result = false;
12255   for (auto U : V->users()) {
12256     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
12257       if (V == U->getOperand(1)) {
12258         switch (Intrinsic->getIntrinsicID()) {
12259         default:
12260           Result = false;
12261           break;
12262         case Intrinsic::amdgcn_if_break:
12263         case Intrinsic::amdgcn_if:
12264         case Intrinsic::amdgcn_else:
12265           Result = true;
12266           break;
12267         }
12268       }
12269       if (V == U->getOperand(0)) {
12270         switch (Intrinsic->getIntrinsicID()) {
12271         default:
12272           Result = false;
12273           break;
12274         case Intrinsic::amdgcn_end_cf:
12275         case Intrinsic::amdgcn_loop:
12276           Result = true;
12277           break;
12278         }
12279       }
12280     } else {
12281       Result = hasCFUser(U, Visited, WaveSize);
12282     }
12283     if (Result)
12284       break;
12285   }
12286   return Result;
12287 }
12288 
12289 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
12290                                                const Value *V) const {
12291   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
12292     if (CI->isInlineAsm()) {
12293       // FIXME: This cannot give a correct answer. This should only trigger in
12294       // the case where inline asm returns mixed SGPR and VGPR results, used
12295       // outside the defining block. We don't have a specific result to
12296       // consider, so this assumes if any value is SGPR, the overall register
12297       // also needs to be SGPR.
12298       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
12299       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
12300           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
12301       for (auto &TC : TargetConstraints) {
12302         if (TC.Type == InlineAsm::isOutput) {
12303           ComputeConstraintToUse(TC, SDValue());
12304           unsigned AssignedReg;
12305           const TargetRegisterClass *RC;
12306           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
12307               SIRI, TC.ConstraintCode, TC.ConstraintVT);
12308           if (RC) {
12309             MachineRegisterInfo &MRI = MF.getRegInfo();
12310             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
12311               return true;
12312             else if (SIRI->isSGPRClass(RC))
12313               return true;
12314           }
12315         }
12316       }
12317     }
12318   }
12319   SmallPtrSet<const Value *, 16> Visited;
12320   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
12321 }
12322 
12323 std::pair<InstructionCost, MVT>
12324 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
12325                                           Type *Ty) const {
12326   std::pair<InstructionCost, MVT> Cost =
12327       TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
12328   auto Size = DL.getTypeSizeInBits(Ty);
12329   // Maximum load or store can handle 8 dwords for scalar and 4 for
12330   // vector ALU. Let's assume anything above 8 dwords is expensive
12331   // even if legal.
12332   if (Size <= 256)
12333     return Cost;
12334 
12335   Cost.first = (Size + 255) / 256;
12336   return Cost;
12337 }
12338