xref: /freebsd/contrib/llvm-project/llvm/lib/Target/AMDGPU/SIISelLowering.cpp (revision d5b0e70f7e04d971691517ce1304d86a1e367e2e)
1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// Custom DAG lowering for SI
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "SIISelLowering.h"
15 #include "AMDGPU.h"
16 #include "AMDGPUInstrInfo.h"
17 #include "AMDGPUTargetMachine.h"
18 #include "SIMachineFunctionInfo.h"
19 #include "SIRegisterInfo.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
22 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
23 #include "llvm/BinaryFormat/ELF.h"
24 #include "llvm/CodeGen/Analysis.h"
25 #include "llvm/CodeGen/FunctionLoweringInfo.h"
26 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
27 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineLoopInfo.h"
30 #include "llvm/IR/DiagnosticInfo.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/IntrinsicsAMDGPU.h"
33 #include "llvm/IR/IntrinsicsR600.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/KnownBits.h"
36 
37 using namespace llvm;
38 
39 #define DEBUG_TYPE "si-lower"
40 
41 STATISTIC(NumTailCalls, "Number of tail calls");
42 
43 static cl::opt<bool> DisableLoopAlignment(
44   "amdgpu-disable-loop-alignment",
45   cl::desc("Do not align and prefetch loops"),
46   cl::init(false));
47 
48 static cl::opt<bool> UseDivergentRegisterIndexing(
49   "amdgpu-use-divergent-register-indexing",
50   cl::Hidden,
51   cl::desc("Use indirect register addressing for divergent indexes"),
52   cl::init(false));
53 
54 static bool hasFP32Denormals(const MachineFunction &MF) {
55   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
56   return Info->getMode().allFP32Denormals();
57 }
58 
59 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
60   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
61   return Info->getMode().allFP64FP16Denormals();
62 }
63 
64 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
65   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
66   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
67     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
68       return AMDGPU::SGPR0 + Reg;
69     }
70   }
71   llvm_unreachable("Cannot allocate sgpr");
72 }
73 
74 SITargetLowering::SITargetLowering(const TargetMachine &TM,
75                                    const GCNSubtarget &STI)
76     : AMDGPUTargetLowering(TM, STI),
77       Subtarget(&STI) {
78   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
79   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
80 
81   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
82   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
83 
84   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
85 
86   const SIRegisterInfo *TRI = STI.getRegisterInfo();
87   const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class();
88 
89   addRegisterClass(MVT::f64, V64RegClass);
90   addRegisterClass(MVT::v2f32, V64RegClass);
91 
92   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
93   addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96));
94 
95   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
96   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
97 
98   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
99   addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128));
100 
101   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
102   addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160));
103 
104   addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass);
105   addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192));
106 
107   addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass);
108   addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192));
109 
110   addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass);
111   addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224));
112 
113   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
114   addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256));
115 
116   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
117   addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256));
118 
119   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
120   addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512));
121 
122   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
123   addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512));
124 
125   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
126   addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024));
127 
128   if (Subtarget->has16BitInsts()) {
129     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
130     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
131 
132     // Unless there are also VOP3P operations, not operations are really legal.
133     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
134     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
135     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
136     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
137     addRegisterClass(MVT::v8i16, &AMDGPU::SGPR_128RegClass);
138     addRegisterClass(MVT::v8f16, &AMDGPU::SGPR_128RegClass);
139   }
140 
141   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
142   addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024));
143 
144   computeRegisterProperties(Subtarget->getRegisterInfo());
145 
146   // The boolean content concept here is too inflexible. Compares only ever
147   // really produce a 1-bit result. Any copy/extend from these will turn into a
148   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
149   // it's what most targets use.
150   setBooleanContents(ZeroOrOneBooleanContent);
151   setBooleanVectorContents(ZeroOrOneBooleanContent);
152 
153   // We need to custom lower vector stores from local memory
154   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
155   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
156   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
157   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
158   setOperationAction(ISD::LOAD, MVT::v6i32, Custom);
159   setOperationAction(ISD::LOAD, MVT::v7i32, Custom);
160   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
161   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
162   setOperationAction(ISD::LOAD, MVT::i1, Custom);
163   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
164 
165   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
166   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
167   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
168   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
169   setOperationAction(ISD::STORE, MVT::v6i32, Custom);
170   setOperationAction(ISD::STORE, MVT::v7i32, Custom);
171   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
172   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
173   setOperationAction(ISD::STORE, MVT::i1, Custom);
174   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
175 
176   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
177   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
178   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
179   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
180   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
181   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
182   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
183   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
184   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
185   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
186   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
187   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
188   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
189   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
190   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
191   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
192 
193   setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand);
194   setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand);
195   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
196   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
197   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
198   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
199   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
200 
201   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
202   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
203 
204   setOperationAction(ISD::SELECT, MVT::i1, Promote);
205   setOperationAction(ISD::SELECT, MVT::i64, Custom);
206   setOperationAction(ISD::SELECT, MVT::f64, Promote);
207   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
208 
209   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
210   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
211   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
212   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
213   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
214 
215   setOperationAction(ISD::SETCC, MVT::i1, Promote);
216   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
217   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
218   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
219 
220   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
221   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
222   setOperationAction(ISD::TRUNCATE, MVT::v3i32, Expand);
223   setOperationAction(ISD::FP_ROUND, MVT::v3f32, Expand);
224   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
225   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
226   setOperationAction(ISD::TRUNCATE, MVT::v5i32, Expand);
227   setOperationAction(ISD::FP_ROUND, MVT::v5f32, Expand);
228   setOperationAction(ISD::TRUNCATE, MVT::v6i32, Expand);
229   setOperationAction(ISD::FP_ROUND, MVT::v6f32, Expand);
230   setOperationAction(ISD::TRUNCATE, MVT::v7i32, Expand);
231   setOperationAction(ISD::FP_ROUND, MVT::v7f32, Expand);
232   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
233   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
234   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
235   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
236 
237   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
238   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
239   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
240   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
241   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
242   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
243   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
244   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
245 
246   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
247   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
248   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
249   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
250   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
251   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
252 
253   setOperationAction(ISD::UADDO, MVT::i32, Legal);
254   setOperationAction(ISD::USUBO, MVT::i32, Legal);
255 
256   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
257   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
258 
259   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
260   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
261   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
262 
263 #if 0
264   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
265   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
266 #endif
267 
268   // We only support LOAD/STORE and vector manipulation ops for vectors
269   // with > 4 elements.
270   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
271                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
272                   MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32,
273                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
274                   MVT::v8i16, MVT::v8f16, MVT::v16i64, MVT::v16f64,
275                   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, MVT::v8i16,
618                    MVT::v8f16}) {
619       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
620         switch (Op) {
621         case ISD::LOAD:
622         case ISD::STORE:
623         case ISD::BUILD_VECTOR:
624         case ISD::BITCAST:
625         case ISD::EXTRACT_VECTOR_ELT:
626         case ISD::INSERT_VECTOR_ELT:
627         case ISD::INSERT_SUBVECTOR:
628         case ISD::EXTRACT_SUBVECTOR:
629         case ISD::SCALAR_TO_VECTOR:
630           break;
631         case ISD::CONCAT_VECTORS:
632           setOperationAction(Op, VT, Custom);
633           break;
634         default:
635           setOperationAction(Op, VT, Expand);
636           break;
637         }
638       }
639     }
640 
641     // v_perm_b32 can handle either of these.
642     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
643     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
644     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
645 
646     // XXX - Do these do anything? Vector constants turn into build_vector.
647     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
648     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
649 
650     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
651     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
652 
653     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
654     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
655     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
656     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
657 
658     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
659     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
660     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
661     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
662 
663     setOperationAction(ISD::AND, MVT::v2i16, Promote);
664     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
665     setOperationAction(ISD::OR, MVT::v2i16, Promote);
666     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
667     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
668     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
669 
670     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
671     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
672     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
673     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
674 
675     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
676     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
677     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
678     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
679 
680     setOperationAction(ISD::LOAD, MVT::v8i16, Promote);
681     AddPromotedToType(ISD::LOAD, MVT::v8i16, MVT::v4i32);
682     setOperationAction(ISD::LOAD, MVT::v8f16, Promote);
683     AddPromotedToType(ISD::LOAD, MVT::v8f16, MVT::v4i32);
684 
685     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
686     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
687     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
688     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
689 
690     setOperationAction(ISD::STORE, MVT::v8i16, Promote);
691     AddPromotedToType(ISD::STORE, MVT::v8i16, MVT::v4i32);
692     setOperationAction(ISD::STORE, MVT::v8f16, Promote);
693     AddPromotedToType(ISD::STORE, MVT::v8f16, MVT::v4i32);
694 
695     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
696     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
697     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
698     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
699 
700     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
701     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
702     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
703 
704     setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Expand);
705     setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Expand);
706     setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Expand);
707 
708     if (!Subtarget->hasVOP3PInsts()) {
709       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
710       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
711     }
712 
713     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
714     // This isn't really legal, but this avoids the legalizer unrolling it (and
715     // allows matching fneg (fabs x) patterns)
716     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
717 
718     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
719     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
720     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
721     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
722 
723     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
724     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
725     setOperationAction(ISD::FMINNUM_IEEE, MVT::v8f16, Custom);
726     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v8f16, Custom);
727 
728     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
729     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
730     setOperationAction(ISD::FMINNUM, MVT::v8f16, Expand);
731     setOperationAction(ISD::FMAXNUM, MVT::v8f16, Expand);
732 
733     for (MVT Vec16 : { MVT::v8i16, MVT::v8f16 }) {
734       setOperationAction(ISD::BUILD_VECTOR, Vec16, Custom);
735       setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec16, Custom);
736       setOperationAction(ISD::INSERT_VECTOR_ELT, Vec16, Expand);
737       setOperationAction(ISD::SCALAR_TO_VECTOR, Vec16, Expand);
738     }
739   }
740 
741   if (Subtarget->hasVOP3PInsts()) {
742     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
743     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
744     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
745     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
746     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
747     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
748     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
749     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
750     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
751     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
752 
753     setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal);
754     setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal);
755     setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal);
756     setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal);
757 
758     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
759     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
760     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
761 
762     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
763     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
764 
765     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
766 
767     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
768     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
769 
770     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
771     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
772     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f16, Custom);
773     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i16, Custom);
774 
775     for (MVT VT : { MVT::v4i16, MVT::v8i16 }) {
776       // Split vector operations.
777       setOperationAction(ISD::SHL, VT, Custom);
778       setOperationAction(ISD::SRA, VT, Custom);
779       setOperationAction(ISD::SRL, VT, Custom);
780       setOperationAction(ISD::ADD, VT, Custom);
781       setOperationAction(ISD::SUB, VT, Custom);
782       setOperationAction(ISD::MUL, VT, Custom);
783 
784       setOperationAction(ISD::SMIN, VT, Custom);
785       setOperationAction(ISD::SMAX, VT, Custom);
786       setOperationAction(ISD::UMIN, VT, Custom);
787       setOperationAction(ISD::UMAX, VT, Custom);
788 
789       setOperationAction(ISD::UADDSAT, VT, Custom);
790       setOperationAction(ISD::SADDSAT, VT, Custom);
791       setOperationAction(ISD::USUBSAT, VT, Custom);
792       setOperationAction(ISD::SSUBSAT, VT, Custom);
793     }
794 
795     for (MVT VT : { MVT::v4f16, MVT::v8f16 }) {
796       // Split vector operations.
797       setOperationAction(ISD::FADD, VT, Custom);
798       setOperationAction(ISD::FMUL, VT, Custom);
799       setOperationAction(ISD::FMA, VT, Custom);
800       setOperationAction(ISD::FCANONICALIZE, VT, Custom);
801     }
802 
803     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
804     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
805 
806     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
807     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
808 
809     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
810     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
811     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
812 
813     if (Subtarget->hasPackedFP32Ops()) {
814       setOperationAction(ISD::FADD, MVT::v2f32, Legal);
815       setOperationAction(ISD::FMUL, MVT::v2f32, Legal);
816       setOperationAction(ISD::FMA,  MVT::v2f32, Legal);
817       setOperationAction(ISD::FNEG, MVT::v2f32, Legal);
818 
819       for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) {
820         setOperationAction(ISD::FADD, VT, Custom);
821         setOperationAction(ISD::FMUL, VT, Custom);
822         setOperationAction(ISD::FMA, VT, Custom);
823       }
824     }
825   }
826 
827   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
828   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
829 
830   if (Subtarget->has16BitInsts()) {
831     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
832     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
833     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
834     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
835   } else {
836     // Legalization hack.
837     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
838     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
839 
840     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
841     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
842   }
843 
844   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8,
845                   MVT::v8i16, MVT::v8f16 }) {
846     setOperationAction(ISD::SELECT, VT, Custom);
847   }
848 
849   setOperationAction(ISD::SMULO, MVT::i64, Custom);
850   setOperationAction(ISD::UMULO, MVT::i64, Custom);
851 
852   if (Subtarget->hasMad64_32()) {
853     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
854     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
855   }
856 
857   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
858   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
859   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
860   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
861   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
862   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
863   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
864 
865   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
866   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
867   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom);
868   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom);
869   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
870   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
871   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
872   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
873   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
874   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
875   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
876 
877   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
878   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
879   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
880   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom);
881   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom);
882   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
883   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
884   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
885   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
886   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
887 
888   setTargetDAGCombine(ISD::ADD);
889   setTargetDAGCombine(ISD::ADDCARRY);
890   setTargetDAGCombine(ISD::SUB);
891   setTargetDAGCombine(ISD::SUBCARRY);
892   setTargetDAGCombine(ISD::FADD);
893   setTargetDAGCombine(ISD::FSUB);
894   setTargetDAGCombine(ISD::FMINNUM);
895   setTargetDAGCombine(ISD::FMAXNUM);
896   setTargetDAGCombine(ISD::FMINNUM_IEEE);
897   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
898   setTargetDAGCombine(ISD::FMA);
899   setTargetDAGCombine(ISD::SMIN);
900   setTargetDAGCombine(ISD::SMAX);
901   setTargetDAGCombine(ISD::UMIN);
902   setTargetDAGCombine(ISD::UMAX);
903   setTargetDAGCombine(ISD::SETCC);
904   setTargetDAGCombine(ISD::AND);
905   setTargetDAGCombine(ISD::OR);
906   setTargetDAGCombine(ISD::XOR);
907   setTargetDAGCombine(ISD::SINT_TO_FP);
908   setTargetDAGCombine(ISD::UINT_TO_FP);
909   setTargetDAGCombine(ISD::FCANONICALIZE);
910   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
911   setTargetDAGCombine(ISD::ZERO_EXTEND);
912   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
913   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
914   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
915 
916   // All memory operations. Some folding on the pointer operand is done to help
917   // matching the constant offsets in the addressing modes.
918   setTargetDAGCombine(ISD::LOAD);
919   setTargetDAGCombine(ISD::STORE);
920   setTargetDAGCombine(ISD::ATOMIC_LOAD);
921   setTargetDAGCombine(ISD::ATOMIC_STORE);
922   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
923   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
924   setTargetDAGCombine(ISD::ATOMIC_SWAP);
925   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
926   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
927   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
928   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
929   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
930   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
931   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
932   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
933   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
934   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
935   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
936   setTargetDAGCombine(ISD::INTRINSIC_VOID);
937   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
938 
939   // FIXME: In other contexts we pretend this is a per-function property.
940   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
941 
942   setSchedulingPreference(Sched::RegPressure);
943 }
944 
945 const GCNSubtarget *SITargetLowering::getSubtarget() const {
946   return Subtarget;
947 }
948 
949 //===----------------------------------------------------------------------===//
950 // TargetLowering queries
951 //===----------------------------------------------------------------------===//
952 
953 // v_mad_mix* support a conversion from f16 to f32.
954 //
955 // There is only one special case when denormals are enabled we don't currently,
956 // where this is OK to use.
957 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
958                                        EVT DestVT, EVT SrcVT) const {
959   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
960           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
961     DestVT.getScalarType() == MVT::f32 &&
962     SrcVT.getScalarType() == MVT::f16 &&
963     // TODO: This probably only requires no input flushing?
964     !hasFP32Denormals(DAG.getMachineFunction());
965 }
966 
967 bool SITargetLowering::isFPExtFoldable(const MachineInstr &MI, unsigned Opcode,
968                                        LLT DestTy, LLT SrcTy) const {
969   return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) ||
970           (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) &&
971          DestTy.getScalarSizeInBits() == 32 &&
972          SrcTy.getScalarSizeInBits() == 16 &&
973          // TODO: This probably only requires no input flushing?
974          !hasFP32Denormals(*MI.getMF());
975 }
976 
977 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
978   // SI has some legal vector types, but no legal vector operations. Say no
979   // shuffles are legal in order to prefer scalarizing some vector operations.
980   return false;
981 }
982 
983 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
984                                                     CallingConv::ID CC,
985                                                     EVT VT) const {
986   if (CC == CallingConv::AMDGPU_KERNEL)
987     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
988 
989   if (VT.isVector()) {
990     EVT ScalarVT = VT.getScalarType();
991     unsigned Size = ScalarVT.getSizeInBits();
992     if (Size == 16) {
993       if (Subtarget->has16BitInsts())
994         return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
995       return VT.isInteger() ? MVT::i32 : MVT::f32;
996     }
997 
998     if (Size < 16)
999       return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
1000     return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
1001   }
1002 
1003   if (VT.getSizeInBits() > 32)
1004     return MVT::i32;
1005 
1006   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1007 }
1008 
1009 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1010                                                          CallingConv::ID CC,
1011                                                          EVT VT) const {
1012   if (CC == CallingConv::AMDGPU_KERNEL)
1013     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1014 
1015   if (VT.isVector()) {
1016     unsigned NumElts = VT.getVectorNumElements();
1017     EVT ScalarVT = VT.getScalarType();
1018     unsigned Size = ScalarVT.getSizeInBits();
1019 
1020     // FIXME: Should probably promote 8-bit vectors to i16.
1021     if (Size == 16 && Subtarget->has16BitInsts())
1022       return (NumElts + 1) / 2;
1023 
1024     if (Size <= 32)
1025       return NumElts;
1026 
1027     if (Size > 32)
1028       return NumElts * ((Size + 31) / 32);
1029   } else if (VT.getSizeInBits() > 32)
1030     return (VT.getSizeInBits() + 31) / 32;
1031 
1032   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1033 }
1034 
1035 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
1036   LLVMContext &Context, CallingConv::ID CC,
1037   EVT VT, EVT &IntermediateVT,
1038   unsigned &NumIntermediates, MVT &RegisterVT) const {
1039   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
1040     unsigned NumElts = VT.getVectorNumElements();
1041     EVT ScalarVT = VT.getScalarType();
1042     unsigned Size = ScalarVT.getSizeInBits();
1043     // FIXME: We should fix the ABI to be the same on targets without 16-bit
1044     // support, but unless we can properly handle 3-vectors, it will be still be
1045     // inconsistent.
1046     if (Size == 16 && Subtarget->has16BitInsts()) {
1047       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
1048       IntermediateVT = RegisterVT;
1049       NumIntermediates = (NumElts + 1) / 2;
1050       return NumIntermediates;
1051     }
1052 
1053     if (Size == 32) {
1054       RegisterVT = ScalarVT.getSimpleVT();
1055       IntermediateVT = RegisterVT;
1056       NumIntermediates = NumElts;
1057       return NumIntermediates;
1058     }
1059 
1060     if (Size < 16 && Subtarget->has16BitInsts()) {
1061       // FIXME: Should probably form v2i16 pieces
1062       RegisterVT = MVT::i16;
1063       IntermediateVT = ScalarVT;
1064       NumIntermediates = NumElts;
1065       return NumIntermediates;
1066     }
1067 
1068 
1069     if (Size != 16 && Size <= 32) {
1070       RegisterVT = MVT::i32;
1071       IntermediateVT = ScalarVT;
1072       NumIntermediates = NumElts;
1073       return NumIntermediates;
1074     }
1075 
1076     if (Size > 32) {
1077       RegisterVT = MVT::i32;
1078       IntermediateVT = RegisterVT;
1079       NumIntermediates = NumElts * ((Size + 31) / 32);
1080       return NumIntermediates;
1081     }
1082   }
1083 
1084   return TargetLowering::getVectorTypeBreakdownForCallingConv(
1085     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
1086 }
1087 
1088 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
1089   assert(DMaskLanes != 0);
1090 
1091   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1092     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
1093     return EVT::getVectorVT(Ty->getContext(),
1094                             EVT::getEVT(VT->getElementType()),
1095                             NumElts);
1096   }
1097 
1098   return EVT::getEVT(Ty);
1099 }
1100 
1101 // Peek through TFE struct returns to only use the data size.
1102 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
1103   auto *ST = dyn_cast<StructType>(Ty);
1104   if (!ST)
1105     return memVTFromImageData(Ty, DMaskLanes);
1106 
1107   // Some intrinsics return an aggregate type - special case to work out the
1108   // correct memVT.
1109   //
1110   // Only limited forms of aggregate type currently expected.
1111   if (ST->getNumContainedTypes() != 2 ||
1112       !ST->getContainedType(1)->isIntegerTy(32))
1113     return EVT();
1114   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
1115 }
1116 
1117 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1118                                           const CallInst &CI,
1119                                           MachineFunction &MF,
1120                                           unsigned IntrID) const {
1121   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1122           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1123     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1124                                                   (Intrinsic::ID)IntrID);
1125     if (Attr.hasFnAttr(Attribute::ReadNone))
1126       return false;
1127 
1128     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1129 
1130     if (RsrcIntr->IsImage) {
1131       Info.ptrVal =
1132           MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1133       Info.align.reset();
1134     } else {
1135       Info.ptrVal =
1136           MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1137     }
1138 
1139     Info.flags = MachineMemOperand::MODereferenceable;
1140     if (Attr.hasFnAttr(Attribute::ReadOnly)) {
1141       unsigned DMaskLanes = 4;
1142 
1143       if (RsrcIntr->IsImage) {
1144         const AMDGPU::ImageDimIntrinsicInfo *Intr
1145           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1146         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1147           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1148 
1149         if (!BaseOpcode->Gather4) {
1150           // If this isn't a gather, we may have excess loaded elements in the
1151           // IR type. Check the dmask for the real number of elements loaded.
1152           unsigned DMask
1153             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1154           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1155         }
1156 
1157         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1158       } else
1159         Info.memVT = EVT::getEVT(CI.getType());
1160 
1161       // FIXME: What does alignment mean for an image?
1162       Info.opc = ISD::INTRINSIC_W_CHAIN;
1163       Info.flags |= MachineMemOperand::MOLoad;
1164     } else if (Attr.hasFnAttr(Attribute::WriteOnly)) {
1165       Info.opc = ISD::INTRINSIC_VOID;
1166 
1167       Type *DataTy = CI.getArgOperand(0)->getType();
1168       if (RsrcIntr->IsImage) {
1169         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1170         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1171         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1172       } else
1173         Info.memVT = EVT::getEVT(DataTy);
1174 
1175       Info.flags |= MachineMemOperand::MOStore;
1176     } else {
1177       // Atomic
1178       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1179                                             ISD::INTRINSIC_W_CHAIN;
1180       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1181       Info.flags = MachineMemOperand::MOLoad |
1182                    MachineMemOperand::MOStore |
1183                    MachineMemOperand::MODereferenceable;
1184 
1185       // XXX - Should this be volatile without known ordering?
1186       Info.flags |= MachineMemOperand::MOVolatile;
1187     }
1188     return true;
1189   }
1190 
1191   switch (IntrID) {
1192   case Intrinsic::amdgcn_atomic_inc:
1193   case Intrinsic::amdgcn_atomic_dec:
1194   case Intrinsic::amdgcn_ds_ordered_add:
1195   case Intrinsic::amdgcn_ds_ordered_swap:
1196   case Intrinsic::amdgcn_ds_fadd:
1197   case Intrinsic::amdgcn_ds_fmin:
1198   case Intrinsic::amdgcn_ds_fmax: {
1199     Info.opc = ISD::INTRINSIC_W_CHAIN;
1200     Info.memVT = MVT::getVT(CI.getType());
1201     Info.ptrVal = CI.getOperand(0);
1202     Info.align.reset();
1203     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1204 
1205     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1206     if (!Vol->isZero())
1207       Info.flags |= MachineMemOperand::MOVolatile;
1208 
1209     return true;
1210   }
1211   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1212     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1213 
1214     Info.opc = ISD::INTRINSIC_W_CHAIN;
1215     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1216     Info.ptrVal =
1217         MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1218     Info.align.reset();
1219     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1220 
1221     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1222     if (!Vol || !Vol->isZero())
1223       Info.flags |= MachineMemOperand::MOVolatile;
1224 
1225     return true;
1226   }
1227   case Intrinsic::amdgcn_ds_append:
1228   case Intrinsic::amdgcn_ds_consume: {
1229     Info.opc = ISD::INTRINSIC_W_CHAIN;
1230     Info.memVT = MVT::getVT(CI.getType());
1231     Info.ptrVal = CI.getOperand(0);
1232     Info.align.reset();
1233     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1234 
1235     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1236     if (!Vol->isZero())
1237       Info.flags |= MachineMemOperand::MOVolatile;
1238 
1239     return true;
1240   }
1241   case Intrinsic::amdgcn_global_atomic_csub: {
1242     Info.opc = ISD::INTRINSIC_W_CHAIN;
1243     Info.memVT = MVT::getVT(CI.getType());
1244     Info.ptrVal = CI.getOperand(0);
1245     Info.align.reset();
1246     Info.flags = MachineMemOperand::MOLoad |
1247                  MachineMemOperand::MOStore |
1248                  MachineMemOperand::MOVolatile;
1249     return true;
1250   }
1251   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1252     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1253     Info.opc = ISD::INTRINSIC_W_CHAIN;
1254     Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1255     Info.ptrVal =
1256         MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1257     Info.align.reset();
1258     Info.flags = MachineMemOperand::MOLoad |
1259                  MachineMemOperand::MODereferenceable;
1260     return true;
1261   }
1262   case Intrinsic::amdgcn_global_atomic_fadd:
1263   case Intrinsic::amdgcn_global_atomic_fmin:
1264   case Intrinsic::amdgcn_global_atomic_fmax:
1265   case Intrinsic::amdgcn_flat_atomic_fadd:
1266   case Intrinsic::amdgcn_flat_atomic_fmin:
1267   case Intrinsic::amdgcn_flat_atomic_fmax: {
1268     Info.opc = ISD::INTRINSIC_W_CHAIN;
1269     Info.memVT = MVT::getVT(CI.getType());
1270     Info.ptrVal = CI.getOperand(0);
1271     Info.align.reset();
1272     Info.flags = MachineMemOperand::MOLoad |
1273                  MachineMemOperand::MOStore |
1274                  MachineMemOperand::MODereferenceable |
1275                  MachineMemOperand::MOVolatile;
1276     return true;
1277   }
1278   case Intrinsic::amdgcn_ds_gws_init:
1279   case Intrinsic::amdgcn_ds_gws_barrier:
1280   case Intrinsic::amdgcn_ds_gws_sema_v:
1281   case Intrinsic::amdgcn_ds_gws_sema_br:
1282   case Intrinsic::amdgcn_ds_gws_sema_p:
1283   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1284     Info.opc = ISD::INTRINSIC_VOID;
1285 
1286     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1287     Info.ptrVal =
1288         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1289 
1290     // This is an abstract access, but we need to specify a type and size.
1291     Info.memVT = MVT::i32;
1292     Info.size = 4;
1293     Info.align = Align(4);
1294 
1295     Info.flags = MachineMemOperand::MOStore;
1296     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1297       Info.flags = MachineMemOperand::MOLoad;
1298     return true;
1299   }
1300   default:
1301     return false;
1302   }
1303 }
1304 
1305 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1306                                             SmallVectorImpl<Value*> &Ops,
1307                                             Type *&AccessTy) const {
1308   switch (II->getIntrinsicID()) {
1309   case Intrinsic::amdgcn_atomic_inc:
1310   case Intrinsic::amdgcn_atomic_dec:
1311   case Intrinsic::amdgcn_ds_ordered_add:
1312   case Intrinsic::amdgcn_ds_ordered_swap:
1313   case Intrinsic::amdgcn_ds_append:
1314   case Intrinsic::amdgcn_ds_consume:
1315   case Intrinsic::amdgcn_ds_fadd:
1316   case Intrinsic::amdgcn_ds_fmin:
1317   case Intrinsic::amdgcn_ds_fmax:
1318   case Intrinsic::amdgcn_global_atomic_fadd:
1319   case Intrinsic::amdgcn_flat_atomic_fadd:
1320   case Intrinsic::amdgcn_flat_atomic_fmin:
1321   case Intrinsic::amdgcn_flat_atomic_fmax:
1322   case Intrinsic::amdgcn_global_atomic_csub: {
1323     Value *Ptr = II->getArgOperand(0);
1324     AccessTy = II->getType();
1325     Ops.push_back(Ptr);
1326     return true;
1327   }
1328   default:
1329     return false;
1330   }
1331 }
1332 
1333 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1334   if (!Subtarget->hasFlatInstOffsets()) {
1335     // Flat instructions do not have offsets, and only have the register
1336     // address.
1337     return AM.BaseOffs == 0 && AM.Scale == 0;
1338   }
1339 
1340   return AM.Scale == 0 &&
1341          (AM.BaseOffs == 0 ||
1342           Subtarget->getInstrInfo()->isLegalFLATOffset(
1343               AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT));
1344 }
1345 
1346 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1347   if (Subtarget->hasFlatGlobalInsts())
1348     return AM.Scale == 0 &&
1349            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1350                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1351                                     SIInstrFlags::FlatGlobal));
1352 
1353   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1354       // Assume the we will use FLAT for all global memory accesses
1355       // on VI.
1356       // FIXME: This assumption is currently wrong.  On VI we still use
1357       // MUBUF instructions for the r + i addressing mode.  As currently
1358       // implemented, the MUBUF instructions only work on buffer < 4GB.
1359       // It may be possible to support > 4GB buffers with MUBUF instructions,
1360       // by setting the stride value in the resource descriptor which would
1361       // increase the size limit to (stride * 4GB).  However, this is risky,
1362       // because it has never been validated.
1363     return isLegalFlatAddressingMode(AM);
1364   }
1365 
1366   return isLegalMUBUFAddressingMode(AM);
1367 }
1368 
1369 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1370   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1371   // additionally can do r + r + i with addr64. 32-bit has more addressing
1372   // mode options. Depending on the resource constant, it can also do
1373   // (i64 r0) + (i32 r1) * (i14 i).
1374   //
1375   // Private arrays end up using a scratch buffer most of the time, so also
1376   // assume those use MUBUF instructions. Scratch loads / stores are currently
1377   // implemented as mubuf instructions with offen bit set, so slightly
1378   // different than the normal addr64.
1379   if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1380     return false;
1381 
1382   // FIXME: Since we can split immediate into soffset and immediate offset,
1383   // would it make sense to allow any immediate?
1384 
1385   switch (AM.Scale) {
1386   case 0: // r + i or just i, depending on HasBaseReg.
1387     return true;
1388   case 1:
1389     return true; // We have r + r or r + i.
1390   case 2:
1391     if (AM.HasBaseReg) {
1392       // Reject 2 * r + r.
1393       return false;
1394     }
1395 
1396     // Allow 2 * r as r + r
1397     // Or  2 * r + i is allowed as r + r + i.
1398     return true;
1399   default: // Don't allow n * r
1400     return false;
1401   }
1402 }
1403 
1404 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1405                                              const AddrMode &AM, Type *Ty,
1406                                              unsigned AS, Instruction *I) const {
1407   // No global is ever allowed as a base.
1408   if (AM.BaseGV)
1409     return false;
1410 
1411   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1412     return isLegalGlobalAddressingMode(AM);
1413 
1414   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1415       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1416       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1417     // If the offset isn't a multiple of 4, it probably isn't going to be
1418     // correctly aligned.
1419     // FIXME: Can we get the real alignment here?
1420     if (AM.BaseOffs % 4 != 0)
1421       return isLegalMUBUFAddressingMode(AM);
1422 
1423     // There are no SMRD extloads, so if we have to do a small type access we
1424     // will use a MUBUF load.
1425     // FIXME?: We also need to do this if unaligned, but we don't know the
1426     // alignment here.
1427     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1428       return isLegalGlobalAddressingMode(AM);
1429 
1430     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1431       // SMRD instructions have an 8-bit, dword offset on SI.
1432       if (!isUInt<8>(AM.BaseOffs / 4))
1433         return false;
1434     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1435       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1436       // in 8-bits, it can use a smaller encoding.
1437       if (!isUInt<32>(AM.BaseOffs / 4))
1438         return false;
1439     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1440       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1441       if (!isUInt<20>(AM.BaseOffs))
1442         return false;
1443     } else
1444       llvm_unreachable("unhandled generation");
1445 
1446     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1447       return true;
1448 
1449     if (AM.Scale == 1 && AM.HasBaseReg)
1450       return true;
1451 
1452     return false;
1453 
1454   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1455     return isLegalMUBUFAddressingMode(AM);
1456   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1457              AS == AMDGPUAS::REGION_ADDRESS) {
1458     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1459     // field.
1460     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1461     // an 8-bit dword offset but we don't know the alignment here.
1462     if (!isUInt<16>(AM.BaseOffs))
1463       return false;
1464 
1465     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1466       return true;
1467 
1468     if (AM.Scale == 1 && AM.HasBaseReg)
1469       return true;
1470 
1471     return false;
1472   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1473              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1474     // For an unknown address space, this usually means that this is for some
1475     // reason being used for pure arithmetic, and not based on some addressing
1476     // computation. We don't have instructions that compute pointers with any
1477     // addressing modes, so treat them as having no offset like flat
1478     // instructions.
1479     return isLegalFlatAddressingMode(AM);
1480   }
1481 
1482   // Assume a user alias of global for unknown address spaces.
1483   return isLegalGlobalAddressingMode(AM);
1484 }
1485 
1486 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1487                                         const MachineFunction &MF) const {
1488   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1489     return (MemVT.getSizeInBits() <= 4 * 32);
1490   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1491     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1492     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1493   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1494     return (MemVT.getSizeInBits() <= 2 * 32);
1495   }
1496   return true;
1497 }
1498 
1499 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1500     unsigned Size, unsigned AddrSpace, Align Alignment,
1501     MachineMemOperand::Flags Flags, bool *IsFast) const {
1502   if (IsFast)
1503     *IsFast = false;
1504 
1505   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1506       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1507     // Check if alignment requirements for ds_read/write instructions are
1508     // disabled.
1509     if (Subtarget->hasUnalignedDSAccessEnabled() &&
1510         !Subtarget->hasLDSMisalignedBug()) {
1511       if (IsFast)
1512         *IsFast = Alignment != Align(2);
1513       return true;
1514     }
1515 
1516     // Either, the alignment requirements are "enabled", or there is an
1517     // unaligned LDS access related hardware bug though alignment requirements
1518     // are "disabled". In either case, we need to check for proper alignment
1519     // requirements.
1520     //
1521     if (Size == 64) {
1522       // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
1523       // can do a 4 byte aligned, 8 byte access in a single operation using
1524       // ds_read2/write2_b32 with adjacent offsets.
1525       bool AlignedBy4 = Alignment >= Align(4);
1526       if (IsFast)
1527         *IsFast = AlignedBy4;
1528 
1529       return AlignedBy4;
1530     }
1531     if (Size == 96) {
1532       // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
1533       // gfx8 and older.
1534       bool AlignedBy16 = Alignment >= Align(16);
1535       if (IsFast)
1536         *IsFast = AlignedBy16;
1537 
1538       return AlignedBy16;
1539     }
1540     if (Size == 128) {
1541       // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
1542       // gfx8 and older, but  we can do a 8 byte aligned, 16 byte access in a
1543       // single operation using ds_read2/write2_b64.
1544       bool AlignedBy8 = Alignment >= Align(8);
1545       if (IsFast)
1546         *IsFast = AlignedBy8;
1547 
1548       return AlignedBy8;
1549     }
1550   }
1551 
1552   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1553     bool AlignedBy4 = Alignment >= Align(4);
1554     if (IsFast)
1555       *IsFast = AlignedBy4;
1556 
1557     return AlignedBy4 ||
1558            Subtarget->enableFlatScratch() ||
1559            Subtarget->hasUnalignedScratchAccess();
1560   }
1561 
1562   // FIXME: We have to be conservative here and assume that flat operations
1563   // will access scratch.  If we had access to the IR function, then we
1564   // could determine if any private memory was used in the function.
1565   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1566       !Subtarget->hasUnalignedScratchAccess()) {
1567     bool AlignedBy4 = Alignment >= Align(4);
1568     if (IsFast)
1569       *IsFast = AlignedBy4;
1570 
1571     return AlignedBy4;
1572   }
1573 
1574   if (Subtarget->hasUnalignedBufferAccessEnabled() &&
1575       !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1576         AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1577     // If we have an uniform constant load, it still requires using a slow
1578     // buffer instruction if unaligned.
1579     if (IsFast) {
1580       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1581       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1582       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1583                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1584         Alignment >= Align(4) : Alignment != Align(2);
1585     }
1586 
1587     return true;
1588   }
1589 
1590   // Smaller than dword value must be aligned.
1591   if (Size < 32)
1592     return false;
1593 
1594   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1595   // byte-address are ignored, thus forcing Dword alignment.
1596   // This applies to private, global, and constant memory.
1597   if (IsFast)
1598     *IsFast = true;
1599 
1600   return Size >= 32 && Alignment >= Align(4);
1601 }
1602 
1603 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1604     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1605     bool *IsFast) const {
1606   if (IsFast)
1607     *IsFast = false;
1608 
1609   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1610   // which isn't a simple VT.
1611   // Until MVT is extended to handle this, simply check for the size and
1612   // rely on the condition below: allow accesses if the size is a multiple of 4.
1613   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1614                            VT.getStoreSize() > 16)) {
1615     return false;
1616   }
1617 
1618   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1619                                             Alignment, Flags, IsFast);
1620 }
1621 
1622 EVT SITargetLowering::getOptimalMemOpType(
1623     const MemOp &Op, const AttributeList &FuncAttributes) const {
1624   // FIXME: Should account for address space here.
1625 
1626   // The default fallback uses the private pointer size as a guess for a type to
1627   // use. Make sure we switch these to 64-bit accesses.
1628 
1629   if (Op.size() >= 16 &&
1630       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1631     return MVT::v4i32;
1632 
1633   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1634     return MVT::v2i32;
1635 
1636   // Use the default.
1637   return MVT::Other;
1638 }
1639 
1640 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1641   const MemSDNode *MemNode = cast<MemSDNode>(N);
1642   const Value *Ptr = MemNode->getMemOperand()->getValue();
1643   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1644   return I && I->getMetadata("amdgpu.noclobber");
1645 }
1646 
1647 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1648   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1649          AS == AMDGPUAS::PRIVATE_ADDRESS;
1650 }
1651 
1652 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1653                                            unsigned DestAS) const {
1654   // Flat -> private/local is a simple truncate.
1655   // Flat -> global is no-op
1656   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1657     return true;
1658 
1659   const GCNTargetMachine &TM =
1660       static_cast<const GCNTargetMachine &>(getTargetMachine());
1661   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1662 }
1663 
1664 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1665   const MemSDNode *MemNode = cast<MemSDNode>(N);
1666 
1667   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1668 }
1669 
1670 TargetLoweringBase::LegalizeTypeAction
1671 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1672   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1673       VT.getScalarType().bitsLE(MVT::i16))
1674     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1675   return TargetLoweringBase::getPreferredVectorAction(VT);
1676 }
1677 
1678 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1679                                                          Type *Ty) const {
1680   // FIXME: Could be smarter if called for vector constants.
1681   return true;
1682 }
1683 
1684 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1685   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1686     switch (Op) {
1687     case ISD::LOAD:
1688     case ISD::STORE:
1689 
1690     // These operations are done with 32-bit instructions anyway.
1691     case ISD::AND:
1692     case ISD::OR:
1693     case ISD::XOR:
1694     case ISD::SELECT:
1695       // TODO: Extensions?
1696       return true;
1697     default:
1698       return false;
1699     }
1700   }
1701 
1702   // SimplifySetCC uses this function to determine whether or not it should
1703   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1704   if (VT == MVT::i1 && Op == ISD::SETCC)
1705     return false;
1706 
1707   return TargetLowering::isTypeDesirableForOp(Op, VT);
1708 }
1709 
1710 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1711                                                    const SDLoc &SL,
1712                                                    SDValue Chain,
1713                                                    uint64_t Offset) const {
1714   const DataLayout &DL = DAG.getDataLayout();
1715   MachineFunction &MF = DAG.getMachineFunction();
1716   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1717 
1718   const ArgDescriptor *InputPtrReg;
1719   const TargetRegisterClass *RC;
1720   LLT ArgTy;
1721   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1722 
1723   std::tie(InputPtrReg, RC, ArgTy) =
1724       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1725 
1726   // We may not have the kernarg segment argument if we have no kernel
1727   // arguments.
1728   if (!InputPtrReg)
1729     return DAG.getConstant(0, SL, PtrVT);
1730 
1731   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1732   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1733     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1734 
1735   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1736 }
1737 
1738 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1739                                             const SDLoc &SL) const {
1740   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1741                                                FIRST_IMPLICIT);
1742   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1743 }
1744 
1745 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1746                                          const SDLoc &SL, SDValue Val,
1747                                          bool Signed,
1748                                          const ISD::InputArg *Arg) const {
1749   // First, if it is a widened vector, narrow it.
1750   if (VT.isVector() &&
1751       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1752     EVT NarrowedVT =
1753         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1754                          VT.getVectorNumElements());
1755     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1756                       DAG.getConstant(0, SL, MVT::i32));
1757   }
1758 
1759   // Then convert the vector elements or scalar value.
1760   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1761       VT.bitsLT(MemVT)) {
1762     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1763     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1764   }
1765 
1766   if (MemVT.isFloatingPoint())
1767     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1768   else if (Signed)
1769     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1770   else
1771     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1772 
1773   return Val;
1774 }
1775 
1776 SDValue SITargetLowering::lowerKernargMemParameter(
1777     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1778     uint64_t Offset, Align Alignment, bool Signed,
1779     const ISD::InputArg *Arg) const {
1780   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1781 
1782   // Try to avoid using an extload by loading earlier than the argument address,
1783   // and extracting the relevant bits. The load should hopefully be merged with
1784   // the previous argument.
1785   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1786     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1787     int64_t AlignDownOffset = alignDown(Offset, 4);
1788     int64_t OffsetDiff = Offset - AlignDownOffset;
1789 
1790     EVT IntVT = MemVT.changeTypeToInteger();
1791 
1792     // TODO: If we passed in the base kernel offset we could have a better
1793     // alignment than 4, but we don't really need it.
1794     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1795     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1796                                MachineMemOperand::MODereferenceable |
1797                                    MachineMemOperand::MOInvariant);
1798 
1799     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1800     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1801 
1802     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1803     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1804     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1805 
1806 
1807     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1808   }
1809 
1810   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1811   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1812                              MachineMemOperand::MODereferenceable |
1813                                  MachineMemOperand::MOInvariant);
1814 
1815   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1816   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1817 }
1818 
1819 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1820                                               const SDLoc &SL, SDValue Chain,
1821                                               const ISD::InputArg &Arg) const {
1822   MachineFunction &MF = DAG.getMachineFunction();
1823   MachineFrameInfo &MFI = MF.getFrameInfo();
1824 
1825   if (Arg.Flags.isByVal()) {
1826     unsigned Size = Arg.Flags.getByValSize();
1827     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1828     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1829   }
1830 
1831   unsigned ArgOffset = VA.getLocMemOffset();
1832   unsigned ArgSize = VA.getValVT().getStoreSize();
1833 
1834   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1835 
1836   // Create load nodes to retrieve arguments from the stack.
1837   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1838   SDValue ArgValue;
1839 
1840   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1841   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1842   MVT MemVT = VA.getValVT();
1843 
1844   switch (VA.getLocInfo()) {
1845   default:
1846     break;
1847   case CCValAssign::BCvt:
1848     MemVT = VA.getLocVT();
1849     break;
1850   case CCValAssign::SExt:
1851     ExtType = ISD::SEXTLOAD;
1852     break;
1853   case CCValAssign::ZExt:
1854     ExtType = ISD::ZEXTLOAD;
1855     break;
1856   case CCValAssign::AExt:
1857     ExtType = ISD::EXTLOAD;
1858     break;
1859   }
1860 
1861   ArgValue = DAG.getExtLoad(
1862     ExtType, SL, VA.getLocVT(), Chain, FIN,
1863     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1864     MemVT);
1865   return ArgValue;
1866 }
1867 
1868 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1869   const SIMachineFunctionInfo &MFI,
1870   EVT VT,
1871   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1872   const ArgDescriptor *Reg;
1873   const TargetRegisterClass *RC;
1874   LLT Ty;
1875 
1876   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1877   if (!Reg) {
1878     if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) {
1879       // It's possible for a kernarg intrinsic call to appear in a kernel with
1880       // no allocated segment, in which case we do not add the user sgpr
1881       // argument, so just return null.
1882       return DAG.getConstant(0, SDLoc(), VT);
1883     }
1884 
1885     // It's undefined behavior if a function marked with the amdgpu-no-*
1886     // attributes uses the corresponding intrinsic.
1887     return DAG.getUNDEF(VT);
1888   }
1889 
1890   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1891 }
1892 
1893 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1894                                CallingConv::ID CallConv,
1895                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1896                                FunctionType *FType,
1897                                SIMachineFunctionInfo *Info) {
1898   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1899     const ISD::InputArg *Arg = &Ins[I];
1900 
1901     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1902            "vector type argument should have been split");
1903 
1904     // First check if it's a PS input addr.
1905     if (CallConv == CallingConv::AMDGPU_PS &&
1906         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1907       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1908 
1909       // Inconveniently only the first part of the split is marked as isSplit,
1910       // so skip to the end. We only want to increment PSInputNum once for the
1911       // entire split argument.
1912       if (Arg->Flags.isSplit()) {
1913         while (!Arg->Flags.isSplitEnd()) {
1914           assert((!Arg->VT.isVector() ||
1915                   Arg->VT.getScalarSizeInBits() == 16) &&
1916                  "unexpected vector split in ps argument type");
1917           if (!SkipArg)
1918             Splits.push_back(*Arg);
1919           Arg = &Ins[++I];
1920         }
1921       }
1922 
1923       if (SkipArg) {
1924         // We can safely skip PS inputs.
1925         Skipped.set(Arg->getOrigArgIndex());
1926         ++PSInputNum;
1927         continue;
1928       }
1929 
1930       Info->markPSInputAllocated(PSInputNum);
1931       if (Arg->Used)
1932         Info->markPSInputEnabled(PSInputNum);
1933 
1934       ++PSInputNum;
1935     }
1936 
1937     Splits.push_back(*Arg);
1938   }
1939 }
1940 
1941 // Allocate special inputs passed in VGPRs.
1942 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1943                                                       MachineFunction &MF,
1944                                                       const SIRegisterInfo &TRI,
1945                                                       SIMachineFunctionInfo &Info) const {
1946   const LLT S32 = LLT::scalar(32);
1947   MachineRegisterInfo &MRI = MF.getRegInfo();
1948 
1949   if (Info.hasWorkItemIDX()) {
1950     Register Reg = AMDGPU::VGPR0;
1951     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1952 
1953     CCInfo.AllocateReg(Reg);
1954     unsigned Mask = (Subtarget->hasPackedTID() &&
1955                      Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
1956     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1957   }
1958 
1959   if (Info.hasWorkItemIDY()) {
1960     assert(Info.hasWorkItemIDX());
1961     if (Subtarget->hasPackedTID()) {
1962       Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1963                                                         0x3ff << 10));
1964     } else {
1965       unsigned Reg = AMDGPU::VGPR1;
1966       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1967 
1968       CCInfo.AllocateReg(Reg);
1969       Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1970     }
1971   }
1972 
1973   if (Info.hasWorkItemIDZ()) {
1974     assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
1975     if (Subtarget->hasPackedTID()) {
1976       Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1977                                                         0x3ff << 20));
1978     } else {
1979       unsigned Reg = AMDGPU::VGPR2;
1980       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1981 
1982       CCInfo.AllocateReg(Reg);
1983       Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1984     }
1985   }
1986 }
1987 
1988 // Try to allocate a VGPR at the end of the argument list, or if no argument
1989 // VGPRs are left allocating a stack slot.
1990 // If \p Mask is is given it indicates bitfield position in the register.
1991 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1992 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1993                                          ArgDescriptor Arg = ArgDescriptor()) {
1994   if (Arg.isSet())
1995     return ArgDescriptor::createArg(Arg, Mask);
1996 
1997   ArrayRef<MCPhysReg> ArgVGPRs
1998     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1999   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
2000   if (RegIdx == ArgVGPRs.size()) {
2001     // Spill to stack required.
2002     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
2003 
2004     return ArgDescriptor::createStack(Offset, Mask);
2005   }
2006 
2007   unsigned Reg = ArgVGPRs[RegIdx];
2008   Reg = CCInfo.AllocateReg(Reg);
2009   assert(Reg != AMDGPU::NoRegister);
2010 
2011   MachineFunction &MF = CCInfo.getMachineFunction();
2012   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
2013   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
2014   return ArgDescriptor::createRegister(Reg, Mask);
2015 }
2016 
2017 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
2018                                              const TargetRegisterClass *RC,
2019                                              unsigned NumArgRegs) {
2020   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
2021   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
2022   if (RegIdx == ArgSGPRs.size())
2023     report_fatal_error("ran out of SGPRs for arguments");
2024 
2025   unsigned Reg = ArgSGPRs[RegIdx];
2026   Reg = CCInfo.AllocateReg(Reg);
2027   assert(Reg != AMDGPU::NoRegister);
2028 
2029   MachineFunction &MF = CCInfo.getMachineFunction();
2030   MF.addLiveIn(Reg, RC);
2031   return ArgDescriptor::createRegister(Reg);
2032 }
2033 
2034 // If this has a fixed position, we still should allocate the register in the
2035 // CCInfo state. Technically we could get away with this for values passed
2036 // outside of the normal argument range.
2037 static void allocateFixedSGPRInputImpl(CCState &CCInfo,
2038                                        const TargetRegisterClass *RC,
2039                                        MCRegister Reg) {
2040   Reg = CCInfo.AllocateReg(Reg);
2041   assert(Reg != AMDGPU::NoRegister);
2042   MachineFunction &MF = CCInfo.getMachineFunction();
2043   MF.addLiveIn(Reg, RC);
2044 }
2045 
2046 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
2047   if (Arg) {
2048     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
2049                                Arg.getRegister());
2050   } else
2051     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
2052 }
2053 
2054 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
2055   if (Arg) {
2056     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
2057                                Arg.getRegister());
2058   } else
2059     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
2060 }
2061 
2062 /// Allocate implicit function VGPR arguments at the end of allocated user
2063 /// arguments.
2064 void SITargetLowering::allocateSpecialInputVGPRs(
2065   CCState &CCInfo, MachineFunction &MF,
2066   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2067   const unsigned Mask = 0x3ff;
2068   ArgDescriptor Arg;
2069 
2070   if (Info.hasWorkItemIDX()) {
2071     Arg = allocateVGPR32Input(CCInfo, Mask);
2072     Info.setWorkItemIDX(Arg);
2073   }
2074 
2075   if (Info.hasWorkItemIDY()) {
2076     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
2077     Info.setWorkItemIDY(Arg);
2078   }
2079 
2080   if (Info.hasWorkItemIDZ())
2081     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
2082 }
2083 
2084 /// Allocate implicit function VGPR arguments in fixed registers.
2085 void SITargetLowering::allocateSpecialInputVGPRsFixed(
2086   CCState &CCInfo, MachineFunction &MF,
2087   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2088   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
2089   if (!Reg)
2090     report_fatal_error("failed to allocated VGPR for implicit arguments");
2091 
2092   const unsigned Mask = 0x3ff;
2093   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2094   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
2095   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
2096 }
2097 
2098 void SITargetLowering::allocateSpecialInputSGPRs(
2099   CCState &CCInfo,
2100   MachineFunction &MF,
2101   const SIRegisterInfo &TRI,
2102   SIMachineFunctionInfo &Info) const {
2103   auto &ArgInfo = Info.getArgInfo();
2104 
2105   // TODO: Unify handling with private memory pointers.
2106   if (Info.hasDispatchPtr())
2107     allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
2108 
2109   if (Info.hasQueuePtr())
2110     allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
2111 
2112   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
2113   // constant offset from the kernarg segment.
2114   if (Info.hasImplicitArgPtr())
2115     allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
2116 
2117   if (Info.hasDispatchID())
2118     allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2119 
2120   // flat_scratch_init is not applicable for non-kernel functions.
2121 
2122   if (Info.hasWorkGroupIDX())
2123     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2124 
2125   if (Info.hasWorkGroupIDY())
2126     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2127 
2128   if (Info.hasWorkGroupIDZ())
2129     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2130 }
2131 
2132 // Allocate special inputs passed in user SGPRs.
2133 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2134                                             MachineFunction &MF,
2135                                             const SIRegisterInfo &TRI,
2136                                             SIMachineFunctionInfo &Info) const {
2137   if (Info.hasImplicitBufferPtr()) {
2138     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2139     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2140     CCInfo.AllocateReg(ImplicitBufferPtrReg);
2141   }
2142 
2143   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2144   if (Info.hasPrivateSegmentBuffer()) {
2145     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2146     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2147     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2148   }
2149 
2150   if (Info.hasDispatchPtr()) {
2151     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2152     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2153     CCInfo.AllocateReg(DispatchPtrReg);
2154   }
2155 
2156   if (Info.hasQueuePtr()) {
2157     Register QueuePtrReg = Info.addQueuePtr(TRI);
2158     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2159     CCInfo.AllocateReg(QueuePtrReg);
2160   }
2161 
2162   if (Info.hasKernargSegmentPtr()) {
2163     MachineRegisterInfo &MRI = MF.getRegInfo();
2164     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2165     CCInfo.AllocateReg(InputPtrReg);
2166 
2167     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2168     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2169   }
2170 
2171   if (Info.hasDispatchID()) {
2172     Register DispatchIDReg = Info.addDispatchID(TRI);
2173     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2174     CCInfo.AllocateReg(DispatchIDReg);
2175   }
2176 
2177   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2178     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2179     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2180     CCInfo.AllocateReg(FlatScratchInitReg);
2181   }
2182 
2183   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2184   // these from the dispatch pointer.
2185 }
2186 
2187 // Allocate special input registers that are initialized per-wave.
2188 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2189                                            MachineFunction &MF,
2190                                            SIMachineFunctionInfo &Info,
2191                                            CallingConv::ID CallConv,
2192                                            bool IsShader) const {
2193   if (Info.hasWorkGroupIDX()) {
2194     Register Reg = Info.addWorkGroupIDX();
2195     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2196     CCInfo.AllocateReg(Reg);
2197   }
2198 
2199   if (Info.hasWorkGroupIDY()) {
2200     Register Reg = Info.addWorkGroupIDY();
2201     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2202     CCInfo.AllocateReg(Reg);
2203   }
2204 
2205   if (Info.hasWorkGroupIDZ()) {
2206     Register Reg = Info.addWorkGroupIDZ();
2207     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2208     CCInfo.AllocateReg(Reg);
2209   }
2210 
2211   if (Info.hasWorkGroupInfo()) {
2212     Register Reg = Info.addWorkGroupInfo();
2213     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2214     CCInfo.AllocateReg(Reg);
2215   }
2216 
2217   if (Info.hasPrivateSegmentWaveByteOffset()) {
2218     // Scratch wave offset passed in system SGPR.
2219     unsigned PrivateSegmentWaveByteOffsetReg;
2220 
2221     if (IsShader) {
2222       PrivateSegmentWaveByteOffsetReg =
2223         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2224 
2225       // This is true if the scratch wave byte offset doesn't have a fixed
2226       // location.
2227       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2228         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2229         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2230       }
2231     } else
2232       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2233 
2234     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2235     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2236   }
2237 }
2238 
2239 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2240                                      MachineFunction &MF,
2241                                      const SIRegisterInfo &TRI,
2242                                      SIMachineFunctionInfo &Info) {
2243   // Now that we've figured out where the scratch register inputs are, see if
2244   // should reserve the arguments and use them directly.
2245   MachineFrameInfo &MFI = MF.getFrameInfo();
2246   bool HasStackObjects = MFI.hasStackObjects();
2247   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2248 
2249   // Record that we know we have non-spill stack objects so we don't need to
2250   // check all stack objects later.
2251   if (HasStackObjects)
2252     Info.setHasNonSpillStackObjects(true);
2253 
2254   // Everything live out of a block is spilled with fast regalloc, so it's
2255   // almost certain that spilling will be required.
2256   if (TM.getOptLevel() == CodeGenOpt::None)
2257     HasStackObjects = true;
2258 
2259   // For now assume stack access is needed in any callee functions, so we need
2260   // the scratch registers to pass in.
2261   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2262 
2263   if (!ST.enableFlatScratch()) {
2264     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2265       // If we have stack objects, we unquestionably need the private buffer
2266       // resource. For the Code Object V2 ABI, this will be the first 4 user
2267       // SGPR inputs. We can reserve those and use them directly.
2268 
2269       Register PrivateSegmentBufferReg =
2270           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2271       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2272     } else {
2273       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2274       // We tentatively reserve the last registers (skipping the last registers
2275       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2276       // we'll replace these with the ones immediately after those which were
2277       // really allocated. In the prologue copies will be inserted from the
2278       // argument to these reserved registers.
2279 
2280       // Without HSA, relocations are used for the scratch pointer and the
2281       // buffer resource setup is always inserted in the prologue. Scratch wave
2282       // offset is still in an input SGPR.
2283       Info.setScratchRSrcReg(ReservedBufferReg);
2284     }
2285   }
2286 
2287   MachineRegisterInfo &MRI = MF.getRegInfo();
2288 
2289   // For entry functions we have to set up the stack pointer if we use it,
2290   // whereas non-entry functions get this "for free". This means there is no
2291   // intrinsic advantage to using S32 over S34 in cases where we do not have
2292   // calls but do need a frame pointer (i.e. if we are requested to have one
2293   // because frame pointer elimination is disabled). To keep things simple we
2294   // only ever use S32 as the call ABI stack pointer, and so using it does not
2295   // imply we need a separate frame pointer.
2296   //
2297   // Try to use s32 as the SP, but move it if it would interfere with input
2298   // arguments. This won't work with calls though.
2299   //
2300   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2301   // registers.
2302   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2303     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2304   } else {
2305     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2306 
2307     if (MFI.hasCalls())
2308       report_fatal_error("call in graphics shader with too many input SGPRs");
2309 
2310     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2311       if (!MRI.isLiveIn(Reg)) {
2312         Info.setStackPtrOffsetReg(Reg);
2313         break;
2314       }
2315     }
2316 
2317     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2318       report_fatal_error("failed to find register for SP");
2319   }
2320 
2321   // hasFP should be accurate for entry functions even before the frame is
2322   // finalized, because it does not rely on the known stack size, only
2323   // properties like whether variable sized objects are present.
2324   if (ST.getFrameLowering()->hasFP(MF)) {
2325     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2326   }
2327 }
2328 
2329 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2330   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2331   return !Info->isEntryFunction();
2332 }
2333 
2334 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2335 
2336 }
2337 
2338 void SITargetLowering::insertCopiesSplitCSR(
2339   MachineBasicBlock *Entry,
2340   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2341   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2342 
2343   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2344   if (!IStart)
2345     return;
2346 
2347   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2348   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2349   MachineBasicBlock::iterator MBBI = Entry->begin();
2350   for (const MCPhysReg *I = IStart; *I; ++I) {
2351     const TargetRegisterClass *RC = nullptr;
2352     if (AMDGPU::SReg_64RegClass.contains(*I))
2353       RC = &AMDGPU::SGPR_64RegClass;
2354     else if (AMDGPU::SReg_32RegClass.contains(*I))
2355       RC = &AMDGPU::SGPR_32RegClass;
2356     else
2357       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2358 
2359     Register NewVR = MRI->createVirtualRegister(RC);
2360     // Create copy from CSR to a virtual register.
2361     Entry->addLiveIn(*I);
2362     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2363       .addReg(*I);
2364 
2365     // Insert the copy-back instructions right before the terminator.
2366     for (auto *Exit : Exits)
2367       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2368               TII->get(TargetOpcode::COPY), *I)
2369         .addReg(NewVR);
2370   }
2371 }
2372 
2373 SDValue SITargetLowering::LowerFormalArguments(
2374     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2375     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2376     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2377   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2378 
2379   MachineFunction &MF = DAG.getMachineFunction();
2380   const Function &Fn = MF.getFunction();
2381   FunctionType *FType = MF.getFunction().getFunctionType();
2382   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2383 
2384   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2385     DiagnosticInfoUnsupported NoGraphicsHSA(
2386         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2387     DAG.getContext()->diagnose(NoGraphicsHSA);
2388     return DAG.getEntryNode();
2389   }
2390 
2391   Info->allocateModuleLDSGlobal(Fn.getParent());
2392 
2393   SmallVector<ISD::InputArg, 16> Splits;
2394   SmallVector<CCValAssign, 16> ArgLocs;
2395   BitVector Skipped(Ins.size());
2396   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2397                  *DAG.getContext());
2398 
2399   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2400   bool IsKernel = AMDGPU::isKernel(CallConv);
2401   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2402 
2403   if (IsGraphics) {
2404     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2405            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2406            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2407            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2408            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2409            !Info->hasWorkItemIDZ());
2410   }
2411 
2412   if (CallConv == CallingConv::AMDGPU_PS) {
2413     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2414 
2415     // At least one interpolation mode must be enabled or else the GPU will
2416     // hang.
2417     //
2418     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2419     // set PSInputAddr, the user wants to enable some bits after the compilation
2420     // based on run-time states. Since we can't know what the final PSInputEna
2421     // will look like, so we shouldn't do anything here and the user should take
2422     // responsibility for the correct programming.
2423     //
2424     // Otherwise, the following restrictions apply:
2425     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2426     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2427     //   enabled too.
2428     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2429         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2430       CCInfo.AllocateReg(AMDGPU::VGPR0);
2431       CCInfo.AllocateReg(AMDGPU::VGPR1);
2432       Info->markPSInputAllocated(0);
2433       Info->markPSInputEnabled(0);
2434     }
2435     if (Subtarget->isAmdPalOS()) {
2436       // For isAmdPalOS, the user does not enable some bits after compilation
2437       // based on run-time states; the register values being generated here are
2438       // the final ones set in hardware. Therefore we need to apply the
2439       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2440       // a bit is set in PSInputAddr but not PSInputEnable is where the
2441       // frontend set up an input arg for a particular interpolation mode, but
2442       // nothing uses that input arg. Really we should have an earlier pass
2443       // that removes such an arg.)
2444       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2445       if ((PsInputBits & 0x7F) == 0 ||
2446           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2447         Info->markPSInputEnabled(
2448             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2449     }
2450   } else if (IsKernel) {
2451     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2452   } else {
2453     Splits.append(Ins.begin(), Ins.end());
2454   }
2455 
2456   if (IsEntryFunc) {
2457     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2458     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2459   } else if (!IsGraphics) {
2460     // For the fixed ABI, pass workitem IDs in the last argument register.
2461     allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2462   }
2463 
2464   if (IsKernel) {
2465     analyzeFormalArgumentsCompute(CCInfo, Ins);
2466   } else {
2467     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2468     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2469   }
2470 
2471   SmallVector<SDValue, 16> Chains;
2472 
2473   // FIXME: This is the minimum kernel argument alignment. We should improve
2474   // this to the maximum alignment of the arguments.
2475   //
2476   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2477   // kern arg offset.
2478   const Align KernelArgBaseAlign = Align(16);
2479 
2480   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2481     const ISD::InputArg &Arg = Ins[i];
2482     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2483       InVals.push_back(DAG.getUNDEF(Arg.VT));
2484       continue;
2485     }
2486 
2487     CCValAssign &VA = ArgLocs[ArgIdx++];
2488     MVT VT = VA.getLocVT();
2489 
2490     if (IsEntryFunc && VA.isMemLoc()) {
2491       VT = Ins[i].VT;
2492       EVT MemVT = VA.getLocVT();
2493 
2494       const uint64_t Offset = VA.getLocMemOffset();
2495       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2496 
2497       if (Arg.Flags.isByRef()) {
2498         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2499 
2500         const GCNTargetMachine &TM =
2501             static_cast<const GCNTargetMachine &>(getTargetMachine());
2502         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2503                                     Arg.Flags.getPointerAddrSpace())) {
2504           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2505                                      Arg.Flags.getPointerAddrSpace());
2506         }
2507 
2508         InVals.push_back(Ptr);
2509         continue;
2510       }
2511 
2512       SDValue Arg = lowerKernargMemParameter(
2513         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2514       Chains.push_back(Arg.getValue(1));
2515 
2516       auto *ParamTy =
2517         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2518       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2519           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2520                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2521         // On SI local pointers are just offsets into LDS, so they are always
2522         // less than 16-bits.  On CI and newer they could potentially be
2523         // real pointers, so we can't guarantee their size.
2524         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2525                           DAG.getValueType(MVT::i16));
2526       }
2527 
2528       InVals.push_back(Arg);
2529       continue;
2530     } else if (!IsEntryFunc && VA.isMemLoc()) {
2531       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2532       InVals.push_back(Val);
2533       if (!Arg.Flags.isByVal())
2534         Chains.push_back(Val.getValue(1));
2535       continue;
2536     }
2537 
2538     assert(VA.isRegLoc() && "Parameter must be in a register!");
2539 
2540     Register Reg = VA.getLocReg();
2541     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2542     EVT ValVT = VA.getValVT();
2543 
2544     Reg = MF.addLiveIn(Reg, RC);
2545     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2546 
2547     if (Arg.Flags.isSRet()) {
2548       // The return object should be reasonably addressable.
2549 
2550       // FIXME: This helps when the return is a real sret. If it is a
2551       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2552       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2553       unsigned NumBits
2554         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2555       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2556         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2557     }
2558 
2559     // If this is an 8 or 16-bit value, it is really passed promoted
2560     // to 32 bits. Insert an assert[sz]ext to capture this, then
2561     // truncate to the right size.
2562     switch (VA.getLocInfo()) {
2563     case CCValAssign::Full:
2564       break;
2565     case CCValAssign::BCvt:
2566       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2567       break;
2568     case CCValAssign::SExt:
2569       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2570                         DAG.getValueType(ValVT));
2571       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2572       break;
2573     case CCValAssign::ZExt:
2574       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2575                         DAG.getValueType(ValVT));
2576       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2577       break;
2578     case CCValAssign::AExt:
2579       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2580       break;
2581     default:
2582       llvm_unreachable("Unknown loc info!");
2583     }
2584 
2585     InVals.push_back(Val);
2586   }
2587 
2588   // Start adding system SGPRs.
2589   if (IsEntryFunc) {
2590     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2591   } else {
2592     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2593     if (!IsGraphics)
2594       allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2595   }
2596 
2597   auto &ArgUsageInfo =
2598     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2599   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2600 
2601   unsigned StackArgSize = CCInfo.getNextStackOffset();
2602   Info->setBytesInStackArgArea(StackArgSize);
2603 
2604   return Chains.empty() ? Chain :
2605     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2606 }
2607 
2608 // TODO: If return values can't fit in registers, we should return as many as
2609 // possible in registers before passing on stack.
2610 bool SITargetLowering::CanLowerReturn(
2611   CallingConv::ID CallConv,
2612   MachineFunction &MF, bool IsVarArg,
2613   const SmallVectorImpl<ISD::OutputArg> &Outs,
2614   LLVMContext &Context) const {
2615   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2616   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2617   // for shaders. Vector types should be explicitly handled by CC.
2618   if (AMDGPU::isEntryFunctionCC(CallConv))
2619     return true;
2620 
2621   SmallVector<CCValAssign, 16> RVLocs;
2622   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2623   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2624 }
2625 
2626 SDValue
2627 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2628                               bool isVarArg,
2629                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2630                               const SmallVectorImpl<SDValue> &OutVals,
2631                               const SDLoc &DL, SelectionDAG &DAG) const {
2632   MachineFunction &MF = DAG.getMachineFunction();
2633   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2634 
2635   if (AMDGPU::isKernel(CallConv)) {
2636     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2637                                              OutVals, DL, DAG);
2638   }
2639 
2640   bool IsShader = AMDGPU::isShader(CallConv);
2641 
2642   Info->setIfReturnsVoid(Outs.empty());
2643   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2644 
2645   // CCValAssign - represent the assignment of the return value to a location.
2646   SmallVector<CCValAssign, 48> RVLocs;
2647   SmallVector<ISD::OutputArg, 48> Splits;
2648 
2649   // CCState - Info about the registers and stack slots.
2650   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2651                  *DAG.getContext());
2652 
2653   // Analyze outgoing return values.
2654   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2655 
2656   SDValue Flag;
2657   SmallVector<SDValue, 48> RetOps;
2658   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2659 
2660   // Add return address for callable functions.
2661   if (!Info->isEntryFunction()) {
2662     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2663     SDValue ReturnAddrReg = CreateLiveInRegister(
2664       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2665 
2666     SDValue ReturnAddrVirtualReg =
2667         DAG.getRegister(MF.getRegInfo().createVirtualRegister(
2668                             CallConv != CallingConv::AMDGPU_Gfx
2669                                 ? &AMDGPU::CCR_SGPR_64RegClass
2670                                 : &AMDGPU::Gfx_CCR_SGPR_64RegClass),
2671                         MVT::i64);
2672     Chain =
2673         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2674     Flag = Chain.getValue(1);
2675     RetOps.push_back(ReturnAddrVirtualReg);
2676   }
2677 
2678   // Copy the result values into the output registers.
2679   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2680        ++I, ++RealRVLocIdx) {
2681     CCValAssign &VA = RVLocs[I];
2682     assert(VA.isRegLoc() && "Can only return in registers!");
2683     // TODO: Partially return in registers if return values don't fit.
2684     SDValue Arg = OutVals[RealRVLocIdx];
2685 
2686     // Copied from other backends.
2687     switch (VA.getLocInfo()) {
2688     case CCValAssign::Full:
2689       break;
2690     case CCValAssign::BCvt:
2691       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2692       break;
2693     case CCValAssign::SExt:
2694       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2695       break;
2696     case CCValAssign::ZExt:
2697       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2698       break;
2699     case CCValAssign::AExt:
2700       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2701       break;
2702     default:
2703       llvm_unreachable("Unknown loc info!");
2704     }
2705 
2706     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2707     Flag = Chain.getValue(1);
2708     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2709   }
2710 
2711   // FIXME: Does sret work properly?
2712   if (!Info->isEntryFunction()) {
2713     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2714     const MCPhysReg *I =
2715       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2716     if (I) {
2717       for (; *I; ++I) {
2718         if (AMDGPU::SReg_64RegClass.contains(*I))
2719           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2720         else if (AMDGPU::SReg_32RegClass.contains(*I))
2721           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2722         else
2723           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2724       }
2725     }
2726   }
2727 
2728   // Update chain and glue.
2729   RetOps[0] = Chain;
2730   if (Flag.getNode())
2731     RetOps.push_back(Flag);
2732 
2733   unsigned Opc = AMDGPUISD::ENDPGM;
2734   if (!IsWaveEnd) {
2735     if (IsShader)
2736       Opc = AMDGPUISD::RETURN_TO_EPILOG;
2737     else if (CallConv == CallingConv::AMDGPU_Gfx)
2738       Opc = AMDGPUISD::RET_GFX_FLAG;
2739     else
2740       Opc = AMDGPUISD::RET_FLAG;
2741   }
2742 
2743   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2744 }
2745 
2746 SDValue SITargetLowering::LowerCallResult(
2747     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2748     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2749     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2750     SDValue ThisVal) const {
2751   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2752 
2753   // Assign locations to each value returned by this call.
2754   SmallVector<CCValAssign, 16> RVLocs;
2755   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2756                  *DAG.getContext());
2757   CCInfo.AnalyzeCallResult(Ins, RetCC);
2758 
2759   // Copy all of the result registers out of their specified physreg.
2760   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2761     CCValAssign VA = RVLocs[i];
2762     SDValue Val;
2763 
2764     if (VA.isRegLoc()) {
2765       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2766       Chain = Val.getValue(1);
2767       InFlag = Val.getValue(2);
2768     } else if (VA.isMemLoc()) {
2769       report_fatal_error("TODO: return values in memory");
2770     } else
2771       llvm_unreachable("unknown argument location type");
2772 
2773     switch (VA.getLocInfo()) {
2774     case CCValAssign::Full:
2775       break;
2776     case CCValAssign::BCvt:
2777       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2778       break;
2779     case CCValAssign::ZExt:
2780       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2781                         DAG.getValueType(VA.getValVT()));
2782       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2783       break;
2784     case CCValAssign::SExt:
2785       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2786                         DAG.getValueType(VA.getValVT()));
2787       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2788       break;
2789     case CCValAssign::AExt:
2790       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2791       break;
2792     default:
2793       llvm_unreachable("Unknown loc info!");
2794     }
2795 
2796     InVals.push_back(Val);
2797   }
2798 
2799   return Chain;
2800 }
2801 
2802 // Add code to pass special inputs required depending on used features separate
2803 // from the explicit user arguments present in the IR.
2804 void SITargetLowering::passSpecialInputs(
2805     CallLoweringInfo &CLI,
2806     CCState &CCInfo,
2807     const SIMachineFunctionInfo &Info,
2808     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2809     SmallVectorImpl<SDValue> &MemOpChains,
2810     SDValue Chain) const {
2811   // If we don't have a call site, this was a call inserted by
2812   // legalization. These can never use special inputs.
2813   if (!CLI.CB)
2814     return;
2815 
2816   SelectionDAG &DAG = CLI.DAG;
2817   const SDLoc &DL = CLI.DL;
2818   const Function &F = DAG.getMachineFunction().getFunction();
2819 
2820   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2821   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2822 
2823   const AMDGPUFunctionArgInfo *CalleeArgInfo
2824     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2825   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2826     auto &ArgUsageInfo =
2827       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2828     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2829   }
2830 
2831   // TODO: Unify with private memory register handling. This is complicated by
2832   // the fact that at least in kernels, the input argument is not necessarily
2833   // in the same location as the input.
2834   static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
2835                              StringLiteral> ImplicitAttrs[] = {
2836     {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"},
2837     {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" },
2838     {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"},
2839     {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"},
2840     {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"},
2841     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"},
2842     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"}
2843   };
2844 
2845   for (auto Attr : ImplicitAttrs) {
2846     const ArgDescriptor *OutgoingArg;
2847     const TargetRegisterClass *ArgRC;
2848     LLT ArgTy;
2849 
2850     AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first;
2851 
2852     // If the callee does not use the attribute value, skip copying the value.
2853     if (CLI.CB->hasFnAttr(Attr.second))
2854       continue;
2855 
2856     std::tie(OutgoingArg, ArgRC, ArgTy) =
2857         CalleeArgInfo->getPreloadedValue(InputID);
2858     if (!OutgoingArg)
2859       continue;
2860 
2861     const ArgDescriptor *IncomingArg;
2862     const TargetRegisterClass *IncomingArgRC;
2863     LLT Ty;
2864     std::tie(IncomingArg, IncomingArgRC, Ty) =
2865         CallerArgInfo.getPreloadedValue(InputID);
2866     assert(IncomingArgRC == ArgRC);
2867 
2868     // All special arguments are ints for now.
2869     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2870     SDValue InputReg;
2871 
2872     if (IncomingArg) {
2873       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2874     } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
2875       // The implicit arg ptr is special because it doesn't have a corresponding
2876       // input for kernels, and is computed from the kernarg segment pointer.
2877       InputReg = getImplicitArgPtr(DAG, DL);
2878     } else {
2879       // We may have proven the input wasn't needed, although the ABI is
2880       // requiring it. We just need to allocate the register appropriately.
2881       InputReg = DAG.getUNDEF(ArgVT);
2882     }
2883 
2884     if (OutgoingArg->isRegister()) {
2885       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2886       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2887         report_fatal_error("failed to allocate implicit input argument");
2888     } else {
2889       unsigned SpecialArgOffset =
2890           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2891       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2892                                               SpecialArgOffset);
2893       MemOpChains.push_back(ArgStore);
2894     }
2895   }
2896 
2897   // Pack workitem IDs into a single register or pass it as is if already
2898   // packed.
2899   const ArgDescriptor *OutgoingArg;
2900   const TargetRegisterClass *ArgRC;
2901   LLT Ty;
2902 
2903   std::tie(OutgoingArg, ArgRC, Ty) =
2904       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2905   if (!OutgoingArg)
2906     std::tie(OutgoingArg, ArgRC, Ty) =
2907         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2908   if (!OutgoingArg)
2909     std::tie(OutgoingArg, ArgRC, Ty) =
2910         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2911   if (!OutgoingArg)
2912     return;
2913 
2914   const ArgDescriptor *IncomingArgX = std::get<0>(
2915       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2916   const ArgDescriptor *IncomingArgY = std::get<0>(
2917       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2918   const ArgDescriptor *IncomingArgZ = std::get<0>(
2919       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2920 
2921   SDValue InputReg;
2922   SDLoc SL;
2923 
2924   const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
2925   const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
2926   const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
2927 
2928   // If incoming ids are not packed we need to pack them.
2929   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
2930       NeedWorkItemIDX) {
2931     if (Subtarget->getMaxWorkitemID(F, 0) != 0) {
2932       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2933     } else {
2934       InputReg = DAG.getConstant(0, DL, MVT::i32);
2935     }
2936   }
2937 
2938   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
2939       NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) {
2940     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2941     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2942                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2943     InputReg = InputReg.getNode() ?
2944                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2945   }
2946 
2947   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
2948       NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) {
2949     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2950     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2951                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2952     InputReg = InputReg.getNode() ?
2953                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2954   }
2955 
2956   if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
2957     if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) {
2958       // We're in a situation where the outgoing function requires the workitem
2959       // ID, but the calling function does not have it (e.g a graphics function
2960       // calling a C calling convention function). This is illegal, but we need
2961       // to produce something.
2962       InputReg = DAG.getUNDEF(MVT::i32);
2963     } else {
2964       // Workitem ids are already packed, any of present incoming arguments
2965       // will carry all required fields.
2966       ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2967         IncomingArgX ? *IncomingArgX :
2968         IncomingArgY ? *IncomingArgY :
2969         *IncomingArgZ, ~0u);
2970       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2971     }
2972   }
2973 
2974   if (OutgoingArg->isRegister()) {
2975     if (InputReg)
2976       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2977 
2978     CCInfo.AllocateReg(OutgoingArg->getRegister());
2979   } else {
2980     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2981     if (InputReg) {
2982       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2983                                               SpecialArgOffset);
2984       MemOpChains.push_back(ArgStore);
2985     }
2986   }
2987 }
2988 
2989 static bool canGuaranteeTCO(CallingConv::ID CC) {
2990   return CC == CallingConv::Fast;
2991 }
2992 
2993 /// Return true if we might ever do TCO for calls with this calling convention.
2994 static bool mayTailCallThisCC(CallingConv::ID CC) {
2995   switch (CC) {
2996   case CallingConv::C:
2997   case CallingConv::AMDGPU_Gfx:
2998     return true;
2999   default:
3000     return canGuaranteeTCO(CC);
3001   }
3002 }
3003 
3004 bool SITargetLowering::isEligibleForTailCallOptimization(
3005     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
3006     const SmallVectorImpl<ISD::OutputArg> &Outs,
3007     const SmallVectorImpl<SDValue> &OutVals,
3008     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3009   if (!mayTailCallThisCC(CalleeCC))
3010     return false;
3011 
3012   // For a divergent call target, we need to do a waterfall loop over the
3013   // possible callees which precludes us from using a simple jump.
3014   if (Callee->isDivergent())
3015     return false;
3016 
3017   MachineFunction &MF = DAG.getMachineFunction();
3018   const Function &CallerF = MF.getFunction();
3019   CallingConv::ID CallerCC = CallerF.getCallingConv();
3020   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3021   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3022 
3023   // Kernels aren't callable, and don't have a live in return address so it
3024   // doesn't make sense to do a tail call with entry functions.
3025   if (!CallerPreserved)
3026     return false;
3027 
3028   bool CCMatch = CallerCC == CalleeCC;
3029 
3030   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3031     if (canGuaranteeTCO(CalleeCC) && CCMatch)
3032       return true;
3033     return false;
3034   }
3035 
3036   // TODO: Can we handle var args?
3037   if (IsVarArg)
3038     return false;
3039 
3040   for (const Argument &Arg : CallerF.args()) {
3041     if (Arg.hasByValAttr())
3042       return false;
3043   }
3044 
3045   LLVMContext &Ctx = *DAG.getContext();
3046 
3047   // Check that the call results are passed in the same way.
3048   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
3049                                   CCAssignFnForCall(CalleeCC, IsVarArg),
3050                                   CCAssignFnForCall(CallerCC, IsVarArg)))
3051     return false;
3052 
3053   // The callee has to preserve all registers the caller needs to preserve.
3054   if (!CCMatch) {
3055     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3056     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3057       return false;
3058   }
3059 
3060   // Nothing more to check if the callee is taking no arguments.
3061   if (Outs.empty())
3062     return true;
3063 
3064   SmallVector<CCValAssign, 16> ArgLocs;
3065   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
3066 
3067   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
3068 
3069   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
3070   // If the stack arguments for this call do not fit into our own save area then
3071   // the call cannot be made tail.
3072   // TODO: Is this really necessary?
3073   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3074     return false;
3075 
3076   const MachineRegisterInfo &MRI = MF.getRegInfo();
3077   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
3078 }
3079 
3080 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3081   if (!CI->isTailCall())
3082     return false;
3083 
3084   const Function *ParentFn = CI->getParent()->getParent();
3085   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
3086     return false;
3087   return true;
3088 }
3089 
3090 // The wave scratch offset register is used as the global base pointer.
3091 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
3092                                     SmallVectorImpl<SDValue> &InVals) const {
3093   SelectionDAG &DAG = CLI.DAG;
3094   const SDLoc &DL = CLI.DL;
3095   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3096   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3097   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3098   SDValue Chain = CLI.Chain;
3099   SDValue Callee = CLI.Callee;
3100   bool &IsTailCall = CLI.IsTailCall;
3101   CallingConv::ID CallConv = CLI.CallConv;
3102   bool IsVarArg = CLI.IsVarArg;
3103   bool IsSibCall = false;
3104   bool IsThisReturn = false;
3105   MachineFunction &MF = DAG.getMachineFunction();
3106 
3107   if (Callee.isUndef() || isNullConstant(Callee)) {
3108     if (!CLI.IsTailCall) {
3109       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
3110         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
3111     }
3112 
3113     return Chain;
3114   }
3115 
3116   if (IsVarArg) {
3117     return lowerUnhandledCall(CLI, InVals,
3118                               "unsupported call to variadic function ");
3119   }
3120 
3121   if (!CLI.CB)
3122     report_fatal_error("unsupported libcall legalization");
3123 
3124   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
3125     return lowerUnhandledCall(CLI, InVals,
3126                               "unsupported required tail call to function ");
3127   }
3128 
3129   if (AMDGPU::isShader(CallConv)) {
3130     // Note the issue is with the CC of the called function, not of the call
3131     // itself.
3132     return lowerUnhandledCall(CLI, InVals,
3133                               "unsupported call to a shader function ");
3134   }
3135 
3136   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
3137       CallConv != CallingConv::AMDGPU_Gfx) {
3138     // Only allow calls with specific calling conventions.
3139     return lowerUnhandledCall(CLI, InVals,
3140                               "unsupported calling convention for call from "
3141                               "graphics shader of function ");
3142   }
3143 
3144   if (IsTailCall) {
3145     IsTailCall = isEligibleForTailCallOptimization(
3146       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3147     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
3148       report_fatal_error("failed to perform tail call elimination on a call "
3149                          "site marked musttail");
3150     }
3151 
3152     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3153 
3154     // A sibling call is one where we're under the usual C ABI and not planning
3155     // to change that but can still do a tail call:
3156     if (!TailCallOpt && IsTailCall)
3157       IsSibCall = true;
3158 
3159     if (IsTailCall)
3160       ++NumTailCalls;
3161   }
3162 
3163   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3164   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3165   SmallVector<SDValue, 8> MemOpChains;
3166 
3167   // Analyze operands of the call, assigning locations to each operand.
3168   SmallVector<CCValAssign, 16> ArgLocs;
3169   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3170   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3171 
3172   if (CallConv != CallingConv::AMDGPU_Gfx) {
3173     // With a fixed ABI, allocate fixed registers before user arguments.
3174     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3175   }
3176 
3177   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3178 
3179   // Get a count of how many bytes are to be pushed on the stack.
3180   unsigned NumBytes = CCInfo.getNextStackOffset();
3181 
3182   if (IsSibCall) {
3183     // Since we're not changing the ABI to make this a tail call, the memory
3184     // operands are already available in the caller's incoming argument space.
3185     NumBytes = 0;
3186   }
3187 
3188   // FPDiff is the byte offset of the call's argument area from the callee's.
3189   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3190   // by this amount for a tail call. In a sibling call it must be 0 because the
3191   // caller will deallocate the entire stack and the callee still expects its
3192   // arguments to begin at SP+0. Completely unused for non-tail calls.
3193   int32_t FPDiff = 0;
3194   MachineFrameInfo &MFI = MF.getFrameInfo();
3195 
3196   // Adjust the stack pointer for the new arguments...
3197   // These operations are automatically eliminated by the prolog/epilog pass
3198   if (!IsSibCall) {
3199     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3200 
3201     if (!Subtarget->enableFlatScratch()) {
3202       SmallVector<SDValue, 4> CopyFromChains;
3203 
3204       // In the HSA case, this should be an identity copy.
3205       SDValue ScratchRSrcReg
3206         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3207       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3208       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3209       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3210     }
3211   }
3212 
3213   MVT PtrVT = MVT::i32;
3214 
3215   // Walk the register/memloc assignments, inserting copies/loads.
3216   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3217     CCValAssign &VA = ArgLocs[i];
3218     SDValue Arg = OutVals[i];
3219 
3220     // Promote the value if needed.
3221     switch (VA.getLocInfo()) {
3222     case CCValAssign::Full:
3223       break;
3224     case CCValAssign::BCvt:
3225       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3226       break;
3227     case CCValAssign::ZExt:
3228       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3229       break;
3230     case CCValAssign::SExt:
3231       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3232       break;
3233     case CCValAssign::AExt:
3234       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3235       break;
3236     case CCValAssign::FPExt:
3237       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3238       break;
3239     default:
3240       llvm_unreachable("Unknown loc info!");
3241     }
3242 
3243     if (VA.isRegLoc()) {
3244       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3245     } else {
3246       assert(VA.isMemLoc());
3247 
3248       SDValue DstAddr;
3249       MachinePointerInfo DstInfo;
3250 
3251       unsigned LocMemOffset = VA.getLocMemOffset();
3252       int32_t Offset = LocMemOffset;
3253 
3254       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3255       MaybeAlign Alignment;
3256 
3257       if (IsTailCall) {
3258         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3259         unsigned OpSize = Flags.isByVal() ?
3260           Flags.getByValSize() : VA.getValVT().getStoreSize();
3261 
3262         // FIXME: We can have better than the minimum byval required alignment.
3263         Alignment =
3264             Flags.isByVal()
3265                 ? Flags.getNonZeroByValAlign()
3266                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3267 
3268         Offset = Offset + FPDiff;
3269         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3270 
3271         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3272         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3273 
3274         // Make sure any stack arguments overlapping with where we're storing
3275         // are loaded before this eventual operation. Otherwise they'll be
3276         // clobbered.
3277 
3278         // FIXME: Why is this really necessary? This seems to just result in a
3279         // lot of code to copy the stack and write them back to the same
3280         // locations, which are supposed to be immutable?
3281         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3282       } else {
3283         // Stores to the argument stack area are relative to the stack pointer.
3284         SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3285                                         MVT::i32);
3286         DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3287         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3288         Alignment =
3289             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3290       }
3291 
3292       if (Outs[i].Flags.isByVal()) {
3293         SDValue SizeNode =
3294             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3295         SDValue Cpy =
3296             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3297                           Outs[i].Flags.getNonZeroByValAlign(),
3298                           /*isVol = */ false, /*AlwaysInline = */ true,
3299                           /*isTailCall = */ false, DstInfo,
3300                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3301 
3302         MemOpChains.push_back(Cpy);
3303       } else {
3304         SDValue Store =
3305             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3306         MemOpChains.push_back(Store);
3307       }
3308     }
3309   }
3310 
3311   if (!MemOpChains.empty())
3312     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3313 
3314   // Build a sequence of copy-to-reg nodes chained together with token chain
3315   // and flag operands which copy the outgoing args into the appropriate regs.
3316   SDValue InFlag;
3317   for (auto &RegToPass : RegsToPass) {
3318     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3319                              RegToPass.second, InFlag);
3320     InFlag = Chain.getValue(1);
3321   }
3322 
3323 
3324   SDValue PhysReturnAddrReg;
3325   if (IsTailCall) {
3326     // Since the return is being combined with the call, we need to pass on the
3327     // return address.
3328 
3329     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3330     SDValue ReturnAddrReg = CreateLiveInRegister(
3331       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3332 
3333     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3334                                         MVT::i64);
3335     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3336     InFlag = Chain.getValue(1);
3337   }
3338 
3339   // We don't usually want to end the call-sequence here because we would tidy
3340   // the frame up *after* the call, however in the ABI-changing tail-call case
3341   // we've carefully laid out the parameters so that when sp is reset they'll be
3342   // in the correct location.
3343   if (IsTailCall && !IsSibCall) {
3344     Chain = DAG.getCALLSEQ_END(Chain,
3345                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3346                                DAG.getTargetConstant(0, DL, MVT::i32),
3347                                InFlag, DL);
3348     InFlag = Chain.getValue(1);
3349   }
3350 
3351   std::vector<SDValue> Ops;
3352   Ops.push_back(Chain);
3353   Ops.push_back(Callee);
3354   // Add a redundant copy of the callee global which will not be legalized, as
3355   // we need direct access to the callee later.
3356   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3357     const GlobalValue *GV = GSD->getGlobal();
3358     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3359   } else {
3360     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3361   }
3362 
3363   if (IsTailCall) {
3364     // Each tail call may have to adjust the stack by a different amount, so
3365     // this information must travel along with the operation for eventual
3366     // consumption by emitEpilogue.
3367     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3368 
3369     Ops.push_back(PhysReturnAddrReg);
3370   }
3371 
3372   // Add argument registers to the end of the list so that they are known live
3373   // into the call.
3374   for (auto &RegToPass : RegsToPass) {
3375     Ops.push_back(DAG.getRegister(RegToPass.first,
3376                                   RegToPass.second.getValueType()));
3377   }
3378 
3379   // Add a register mask operand representing the call-preserved registers.
3380 
3381   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3382   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3383   assert(Mask && "Missing call preserved mask for calling convention");
3384   Ops.push_back(DAG.getRegisterMask(Mask));
3385 
3386   if (InFlag.getNode())
3387     Ops.push_back(InFlag);
3388 
3389   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3390 
3391   // If we're doing a tall call, use a TC_RETURN here rather than an
3392   // actual call instruction.
3393   if (IsTailCall) {
3394     MFI.setHasTailCall();
3395     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3396   }
3397 
3398   // Returns a chain and a flag for retval copy to use.
3399   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3400   Chain = Call.getValue(0);
3401   InFlag = Call.getValue(1);
3402 
3403   uint64_t CalleePopBytes = NumBytes;
3404   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3405                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3406                              InFlag, DL);
3407   if (!Ins.empty())
3408     InFlag = Chain.getValue(1);
3409 
3410   // Handle result values, copying them out of physregs into vregs that we
3411   // return.
3412   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3413                          InVals, IsThisReturn,
3414                          IsThisReturn ? OutVals[0] : SDValue());
3415 }
3416 
3417 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3418 // except for applying the wave size scale to the increment amount.
3419 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3420     SDValue Op, SelectionDAG &DAG) const {
3421   const MachineFunction &MF = DAG.getMachineFunction();
3422   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3423 
3424   SDLoc dl(Op);
3425   EVT VT = Op.getValueType();
3426   SDValue Tmp1 = Op;
3427   SDValue Tmp2 = Op.getValue(1);
3428   SDValue Tmp3 = Op.getOperand(2);
3429   SDValue Chain = Tmp1.getOperand(0);
3430 
3431   Register SPReg = Info->getStackPtrOffsetReg();
3432 
3433   // Chain the dynamic stack allocation so that it doesn't modify the stack
3434   // pointer when other instructions are using the stack.
3435   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3436 
3437   SDValue Size  = Tmp2.getOperand(1);
3438   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3439   Chain = SP.getValue(1);
3440   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3441   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3442   const TargetFrameLowering *TFL = ST.getFrameLowering();
3443   unsigned Opc =
3444     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3445     ISD::ADD : ISD::SUB;
3446 
3447   SDValue ScaledSize = DAG.getNode(
3448       ISD::SHL, dl, VT, Size,
3449       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3450 
3451   Align StackAlign = TFL->getStackAlign();
3452   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3453   if (Alignment && *Alignment > StackAlign) {
3454     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3455                        DAG.getConstant(-(uint64_t)Alignment->value()
3456                                            << ST.getWavefrontSizeLog2(),
3457                                        dl, VT));
3458   }
3459 
3460   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3461   Tmp2 = DAG.getCALLSEQ_END(
3462       Chain, DAG.getIntPtrConstant(0, dl, true),
3463       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3464 
3465   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3466 }
3467 
3468 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3469                                                   SelectionDAG &DAG) const {
3470   // We only handle constant sizes here to allow non-entry block, static sized
3471   // allocas. A truly dynamic value is more difficult to support because we
3472   // don't know if the size value is uniform or not. If the size isn't uniform,
3473   // we would need to do a wave reduction to get the maximum size to know how
3474   // much to increment the uniform stack pointer.
3475   SDValue Size = Op.getOperand(1);
3476   if (isa<ConstantSDNode>(Size))
3477       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3478 
3479   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3480 }
3481 
3482 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3483                                              const MachineFunction &MF) const {
3484   Register Reg = StringSwitch<Register>(RegName)
3485     .Case("m0", AMDGPU::M0)
3486     .Case("exec", AMDGPU::EXEC)
3487     .Case("exec_lo", AMDGPU::EXEC_LO)
3488     .Case("exec_hi", AMDGPU::EXEC_HI)
3489     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3490     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3491     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3492     .Default(Register());
3493 
3494   if (Reg == AMDGPU::NoRegister) {
3495     report_fatal_error(Twine("invalid register name \""
3496                              + StringRef(RegName)  + "\"."));
3497 
3498   }
3499 
3500   if (!Subtarget->hasFlatScrRegister() &&
3501        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3502     report_fatal_error(Twine("invalid register \""
3503                              + StringRef(RegName)  + "\" for subtarget."));
3504   }
3505 
3506   switch (Reg) {
3507   case AMDGPU::M0:
3508   case AMDGPU::EXEC_LO:
3509   case AMDGPU::EXEC_HI:
3510   case AMDGPU::FLAT_SCR_LO:
3511   case AMDGPU::FLAT_SCR_HI:
3512     if (VT.getSizeInBits() == 32)
3513       return Reg;
3514     break;
3515   case AMDGPU::EXEC:
3516   case AMDGPU::FLAT_SCR:
3517     if (VT.getSizeInBits() == 64)
3518       return Reg;
3519     break;
3520   default:
3521     llvm_unreachable("missing register type checking");
3522   }
3523 
3524   report_fatal_error(Twine("invalid type for register \""
3525                            + StringRef(RegName) + "\"."));
3526 }
3527 
3528 // If kill is not the last instruction, split the block so kill is always a
3529 // proper terminator.
3530 MachineBasicBlock *
3531 SITargetLowering::splitKillBlock(MachineInstr &MI,
3532                                  MachineBasicBlock *BB) const {
3533   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3534   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3535   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3536   return SplitBB;
3537 }
3538 
3539 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3540 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3541 // be the first instruction in the remainder block.
3542 //
3543 /// \returns { LoopBody, Remainder }
3544 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3545 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3546   MachineFunction *MF = MBB.getParent();
3547   MachineBasicBlock::iterator I(&MI);
3548 
3549   // To insert the loop we need to split the block. Move everything after this
3550   // point to a new block, and insert a new empty block between the two.
3551   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3552   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3553   MachineFunction::iterator MBBI(MBB);
3554   ++MBBI;
3555 
3556   MF->insert(MBBI, LoopBB);
3557   MF->insert(MBBI, RemainderBB);
3558 
3559   LoopBB->addSuccessor(LoopBB);
3560   LoopBB->addSuccessor(RemainderBB);
3561 
3562   // Move the rest of the block into a new block.
3563   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3564 
3565   if (InstInLoop) {
3566     auto Next = std::next(I);
3567 
3568     // Move instruction to loop body.
3569     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3570 
3571     // Move the rest of the block.
3572     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3573   } else {
3574     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3575   }
3576 
3577   MBB.addSuccessor(LoopBB);
3578 
3579   return std::make_pair(LoopBB, RemainderBB);
3580 }
3581 
3582 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3583 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3584   MachineBasicBlock *MBB = MI.getParent();
3585   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3586   auto I = MI.getIterator();
3587   auto E = std::next(I);
3588 
3589   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3590     .addImm(0);
3591 
3592   MIBundleBuilder Bundler(*MBB, I, E);
3593   finalizeBundle(*MBB, Bundler.begin());
3594 }
3595 
3596 MachineBasicBlock *
3597 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3598                                          MachineBasicBlock *BB) const {
3599   const DebugLoc &DL = MI.getDebugLoc();
3600 
3601   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3602 
3603   MachineBasicBlock *LoopBB;
3604   MachineBasicBlock *RemainderBB;
3605   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3606 
3607   // Apparently kill flags are only valid if the def is in the same block?
3608   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3609     Src->setIsKill(false);
3610 
3611   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3612 
3613   MachineBasicBlock::iterator I = LoopBB->end();
3614 
3615   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3616     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3617 
3618   // Clear TRAP_STS.MEM_VIOL
3619   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3620     .addImm(0)
3621     .addImm(EncodedReg);
3622 
3623   bundleInstWithWaitcnt(MI);
3624 
3625   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3626 
3627   // Load and check TRAP_STS.MEM_VIOL
3628   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3629     .addImm(EncodedReg);
3630 
3631   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3632   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3633     .addReg(Reg, RegState::Kill)
3634     .addImm(0);
3635   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3636     .addMBB(LoopBB);
3637 
3638   return RemainderBB;
3639 }
3640 
3641 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3642 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3643 // will only do one iteration. In the worst case, this will loop 64 times.
3644 //
3645 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3646 static MachineBasicBlock::iterator
3647 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3648                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3649                        const DebugLoc &DL, const MachineOperand &Idx,
3650                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3651                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3652                        Register &SGPRIdxReg) {
3653 
3654   MachineFunction *MF = OrigBB.getParent();
3655   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3656   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3657   MachineBasicBlock::iterator I = LoopBB.begin();
3658 
3659   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3660   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3661   Register NewExec = MRI.createVirtualRegister(BoolRC);
3662   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3663   Register CondReg = MRI.createVirtualRegister(BoolRC);
3664 
3665   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3666     .addReg(InitReg)
3667     .addMBB(&OrigBB)
3668     .addReg(ResultReg)
3669     .addMBB(&LoopBB);
3670 
3671   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3672     .addReg(InitSaveExecReg)
3673     .addMBB(&OrigBB)
3674     .addReg(NewExec)
3675     .addMBB(&LoopBB);
3676 
3677   // Read the next variant <- also loop target.
3678   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3679       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3680 
3681   // Compare the just read M0 value to all possible Idx values.
3682   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3683       .addReg(CurrentIdxReg)
3684       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3685 
3686   // Update EXEC, save the original EXEC value to VCC.
3687   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3688                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3689           NewExec)
3690     .addReg(CondReg, RegState::Kill);
3691 
3692   MRI.setSimpleHint(NewExec, CondReg);
3693 
3694   if (UseGPRIdxMode) {
3695     if (Offset == 0) {
3696       SGPRIdxReg = CurrentIdxReg;
3697     } else {
3698       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3699       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3700           .addReg(CurrentIdxReg, RegState::Kill)
3701           .addImm(Offset);
3702     }
3703   } else {
3704     // Move index from VCC into M0
3705     if (Offset == 0) {
3706       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3707         .addReg(CurrentIdxReg, RegState::Kill);
3708     } else {
3709       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3710         .addReg(CurrentIdxReg, RegState::Kill)
3711         .addImm(Offset);
3712     }
3713   }
3714 
3715   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3716   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3717   MachineInstr *InsertPt =
3718     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3719                                                   : AMDGPU::S_XOR_B64_term), Exec)
3720       .addReg(Exec)
3721       .addReg(NewExec);
3722 
3723   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3724   // s_cbranch_scc0?
3725 
3726   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3727   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3728     .addMBB(&LoopBB);
3729 
3730   return InsertPt->getIterator();
3731 }
3732 
3733 // This has slightly sub-optimal regalloc when the source vector is killed by
3734 // the read. The register allocator does not understand that the kill is
3735 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3736 // subregister from it, using 1 more VGPR than necessary. This was saved when
3737 // this was expanded after register allocation.
3738 static MachineBasicBlock::iterator
3739 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3740                unsigned InitResultReg, unsigned PhiReg, int Offset,
3741                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3742   MachineFunction *MF = MBB.getParent();
3743   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3744   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3745   MachineRegisterInfo &MRI = MF->getRegInfo();
3746   const DebugLoc &DL = MI.getDebugLoc();
3747   MachineBasicBlock::iterator I(&MI);
3748 
3749   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3750   Register DstReg = MI.getOperand(0).getReg();
3751   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3752   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3753   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3754   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3755 
3756   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3757 
3758   // Save the EXEC mask
3759   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3760     .addReg(Exec);
3761 
3762   MachineBasicBlock *LoopBB;
3763   MachineBasicBlock *RemainderBB;
3764   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3765 
3766   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3767 
3768   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3769                                       InitResultReg, DstReg, PhiReg, TmpExec,
3770                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3771 
3772   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3773   MachineFunction::iterator MBBI(LoopBB);
3774   ++MBBI;
3775   MF->insert(MBBI, LandingPad);
3776   LoopBB->removeSuccessor(RemainderBB);
3777   LandingPad->addSuccessor(RemainderBB);
3778   LoopBB->addSuccessor(LandingPad);
3779   MachineBasicBlock::iterator First = LandingPad->begin();
3780   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3781     .addReg(SaveExec);
3782 
3783   return InsPt;
3784 }
3785 
3786 // Returns subreg index, offset
3787 static std::pair<unsigned, int>
3788 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3789                             const TargetRegisterClass *SuperRC,
3790                             unsigned VecReg,
3791                             int Offset) {
3792   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3793 
3794   // Skip out of bounds offsets, or else we would end up using an undefined
3795   // register.
3796   if (Offset >= NumElts || Offset < 0)
3797     return std::make_pair(AMDGPU::sub0, Offset);
3798 
3799   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3800 }
3801 
3802 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3803                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3804                                  int Offset) {
3805   MachineBasicBlock *MBB = MI.getParent();
3806   const DebugLoc &DL = MI.getDebugLoc();
3807   MachineBasicBlock::iterator I(&MI);
3808 
3809   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3810 
3811   assert(Idx->getReg() != AMDGPU::NoRegister);
3812 
3813   if (Offset == 0) {
3814     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3815   } else {
3816     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3817         .add(*Idx)
3818         .addImm(Offset);
3819   }
3820 }
3821 
3822 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3823                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3824                                    int Offset) {
3825   MachineBasicBlock *MBB = MI.getParent();
3826   const DebugLoc &DL = MI.getDebugLoc();
3827   MachineBasicBlock::iterator I(&MI);
3828 
3829   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3830 
3831   if (Offset == 0)
3832     return Idx->getReg();
3833 
3834   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3835   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3836       .add(*Idx)
3837       .addImm(Offset);
3838   return Tmp;
3839 }
3840 
3841 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3842                                           MachineBasicBlock &MBB,
3843                                           const GCNSubtarget &ST) {
3844   const SIInstrInfo *TII = ST.getInstrInfo();
3845   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3846   MachineFunction *MF = MBB.getParent();
3847   MachineRegisterInfo &MRI = MF->getRegInfo();
3848 
3849   Register Dst = MI.getOperand(0).getReg();
3850   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3851   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3852   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3853 
3854   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3855   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3856 
3857   unsigned SubReg;
3858   std::tie(SubReg, Offset)
3859     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3860 
3861   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3862 
3863   // Check for a SGPR index.
3864   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3865     MachineBasicBlock::iterator I(&MI);
3866     const DebugLoc &DL = MI.getDebugLoc();
3867 
3868     if (UseGPRIdxMode) {
3869       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3870       // to avoid interfering with other uses, so probably requires a new
3871       // optimization pass.
3872       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3873 
3874       const MCInstrDesc &GPRIDXDesc =
3875           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3876       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3877           .addReg(SrcReg)
3878           .addReg(Idx)
3879           .addImm(SubReg);
3880     } else {
3881       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3882 
3883       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3884         .addReg(SrcReg, 0, SubReg)
3885         .addReg(SrcReg, RegState::Implicit);
3886     }
3887 
3888     MI.eraseFromParent();
3889 
3890     return &MBB;
3891   }
3892 
3893   // Control flow needs to be inserted if indexing with a VGPR.
3894   const DebugLoc &DL = MI.getDebugLoc();
3895   MachineBasicBlock::iterator I(&MI);
3896 
3897   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3898   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3899 
3900   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3901 
3902   Register SGPRIdxReg;
3903   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3904                               UseGPRIdxMode, SGPRIdxReg);
3905 
3906   MachineBasicBlock *LoopBB = InsPt->getParent();
3907 
3908   if (UseGPRIdxMode) {
3909     const MCInstrDesc &GPRIDXDesc =
3910         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3911 
3912     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3913         .addReg(SrcReg)
3914         .addReg(SGPRIdxReg)
3915         .addImm(SubReg);
3916   } else {
3917     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3918       .addReg(SrcReg, 0, SubReg)
3919       .addReg(SrcReg, RegState::Implicit);
3920   }
3921 
3922   MI.eraseFromParent();
3923 
3924   return LoopBB;
3925 }
3926 
3927 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3928                                           MachineBasicBlock &MBB,
3929                                           const GCNSubtarget &ST) {
3930   const SIInstrInfo *TII = ST.getInstrInfo();
3931   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3932   MachineFunction *MF = MBB.getParent();
3933   MachineRegisterInfo &MRI = MF->getRegInfo();
3934 
3935   Register Dst = MI.getOperand(0).getReg();
3936   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3937   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3938   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3939   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3940   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3941   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3942 
3943   // This can be an immediate, but will be folded later.
3944   assert(Val->getReg());
3945 
3946   unsigned SubReg;
3947   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3948                                                          SrcVec->getReg(),
3949                                                          Offset);
3950   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3951 
3952   if (Idx->getReg() == AMDGPU::NoRegister) {
3953     MachineBasicBlock::iterator I(&MI);
3954     const DebugLoc &DL = MI.getDebugLoc();
3955 
3956     assert(Offset == 0);
3957 
3958     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3959         .add(*SrcVec)
3960         .add(*Val)
3961         .addImm(SubReg);
3962 
3963     MI.eraseFromParent();
3964     return &MBB;
3965   }
3966 
3967   // Check for a SGPR index.
3968   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3969     MachineBasicBlock::iterator I(&MI);
3970     const DebugLoc &DL = MI.getDebugLoc();
3971 
3972     if (UseGPRIdxMode) {
3973       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3974 
3975       const MCInstrDesc &GPRIDXDesc =
3976           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3977       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3978           .addReg(SrcVec->getReg())
3979           .add(*Val)
3980           .addReg(Idx)
3981           .addImm(SubReg);
3982     } else {
3983       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3984 
3985       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3986           TRI.getRegSizeInBits(*VecRC), 32, false);
3987       BuildMI(MBB, I, DL, MovRelDesc, Dst)
3988           .addReg(SrcVec->getReg())
3989           .add(*Val)
3990           .addImm(SubReg);
3991     }
3992     MI.eraseFromParent();
3993     return &MBB;
3994   }
3995 
3996   // Control flow needs to be inserted if indexing with a VGPR.
3997   if (Val->isReg())
3998     MRI.clearKillFlags(Val->getReg());
3999 
4000   const DebugLoc &DL = MI.getDebugLoc();
4001 
4002   Register PhiReg = MRI.createVirtualRegister(VecRC);
4003 
4004   Register SGPRIdxReg;
4005   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
4006                               UseGPRIdxMode, SGPRIdxReg);
4007   MachineBasicBlock *LoopBB = InsPt->getParent();
4008 
4009   if (UseGPRIdxMode) {
4010     const MCInstrDesc &GPRIDXDesc =
4011         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
4012 
4013     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
4014         .addReg(PhiReg)
4015         .add(*Val)
4016         .addReg(SGPRIdxReg)
4017         .addImm(AMDGPU::sub0);
4018   } else {
4019     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
4020         TRI.getRegSizeInBits(*VecRC), 32, false);
4021     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
4022         .addReg(PhiReg)
4023         .add(*Val)
4024         .addImm(AMDGPU::sub0);
4025   }
4026 
4027   MI.eraseFromParent();
4028   return LoopBB;
4029 }
4030 
4031 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
4032   MachineInstr &MI, MachineBasicBlock *BB) const {
4033 
4034   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4035   MachineFunction *MF = BB->getParent();
4036   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
4037 
4038   switch (MI.getOpcode()) {
4039   case AMDGPU::S_UADDO_PSEUDO:
4040   case AMDGPU::S_USUBO_PSEUDO: {
4041     const DebugLoc &DL = MI.getDebugLoc();
4042     MachineOperand &Dest0 = MI.getOperand(0);
4043     MachineOperand &Dest1 = MI.getOperand(1);
4044     MachineOperand &Src0 = MI.getOperand(2);
4045     MachineOperand &Src1 = MI.getOperand(3);
4046 
4047     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
4048                        ? AMDGPU::S_ADD_I32
4049                        : AMDGPU::S_SUB_I32;
4050     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
4051 
4052     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
4053         .addImm(1)
4054         .addImm(0);
4055 
4056     MI.eraseFromParent();
4057     return BB;
4058   }
4059   case AMDGPU::S_ADD_U64_PSEUDO:
4060   case AMDGPU::S_SUB_U64_PSEUDO: {
4061     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4062     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4063     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4064     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
4065     const DebugLoc &DL = MI.getDebugLoc();
4066 
4067     MachineOperand &Dest = MI.getOperand(0);
4068     MachineOperand &Src0 = MI.getOperand(1);
4069     MachineOperand &Src1 = MI.getOperand(2);
4070 
4071     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4072     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4073 
4074     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
4075         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4076     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
4077         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4078 
4079     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
4080         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4081     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
4082         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4083 
4084     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
4085 
4086     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
4087     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
4088     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
4089     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
4090     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4091         .addReg(DestSub0)
4092         .addImm(AMDGPU::sub0)
4093         .addReg(DestSub1)
4094         .addImm(AMDGPU::sub1);
4095     MI.eraseFromParent();
4096     return BB;
4097   }
4098   case AMDGPU::V_ADD_U64_PSEUDO:
4099   case AMDGPU::V_SUB_U64_PSEUDO: {
4100     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4101     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4102     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4103     const DebugLoc &DL = MI.getDebugLoc();
4104 
4105     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
4106 
4107     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4108 
4109     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4110     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4111 
4112     Register CarryReg = MRI.createVirtualRegister(CarryRC);
4113     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
4114 
4115     MachineOperand &Dest = MI.getOperand(0);
4116     MachineOperand &Src0 = MI.getOperand(1);
4117     MachineOperand &Src1 = MI.getOperand(2);
4118 
4119     const TargetRegisterClass *Src0RC = Src0.isReg()
4120                                             ? MRI.getRegClass(Src0.getReg())
4121                                             : &AMDGPU::VReg_64RegClass;
4122     const TargetRegisterClass *Src1RC = Src1.isReg()
4123                                             ? MRI.getRegClass(Src1.getReg())
4124                                             : &AMDGPU::VReg_64RegClass;
4125 
4126     const TargetRegisterClass *Src0SubRC =
4127         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
4128     const TargetRegisterClass *Src1SubRC =
4129         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
4130 
4131     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
4132         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
4133     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
4134         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
4135 
4136     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
4137         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
4138     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
4139         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
4140 
4141     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
4142     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
4143                                .addReg(CarryReg, RegState::Define)
4144                                .add(SrcReg0Sub0)
4145                                .add(SrcReg1Sub0)
4146                                .addImm(0); // clamp bit
4147 
4148     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
4149     MachineInstr *HiHalf =
4150         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4151             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4152             .add(SrcReg0Sub1)
4153             .add(SrcReg1Sub1)
4154             .addReg(CarryReg, RegState::Kill)
4155             .addImm(0); // clamp bit
4156 
4157     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4158         .addReg(DestSub0)
4159         .addImm(AMDGPU::sub0)
4160         .addReg(DestSub1)
4161         .addImm(AMDGPU::sub1);
4162     TII->legalizeOperands(*LoHalf);
4163     TII->legalizeOperands(*HiHalf);
4164     MI.eraseFromParent();
4165     return BB;
4166   }
4167   case AMDGPU::S_ADD_CO_PSEUDO:
4168   case AMDGPU::S_SUB_CO_PSEUDO: {
4169     // This pseudo has a chance to be selected
4170     // only from uniform add/subcarry node. All the VGPR operands
4171     // therefore assumed to be splat vectors.
4172     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4173     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4174     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4175     MachineBasicBlock::iterator MII = MI;
4176     const DebugLoc &DL = MI.getDebugLoc();
4177     MachineOperand &Dest = MI.getOperand(0);
4178     MachineOperand &CarryDest = MI.getOperand(1);
4179     MachineOperand &Src0 = MI.getOperand(2);
4180     MachineOperand &Src1 = MI.getOperand(3);
4181     MachineOperand &Src2 = MI.getOperand(4);
4182     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4183                        ? AMDGPU::S_ADDC_U32
4184                        : AMDGPU::S_SUBB_U32;
4185     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4186       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4187       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4188           .addReg(Src0.getReg());
4189       Src0.setReg(RegOp0);
4190     }
4191     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4192       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4193       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4194           .addReg(Src1.getReg());
4195       Src1.setReg(RegOp1);
4196     }
4197     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4198     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4199       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4200           .addReg(Src2.getReg());
4201       Src2.setReg(RegOp2);
4202     }
4203 
4204     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4205     unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC);
4206     assert(WaveSize == 64 || WaveSize == 32);
4207 
4208     if (WaveSize == 64) {
4209       if (ST.hasScalarCompareEq64()) {
4210         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4211             .addReg(Src2.getReg())
4212             .addImm(0);
4213       } else {
4214         const TargetRegisterClass *SubRC =
4215             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4216         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4217             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4218         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4219             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4220         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4221 
4222         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4223             .add(Src2Sub0)
4224             .add(Src2Sub1);
4225 
4226         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4227             .addReg(Src2_32, RegState::Kill)
4228             .addImm(0);
4229       }
4230     } else {
4231       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4232           .addReg(Src2.getReg())
4233           .addImm(0);
4234     }
4235 
4236     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4237 
4238     unsigned SelOpc =
4239         (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
4240 
4241     BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg())
4242         .addImm(-1)
4243         .addImm(0);
4244 
4245     MI.eraseFromParent();
4246     return BB;
4247   }
4248   case AMDGPU::SI_INIT_M0: {
4249     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4250             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4251         .add(MI.getOperand(0));
4252     MI.eraseFromParent();
4253     return BB;
4254   }
4255   case AMDGPU::GET_GROUPSTATICSIZE: {
4256     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4257            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4258     DebugLoc DL = MI.getDebugLoc();
4259     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4260         .add(MI.getOperand(0))
4261         .addImm(MFI->getLDSSize());
4262     MI.eraseFromParent();
4263     return BB;
4264   }
4265   case AMDGPU::SI_INDIRECT_SRC_V1:
4266   case AMDGPU::SI_INDIRECT_SRC_V2:
4267   case AMDGPU::SI_INDIRECT_SRC_V4:
4268   case AMDGPU::SI_INDIRECT_SRC_V8:
4269   case AMDGPU::SI_INDIRECT_SRC_V16:
4270   case AMDGPU::SI_INDIRECT_SRC_V32:
4271     return emitIndirectSrc(MI, *BB, *getSubtarget());
4272   case AMDGPU::SI_INDIRECT_DST_V1:
4273   case AMDGPU::SI_INDIRECT_DST_V2:
4274   case AMDGPU::SI_INDIRECT_DST_V4:
4275   case AMDGPU::SI_INDIRECT_DST_V8:
4276   case AMDGPU::SI_INDIRECT_DST_V16:
4277   case AMDGPU::SI_INDIRECT_DST_V32:
4278     return emitIndirectDst(MI, *BB, *getSubtarget());
4279   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4280   case AMDGPU::SI_KILL_I1_PSEUDO:
4281     return splitKillBlock(MI, BB);
4282   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4283     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4284     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4285     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4286 
4287     Register Dst = MI.getOperand(0).getReg();
4288     Register Src0 = MI.getOperand(1).getReg();
4289     Register Src1 = MI.getOperand(2).getReg();
4290     const DebugLoc &DL = MI.getDebugLoc();
4291     Register SrcCond = MI.getOperand(3).getReg();
4292 
4293     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4294     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4295     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4296     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4297 
4298     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4299       .addReg(SrcCond);
4300     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4301       .addImm(0)
4302       .addReg(Src0, 0, AMDGPU::sub0)
4303       .addImm(0)
4304       .addReg(Src1, 0, AMDGPU::sub0)
4305       .addReg(SrcCondCopy);
4306     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4307       .addImm(0)
4308       .addReg(Src0, 0, AMDGPU::sub1)
4309       .addImm(0)
4310       .addReg(Src1, 0, AMDGPU::sub1)
4311       .addReg(SrcCondCopy);
4312 
4313     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4314       .addReg(DstLo)
4315       .addImm(AMDGPU::sub0)
4316       .addReg(DstHi)
4317       .addImm(AMDGPU::sub1);
4318     MI.eraseFromParent();
4319     return BB;
4320   }
4321   case AMDGPU::SI_BR_UNDEF: {
4322     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4323     const DebugLoc &DL = MI.getDebugLoc();
4324     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4325                            .add(MI.getOperand(0));
4326     Br->getOperand(1).setIsUndef(true); // read undef SCC
4327     MI.eraseFromParent();
4328     return BB;
4329   }
4330   case AMDGPU::ADJCALLSTACKUP:
4331   case AMDGPU::ADJCALLSTACKDOWN: {
4332     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4333     MachineInstrBuilder MIB(*MF, &MI);
4334     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4335        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4336     return BB;
4337   }
4338   case AMDGPU::SI_CALL_ISEL: {
4339     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4340     const DebugLoc &DL = MI.getDebugLoc();
4341 
4342     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4343 
4344     MachineInstrBuilder MIB;
4345     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4346 
4347     for (const MachineOperand &MO : MI.operands())
4348       MIB.add(MO);
4349 
4350     MIB.cloneMemRefs(MI);
4351     MI.eraseFromParent();
4352     return BB;
4353   }
4354   case AMDGPU::V_ADD_CO_U32_e32:
4355   case AMDGPU::V_SUB_CO_U32_e32:
4356   case AMDGPU::V_SUBREV_CO_U32_e32: {
4357     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4358     const DebugLoc &DL = MI.getDebugLoc();
4359     unsigned Opc = MI.getOpcode();
4360 
4361     bool NeedClampOperand = false;
4362     if (TII->pseudoToMCOpcode(Opc) == -1) {
4363       Opc = AMDGPU::getVOPe64(Opc);
4364       NeedClampOperand = true;
4365     }
4366 
4367     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4368     if (TII->isVOP3(*I)) {
4369       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4370       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4371       I.addReg(TRI->getVCC(), RegState::Define);
4372     }
4373     I.add(MI.getOperand(1))
4374      .add(MI.getOperand(2));
4375     if (NeedClampOperand)
4376       I.addImm(0); // clamp bit for e64 encoding
4377 
4378     TII->legalizeOperands(*I);
4379 
4380     MI.eraseFromParent();
4381     return BB;
4382   }
4383   case AMDGPU::V_ADDC_U32_e32:
4384   case AMDGPU::V_SUBB_U32_e32:
4385   case AMDGPU::V_SUBBREV_U32_e32:
4386     // These instructions have an implicit use of vcc which counts towards the
4387     // constant bus limit.
4388     TII->legalizeOperands(MI);
4389     return BB;
4390   case AMDGPU::DS_GWS_INIT:
4391   case AMDGPU::DS_GWS_SEMA_BR:
4392   case AMDGPU::DS_GWS_BARRIER:
4393     if (Subtarget->needsAlignedVGPRs()) {
4394       // Add implicit aligned super-reg to force alignment on the data operand.
4395       const DebugLoc &DL = MI.getDebugLoc();
4396       MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4397       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
4398       MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0);
4399       Register DataReg = Op->getReg();
4400       bool IsAGPR = TRI->isAGPR(MRI, DataReg);
4401       Register Undef = MRI.createVirtualRegister(
4402           IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass);
4403       BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef);
4404       Register NewVR =
4405           MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass
4406                                            : &AMDGPU::VReg_64_Align2RegClass);
4407       BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR)
4408           .addReg(DataReg, 0, Op->getSubReg())
4409           .addImm(AMDGPU::sub0)
4410           .addReg(Undef)
4411           .addImm(AMDGPU::sub1);
4412       Op->setReg(NewVR);
4413       Op->setSubReg(AMDGPU::sub0);
4414       MI.addOperand(MachineOperand::CreateReg(NewVR, false, true));
4415     }
4416     LLVM_FALLTHROUGH;
4417   case AMDGPU::DS_GWS_SEMA_V:
4418   case AMDGPU::DS_GWS_SEMA_P:
4419   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4420     // A s_waitcnt 0 is required to be the instruction immediately following.
4421     if (getSubtarget()->hasGWSAutoReplay()) {
4422       bundleInstWithWaitcnt(MI);
4423       return BB;
4424     }
4425 
4426     return emitGWSMemViolTestLoop(MI, BB);
4427   case AMDGPU::S_SETREG_B32: {
4428     // Try to optimize cases that only set the denormal mode or rounding mode.
4429     //
4430     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4431     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4432     // instead.
4433     //
4434     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4435     // allow you to have a no side effect instruction in the output of a
4436     // sideeffecting pattern.
4437     unsigned ID, Offset, Width;
4438     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4439     if (ID != AMDGPU::Hwreg::ID_MODE)
4440       return BB;
4441 
4442     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4443     const unsigned SetMask = WidthMask << Offset;
4444 
4445     if (getSubtarget()->hasDenormModeInst()) {
4446       unsigned SetDenormOp = 0;
4447       unsigned SetRoundOp = 0;
4448 
4449       // The dedicated instructions can only set the whole denorm or round mode
4450       // at once, not a subset of bits in either.
4451       if (SetMask ==
4452           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4453         // If this fully sets both the round and denorm mode, emit the two
4454         // dedicated instructions for these.
4455         SetRoundOp = AMDGPU::S_ROUND_MODE;
4456         SetDenormOp = AMDGPU::S_DENORM_MODE;
4457       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4458         SetRoundOp = AMDGPU::S_ROUND_MODE;
4459       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4460         SetDenormOp = AMDGPU::S_DENORM_MODE;
4461       }
4462 
4463       if (SetRoundOp || SetDenormOp) {
4464         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4465         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4466         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4467           unsigned ImmVal = Def->getOperand(1).getImm();
4468           if (SetRoundOp) {
4469             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4470                 .addImm(ImmVal & 0xf);
4471 
4472             // If we also have the denorm mode, get just the denorm mode bits.
4473             ImmVal >>= 4;
4474           }
4475 
4476           if (SetDenormOp) {
4477             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4478                 .addImm(ImmVal & 0xf);
4479           }
4480 
4481           MI.eraseFromParent();
4482           return BB;
4483         }
4484       }
4485     }
4486 
4487     // If only FP bits are touched, used the no side effects pseudo.
4488     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4489                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4490       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4491 
4492     return BB;
4493   }
4494   default:
4495     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4496   }
4497 }
4498 
4499 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4500   return isTypeLegal(VT.getScalarType());
4501 }
4502 
4503 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4504   // This currently forces unfolding various combinations of fsub into fma with
4505   // free fneg'd operands. As long as we have fast FMA (controlled by
4506   // isFMAFasterThanFMulAndFAdd), we should perform these.
4507 
4508   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4509   // most of these combines appear to be cycle neutral but save on instruction
4510   // count / code size.
4511   return true;
4512 }
4513 
4514 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; }
4515 
4516 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4517                                          EVT VT) const {
4518   if (!VT.isVector()) {
4519     return MVT::i1;
4520   }
4521   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4522 }
4523 
4524 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4525   // TODO: Should i16 be used always if legal? For now it would force VALU
4526   // shifts.
4527   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4528 }
4529 
4530 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4531   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4532              ? Ty.changeElementSize(16)
4533              : Ty.changeElementSize(32);
4534 }
4535 
4536 // Answering this is somewhat tricky and depends on the specific device which
4537 // have different rates for fma or all f64 operations.
4538 //
4539 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4540 // regardless of which device (although the number of cycles differs between
4541 // devices), so it is always profitable for f64.
4542 //
4543 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4544 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4545 // which we can always do even without fused FP ops since it returns the same
4546 // result as the separate operations and since it is always full
4547 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4548 // however does not support denormals, so we do report fma as faster if we have
4549 // a fast fma device and require denormals.
4550 //
4551 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4552                                                   EVT VT) const {
4553   VT = VT.getScalarType();
4554 
4555   switch (VT.getSimpleVT().SimpleTy) {
4556   case MVT::f32: {
4557     // If mad is not available this depends only on if f32 fma is full rate.
4558     if (!Subtarget->hasMadMacF32Insts())
4559       return Subtarget->hasFastFMAF32();
4560 
4561     // Otherwise f32 mad is always full rate and returns the same result as
4562     // the separate operations so should be preferred over fma.
4563     // However does not support denomals.
4564     if (hasFP32Denormals(MF))
4565       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4566 
4567     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4568     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4569   }
4570   case MVT::f64:
4571     return true;
4572   case MVT::f16:
4573     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4574   default:
4575     break;
4576   }
4577 
4578   return false;
4579 }
4580 
4581 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4582                                                   LLT Ty) const {
4583   switch (Ty.getScalarSizeInBits()) {
4584   case 16:
4585     return isFMAFasterThanFMulAndFAdd(MF, MVT::f16);
4586   case 32:
4587     return isFMAFasterThanFMulAndFAdd(MF, MVT::f32);
4588   case 64:
4589     return isFMAFasterThanFMulAndFAdd(MF, MVT::f64);
4590   default:
4591     break;
4592   }
4593 
4594   return false;
4595 }
4596 
4597 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const {
4598   if (!Ty.isScalar())
4599     return false;
4600 
4601   if (Ty.getScalarSizeInBits() == 16)
4602     return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF());
4603   if (Ty.getScalarSizeInBits() == 32)
4604     return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF());
4605 
4606   return false;
4607 }
4608 
4609 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4610                                    const SDNode *N) const {
4611   // TODO: Check future ftz flag
4612   // v_mad_f32/v_mac_f32 do not support denormals.
4613   EVT VT = N->getValueType(0);
4614   if (VT == MVT::f32)
4615     return Subtarget->hasMadMacF32Insts() &&
4616            !hasFP32Denormals(DAG.getMachineFunction());
4617   if (VT == MVT::f16) {
4618     return Subtarget->hasMadF16() &&
4619            !hasFP64FP16Denormals(DAG.getMachineFunction());
4620   }
4621 
4622   return false;
4623 }
4624 
4625 //===----------------------------------------------------------------------===//
4626 // Custom DAG Lowering Operations
4627 //===----------------------------------------------------------------------===//
4628 
4629 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4630 // wider vector type is legal.
4631 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4632                                              SelectionDAG &DAG) const {
4633   unsigned Opc = Op.getOpcode();
4634   EVT VT = Op.getValueType();
4635   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4636 
4637   SDValue Lo, Hi;
4638   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4639 
4640   SDLoc SL(Op);
4641   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4642                              Op->getFlags());
4643   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4644                              Op->getFlags());
4645 
4646   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4647 }
4648 
4649 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4650 // wider vector type is legal.
4651 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4652                                               SelectionDAG &DAG) const {
4653   unsigned Opc = Op.getOpcode();
4654   EVT VT = Op.getValueType();
4655   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4656          VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8f32 ||
4657          VT == MVT::v16f32 || VT == MVT::v32f32);
4658 
4659   SDValue Lo0, Hi0;
4660   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4661   SDValue Lo1, Hi1;
4662   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4663 
4664   SDLoc SL(Op);
4665 
4666   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4667                              Op->getFlags());
4668   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4669                              Op->getFlags());
4670 
4671   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4672 }
4673 
4674 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4675                                               SelectionDAG &DAG) const {
4676   unsigned Opc = Op.getOpcode();
4677   EVT VT = Op.getValueType();
4678   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 ||
4679          VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v8f32 ||
4680          VT == MVT::v16f32 || VT == MVT::v32f32);
4681 
4682   SDValue Lo0, Hi0;
4683   SDValue Op0 = Op.getOperand(0);
4684   std::tie(Lo0, Hi0) = Op0.getValueType().isVector()
4685                          ? DAG.SplitVectorOperand(Op.getNode(), 0)
4686                          : std::make_pair(Op0, Op0);
4687   SDValue Lo1, Hi1;
4688   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4689   SDValue Lo2, Hi2;
4690   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4691 
4692   SDLoc SL(Op);
4693   auto ResVT = DAG.GetSplitDestVTs(VT);
4694 
4695   SDValue OpLo = DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2,
4696                              Op->getFlags());
4697   SDValue OpHi = DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2,
4698                              Op->getFlags());
4699 
4700   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4701 }
4702 
4703 
4704 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4705   switch (Op.getOpcode()) {
4706   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4707   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4708   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4709   case ISD::LOAD: {
4710     SDValue Result = LowerLOAD(Op, DAG);
4711     assert((!Result.getNode() ||
4712             Result.getNode()->getNumValues() == 2) &&
4713            "Load should return a value and a chain");
4714     return Result;
4715   }
4716 
4717   case ISD::FSIN:
4718   case ISD::FCOS:
4719     return LowerTrig(Op, DAG);
4720   case ISD::SELECT: return LowerSELECT(Op, DAG);
4721   case ISD::FDIV: return LowerFDIV(Op, DAG);
4722   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4723   case ISD::STORE: return LowerSTORE(Op, DAG);
4724   case ISD::GlobalAddress: {
4725     MachineFunction &MF = DAG.getMachineFunction();
4726     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4727     return LowerGlobalAddress(MFI, Op, DAG);
4728   }
4729   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4730   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4731   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4732   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4733   case ISD::INSERT_SUBVECTOR:
4734     return lowerINSERT_SUBVECTOR(Op, DAG);
4735   case ISD::INSERT_VECTOR_ELT:
4736     return lowerINSERT_VECTOR_ELT(Op, DAG);
4737   case ISD::EXTRACT_VECTOR_ELT:
4738     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4739   case ISD::VECTOR_SHUFFLE:
4740     return lowerVECTOR_SHUFFLE(Op, DAG);
4741   case ISD::BUILD_VECTOR:
4742     return lowerBUILD_VECTOR(Op, DAG);
4743   case ISD::FP_ROUND:
4744     return lowerFP_ROUND(Op, DAG);
4745   case ISD::TRAP:
4746     return lowerTRAP(Op, DAG);
4747   case ISD::DEBUGTRAP:
4748     return lowerDEBUGTRAP(Op, DAG);
4749   case ISD::FABS:
4750   case ISD::FNEG:
4751   case ISD::FCANONICALIZE:
4752   case ISD::BSWAP:
4753     return splitUnaryVectorOp(Op, DAG);
4754   case ISD::FMINNUM:
4755   case ISD::FMAXNUM:
4756     return lowerFMINNUM_FMAXNUM(Op, DAG);
4757   case ISD::FMA:
4758     return splitTernaryVectorOp(Op, DAG);
4759   case ISD::FP_TO_SINT:
4760   case ISD::FP_TO_UINT:
4761     return LowerFP_TO_INT(Op, DAG);
4762   case ISD::SHL:
4763   case ISD::SRA:
4764   case ISD::SRL:
4765   case ISD::ADD:
4766   case ISD::SUB:
4767   case ISD::MUL:
4768   case ISD::SMIN:
4769   case ISD::SMAX:
4770   case ISD::UMIN:
4771   case ISD::UMAX:
4772   case ISD::FADD:
4773   case ISD::FMUL:
4774   case ISD::FMINNUM_IEEE:
4775   case ISD::FMAXNUM_IEEE:
4776   case ISD::UADDSAT:
4777   case ISD::USUBSAT:
4778   case ISD::SADDSAT:
4779   case ISD::SSUBSAT:
4780     return splitBinaryVectorOp(Op, DAG);
4781   case ISD::SMULO:
4782   case ISD::UMULO:
4783     return lowerXMULO(Op, DAG);
4784   case ISD::SMUL_LOHI:
4785   case ISD::UMUL_LOHI:
4786     return lowerXMUL_LOHI(Op, DAG);
4787   case ISD::DYNAMIC_STACKALLOC:
4788     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4789   }
4790   return SDValue();
4791 }
4792 
4793 // Used for D16: Casts the result of an instruction into the right vector,
4794 // packs values if loads return unpacked values.
4795 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4796                                        const SDLoc &DL,
4797                                        SelectionDAG &DAG, bool Unpacked) {
4798   if (!LoadVT.isVector())
4799     return Result;
4800 
4801   // Cast back to the original packed type or to a larger type that is a
4802   // multiple of 32 bit for D16. Widening the return type is a required for
4803   // legalization.
4804   EVT FittingLoadVT = LoadVT;
4805   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4806     FittingLoadVT =
4807         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4808                          LoadVT.getVectorNumElements() + 1);
4809   }
4810 
4811   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4812     // Truncate to v2i16/v4i16.
4813     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4814 
4815     // Workaround legalizer not scalarizing truncate after vector op
4816     // legalization but not creating intermediate vector trunc.
4817     SmallVector<SDValue, 4> Elts;
4818     DAG.ExtractVectorElements(Result, Elts);
4819     for (SDValue &Elt : Elts)
4820       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4821 
4822     // Pad illegal v1i16/v3fi6 to v4i16
4823     if ((LoadVT.getVectorNumElements() % 2) == 1)
4824       Elts.push_back(DAG.getUNDEF(MVT::i16));
4825 
4826     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4827 
4828     // Bitcast to original type (v2f16/v4f16).
4829     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4830   }
4831 
4832   // Cast back to the original packed type.
4833   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4834 }
4835 
4836 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4837                                               MemSDNode *M,
4838                                               SelectionDAG &DAG,
4839                                               ArrayRef<SDValue> Ops,
4840                                               bool IsIntrinsic) const {
4841   SDLoc DL(M);
4842 
4843   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4844   EVT LoadVT = M->getValueType(0);
4845 
4846   EVT EquivLoadVT = LoadVT;
4847   if (LoadVT.isVector()) {
4848     if (Unpacked) {
4849       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4850                                      LoadVT.getVectorNumElements());
4851     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4852       // Widen v3f16 to legal type
4853       EquivLoadVT =
4854           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4855                            LoadVT.getVectorNumElements() + 1);
4856     }
4857   }
4858 
4859   // Change from v4f16/v2f16 to EquivLoadVT.
4860   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4861 
4862   SDValue Load
4863     = DAG.getMemIntrinsicNode(
4864       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4865       VTList, Ops, M->getMemoryVT(),
4866       M->getMemOperand());
4867 
4868   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4869 
4870   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4871 }
4872 
4873 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4874                                              SelectionDAG &DAG,
4875                                              ArrayRef<SDValue> Ops) const {
4876   SDLoc DL(M);
4877   EVT LoadVT = M->getValueType(0);
4878   EVT EltType = LoadVT.getScalarType();
4879   EVT IntVT = LoadVT.changeTypeToInteger();
4880 
4881   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4882 
4883   unsigned Opc =
4884       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4885 
4886   if (IsD16) {
4887     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4888   }
4889 
4890   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4891   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4892     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4893 
4894   if (isTypeLegal(LoadVT)) {
4895     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4896                                M->getMemOperand(), DAG);
4897   }
4898 
4899   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4900   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4901   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4902                                         M->getMemOperand(), DAG);
4903   return DAG.getMergeValues(
4904       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4905       DL);
4906 }
4907 
4908 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4909                                   SDNode *N, SelectionDAG &DAG) {
4910   EVT VT = N->getValueType(0);
4911   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4912   unsigned CondCode = CD->getZExtValue();
4913   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4914     return DAG.getUNDEF(VT);
4915 
4916   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4917 
4918   SDValue LHS = N->getOperand(1);
4919   SDValue RHS = N->getOperand(2);
4920 
4921   SDLoc DL(N);
4922 
4923   EVT CmpVT = LHS.getValueType();
4924   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4925     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4926       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4927     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4928     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4929   }
4930 
4931   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4932 
4933   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4934   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4935 
4936   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4937                               DAG.getCondCode(CCOpcode));
4938   if (VT.bitsEq(CCVT))
4939     return SetCC;
4940   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4941 }
4942 
4943 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4944                                   SDNode *N, SelectionDAG &DAG) {
4945   EVT VT = N->getValueType(0);
4946   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4947 
4948   unsigned CondCode = CD->getZExtValue();
4949   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4950     return DAG.getUNDEF(VT);
4951 
4952   SDValue Src0 = N->getOperand(1);
4953   SDValue Src1 = N->getOperand(2);
4954   EVT CmpVT = Src0.getValueType();
4955   SDLoc SL(N);
4956 
4957   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4958     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4959     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4960   }
4961 
4962   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4963   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4964   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4965   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4966   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4967                               Src1, DAG.getCondCode(CCOpcode));
4968   if (VT.bitsEq(CCVT))
4969     return SetCC;
4970   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4971 }
4972 
4973 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4974                                     SelectionDAG &DAG) {
4975   EVT VT = N->getValueType(0);
4976   SDValue Src = N->getOperand(1);
4977   SDLoc SL(N);
4978 
4979   if (Src.getOpcode() == ISD::SETCC) {
4980     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4981     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4982                        Src.getOperand(1), Src.getOperand(2));
4983   }
4984   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4985     // (ballot 0) -> 0
4986     if (Arg->isZero())
4987       return DAG.getConstant(0, SL, VT);
4988 
4989     // (ballot 1) -> EXEC/EXEC_LO
4990     if (Arg->isOne()) {
4991       Register Exec;
4992       if (VT.getScalarSizeInBits() == 32)
4993         Exec = AMDGPU::EXEC_LO;
4994       else if (VT.getScalarSizeInBits() == 64)
4995         Exec = AMDGPU::EXEC;
4996       else
4997         return SDValue();
4998 
4999       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
5000     }
5001   }
5002 
5003   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
5004   // ISD::SETNE)
5005   return DAG.getNode(
5006       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
5007       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
5008 }
5009 
5010 void SITargetLowering::ReplaceNodeResults(SDNode *N,
5011                                           SmallVectorImpl<SDValue> &Results,
5012                                           SelectionDAG &DAG) const {
5013   switch (N->getOpcode()) {
5014   case ISD::INSERT_VECTOR_ELT: {
5015     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
5016       Results.push_back(Res);
5017     return;
5018   }
5019   case ISD::EXTRACT_VECTOR_ELT: {
5020     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
5021       Results.push_back(Res);
5022     return;
5023   }
5024   case ISD::INTRINSIC_WO_CHAIN: {
5025     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5026     switch (IID) {
5027     case Intrinsic::amdgcn_cvt_pkrtz: {
5028       SDValue Src0 = N->getOperand(1);
5029       SDValue Src1 = N->getOperand(2);
5030       SDLoc SL(N);
5031       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
5032                                 Src0, Src1);
5033       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
5034       return;
5035     }
5036     case Intrinsic::amdgcn_cvt_pknorm_i16:
5037     case Intrinsic::amdgcn_cvt_pknorm_u16:
5038     case Intrinsic::amdgcn_cvt_pk_i16:
5039     case Intrinsic::amdgcn_cvt_pk_u16: {
5040       SDValue Src0 = N->getOperand(1);
5041       SDValue Src1 = N->getOperand(2);
5042       SDLoc SL(N);
5043       unsigned Opcode;
5044 
5045       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
5046         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
5047       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
5048         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
5049       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
5050         Opcode = AMDGPUISD::CVT_PK_I16_I32;
5051       else
5052         Opcode = AMDGPUISD::CVT_PK_U16_U32;
5053 
5054       EVT VT = N->getValueType(0);
5055       if (isTypeLegal(VT))
5056         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
5057       else {
5058         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
5059         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
5060       }
5061       return;
5062     }
5063     }
5064     break;
5065   }
5066   case ISD::INTRINSIC_W_CHAIN: {
5067     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
5068       if (Res.getOpcode() == ISD::MERGE_VALUES) {
5069         // FIXME: Hacky
5070         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
5071           Results.push_back(Res.getOperand(I));
5072         }
5073       } else {
5074         Results.push_back(Res);
5075         Results.push_back(Res.getValue(1));
5076       }
5077       return;
5078     }
5079 
5080     break;
5081   }
5082   case ISD::SELECT: {
5083     SDLoc SL(N);
5084     EVT VT = N->getValueType(0);
5085     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
5086     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
5087     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
5088 
5089     EVT SelectVT = NewVT;
5090     if (NewVT.bitsLT(MVT::i32)) {
5091       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
5092       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
5093       SelectVT = MVT::i32;
5094     }
5095 
5096     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
5097                                     N->getOperand(0), LHS, RHS);
5098 
5099     if (NewVT != SelectVT)
5100       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
5101     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
5102     return;
5103   }
5104   case ISD::FNEG: {
5105     if (N->getValueType(0) != MVT::v2f16)
5106       break;
5107 
5108     SDLoc SL(N);
5109     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5110 
5111     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
5112                              BC,
5113                              DAG.getConstant(0x80008000, SL, MVT::i32));
5114     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5115     return;
5116   }
5117   case ISD::FABS: {
5118     if (N->getValueType(0) != MVT::v2f16)
5119       break;
5120 
5121     SDLoc SL(N);
5122     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5123 
5124     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
5125                              BC,
5126                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
5127     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5128     return;
5129   }
5130   default:
5131     break;
5132   }
5133 }
5134 
5135 /// Helper function for LowerBRCOND
5136 static SDNode *findUser(SDValue Value, unsigned Opcode) {
5137 
5138   SDNode *Parent = Value.getNode();
5139   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
5140        I != E; ++I) {
5141 
5142     if (I.getUse().get() != Value)
5143       continue;
5144 
5145     if (I->getOpcode() == Opcode)
5146       return *I;
5147   }
5148   return nullptr;
5149 }
5150 
5151 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
5152   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
5153     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
5154     case Intrinsic::amdgcn_if:
5155       return AMDGPUISD::IF;
5156     case Intrinsic::amdgcn_else:
5157       return AMDGPUISD::ELSE;
5158     case Intrinsic::amdgcn_loop:
5159       return AMDGPUISD::LOOP;
5160     case Intrinsic::amdgcn_end_cf:
5161       llvm_unreachable("should not occur");
5162     default:
5163       return 0;
5164     }
5165   }
5166 
5167   // break, if_break, else_break are all only used as inputs to loop, not
5168   // directly as branch conditions.
5169   return 0;
5170 }
5171 
5172 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
5173   const Triple &TT = getTargetMachine().getTargetTriple();
5174   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5175           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5176          AMDGPU::shouldEmitConstantsToTextSection(TT);
5177 }
5178 
5179 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
5180   // FIXME: Either avoid relying on address space here or change the default
5181   // address space for functions to avoid the explicit check.
5182   return (GV->getValueType()->isFunctionTy() ||
5183           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
5184          !shouldEmitFixup(GV) &&
5185          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
5186 }
5187 
5188 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
5189   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
5190 }
5191 
5192 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
5193   if (!GV->hasExternalLinkage())
5194     return true;
5195 
5196   const auto OS = getTargetMachine().getTargetTriple().getOS();
5197   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
5198 }
5199 
5200 /// This transforms the control flow intrinsics to get the branch destination as
5201 /// last parameter, also switches branch target with BR if the need arise
5202 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
5203                                       SelectionDAG &DAG) const {
5204   SDLoc DL(BRCOND);
5205 
5206   SDNode *Intr = BRCOND.getOperand(1).getNode();
5207   SDValue Target = BRCOND.getOperand(2);
5208   SDNode *BR = nullptr;
5209   SDNode *SetCC = nullptr;
5210 
5211   if (Intr->getOpcode() == ISD::SETCC) {
5212     // As long as we negate the condition everything is fine
5213     SetCC = Intr;
5214     Intr = SetCC->getOperand(0).getNode();
5215 
5216   } else {
5217     // Get the target from BR if we don't negate the condition
5218     BR = findUser(BRCOND, ISD::BR);
5219     assert(BR && "brcond missing unconditional branch user");
5220     Target = BR->getOperand(1);
5221   }
5222 
5223   unsigned CFNode = isCFIntrinsic(Intr);
5224   if (CFNode == 0) {
5225     // This is a uniform branch so we don't need to legalize.
5226     return BRCOND;
5227   }
5228 
5229   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5230                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5231 
5232   assert(!SetCC ||
5233         (SetCC->getConstantOperandVal(1) == 1 &&
5234          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5235                                                              ISD::SETNE));
5236 
5237   // operands of the new intrinsic call
5238   SmallVector<SDValue, 4> Ops;
5239   if (HaveChain)
5240     Ops.push_back(BRCOND.getOperand(0));
5241 
5242   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5243   Ops.push_back(Target);
5244 
5245   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5246 
5247   // build the new intrinsic call
5248   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5249 
5250   if (!HaveChain) {
5251     SDValue Ops[] =  {
5252       SDValue(Result, 0),
5253       BRCOND.getOperand(0)
5254     };
5255 
5256     Result = DAG.getMergeValues(Ops, DL).getNode();
5257   }
5258 
5259   if (BR) {
5260     // Give the branch instruction our target
5261     SDValue Ops[] = {
5262       BR->getOperand(0),
5263       BRCOND.getOperand(2)
5264     };
5265     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5266     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5267   }
5268 
5269   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5270 
5271   // Copy the intrinsic results to registers
5272   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5273     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5274     if (!CopyToReg)
5275       continue;
5276 
5277     Chain = DAG.getCopyToReg(
5278       Chain, DL,
5279       CopyToReg->getOperand(1),
5280       SDValue(Result, i - 1),
5281       SDValue());
5282 
5283     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5284   }
5285 
5286   // Remove the old intrinsic from the chain
5287   DAG.ReplaceAllUsesOfValueWith(
5288     SDValue(Intr, Intr->getNumValues() - 1),
5289     Intr->getOperand(0));
5290 
5291   return Chain;
5292 }
5293 
5294 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5295                                           SelectionDAG &DAG) const {
5296   MVT VT = Op.getSimpleValueType();
5297   SDLoc DL(Op);
5298   // Checking the depth
5299   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5300     return DAG.getConstant(0, DL, VT);
5301 
5302   MachineFunction &MF = DAG.getMachineFunction();
5303   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5304   // Check for kernel and shader functions
5305   if (Info->isEntryFunction())
5306     return DAG.getConstant(0, DL, VT);
5307 
5308   MachineFrameInfo &MFI = MF.getFrameInfo();
5309   // There is a call to @llvm.returnaddress in this function
5310   MFI.setReturnAddressIsTaken(true);
5311 
5312   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5313   // Get the return address reg and mark it as an implicit live-in
5314   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5315 
5316   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5317 }
5318 
5319 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5320                                             SDValue Op,
5321                                             const SDLoc &DL,
5322                                             EVT VT) const {
5323   return Op.getValueType().bitsLE(VT) ?
5324       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5325     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5326                 DAG.getTargetConstant(0, DL, MVT::i32));
5327 }
5328 
5329 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5330   assert(Op.getValueType() == MVT::f16 &&
5331          "Do not know how to custom lower FP_ROUND for non-f16 type");
5332 
5333   SDValue Src = Op.getOperand(0);
5334   EVT SrcVT = Src.getValueType();
5335   if (SrcVT != MVT::f64)
5336     return Op;
5337 
5338   SDLoc DL(Op);
5339 
5340   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5341   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5342   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5343 }
5344 
5345 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5346                                                SelectionDAG &DAG) const {
5347   EVT VT = Op.getValueType();
5348   const MachineFunction &MF = DAG.getMachineFunction();
5349   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5350   bool IsIEEEMode = Info->getMode().IEEE;
5351 
5352   // FIXME: Assert during selection that this is only selected for
5353   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5354   // mode functions, but this happens to be OK since it's only done in cases
5355   // where there is known no sNaN.
5356   if (IsIEEEMode)
5357     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5358 
5359   if (VT == MVT::v4f16 || VT == MVT::v8f16)
5360     return splitBinaryVectorOp(Op, DAG);
5361   return Op;
5362 }
5363 
5364 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5365   EVT VT = Op.getValueType();
5366   SDLoc SL(Op);
5367   SDValue LHS = Op.getOperand(0);
5368   SDValue RHS = Op.getOperand(1);
5369   bool isSigned = Op.getOpcode() == ISD::SMULO;
5370 
5371   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5372     const APInt &C = RHSC->getAPIntValue();
5373     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5374     if (C.isPowerOf2()) {
5375       // smulo(x, signed_min) is same as umulo(x, signed_min).
5376       bool UseArithShift = isSigned && !C.isMinSignedValue();
5377       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5378       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5379       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5380           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5381                       SL, VT, Result, ShiftAmt),
5382           LHS, ISD::SETNE);
5383       return DAG.getMergeValues({ Result, Overflow }, SL);
5384     }
5385   }
5386 
5387   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5388   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5389                             SL, VT, LHS, RHS);
5390 
5391   SDValue Sign = isSigned
5392     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5393                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5394     : DAG.getConstant(0, SL, VT);
5395   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5396 
5397   return DAG.getMergeValues({ Result, Overflow }, SL);
5398 }
5399 
5400 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const {
5401   if (Op->isDivergent()) {
5402     // Select to V_MAD_[IU]64_[IU]32.
5403     return Op;
5404   }
5405   if (Subtarget->hasSMulHi()) {
5406     // Expand to S_MUL_I32 + S_MUL_HI_[IU]32.
5407     return SDValue();
5408   }
5409   // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to
5410   // calculate the high part, so we might as well do the whole thing with
5411   // V_MAD_[IU]64_[IU]32.
5412   return Op;
5413 }
5414 
5415 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5416   if (!Subtarget->isTrapHandlerEnabled() ||
5417       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5418     return lowerTrapEndpgm(Op, DAG);
5419 
5420   if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) {
5421     switch (*HsaAbiVer) {
5422     case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
5423     case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
5424       return lowerTrapHsaQueuePtr(Op, DAG);
5425     case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
5426     case ELF::ELFABIVERSION_AMDGPU_HSA_V5:
5427       return Subtarget->supportsGetDoorbellID() ?
5428           lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG);
5429     }
5430   }
5431 
5432   llvm_unreachable("Unknown trap handler");
5433 }
5434 
5435 SDValue SITargetLowering::lowerTrapEndpgm(
5436     SDValue Op, SelectionDAG &DAG) const {
5437   SDLoc SL(Op);
5438   SDValue Chain = Op.getOperand(0);
5439   return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5440 }
5441 
5442 SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5443     SDValue Op, SelectionDAG &DAG) const {
5444   SDLoc SL(Op);
5445   SDValue Chain = Op.getOperand(0);
5446 
5447   MachineFunction &MF = DAG.getMachineFunction();
5448   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5449   Register UserSGPR = Info->getQueuePtrUserSGPR();
5450 
5451   SDValue QueuePtr;
5452   if (UserSGPR == AMDGPU::NoRegister) {
5453     // We probably are in a function incorrectly marked with
5454     // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the trap,
5455     // so just use a null pointer.
5456     QueuePtr = DAG.getConstant(0, SL, MVT::i64);
5457   } else {
5458     QueuePtr = CreateLiveInRegister(
5459       DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5460   }
5461 
5462   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5463   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5464                                    QueuePtr, SDValue());
5465 
5466   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5467   SDValue Ops[] = {
5468     ToReg,
5469     DAG.getTargetConstant(TrapID, SL, MVT::i16),
5470     SGPR01,
5471     ToReg.getValue(1)
5472   };
5473   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5474 }
5475 
5476 SDValue SITargetLowering::lowerTrapHsa(
5477     SDValue Op, SelectionDAG &DAG) const {
5478   SDLoc SL(Op);
5479   SDValue Chain = Op.getOperand(0);
5480 
5481   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5482   SDValue Ops[] = {
5483     Chain,
5484     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5485   };
5486   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5487 }
5488 
5489 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5490   SDLoc SL(Op);
5491   SDValue Chain = Op.getOperand(0);
5492   MachineFunction &MF = DAG.getMachineFunction();
5493 
5494   if (!Subtarget->isTrapHandlerEnabled() ||
5495       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5496     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5497                                      "debugtrap handler not supported",
5498                                      Op.getDebugLoc(),
5499                                      DS_Warning);
5500     LLVMContext &Ctx = MF.getFunction().getContext();
5501     Ctx.diagnose(NoTrap);
5502     return Chain;
5503   }
5504 
5505   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5506   SDValue Ops[] = {
5507     Chain,
5508     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5509   };
5510   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5511 }
5512 
5513 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5514                                              SelectionDAG &DAG) const {
5515   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5516   if (Subtarget->hasApertureRegs()) {
5517     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5518         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5519         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5520     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5521         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5522         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5523     unsigned Encoding =
5524         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5525         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5526         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5527 
5528     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5529     SDValue ApertureReg = SDValue(
5530         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5531     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5532     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5533   }
5534 
5535   MachineFunction &MF = DAG.getMachineFunction();
5536   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5537   Register UserSGPR = Info->getQueuePtrUserSGPR();
5538   if (UserSGPR == AMDGPU::NoRegister) {
5539     // We probably are in a function incorrectly marked with
5540     // amdgpu-no-queue-ptr. This is undefined.
5541     return DAG.getUNDEF(MVT::i32);
5542   }
5543 
5544   SDValue QueuePtr = CreateLiveInRegister(
5545     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5546 
5547   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5548   // private_segment_aperture_base_hi.
5549   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5550 
5551   SDValue Ptr =
5552       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5553 
5554   // TODO: Use custom target PseudoSourceValue.
5555   // TODO: We should use the value from the IR intrinsic call, but it might not
5556   // be available and how do we get it?
5557   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5558   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5559                      commonAlignment(Align(64), StructOffset),
5560                      MachineMemOperand::MODereferenceable |
5561                          MachineMemOperand::MOInvariant);
5562 }
5563 
5564 /// Return true if the value is a known valid address, such that a null check is
5565 /// not necessary.
5566 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG,
5567                            const AMDGPUTargetMachine &TM, unsigned AddrSpace) {
5568   if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) ||
5569       isa<BasicBlockSDNode>(Val))
5570     return true;
5571 
5572   if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val))
5573     return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace);
5574 
5575   // TODO: Search through arithmetic, handle arguments and loads
5576   // marked nonnull.
5577   return false;
5578 }
5579 
5580 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5581                                              SelectionDAG &DAG) const {
5582   SDLoc SL(Op);
5583   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5584 
5585   SDValue Src = ASC->getOperand(0);
5586   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5587   unsigned SrcAS = ASC->getSrcAddressSpace();
5588 
5589   const AMDGPUTargetMachine &TM =
5590     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5591 
5592   // flat -> local/private
5593   if (SrcAS == AMDGPUAS::FLAT_ADDRESS) {
5594     unsigned DestAS = ASC->getDestAddressSpace();
5595 
5596     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5597         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5598       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5599 
5600       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5601         return Ptr;
5602 
5603       unsigned NullVal = TM.getNullPointerValue(DestAS);
5604       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5605       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5606 
5607       return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr,
5608                          SegmentNullPtr);
5609     }
5610   }
5611 
5612   // local/private -> flat
5613   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5614     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5615         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5616 
5617       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5618       SDValue CvtPtr =
5619           DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5620       CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr);
5621 
5622       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5623         return CvtPtr;
5624 
5625       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5626       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5627 
5628       SDValue NonNull
5629         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5630 
5631       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr,
5632                          FlatNullPtr);
5633     }
5634   }
5635 
5636   if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5637       Op.getValueType() == MVT::i64) {
5638     const SIMachineFunctionInfo *Info =
5639         DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>();
5640     SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32);
5641     SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi);
5642     return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
5643   }
5644 
5645   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5646       Src.getValueType() == MVT::i64)
5647     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5648 
5649   // global <-> flat are no-ops and never emitted.
5650 
5651   const MachineFunction &MF = DAG.getMachineFunction();
5652   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5653     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5654   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5655 
5656   return DAG.getUNDEF(ASC->getValueType(0));
5657 }
5658 
5659 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5660 // the small vector and inserting them into the big vector. That is better than
5661 // the default expansion of doing it via a stack slot. Even though the use of
5662 // the stack slot would be optimized away afterwards, the stack slot itself
5663 // remains.
5664 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5665                                                 SelectionDAG &DAG) const {
5666   SDValue Vec = Op.getOperand(0);
5667   SDValue Ins = Op.getOperand(1);
5668   SDValue Idx = Op.getOperand(2);
5669   EVT VecVT = Vec.getValueType();
5670   EVT InsVT = Ins.getValueType();
5671   EVT EltVT = VecVT.getVectorElementType();
5672   unsigned InsNumElts = InsVT.getVectorNumElements();
5673   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5674   SDLoc SL(Op);
5675 
5676   for (unsigned I = 0; I != InsNumElts; ++I) {
5677     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5678                               DAG.getConstant(I, SL, MVT::i32));
5679     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5680                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5681   }
5682   return Vec;
5683 }
5684 
5685 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5686                                                  SelectionDAG &DAG) const {
5687   SDValue Vec = Op.getOperand(0);
5688   SDValue InsVal = Op.getOperand(1);
5689   SDValue Idx = Op.getOperand(2);
5690   EVT VecVT = Vec.getValueType();
5691   EVT EltVT = VecVT.getVectorElementType();
5692   unsigned VecSize = VecVT.getSizeInBits();
5693   unsigned EltSize = EltVT.getSizeInBits();
5694 
5695 
5696   assert(VecSize <= 64);
5697 
5698   unsigned NumElts = VecVT.getVectorNumElements();
5699   SDLoc SL(Op);
5700   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5701 
5702   if (NumElts == 4 && EltSize == 16 && KIdx) {
5703     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5704 
5705     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5706                                  DAG.getConstant(0, SL, MVT::i32));
5707     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5708                                  DAG.getConstant(1, SL, MVT::i32));
5709 
5710     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5711     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5712 
5713     unsigned Idx = KIdx->getZExtValue();
5714     bool InsertLo = Idx < 2;
5715     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5716       InsertLo ? LoVec : HiVec,
5717       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5718       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5719 
5720     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5721 
5722     SDValue Concat = InsertLo ?
5723       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5724       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5725 
5726     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5727   }
5728 
5729   if (isa<ConstantSDNode>(Idx))
5730     return SDValue();
5731 
5732   MVT IntVT = MVT::getIntegerVT(VecSize);
5733 
5734   // Avoid stack access for dynamic indexing.
5735   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5736 
5737   // Create a congruent vector with the target value in each element so that
5738   // the required element can be masked and ORed into the target vector.
5739   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5740                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5741 
5742   assert(isPowerOf2_32(EltSize));
5743   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5744 
5745   // Convert vector index to bit-index.
5746   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5747 
5748   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5749   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5750                             DAG.getConstant(0xffff, SL, IntVT),
5751                             ScaledIdx);
5752 
5753   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5754   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5755                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5756 
5757   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5758   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5759 }
5760 
5761 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5762                                                   SelectionDAG &DAG) const {
5763   SDLoc SL(Op);
5764 
5765   EVT ResultVT = Op.getValueType();
5766   SDValue Vec = Op.getOperand(0);
5767   SDValue Idx = Op.getOperand(1);
5768   EVT VecVT = Vec.getValueType();
5769   unsigned VecSize = VecVT.getSizeInBits();
5770   EVT EltVT = VecVT.getVectorElementType();
5771 
5772   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5773 
5774   // Make sure we do any optimizations that will make it easier to fold
5775   // source modifiers before obscuring it with bit operations.
5776 
5777   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5778   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5779     return Combined;
5780 
5781   if (VecSize == 128) {
5782     SDValue Lo, Hi;
5783     EVT LoVT, HiVT;
5784     SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec);
5785     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5786     Lo =
5787         DAG.getBitcast(LoVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5788                                          V2, DAG.getConstant(0, SL, MVT::i32)));
5789     Hi =
5790         DAG.getBitcast(HiVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5791                                          V2, DAG.getConstant(1, SL, MVT::i32)));
5792     EVT IdxVT = Idx.getValueType();
5793     unsigned NElem = VecVT.getVectorNumElements();
5794     assert(isPowerOf2_32(NElem));
5795     SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT);
5796     SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask);
5797     SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT);
5798     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx);
5799   }
5800 
5801   assert(VecSize <= 64);
5802 
5803   unsigned EltSize = EltVT.getSizeInBits();
5804   assert(isPowerOf2_32(EltSize));
5805 
5806   MVT IntVT = MVT::getIntegerVT(VecSize);
5807   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5808 
5809   // Convert vector index to bit-index (* EltSize)
5810   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5811 
5812   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5813   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5814 
5815   if (ResultVT == MVT::f16) {
5816     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5817     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5818   }
5819 
5820   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5821 }
5822 
5823 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5824   assert(Elt % 2 == 0);
5825   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5826 }
5827 
5828 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5829                                               SelectionDAG &DAG) const {
5830   SDLoc SL(Op);
5831   EVT ResultVT = Op.getValueType();
5832   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5833 
5834   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5835   EVT EltVT = PackVT.getVectorElementType();
5836   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5837 
5838   // vector_shuffle <0,1,6,7> lhs, rhs
5839   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5840   //
5841   // vector_shuffle <6,7,2,3> lhs, rhs
5842   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5843   //
5844   // vector_shuffle <6,7,0,1> lhs, rhs
5845   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5846 
5847   // Avoid scalarizing when both halves are reading from consecutive elements.
5848   SmallVector<SDValue, 4> Pieces;
5849   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5850     if (elementPairIsContiguous(SVN->getMask(), I)) {
5851       const int Idx = SVN->getMaskElt(I);
5852       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5853       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5854       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5855                                     PackVT, SVN->getOperand(VecIdx),
5856                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5857       Pieces.push_back(SubVec);
5858     } else {
5859       const int Idx0 = SVN->getMaskElt(I);
5860       const int Idx1 = SVN->getMaskElt(I + 1);
5861       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5862       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5863       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5864       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5865 
5866       SDValue Vec0 = SVN->getOperand(VecIdx0);
5867       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5868                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5869 
5870       SDValue Vec1 = SVN->getOperand(VecIdx1);
5871       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5872                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5873       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5874     }
5875   }
5876 
5877   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5878 }
5879 
5880 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5881                                             SelectionDAG &DAG) const {
5882   SDLoc SL(Op);
5883   EVT VT = Op.getValueType();
5884 
5885   if (VT == MVT::v4i16 || VT == MVT::v4f16 ||
5886       VT == MVT::v8i16 || VT == MVT::v8f16) {
5887     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(),
5888                                   VT.getVectorNumElements() / 2);
5889     MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits());
5890 
5891     // Turn into pair of packed build_vectors.
5892     // TODO: Special case for constants that can be materialized with s_mov_b64.
5893     SmallVector<SDValue, 4> LoOps, HiOps;
5894     for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) {
5895       LoOps.push_back(Op.getOperand(I));
5896       HiOps.push_back(Op.getOperand(I + E));
5897     }
5898     SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps);
5899     SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps);
5900 
5901     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo);
5902     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi);
5903 
5904     SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL,
5905                                        { CastLo, CastHi });
5906     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5907   }
5908 
5909   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5910   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5911 
5912   SDValue Lo = Op.getOperand(0);
5913   SDValue Hi = Op.getOperand(1);
5914 
5915   // Avoid adding defined bits with the zero_extend.
5916   if (Hi.isUndef()) {
5917     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5918     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5919     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5920   }
5921 
5922   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5923   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5924 
5925   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5926                               DAG.getConstant(16, SL, MVT::i32));
5927   if (Lo.isUndef())
5928     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5929 
5930   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5931   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5932 
5933   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5934   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5935 }
5936 
5937 bool
5938 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5939   // We can fold offsets for anything that doesn't require a GOT relocation.
5940   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5941           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5942           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5943          !shouldEmitGOTReloc(GA->getGlobal());
5944 }
5945 
5946 static SDValue
5947 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5948                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5949                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5950   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5951   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5952   // lowered to the following code sequence:
5953   //
5954   // For constant address space:
5955   //   s_getpc_b64 s[0:1]
5956   //   s_add_u32 s0, s0, $symbol
5957   //   s_addc_u32 s1, s1, 0
5958   //
5959   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5960   //   a fixup or relocation is emitted to replace $symbol with a literal
5961   //   constant, which is a pc-relative offset from the encoding of the $symbol
5962   //   operand to the global variable.
5963   //
5964   // For global address space:
5965   //   s_getpc_b64 s[0:1]
5966   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5967   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5968   //
5969   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5970   //   fixups or relocations are emitted to replace $symbol@*@lo and
5971   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5972   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5973   //   operand to the global variable.
5974   //
5975   // What we want here is an offset from the value returned by s_getpc
5976   // (which is the address of the s_add_u32 instruction) to the global
5977   // variable, but since the encoding of $symbol starts 4 bytes after the start
5978   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5979   // small. This requires us to add 4 to the global variable offset in order to
5980   // compute the correct address. Similarly for the s_addc_u32 instruction, the
5981   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
5982   // instruction.
5983   SDValue PtrLo =
5984       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5985   SDValue PtrHi;
5986   if (GAFlags == SIInstrInfo::MO_NONE) {
5987     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5988   } else {
5989     PtrHi =
5990         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
5991   }
5992   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5993 }
5994 
5995 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5996                                              SDValue Op,
5997                                              SelectionDAG &DAG) const {
5998   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5999   SDLoc DL(GSD);
6000   EVT PtrVT = Op.getValueType();
6001 
6002   const GlobalValue *GV = GSD->getGlobal();
6003   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
6004        shouldUseLDSConstAddress(GV)) ||
6005       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
6006       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
6007     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
6008         GV->hasExternalLinkage()) {
6009       Type *Ty = GV->getValueType();
6010       // HIP uses an unsized array `extern __shared__ T s[]` or similar
6011       // zero-sized type in other languages to declare the dynamic shared
6012       // memory which size is not known at the compile time. They will be
6013       // allocated by the runtime and placed directly after the static
6014       // allocated ones. They all share the same offset.
6015       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
6016         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
6017         // Adjust alignment for that dynamic shared memory array.
6018         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
6019         return SDValue(
6020             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
6021       }
6022     }
6023     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
6024   }
6025 
6026   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
6027     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
6028                                             SIInstrInfo::MO_ABS32_LO);
6029     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
6030   }
6031 
6032   if (shouldEmitFixup(GV))
6033     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
6034   else if (shouldEmitPCReloc(GV))
6035     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
6036                                    SIInstrInfo::MO_REL32);
6037 
6038   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
6039                                             SIInstrInfo::MO_GOTPCREL32);
6040 
6041   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
6042   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
6043   const DataLayout &DataLayout = DAG.getDataLayout();
6044   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
6045   MachinePointerInfo PtrInfo
6046     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
6047 
6048   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
6049                      MachineMemOperand::MODereferenceable |
6050                          MachineMemOperand::MOInvariant);
6051 }
6052 
6053 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
6054                                    const SDLoc &DL, SDValue V) const {
6055   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
6056   // the destination register.
6057   //
6058   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
6059   // so we will end up with redundant moves to m0.
6060   //
6061   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
6062 
6063   // A Null SDValue creates a glue result.
6064   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
6065                                   V, Chain);
6066   return SDValue(M0, 0);
6067 }
6068 
6069 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
6070                                                  SDValue Op,
6071                                                  MVT VT,
6072                                                  unsigned Offset) const {
6073   SDLoc SL(Op);
6074   SDValue Param = lowerKernargMemParameter(
6075       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
6076   // The local size values will have the hi 16-bits as zero.
6077   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
6078                      DAG.getValueType(VT));
6079 }
6080 
6081 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6082                                         EVT VT) {
6083   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6084                                       "non-hsa intrinsic with hsa target",
6085                                       DL.getDebugLoc());
6086   DAG.getContext()->diagnose(BadIntrin);
6087   return DAG.getUNDEF(VT);
6088 }
6089 
6090 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6091                                          EVT VT) {
6092   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6093                                       "intrinsic not supported on subtarget",
6094                                       DL.getDebugLoc());
6095   DAG.getContext()->diagnose(BadIntrin);
6096   return DAG.getUNDEF(VT);
6097 }
6098 
6099 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
6100                                     ArrayRef<SDValue> Elts) {
6101   assert(!Elts.empty());
6102   MVT Type;
6103   unsigned NumElts = Elts.size();
6104 
6105   if (NumElts <= 8) {
6106     Type = MVT::getVectorVT(MVT::f32, NumElts);
6107   } else {
6108     assert(Elts.size() <= 16);
6109     Type = MVT::v16f32;
6110     NumElts = 16;
6111   }
6112 
6113   SmallVector<SDValue, 16> VecElts(NumElts);
6114   for (unsigned i = 0; i < Elts.size(); ++i) {
6115     SDValue Elt = Elts[i];
6116     if (Elt.getValueType() != MVT::f32)
6117       Elt = DAG.getBitcast(MVT::f32, Elt);
6118     VecElts[i] = Elt;
6119   }
6120   for (unsigned i = Elts.size(); i < NumElts; ++i)
6121     VecElts[i] = DAG.getUNDEF(MVT::f32);
6122 
6123   if (NumElts == 1)
6124     return VecElts[0];
6125   return DAG.getBuildVector(Type, DL, VecElts);
6126 }
6127 
6128 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
6129                               SDValue Src, int ExtraElts) {
6130   EVT SrcVT = Src.getValueType();
6131 
6132   SmallVector<SDValue, 8> Elts;
6133 
6134   if (SrcVT.isVector())
6135     DAG.ExtractVectorElements(Src, Elts);
6136   else
6137     Elts.push_back(Src);
6138 
6139   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
6140   while (ExtraElts--)
6141     Elts.push_back(Undef);
6142 
6143   return DAG.getBuildVector(CastVT, DL, Elts);
6144 }
6145 
6146 // Re-construct the required return value for a image load intrinsic.
6147 // This is more complicated due to the optional use TexFailCtrl which means the required
6148 // return type is an aggregate
6149 static SDValue constructRetValue(SelectionDAG &DAG,
6150                                  MachineSDNode *Result,
6151                                  ArrayRef<EVT> ResultTypes,
6152                                  bool IsTexFail, bool Unpacked, bool IsD16,
6153                                  int DMaskPop, int NumVDataDwords,
6154                                  const SDLoc &DL) {
6155   // Determine the required return type. This is the same regardless of IsTexFail flag
6156   EVT ReqRetVT = ResultTypes[0];
6157   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
6158   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6159     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
6160 
6161   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6162     DMaskPop : (DMaskPop + 1) / 2;
6163 
6164   MVT DataDwordVT = NumDataDwords == 1 ?
6165     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
6166 
6167   MVT MaskPopVT = MaskPopDwords == 1 ?
6168     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
6169 
6170   SDValue Data(Result, 0);
6171   SDValue TexFail;
6172 
6173   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
6174     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
6175     if (MaskPopVT.isVector()) {
6176       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
6177                          SDValue(Result, 0), ZeroIdx);
6178     } else {
6179       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
6180                          SDValue(Result, 0), ZeroIdx);
6181     }
6182   }
6183 
6184   if (DataDwordVT.isVector())
6185     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
6186                           NumDataDwords - MaskPopDwords);
6187 
6188   if (IsD16)
6189     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
6190 
6191   EVT LegalReqRetVT = ReqRetVT;
6192   if (!ReqRetVT.isVector()) {
6193     if (!Data.getValueType().isInteger())
6194       Data = DAG.getNode(ISD::BITCAST, DL,
6195                          Data.getValueType().changeTypeToInteger(), Data);
6196     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
6197   } else {
6198     // We need to widen the return vector to a legal type
6199     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
6200         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
6201       LegalReqRetVT =
6202           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
6203                            ReqRetVT.getVectorNumElements() + 1);
6204     }
6205   }
6206   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
6207 
6208   if (IsTexFail) {
6209     TexFail =
6210         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
6211                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
6212 
6213     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
6214   }
6215 
6216   if (Result->getNumValues() == 1)
6217     return Data;
6218 
6219   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
6220 }
6221 
6222 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
6223                          SDValue *LWE, bool &IsTexFail) {
6224   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
6225 
6226   uint64_t Value = TexFailCtrlConst->getZExtValue();
6227   if (Value) {
6228     IsTexFail = true;
6229   }
6230 
6231   SDLoc DL(TexFailCtrlConst);
6232   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
6233   Value &= ~(uint64_t)0x1;
6234   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
6235   Value &= ~(uint64_t)0x2;
6236 
6237   return Value == 0;
6238 }
6239 
6240 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
6241                                       MVT PackVectorVT,
6242                                       SmallVectorImpl<SDValue> &PackedAddrs,
6243                                       unsigned DimIdx, unsigned EndIdx,
6244                                       unsigned NumGradients) {
6245   SDLoc DL(Op);
6246   for (unsigned I = DimIdx; I < EndIdx; I++) {
6247     SDValue Addr = Op.getOperand(I);
6248 
6249     // Gradients are packed with undef for each coordinate.
6250     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
6251     // 1D: undef,dx/dh; undef,dx/dv
6252     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
6253     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
6254     if (((I + 1) >= EndIdx) ||
6255         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
6256                                          I == DimIdx + NumGradients - 1))) {
6257       if (Addr.getValueType() != MVT::i16)
6258         Addr = DAG.getBitcast(MVT::i16, Addr);
6259       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
6260     } else {
6261       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
6262       I++;
6263     }
6264     Addr = DAG.getBitcast(MVT::f32, Addr);
6265     PackedAddrs.push_back(Addr);
6266   }
6267 }
6268 
6269 SDValue SITargetLowering::lowerImage(SDValue Op,
6270                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
6271                                      SelectionDAG &DAG, bool WithChain) const {
6272   SDLoc DL(Op);
6273   MachineFunction &MF = DAG.getMachineFunction();
6274   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
6275   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
6276       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
6277   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
6278   unsigned IntrOpcode = Intr->BaseOpcode;
6279   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6280 
6281   SmallVector<EVT, 3> ResultTypes(Op->values());
6282   SmallVector<EVT, 3> OrigResultTypes(Op->values());
6283   bool IsD16 = false;
6284   bool IsG16 = false;
6285   bool IsA16 = false;
6286   SDValue VData;
6287   int NumVDataDwords;
6288   bool AdjustRetType = false;
6289 
6290   // Offset of intrinsic arguments
6291   const unsigned ArgOffset = WithChain ? 2 : 1;
6292 
6293   unsigned DMask;
6294   unsigned DMaskLanes = 0;
6295 
6296   if (BaseOpcode->Atomic) {
6297     VData = Op.getOperand(2);
6298 
6299     bool Is64Bit = VData.getValueType() == MVT::i64;
6300     if (BaseOpcode->AtomicX2) {
6301       SDValue VData2 = Op.getOperand(3);
6302       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6303                                  {VData, VData2});
6304       if (Is64Bit)
6305         VData = DAG.getBitcast(MVT::v4i32, VData);
6306 
6307       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6308       DMask = Is64Bit ? 0xf : 0x3;
6309       NumVDataDwords = Is64Bit ? 4 : 2;
6310     } else {
6311       DMask = Is64Bit ? 0x3 : 0x1;
6312       NumVDataDwords = Is64Bit ? 2 : 1;
6313     }
6314   } else {
6315     auto *DMaskConst =
6316         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6317     DMask = DMaskConst->getZExtValue();
6318     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6319 
6320     if (BaseOpcode->Store) {
6321       VData = Op.getOperand(2);
6322 
6323       MVT StoreVT = VData.getSimpleValueType();
6324       if (StoreVT.getScalarType() == MVT::f16) {
6325         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6326           return Op; // D16 is unsupported for this instruction
6327 
6328         IsD16 = true;
6329         VData = handleD16VData(VData, DAG, true);
6330       }
6331 
6332       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6333     } else {
6334       // Work out the num dwords based on the dmask popcount and underlying type
6335       // and whether packing is supported.
6336       MVT LoadVT = ResultTypes[0].getSimpleVT();
6337       if (LoadVT.getScalarType() == MVT::f16) {
6338         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6339           return Op; // D16 is unsupported for this instruction
6340 
6341         IsD16 = true;
6342       }
6343 
6344       // Confirm that the return type is large enough for the dmask specified
6345       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6346           (!LoadVT.isVector() && DMaskLanes > 1))
6347           return Op;
6348 
6349       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6350       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6351       // instructions.
6352       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6353           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6354         NumVDataDwords = (DMaskLanes + 1) / 2;
6355       else
6356         NumVDataDwords = DMaskLanes;
6357 
6358       AdjustRetType = true;
6359     }
6360   }
6361 
6362   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6363   SmallVector<SDValue, 4> VAddrs;
6364 
6365   // Check for 16 bit addresses or derivatives and pack if true.
6366   MVT VAddrVT =
6367       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6368   MVT VAddrScalarVT = VAddrVT.getScalarType();
6369   MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6370   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6371 
6372   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6373   VAddrScalarVT = VAddrVT.getScalarType();
6374   MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6375   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6376 
6377   // Push back extra arguments.
6378   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) {
6379     if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) {
6380       assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument");
6381       // Special handling of bias when A16 is on. Bias is of type half but
6382       // occupies full 32-bit.
6383       SDValue Bias = DAG.getBuildVector(
6384           MVT::v2f16, DL,
6385           {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)});
6386       VAddrs.push_back(Bias);
6387     } else {
6388       assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) &&
6389              "Bias needs to be converted to 16 bit in A16 mode");
6390       VAddrs.push_back(Op.getOperand(ArgOffset + I));
6391     }
6392   }
6393 
6394   if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
6395     // 16 bit gradients are supported, but are tied to the A16 control
6396     // so both gradients and addresses must be 16 bit
6397     LLVM_DEBUG(
6398         dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6399                   "require 16 bit args for both gradients and addresses");
6400     return Op;
6401   }
6402 
6403   if (IsA16) {
6404     if (!ST->hasA16()) {
6405       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6406                            "support 16 bit addresses\n");
6407       return Op;
6408     }
6409   }
6410 
6411   // We've dealt with incorrect input so we know that if IsA16, IsG16
6412   // are set then we have to compress/pack operands (either address,
6413   // gradient or both)
6414   // In the case where a16 and gradients are tied (no G16 support) then we
6415   // have already verified that both IsA16 and IsG16 are true
6416   if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
6417     // Activate g16
6418     const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6419         AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6420     IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6421   }
6422 
6423   // Add gradients (packed or unpacked)
6424   if (IsG16) {
6425     // Pack the gradients
6426     // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6427     packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
6428                               ArgOffset + Intr->GradientStart,
6429                               ArgOffset + Intr->CoordStart, Intr->NumGradients);
6430   } else {
6431     for (unsigned I = ArgOffset + Intr->GradientStart;
6432          I < ArgOffset + Intr->CoordStart; I++)
6433       VAddrs.push_back(Op.getOperand(I));
6434   }
6435 
6436   // Add addresses (packed or unpacked)
6437   if (IsA16) {
6438     packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
6439                               ArgOffset + Intr->CoordStart, VAddrEnd,
6440                               0 /* No gradients */);
6441   } else {
6442     // Add uncompressed address
6443     for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6444       VAddrs.push_back(Op.getOperand(I));
6445   }
6446 
6447   // If the register allocator cannot place the address registers contiguously
6448   // without introducing moves, then using the non-sequential address encoding
6449   // is always preferable, since it saves VALU instructions and is usually a
6450   // wash in terms of code size or even better.
6451   //
6452   // However, we currently have no way of hinting to the register allocator that
6453   // MIMG addresses should be placed contiguously when it is possible to do so,
6454   // so force non-NSA for the common 2-address case as a heuristic.
6455   //
6456   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6457   // allocation when possible.
6458   bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) &&
6459                 VAddrs.size() >= 3 &&
6460                 VAddrs.size() <= (unsigned)ST->getNSAMaxSize();
6461   SDValue VAddr;
6462   if (!UseNSA)
6463     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6464 
6465   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6466   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6467   SDValue Unorm;
6468   if (!BaseOpcode->Sampler) {
6469     Unorm = True;
6470   } else {
6471     auto UnormConst =
6472         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6473 
6474     Unorm = UnormConst->getZExtValue() ? True : False;
6475   }
6476 
6477   SDValue TFE;
6478   SDValue LWE;
6479   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6480   bool IsTexFail = false;
6481   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6482     return Op;
6483 
6484   if (IsTexFail) {
6485     if (!DMaskLanes) {
6486       // Expecting to get an error flag since TFC is on - and dmask is 0
6487       // Force dmask to be at least 1 otherwise the instruction will fail
6488       DMask = 0x1;
6489       DMaskLanes = 1;
6490       NumVDataDwords = 1;
6491     }
6492     NumVDataDwords += 1;
6493     AdjustRetType = true;
6494   }
6495 
6496   // Has something earlier tagged that the return type needs adjusting
6497   // This happens if the instruction is a load or has set TexFailCtrl flags
6498   if (AdjustRetType) {
6499     // NumVDataDwords reflects the true number of dwords required in the return type
6500     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6501       // This is a no-op load. This can be eliminated
6502       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6503       if (isa<MemSDNode>(Op))
6504         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6505       return Undef;
6506     }
6507 
6508     EVT NewVT = NumVDataDwords > 1 ?
6509                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6510                 : MVT::i32;
6511 
6512     ResultTypes[0] = NewVT;
6513     if (ResultTypes.size() == 3) {
6514       // Original result was aggregate type used for TexFailCtrl results
6515       // The actual instruction returns as a vector type which has now been
6516       // created. Remove the aggregate result.
6517       ResultTypes.erase(&ResultTypes[1]);
6518     }
6519   }
6520 
6521   unsigned CPol = cast<ConstantSDNode>(
6522       Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6523   if (BaseOpcode->Atomic)
6524     CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6525   if (CPol & ~AMDGPU::CPol::ALL)
6526     return Op;
6527 
6528   SmallVector<SDValue, 26> Ops;
6529   if (BaseOpcode->Store || BaseOpcode->Atomic)
6530     Ops.push_back(VData); // vdata
6531   if (UseNSA)
6532     append_range(Ops, VAddrs);
6533   else
6534     Ops.push_back(VAddr);
6535   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6536   if (BaseOpcode->Sampler)
6537     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6538   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6539   if (IsGFX10Plus)
6540     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6541   Ops.push_back(Unorm);
6542   Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6543   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6544                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6545   if (IsGFX10Plus)
6546     Ops.push_back(IsA16 ? True : False);
6547   if (!Subtarget->hasGFX90AInsts()) {
6548     Ops.push_back(TFE); //tfe
6549   } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6550     report_fatal_error("TFE is not supported on this GPU");
6551   }
6552   Ops.push_back(LWE); // lwe
6553   if (!IsGFX10Plus)
6554     Ops.push_back(DimInfo->DA ? True : False);
6555   if (BaseOpcode->HasD16)
6556     Ops.push_back(IsD16 ? True : False);
6557   if (isa<MemSDNode>(Op))
6558     Ops.push_back(Op.getOperand(0)); // chain
6559 
6560   int NumVAddrDwords =
6561       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6562   int Opcode = -1;
6563 
6564   if (IsGFX10Plus) {
6565     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6566                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6567                                           : AMDGPU::MIMGEncGfx10Default,
6568                                    NumVDataDwords, NumVAddrDwords);
6569   } else {
6570     if (Subtarget->hasGFX90AInsts()) {
6571       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6572                                      NumVDataDwords, NumVAddrDwords);
6573       if (Opcode == -1)
6574         report_fatal_error(
6575             "requested image instruction is not supported on this GPU");
6576     }
6577     if (Opcode == -1 &&
6578         Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6579       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6580                                      NumVDataDwords, NumVAddrDwords);
6581     if (Opcode == -1)
6582       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6583                                      NumVDataDwords, NumVAddrDwords);
6584   }
6585   assert(Opcode != -1);
6586 
6587   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6588   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6589     MachineMemOperand *MemRef = MemOp->getMemOperand();
6590     DAG.setNodeMemRefs(NewNode, {MemRef});
6591   }
6592 
6593   if (BaseOpcode->AtomicX2) {
6594     SmallVector<SDValue, 1> Elt;
6595     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6596     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6597   }
6598   if (BaseOpcode->Store)
6599     return SDValue(NewNode, 0);
6600   return constructRetValue(DAG, NewNode,
6601                            OrigResultTypes, IsTexFail,
6602                            Subtarget->hasUnpackedD16VMem(), IsD16,
6603                            DMaskLanes, NumVDataDwords, DL);
6604 }
6605 
6606 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6607                                        SDValue Offset, SDValue CachePolicy,
6608                                        SelectionDAG &DAG) const {
6609   MachineFunction &MF = DAG.getMachineFunction();
6610 
6611   const DataLayout &DataLayout = DAG.getDataLayout();
6612   Align Alignment =
6613       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6614 
6615   MachineMemOperand *MMO = MF.getMachineMemOperand(
6616       MachinePointerInfo(),
6617       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6618           MachineMemOperand::MOInvariant,
6619       VT.getStoreSize(), Alignment);
6620 
6621   if (!Offset->isDivergent()) {
6622     SDValue Ops[] = {
6623         Rsrc,
6624         Offset, // Offset
6625         CachePolicy
6626     };
6627 
6628     // Widen vec3 load to vec4.
6629     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6630       EVT WidenedVT =
6631           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6632       auto WidenedOp = DAG.getMemIntrinsicNode(
6633           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6634           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6635       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6636                                    DAG.getVectorIdxConstant(0, DL));
6637       return Subvector;
6638     }
6639 
6640     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6641                                    DAG.getVTList(VT), Ops, VT, MMO);
6642   }
6643 
6644   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6645   // assume that the buffer is unswizzled.
6646   SmallVector<SDValue, 4> Loads;
6647   unsigned NumLoads = 1;
6648   MVT LoadVT = VT.getSimpleVT();
6649   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6650   assert((LoadVT.getScalarType() == MVT::i32 ||
6651           LoadVT.getScalarType() == MVT::f32));
6652 
6653   if (NumElts == 8 || NumElts == 16) {
6654     NumLoads = NumElts / 4;
6655     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6656   }
6657 
6658   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6659   SDValue Ops[] = {
6660       DAG.getEntryNode(),                               // Chain
6661       Rsrc,                                             // rsrc
6662       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6663       {},                                               // voffset
6664       {},                                               // soffset
6665       {},                                               // offset
6666       CachePolicy,                                      // cachepolicy
6667       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6668   };
6669 
6670   // Use the alignment to ensure that the required offsets will fit into the
6671   // immediate offsets.
6672   setBufferOffsets(Offset, DAG, &Ops[3],
6673                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6674 
6675   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6676   for (unsigned i = 0; i < NumLoads; ++i) {
6677     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6678     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6679                                         LoadVT, MMO, DAG));
6680   }
6681 
6682   if (NumElts == 8 || NumElts == 16)
6683     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6684 
6685   return Loads[0];
6686 }
6687 
6688 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6689                                                   SelectionDAG &DAG) const {
6690   MachineFunction &MF = DAG.getMachineFunction();
6691   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6692 
6693   EVT VT = Op.getValueType();
6694   SDLoc DL(Op);
6695   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6696 
6697   // TODO: Should this propagate fast-math-flags?
6698 
6699   switch (IntrinsicID) {
6700   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6701     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6702       return emitNonHSAIntrinsicError(DAG, DL, VT);
6703     return getPreloadedValue(DAG, *MFI, VT,
6704                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6705   }
6706   case Intrinsic::amdgcn_dispatch_ptr:
6707   case Intrinsic::amdgcn_queue_ptr: {
6708     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6709       DiagnosticInfoUnsupported BadIntrin(
6710           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6711           DL.getDebugLoc());
6712       DAG.getContext()->diagnose(BadIntrin);
6713       return DAG.getUNDEF(VT);
6714     }
6715 
6716     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6717       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6718     return getPreloadedValue(DAG, *MFI, VT, RegID);
6719   }
6720   case Intrinsic::amdgcn_implicitarg_ptr: {
6721     if (MFI->isEntryFunction())
6722       return getImplicitArgPtr(DAG, DL);
6723     return getPreloadedValue(DAG, *MFI, VT,
6724                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6725   }
6726   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6727     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6728       // This only makes sense to call in a kernel, so just lower to null.
6729       return DAG.getConstant(0, DL, VT);
6730     }
6731 
6732     return getPreloadedValue(DAG, *MFI, VT,
6733                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6734   }
6735   case Intrinsic::amdgcn_dispatch_id: {
6736     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6737   }
6738   case Intrinsic::amdgcn_rcp:
6739     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6740   case Intrinsic::amdgcn_rsq:
6741     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6742   case Intrinsic::amdgcn_rsq_legacy:
6743     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6744       return emitRemovedIntrinsicError(DAG, DL, VT);
6745     return SDValue();
6746   case Intrinsic::amdgcn_rcp_legacy:
6747     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6748       return emitRemovedIntrinsicError(DAG, DL, VT);
6749     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6750   case Intrinsic::amdgcn_rsq_clamp: {
6751     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6752       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6753 
6754     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6755     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6756     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6757 
6758     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6759     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6760                               DAG.getConstantFP(Max, DL, VT));
6761     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6762                        DAG.getConstantFP(Min, DL, VT));
6763   }
6764   case Intrinsic::r600_read_ngroups_x:
6765     if (Subtarget->isAmdHsaOS())
6766       return emitNonHSAIntrinsicError(DAG, DL, VT);
6767 
6768     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6769                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6770                                     false);
6771   case Intrinsic::r600_read_ngroups_y:
6772     if (Subtarget->isAmdHsaOS())
6773       return emitNonHSAIntrinsicError(DAG, DL, VT);
6774 
6775     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6776                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6777                                     false);
6778   case Intrinsic::r600_read_ngroups_z:
6779     if (Subtarget->isAmdHsaOS())
6780       return emitNonHSAIntrinsicError(DAG, DL, VT);
6781 
6782     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6783                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6784                                     false);
6785   case Intrinsic::r600_read_global_size_x:
6786     if (Subtarget->isAmdHsaOS())
6787       return emitNonHSAIntrinsicError(DAG, DL, VT);
6788 
6789     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6790                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6791                                     Align(4), false);
6792   case Intrinsic::r600_read_global_size_y:
6793     if (Subtarget->isAmdHsaOS())
6794       return emitNonHSAIntrinsicError(DAG, DL, VT);
6795 
6796     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6797                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6798                                     Align(4), false);
6799   case Intrinsic::r600_read_global_size_z:
6800     if (Subtarget->isAmdHsaOS())
6801       return emitNonHSAIntrinsicError(DAG, DL, VT);
6802 
6803     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6804                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6805                                     Align(4), false);
6806   case Intrinsic::r600_read_local_size_x:
6807     if (Subtarget->isAmdHsaOS())
6808       return emitNonHSAIntrinsicError(DAG, DL, VT);
6809 
6810     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6811                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6812   case Intrinsic::r600_read_local_size_y:
6813     if (Subtarget->isAmdHsaOS())
6814       return emitNonHSAIntrinsicError(DAG, DL, VT);
6815 
6816     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6817                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6818   case Intrinsic::r600_read_local_size_z:
6819     if (Subtarget->isAmdHsaOS())
6820       return emitNonHSAIntrinsicError(DAG, DL, VT);
6821 
6822     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6823                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6824   case Intrinsic::amdgcn_workgroup_id_x:
6825     return getPreloadedValue(DAG, *MFI, VT,
6826                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6827   case Intrinsic::amdgcn_workgroup_id_y:
6828     return getPreloadedValue(DAG, *MFI, VT,
6829                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6830   case Intrinsic::amdgcn_workgroup_id_z:
6831     return getPreloadedValue(DAG, *MFI, VT,
6832                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6833   case Intrinsic::amdgcn_workitem_id_x:
6834     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 0) == 0)
6835       return DAG.getConstant(0, DL, MVT::i32);
6836 
6837     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6838                           SDLoc(DAG.getEntryNode()),
6839                           MFI->getArgInfo().WorkItemIDX);
6840   case Intrinsic::amdgcn_workitem_id_y:
6841     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 1) == 0)
6842       return DAG.getConstant(0, DL, MVT::i32);
6843 
6844     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6845                           SDLoc(DAG.getEntryNode()),
6846                           MFI->getArgInfo().WorkItemIDY);
6847   case Intrinsic::amdgcn_workitem_id_z:
6848     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 2) == 0)
6849       return DAG.getConstant(0, DL, MVT::i32);
6850 
6851     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6852                           SDLoc(DAG.getEntryNode()),
6853                           MFI->getArgInfo().WorkItemIDZ);
6854   case Intrinsic::amdgcn_wavefrontsize:
6855     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6856                            SDLoc(Op), MVT::i32);
6857   case Intrinsic::amdgcn_s_buffer_load: {
6858     unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6859     if (CPol & ~AMDGPU::CPol::ALL)
6860       return Op;
6861     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6862                         DAG);
6863   }
6864   case Intrinsic::amdgcn_fdiv_fast:
6865     return lowerFDIV_FAST(Op, DAG);
6866   case Intrinsic::amdgcn_sin:
6867     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6868 
6869   case Intrinsic::amdgcn_cos:
6870     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6871 
6872   case Intrinsic::amdgcn_mul_u24:
6873     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6874   case Intrinsic::amdgcn_mul_i24:
6875     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6876 
6877   case Intrinsic::amdgcn_log_clamp: {
6878     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6879       return SDValue();
6880 
6881     return emitRemovedIntrinsicError(DAG, DL, VT);
6882   }
6883   case Intrinsic::amdgcn_ldexp:
6884     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6885                        Op.getOperand(1), Op.getOperand(2));
6886 
6887   case Intrinsic::amdgcn_fract:
6888     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6889 
6890   case Intrinsic::amdgcn_class:
6891     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6892                        Op.getOperand(1), Op.getOperand(2));
6893   case Intrinsic::amdgcn_div_fmas:
6894     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6895                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6896                        Op.getOperand(4));
6897 
6898   case Intrinsic::amdgcn_div_fixup:
6899     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6900                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6901 
6902   case Intrinsic::amdgcn_div_scale: {
6903     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6904 
6905     // Translate to the operands expected by the machine instruction. The
6906     // first parameter must be the same as the first instruction.
6907     SDValue Numerator = Op.getOperand(1);
6908     SDValue Denominator = Op.getOperand(2);
6909 
6910     // Note this order is opposite of the machine instruction's operations,
6911     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6912     // intrinsic has the numerator as the first operand to match a normal
6913     // division operation.
6914 
6915     SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator;
6916 
6917     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6918                        Denominator, Numerator);
6919   }
6920   case Intrinsic::amdgcn_icmp: {
6921     // There is a Pat that handles this variant, so return it as-is.
6922     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6923         Op.getConstantOperandVal(2) == 0 &&
6924         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6925       return Op;
6926     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6927   }
6928   case Intrinsic::amdgcn_fcmp: {
6929     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6930   }
6931   case Intrinsic::amdgcn_ballot:
6932     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6933   case Intrinsic::amdgcn_fmed3:
6934     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6935                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6936   case Intrinsic::amdgcn_fdot2:
6937     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6938                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6939                        Op.getOperand(4));
6940   case Intrinsic::amdgcn_fmul_legacy:
6941     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6942                        Op.getOperand(1), Op.getOperand(2));
6943   case Intrinsic::amdgcn_sffbh:
6944     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6945   case Intrinsic::amdgcn_sbfe:
6946     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6947                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6948   case Intrinsic::amdgcn_ubfe:
6949     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6950                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6951   case Intrinsic::amdgcn_cvt_pkrtz:
6952   case Intrinsic::amdgcn_cvt_pknorm_i16:
6953   case Intrinsic::amdgcn_cvt_pknorm_u16:
6954   case Intrinsic::amdgcn_cvt_pk_i16:
6955   case Intrinsic::amdgcn_cvt_pk_u16: {
6956     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6957     EVT VT = Op.getValueType();
6958     unsigned Opcode;
6959 
6960     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6961       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6962     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6963       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6964     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6965       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6966     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6967       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6968     else
6969       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6970 
6971     if (isTypeLegal(VT))
6972       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6973 
6974     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6975                                Op.getOperand(1), Op.getOperand(2));
6976     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6977   }
6978   case Intrinsic::amdgcn_fmad_ftz:
6979     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6980                        Op.getOperand(2), Op.getOperand(3));
6981 
6982   case Intrinsic::amdgcn_if_break:
6983     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6984                                       Op->getOperand(1), Op->getOperand(2)), 0);
6985 
6986   case Intrinsic::amdgcn_groupstaticsize: {
6987     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6988     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6989       return Op;
6990 
6991     const Module *M = MF.getFunction().getParent();
6992     const GlobalValue *GV =
6993         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6994     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6995                                             SIInstrInfo::MO_ABS32_LO);
6996     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6997   }
6998   case Intrinsic::amdgcn_is_shared:
6999   case Intrinsic::amdgcn_is_private: {
7000     SDLoc SL(Op);
7001     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
7002       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
7003     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
7004     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
7005                                  Op.getOperand(1));
7006 
7007     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
7008                                 DAG.getConstant(1, SL, MVT::i32));
7009     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
7010   }
7011   case Intrinsic::amdgcn_perm:
7012     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
7013                        Op.getOperand(2), Op.getOperand(3));
7014   case Intrinsic::amdgcn_reloc_constant: {
7015     Module *M = const_cast<Module *>(MF.getFunction().getParent());
7016     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
7017     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
7018     auto RelocSymbol = cast<GlobalVariable>(
7019         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
7020     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
7021                                             SIInstrInfo::MO_ABS32_LO);
7022     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
7023   }
7024   default:
7025     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7026             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7027       return lowerImage(Op, ImageDimIntr, DAG, false);
7028 
7029     return Op;
7030   }
7031 }
7032 
7033 /// Update \p MMO based on the offset inputs to an intrinsic.
7034 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset,
7035                             SDValue SOffset, SDValue Offset,
7036                             SDValue VIndex = SDValue()) {
7037   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
7038       !isa<ConstantSDNode>(Offset)) {
7039     // The combined offset is not known to be constant, so we cannot represent
7040     // it in the MMO. Give up.
7041     MMO->setValue((Value *)nullptr);
7042     return;
7043   }
7044 
7045   if (VIndex && (!isa<ConstantSDNode>(VIndex) ||
7046                  !cast<ConstantSDNode>(VIndex)->isZero())) {
7047     // The strided index component of the address is not known to be zero, so we
7048     // cannot represent it in the MMO. Give up.
7049     MMO->setValue((Value *)nullptr);
7050     return;
7051   }
7052 
7053   MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() +
7054                  cast<ConstantSDNode>(SOffset)->getSExtValue() +
7055                  cast<ConstantSDNode>(Offset)->getSExtValue());
7056 }
7057 
7058 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
7059                                                      SelectionDAG &DAG,
7060                                                      unsigned NewOpcode) const {
7061   SDLoc DL(Op);
7062 
7063   SDValue VData = Op.getOperand(2);
7064   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7065   SDValue Ops[] = {
7066     Op.getOperand(0), // Chain
7067     VData,            // vdata
7068     Op.getOperand(3), // rsrc
7069     DAG.getConstant(0, DL, MVT::i32), // vindex
7070     Offsets.first,    // voffset
7071     Op.getOperand(5), // soffset
7072     Offsets.second,   // offset
7073     Op.getOperand(6), // cachepolicy
7074     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7075   };
7076 
7077   auto *M = cast<MemSDNode>(Op);
7078   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
7079 
7080   EVT MemVT = VData.getValueType();
7081   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7082                                  M->getMemOperand());
7083 }
7084 
7085 // Return a value to use for the idxen operand by examining the vindex operand.
7086 static unsigned getIdxEn(SDValue VIndex) {
7087   if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex))
7088     // No need to set idxen if vindex is known to be zero.
7089     return VIndexC->getZExtValue() != 0;
7090   return 1;
7091 }
7092 
7093 SDValue
7094 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
7095                                                 unsigned NewOpcode) const {
7096   SDLoc DL(Op);
7097 
7098   SDValue VData = Op.getOperand(2);
7099   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7100   SDValue Ops[] = {
7101     Op.getOperand(0), // Chain
7102     VData,            // vdata
7103     Op.getOperand(3), // rsrc
7104     Op.getOperand(4), // vindex
7105     Offsets.first,    // voffset
7106     Op.getOperand(6), // soffset
7107     Offsets.second,   // offset
7108     Op.getOperand(7), // cachepolicy
7109     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7110   };
7111 
7112   auto *M = cast<MemSDNode>(Op);
7113   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7114 
7115   EVT MemVT = VData.getValueType();
7116   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7117                                  M->getMemOperand());
7118 }
7119 
7120 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
7121                                                  SelectionDAG &DAG) const {
7122   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7123   SDLoc DL(Op);
7124 
7125   switch (IntrID) {
7126   case Intrinsic::amdgcn_ds_ordered_add:
7127   case Intrinsic::amdgcn_ds_ordered_swap: {
7128     MemSDNode *M = cast<MemSDNode>(Op);
7129     SDValue Chain = M->getOperand(0);
7130     SDValue M0 = M->getOperand(2);
7131     SDValue Value = M->getOperand(3);
7132     unsigned IndexOperand = M->getConstantOperandVal(7);
7133     unsigned WaveRelease = M->getConstantOperandVal(8);
7134     unsigned WaveDone = M->getConstantOperandVal(9);
7135 
7136     unsigned OrderedCountIndex = IndexOperand & 0x3f;
7137     IndexOperand &= ~0x3f;
7138     unsigned CountDw = 0;
7139 
7140     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
7141       CountDw = (IndexOperand >> 24) & 0xf;
7142       IndexOperand &= ~(0xf << 24);
7143 
7144       if (CountDw < 1 || CountDw > 4) {
7145         report_fatal_error(
7146             "ds_ordered_count: dword count must be between 1 and 4");
7147       }
7148     }
7149 
7150     if (IndexOperand)
7151       report_fatal_error("ds_ordered_count: bad index operand");
7152 
7153     if (WaveDone && !WaveRelease)
7154       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
7155 
7156     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
7157     unsigned ShaderType =
7158         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
7159     unsigned Offset0 = OrderedCountIndex << 2;
7160     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
7161                        (Instruction << 4);
7162 
7163     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
7164       Offset1 |= (CountDw - 1) << 6;
7165 
7166     unsigned Offset = Offset0 | (Offset1 << 8);
7167 
7168     SDValue Ops[] = {
7169       Chain,
7170       Value,
7171       DAG.getTargetConstant(Offset, DL, MVT::i16),
7172       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
7173     };
7174     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
7175                                    M->getVTList(), Ops, M->getMemoryVT(),
7176                                    M->getMemOperand());
7177   }
7178   case Intrinsic::amdgcn_ds_fadd: {
7179     MemSDNode *M = cast<MemSDNode>(Op);
7180     unsigned Opc;
7181     switch (IntrID) {
7182     case Intrinsic::amdgcn_ds_fadd:
7183       Opc = ISD::ATOMIC_LOAD_FADD;
7184       break;
7185     }
7186 
7187     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
7188                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
7189                          M->getMemOperand());
7190   }
7191   case Intrinsic::amdgcn_atomic_inc:
7192   case Intrinsic::amdgcn_atomic_dec:
7193   case Intrinsic::amdgcn_ds_fmin:
7194   case Intrinsic::amdgcn_ds_fmax: {
7195     MemSDNode *M = cast<MemSDNode>(Op);
7196     unsigned Opc;
7197     switch (IntrID) {
7198     case Intrinsic::amdgcn_atomic_inc:
7199       Opc = AMDGPUISD::ATOMIC_INC;
7200       break;
7201     case Intrinsic::amdgcn_atomic_dec:
7202       Opc = AMDGPUISD::ATOMIC_DEC;
7203       break;
7204     case Intrinsic::amdgcn_ds_fmin:
7205       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
7206       break;
7207     case Intrinsic::amdgcn_ds_fmax:
7208       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
7209       break;
7210     default:
7211       llvm_unreachable("Unknown intrinsic!");
7212     }
7213     SDValue Ops[] = {
7214       M->getOperand(0), // Chain
7215       M->getOperand(2), // Ptr
7216       M->getOperand(3)  // Value
7217     };
7218 
7219     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
7220                                    M->getMemoryVT(), M->getMemOperand());
7221   }
7222   case Intrinsic::amdgcn_buffer_load:
7223   case Intrinsic::amdgcn_buffer_load_format: {
7224     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
7225     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7226     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7227     SDValue Ops[] = {
7228       Op.getOperand(0), // Chain
7229       Op.getOperand(2), // rsrc
7230       Op.getOperand(3), // vindex
7231       SDValue(),        // voffset -- will be set by setBufferOffsets
7232       SDValue(),        // soffset -- will be set by setBufferOffsets
7233       SDValue(),        // offset -- will be set by setBufferOffsets
7234       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7235       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7236     };
7237     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
7238 
7239     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
7240         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
7241 
7242     EVT VT = Op.getValueType();
7243     EVT IntVT = VT.changeTypeToInteger();
7244     auto *M = cast<MemSDNode>(Op);
7245     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7246     EVT LoadVT = Op.getValueType();
7247 
7248     if (LoadVT.getScalarType() == MVT::f16)
7249       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
7250                                  M, DAG, Ops);
7251 
7252     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
7253     if (LoadVT.getScalarType() == MVT::i8 ||
7254         LoadVT.getScalarType() == MVT::i16)
7255       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
7256 
7257     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
7258                                M->getMemOperand(), DAG);
7259   }
7260   case Intrinsic::amdgcn_raw_buffer_load:
7261   case Intrinsic::amdgcn_raw_buffer_load_format: {
7262     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
7263 
7264     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7265     SDValue Ops[] = {
7266       Op.getOperand(0), // Chain
7267       Op.getOperand(2), // rsrc
7268       DAG.getConstant(0, DL, MVT::i32), // vindex
7269       Offsets.first,    // voffset
7270       Op.getOperand(4), // soffset
7271       Offsets.second,   // offset
7272       Op.getOperand(5), // cachepolicy, swizzled buffer
7273       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7274     };
7275 
7276     auto *M = cast<MemSDNode>(Op);
7277     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]);
7278     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
7279   }
7280   case Intrinsic::amdgcn_struct_buffer_load:
7281   case Intrinsic::amdgcn_struct_buffer_load_format: {
7282     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
7283 
7284     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7285     SDValue Ops[] = {
7286       Op.getOperand(0), // Chain
7287       Op.getOperand(2), // rsrc
7288       Op.getOperand(3), // vindex
7289       Offsets.first,    // voffset
7290       Op.getOperand(5), // soffset
7291       Offsets.second,   // offset
7292       Op.getOperand(6), // cachepolicy, swizzled buffer
7293       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7294     };
7295 
7296     auto *M = cast<MemSDNode>(Op);
7297     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7298     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7299   }
7300   case Intrinsic::amdgcn_tbuffer_load: {
7301     MemSDNode *M = cast<MemSDNode>(Op);
7302     EVT LoadVT = Op.getValueType();
7303 
7304     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7305     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7306     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7307     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7308     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7309     SDValue Ops[] = {
7310       Op.getOperand(0),  // Chain
7311       Op.getOperand(2),  // rsrc
7312       Op.getOperand(3),  // vindex
7313       Op.getOperand(4),  // voffset
7314       Op.getOperand(5),  // soffset
7315       Op.getOperand(6),  // offset
7316       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7317       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7318       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7319     };
7320 
7321     if (LoadVT.getScalarType() == MVT::f16)
7322       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7323                                  M, DAG, Ops);
7324     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7325                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7326                                DAG);
7327   }
7328   case Intrinsic::amdgcn_raw_tbuffer_load: {
7329     MemSDNode *M = cast<MemSDNode>(Op);
7330     EVT LoadVT = Op.getValueType();
7331     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7332 
7333     SDValue Ops[] = {
7334       Op.getOperand(0),  // Chain
7335       Op.getOperand(2),  // rsrc
7336       DAG.getConstant(0, DL, MVT::i32), // vindex
7337       Offsets.first,     // voffset
7338       Op.getOperand(4),  // soffset
7339       Offsets.second,    // offset
7340       Op.getOperand(5),  // format
7341       Op.getOperand(6),  // cachepolicy, swizzled buffer
7342       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7343     };
7344 
7345     if (LoadVT.getScalarType() == MVT::f16)
7346       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7347                                  M, DAG, Ops);
7348     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7349                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7350                                DAG);
7351   }
7352   case Intrinsic::amdgcn_struct_tbuffer_load: {
7353     MemSDNode *M = cast<MemSDNode>(Op);
7354     EVT LoadVT = Op.getValueType();
7355     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7356 
7357     SDValue Ops[] = {
7358       Op.getOperand(0),  // Chain
7359       Op.getOperand(2),  // rsrc
7360       Op.getOperand(3),  // vindex
7361       Offsets.first,     // voffset
7362       Op.getOperand(5),  // soffset
7363       Offsets.second,    // offset
7364       Op.getOperand(6),  // format
7365       Op.getOperand(7),  // cachepolicy, swizzled buffer
7366       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7367     };
7368 
7369     if (LoadVT.getScalarType() == MVT::f16)
7370       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7371                                  M, DAG, Ops);
7372     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7373                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7374                                DAG);
7375   }
7376   case Intrinsic::amdgcn_buffer_atomic_swap:
7377   case Intrinsic::amdgcn_buffer_atomic_add:
7378   case Intrinsic::amdgcn_buffer_atomic_sub:
7379   case Intrinsic::amdgcn_buffer_atomic_csub:
7380   case Intrinsic::amdgcn_buffer_atomic_smin:
7381   case Intrinsic::amdgcn_buffer_atomic_umin:
7382   case Intrinsic::amdgcn_buffer_atomic_smax:
7383   case Intrinsic::amdgcn_buffer_atomic_umax:
7384   case Intrinsic::amdgcn_buffer_atomic_and:
7385   case Intrinsic::amdgcn_buffer_atomic_or:
7386   case Intrinsic::amdgcn_buffer_atomic_xor:
7387   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7388     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7389     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7390     SDValue Ops[] = {
7391       Op.getOperand(0), // Chain
7392       Op.getOperand(2), // vdata
7393       Op.getOperand(3), // rsrc
7394       Op.getOperand(4), // vindex
7395       SDValue(),        // voffset -- will be set by setBufferOffsets
7396       SDValue(),        // soffset -- will be set by setBufferOffsets
7397       SDValue(),        // offset -- will be set by setBufferOffsets
7398       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7399       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7400     };
7401     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7402 
7403     EVT VT = Op.getValueType();
7404 
7405     auto *M = cast<MemSDNode>(Op);
7406     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7407     unsigned Opcode = 0;
7408 
7409     switch (IntrID) {
7410     case Intrinsic::amdgcn_buffer_atomic_swap:
7411       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7412       break;
7413     case Intrinsic::amdgcn_buffer_atomic_add:
7414       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7415       break;
7416     case Intrinsic::amdgcn_buffer_atomic_sub:
7417       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7418       break;
7419     case Intrinsic::amdgcn_buffer_atomic_csub:
7420       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7421       break;
7422     case Intrinsic::amdgcn_buffer_atomic_smin:
7423       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7424       break;
7425     case Intrinsic::amdgcn_buffer_atomic_umin:
7426       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7427       break;
7428     case Intrinsic::amdgcn_buffer_atomic_smax:
7429       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7430       break;
7431     case Intrinsic::amdgcn_buffer_atomic_umax:
7432       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7433       break;
7434     case Intrinsic::amdgcn_buffer_atomic_and:
7435       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7436       break;
7437     case Intrinsic::amdgcn_buffer_atomic_or:
7438       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7439       break;
7440     case Intrinsic::amdgcn_buffer_atomic_xor:
7441       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7442       break;
7443     case Intrinsic::amdgcn_buffer_atomic_fadd:
7444       if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7445         DiagnosticInfoUnsupported
7446           NoFpRet(DAG.getMachineFunction().getFunction(),
7447                   "return versions of fp atomics not supported",
7448                   DL.getDebugLoc(), DS_Error);
7449         DAG.getContext()->diagnose(NoFpRet);
7450         return SDValue();
7451       }
7452       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7453       break;
7454     default:
7455       llvm_unreachable("unhandled atomic opcode");
7456     }
7457 
7458     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7459                                    M->getMemOperand());
7460   }
7461   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7462     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7463   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7464     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7465   case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7466     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7467   case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7468     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7469   case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7470     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7471   case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7472     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7473   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7474     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7475   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7476     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7477   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7478     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7479   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7480     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7481   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7482     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7483   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7484     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7485   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7486     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7487   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7488     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7489   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7490     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7491   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7492     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7493   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7494     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7495   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7496     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7497   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7498     return lowerStructBufferAtomicIntrin(Op, DAG,
7499                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7500   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7501     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7502   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7503     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7504   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7505     return lowerStructBufferAtomicIntrin(Op, DAG,
7506                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7507   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7508     return lowerStructBufferAtomicIntrin(Op, DAG,
7509                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7510   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7511     return lowerStructBufferAtomicIntrin(Op, DAG,
7512                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7513   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7514     return lowerStructBufferAtomicIntrin(Op, DAG,
7515                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7516   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7517     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7518   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7519     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7520   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7521     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7522   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7523     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7524   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7525     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7526 
7527   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7528     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7529     unsigned IdxEn = getIdxEn(Op.getOperand(5));
7530     SDValue Ops[] = {
7531       Op.getOperand(0), // Chain
7532       Op.getOperand(2), // src
7533       Op.getOperand(3), // cmp
7534       Op.getOperand(4), // rsrc
7535       Op.getOperand(5), // vindex
7536       SDValue(),        // voffset -- will be set by setBufferOffsets
7537       SDValue(),        // soffset -- will be set by setBufferOffsets
7538       SDValue(),        // offset -- will be set by setBufferOffsets
7539       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7540       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7541     };
7542     setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7543 
7544     EVT VT = Op.getValueType();
7545     auto *M = cast<MemSDNode>(Op);
7546     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7547 
7548     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7549                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7550   }
7551   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7552     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7553     SDValue Ops[] = {
7554       Op.getOperand(0), // Chain
7555       Op.getOperand(2), // src
7556       Op.getOperand(3), // cmp
7557       Op.getOperand(4), // rsrc
7558       DAG.getConstant(0, DL, MVT::i32), // vindex
7559       Offsets.first,    // voffset
7560       Op.getOperand(6), // soffset
7561       Offsets.second,   // offset
7562       Op.getOperand(7), // cachepolicy
7563       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7564     };
7565     EVT VT = Op.getValueType();
7566     auto *M = cast<MemSDNode>(Op);
7567     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]);
7568 
7569     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7570                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7571   }
7572   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7573     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7574     SDValue Ops[] = {
7575       Op.getOperand(0), // Chain
7576       Op.getOperand(2), // src
7577       Op.getOperand(3), // cmp
7578       Op.getOperand(4), // rsrc
7579       Op.getOperand(5), // vindex
7580       Offsets.first,    // voffset
7581       Op.getOperand(7), // soffset
7582       Offsets.second,   // offset
7583       Op.getOperand(8), // cachepolicy
7584       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7585     };
7586     EVT VT = Op.getValueType();
7587     auto *M = cast<MemSDNode>(Op);
7588     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7589 
7590     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7591                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7592   }
7593   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7594     MemSDNode *M = cast<MemSDNode>(Op);
7595     SDValue NodePtr = M->getOperand(2);
7596     SDValue RayExtent = M->getOperand(3);
7597     SDValue RayOrigin = M->getOperand(4);
7598     SDValue RayDir = M->getOperand(5);
7599     SDValue RayInvDir = M->getOperand(6);
7600     SDValue TDescr = M->getOperand(7);
7601 
7602     assert(NodePtr.getValueType() == MVT::i32 ||
7603            NodePtr.getValueType() == MVT::i64);
7604     assert(RayDir.getValueType() == MVT::v3f16 ||
7605            RayDir.getValueType() == MVT::v3f32);
7606 
7607     if (!Subtarget->hasGFX10_AEncoding()) {
7608       emitRemovedIntrinsicError(DAG, DL, Op.getValueType());
7609       return SDValue();
7610     }
7611 
7612     const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7613     const bool Is64 = NodePtr.getValueType() == MVT::i64;
7614     const unsigned NumVDataDwords = 4;
7615     const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
7616     const bool UseNSA = Subtarget->hasNSAEncoding() &&
7617                         NumVAddrDwords <= Subtarget->getNSAMaxSize();
7618     const unsigned BaseOpcodes[2][2] = {
7619         {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
7620         {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
7621          AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
7622     int Opcode;
7623     if (UseNSA) {
7624       Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7625                                      AMDGPU::MIMGEncGfx10NSA, NumVDataDwords,
7626                                      NumVAddrDwords);
7627     } else {
7628       Opcode = AMDGPU::getMIMGOpcode(
7629           BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords,
7630           PowerOf2Ceil(NumVAddrDwords));
7631     }
7632     assert(Opcode != -1);
7633 
7634     SmallVector<SDValue, 16> Ops;
7635 
7636     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7637       SmallVector<SDValue, 3> Lanes;
7638       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7639       if (Lanes[0].getValueSizeInBits() == 32) {
7640         for (unsigned I = 0; I < 3; ++I)
7641           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7642       } else {
7643         if (IsAligned) {
7644           Ops.push_back(
7645             DAG.getBitcast(MVT::i32,
7646                            DAG.getBuildVector(MVT::v2f16, DL,
7647                                               { Lanes[0], Lanes[1] })));
7648           Ops.push_back(Lanes[2]);
7649         } else {
7650           SDValue Elt0 = Ops.pop_back_val();
7651           Ops.push_back(
7652             DAG.getBitcast(MVT::i32,
7653                            DAG.getBuildVector(MVT::v2f16, DL,
7654                                               { Elt0, Lanes[0] })));
7655           Ops.push_back(
7656             DAG.getBitcast(MVT::i32,
7657                            DAG.getBuildVector(MVT::v2f16, DL,
7658                                               { Lanes[1], Lanes[2] })));
7659         }
7660       }
7661     };
7662 
7663     if (Is64)
7664       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7665     else
7666       Ops.push_back(NodePtr);
7667 
7668     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7669     packLanes(RayOrigin, true);
7670     packLanes(RayDir, true);
7671     packLanes(RayInvDir, false);
7672 
7673     if (!UseNSA) {
7674       // Build a single vector containing all the operands so far prepared.
7675       if (NumVAddrDwords > 8) {
7676         SDValue Undef = DAG.getUNDEF(MVT::i32);
7677         Ops.append(16 - Ops.size(), Undef);
7678       }
7679       assert(Ops.size() == 8 || Ops.size() == 16);
7680       SDValue MergedOps = DAG.getBuildVector(
7681           Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops);
7682       Ops.clear();
7683       Ops.push_back(MergedOps);
7684     }
7685 
7686     Ops.push_back(TDescr);
7687     if (IsA16)
7688       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7689     Ops.push_back(M->getChain());
7690 
7691     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7692     MachineMemOperand *MemRef = M->getMemOperand();
7693     DAG.setNodeMemRefs(NewNode, {MemRef});
7694     return SDValue(NewNode, 0);
7695   }
7696   case Intrinsic::amdgcn_global_atomic_fadd:
7697     if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7698       DiagnosticInfoUnsupported
7699         NoFpRet(DAG.getMachineFunction().getFunction(),
7700                 "return versions of fp atomics not supported",
7701                 DL.getDebugLoc(), DS_Error);
7702       DAG.getContext()->diagnose(NoFpRet);
7703       return SDValue();
7704     }
7705     LLVM_FALLTHROUGH;
7706   case Intrinsic::amdgcn_global_atomic_fmin:
7707   case Intrinsic::amdgcn_global_atomic_fmax:
7708   case Intrinsic::amdgcn_flat_atomic_fadd:
7709   case Intrinsic::amdgcn_flat_atomic_fmin:
7710   case Intrinsic::amdgcn_flat_atomic_fmax: {
7711     MemSDNode *M = cast<MemSDNode>(Op);
7712     SDValue Ops[] = {
7713       M->getOperand(0), // Chain
7714       M->getOperand(2), // Ptr
7715       M->getOperand(3)  // Value
7716     };
7717     unsigned Opcode = 0;
7718     switch (IntrID) {
7719     case Intrinsic::amdgcn_global_atomic_fadd:
7720     case Intrinsic::amdgcn_flat_atomic_fadd: {
7721       EVT VT = Op.getOperand(3).getValueType();
7722       return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7723                            DAG.getVTList(VT, MVT::Other), Ops,
7724                            M->getMemOperand());
7725     }
7726     case Intrinsic::amdgcn_global_atomic_fmin:
7727     case Intrinsic::amdgcn_flat_atomic_fmin: {
7728       Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7729       break;
7730     }
7731     case Intrinsic::amdgcn_global_atomic_fmax:
7732     case Intrinsic::amdgcn_flat_atomic_fmax: {
7733       Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7734       break;
7735     }
7736     default:
7737       llvm_unreachable("unhandled atomic opcode");
7738     }
7739     return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7740                                    M->getVTList(), Ops, M->getMemoryVT(),
7741                                    M->getMemOperand());
7742   }
7743   default:
7744 
7745     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7746             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7747       return lowerImage(Op, ImageDimIntr, DAG, true);
7748 
7749     return SDValue();
7750   }
7751 }
7752 
7753 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7754 // dwordx4 if on SI.
7755 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7756                                               SDVTList VTList,
7757                                               ArrayRef<SDValue> Ops, EVT MemVT,
7758                                               MachineMemOperand *MMO,
7759                                               SelectionDAG &DAG) const {
7760   EVT VT = VTList.VTs[0];
7761   EVT WidenedVT = VT;
7762   EVT WidenedMemVT = MemVT;
7763   if (!Subtarget->hasDwordx3LoadStores() &&
7764       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7765     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7766                                  WidenedVT.getVectorElementType(), 4);
7767     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7768                                     WidenedMemVT.getVectorElementType(), 4);
7769     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7770   }
7771 
7772   assert(VTList.NumVTs == 2);
7773   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7774 
7775   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7776                                        WidenedMemVT, MMO);
7777   if (WidenedVT != VT) {
7778     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7779                                DAG.getVectorIdxConstant(0, DL));
7780     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7781   }
7782   return NewOp;
7783 }
7784 
7785 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7786                                          bool ImageStore) const {
7787   EVT StoreVT = VData.getValueType();
7788 
7789   // No change for f16 and legal vector D16 types.
7790   if (!StoreVT.isVector())
7791     return VData;
7792 
7793   SDLoc DL(VData);
7794   unsigned NumElements = StoreVT.getVectorNumElements();
7795 
7796   if (Subtarget->hasUnpackedD16VMem()) {
7797     // We need to unpack the packed data to store.
7798     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7799     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7800 
7801     EVT EquivStoreVT =
7802         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7803     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7804     return DAG.UnrollVectorOp(ZExt.getNode());
7805   }
7806 
7807   // The sq block of gfx8.1 does not estimate register use correctly for d16
7808   // image store instructions. The data operand is computed as if it were not a
7809   // d16 image instruction.
7810   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7811     // Bitcast to i16
7812     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7813     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7814 
7815     // Decompose into scalars
7816     SmallVector<SDValue, 4> Elts;
7817     DAG.ExtractVectorElements(IntVData, Elts);
7818 
7819     // Group pairs of i16 into v2i16 and bitcast to i32
7820     SmallVector<SDValue, 4> PackedElts;
7821     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7822       SDValue Pair =
7823           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7824       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7825       PackedElts.push_back(IntPair);
7826     }
7827     if ((NumElements % 2) == 1) {
7828       // Handle v3i16
7829       unsigned I = Elts.size() / 2;
7830       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7831                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7832       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7833       PackedElts.push_back(IntPair);
7834     }
7835 
7836     // Pad using UNDEF
7837     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7838 
7839     // Build final vector
7840     EVT VecVT =
7841         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7842     return DAG.getBuildVector(VecVT, DL, PackedElts);
7843   }
7844 
7845   if (NumElements == 3) {
7846     EVT IntStoreVT =
7847         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7848     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7849 
7850     EVT WidenedStoreVT = EVT::getVectorVT(
7851         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7852     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7853                                          WidenedStoreVT.getStoreSizeInBits());
7854     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7855     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7856   }
7857 
7858   assert(isTypeLegal(StoreVT));
7859   return VData;
7860 }
7861 
7862 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7863                                               SelectionDAG &DAG) const {
7864   SDLoc DL(Op);
7865   SDValue Chain = Op.getOperand(0);
7866   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7867   MachineFunction &MF = DAG.getMachineFunction();
7868 
7869   switch (IntrinsicID) {
7870   case Intrinsic::amdgcn_exp_compr: {
7871     SDValue Src0 = Op.getOperand(4);
7872     SDValue Src1 = Op.getOperand(5);
7873     // Hack around illegal type on SI by directly selecting it.
7874     if (isTypeLegal(Src0.getValueType()))
7875       return SDValue();
7876 
7877     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7878     SDValue Undef = DAG.getUNDEF(MVT::f32);
7879     const SDValue Ops[] = {
7880       Op.getOperand(2), // tgt
7881       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7882       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7883       Undef, // src2
7884       Undef, // src3
7885       Op.getOperand(7), // vm
7886       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7887       Op.getOperand(3), // en
7888       Op.getOperand(0) // Chain
7889     };
7890 
7891     unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7892     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7893   }
7894   case Intrinsic::amdgcn_s_barrier: {
7895     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7896       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7897       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7898       if (WGSize <= ST.getWavefrontSize())
7899         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7900                                           Op.getOperand(0)), 0);
7901     }
7902     return SDValue();
7903   };
7904   case Intrinsic::amdgcn_tbuffer_store: {
7905     SDValue VData = Op.getOperand(2);
7906     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7907     if (IsD16)
7908       VData = handleD16VData(VData, DAG);
7909     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7910     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7911     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7912     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7913     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7914     SDValue Ops[] = {
7915       Chain,
7916       VData,             // vdata
7917       Op.getOperand(3),  // rsrc
7918       Op.getOperand(4),  // vindex
7919       Op.getOperand(5),  // voffset
7920       Op.getOperand(6),  // soffset
7921       Op.getOperand(7),  // offset
7922       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7923       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7924       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7925     };
7926     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7927                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7928     MemSDNode *M = cast<MemSDNode>(Op);
7929     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7930                                    M->getMemoryVT(), M->getMemOperand());
7931   }
7932 
7933   case Intrinsic::amdgcn_struct_tbuffer_store: {
7934     SDValue VData = Op.getOperand(2);
7935     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7936     if (IsD16)
7937       VData = handleD16VData(VData, DAG);
7938     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7939     SDValue Ops[] = {
7940       Chain,
7941       VData,             // vdata
7942       Op.getOperand(3),  // rsrc
7943       Op.getOperand(4),  // vindex
7944       Offsets.first,     // voffset
7945       Op.getOperand(6),  // soffset
7946       Offsets.second,    // offset
7947       Op.getOperand(7),  // format
7948       Op.getOperand(8),  // cachepolicy, swizzled buffer
7949       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7950     };
7951     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7952                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7953     MemSDNode *M = cast<MemSDNode>(Op);
7954     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7955                                    M->getMemoryVT(), M->getMemOperand());
7956   }
7957 
7958   case Intrinsic::amdgcn_raw_tbuffer_store: {
7959     SDValue VData = Op.getOperand(2);
7960     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7961     if (IsD16)
7962       VData = handleD16VData(VData, DAG);
7963     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7964     SDValue Ops[] = {
7965       Chain,
7966       VData,             // vdata
7967       Op.getOperand(3),  // rsrc
7968       DAG.getConstant(0, DL, MVT::i32), // vindex
7969       Offsets.first,     // voffset
7970       Op.getOperand(5),  // soffset
7971       Offsets.second,    // offset
7972       Op.getOperand(6),  // format
7973       Op.getOperand(7),  // cachepolicy, swizzled buffer
7974       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7975     };
7976     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7977                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7978     MemSDNode *M = cast<MemSDNode>(Op);
7979     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7980                                    M->getMemoryVT(), M->getMemOperand());
7981   }
7982 
7983   case Intrinsic::amdgcn_buffer_store:
7984   case Intrinsic::amdgcn_buffer_store_format: {
7985     SDValue VData = Op.getOperand(2);
7986     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7987     if (IsD16)
7988       VData = handleD16VData(VData, DAG);
7989     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7990     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7991     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7992     SDValue Ops[] = {
7993       Chain,
7994       VData,
7995       Op.getOperand(3), // rsrc
7996       Op.getOperand(4), // vindex
7997       SDValue(), // voffset -- will be set by setBufferOffsets
7998       SDValue(), // soffset -- will be set by setBufferOffsets
7999       SDValue(), // offset -- will be set by setBufferOffsets
8000       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
8001       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
8002     };
8003     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
8004 
8005     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
8006                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8007     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8008     MemSDNode *M = cast<MemSDNode>(Op);
8009     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8010 
8011     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8012     EVT VDataType = VData.getValueType().getScalarType();
8013     if (VDataType == MVT::i8 || VDataType == MVT::i16)
8014       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8015 
8016     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8017                                    M->getMemoryVT(), M->getMemOperand());
8018   }
8019 
8020   case Intrinsic::amdgcn_raw_buffer_store:
8021   case Intrinsic::amdgcn_raw_buffer_store_format: {
8022     const bool IsFormat =
8023         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
8024 
8025     SDValue VData = Op.getOperand(2);
8026     EVT VDataVT = VData.getValueType();
8027     EVT EltType = VDataVT.getScalarType();
8028     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8029     if (IsD16) {
8030       VData = handleD16VData(VData, DAG);
8031       VDataVT = VData.getValueType();
8032     }
8033 
8034     if (!isTypeLegal(VDataVT)) {
8035       VData =
8036           DAG.getNode(ISD::BITCAST, DL,
8037                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8038     }
8039 
8040     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
8041     SDValue Ops[] = {
8042       Chain,
8043       VData,
8044       Op.getOperand(3), // rsrc
8045       DAG.getConstant(0, DL, MVT::i32), // vindex
8046       Offsets.first,    // voffset
8047       Op.getOperand(5), // soffset
8048       Offsets.second,   // offset
8049       Op.getOperand(6), // cachepolicy, swizzled buffer
8050       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8051     };
8052     unsigned Opc =
8053         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
8054     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8055     MemSDNode *M = cast<MemSDNode>(Op);
8056     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
8057 
8058     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8059     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8060       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
8061 
8062     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8063                                    M->getMemoryVT(), M->getMemOperand());
8064   }
8065 
8066   case Intrinsic::amdgcn_struct_buffer_store:
8067   case Intrinsic::amdgcn_struct_buffer_store_format: {
8068     const bool IsFormat =
8069         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
8070 
8071     SDValue VData = Op.getOperand(2);
8072     EVT VDataVT = VData.getValueType();
8073     EVT EltType = VDataVT.getScalarType();
8074     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8075 
8076     if (IsD16) {
8077       VData = handleD16VData(VData, DAG);
8078       VDataVT = VData.getValueType();
8079     }
8080 
8081     if (!isTypeLegal(VDataVT)) {
8082       VData =
8083           DAG.getNode(ISD::BITCAST, DL,
8084                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8085     }
8086 
8087     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
8088     SDValue Ops[] = {
8089       Chain,
8090       VData,
8091       Op.getOperand(3), // rsrc
8092       Op.getOperand(4), // vindex
8093       Offsets.first,    // voffset
8094       Op.getOperand(6), // soffset
8095       Offsets.second,   // offset
8096       Op.getOperand(7), // cachepolicy, swizzled buffer
8097       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8098     };
8099     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
8100                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8101     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8102     MemSDNode *M = cast<MemSDNode>(Op);
8103     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8104 
8105     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8106     EVT VDataType = VData.getValueType().getScalarType();
8107     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8108       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8109 
8110     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8111                                    M->getMemoryVT(), M->getMemOperand());
8112   }
8113   case Intrinsic::amdgcn_end_cf:
8114     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
8115                                       Op->getOperand(2), Chain), 0);
8116 
8117   default: {
8118     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
8119             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
8120       return lowerImage(Op, ImageDimIntr, DAG, true);
8121 
8122     return Op;
8123   }
8124   }
8125 }
8126 
8127 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
8128 // offset (the offset that is included in bounds checking and swizzling, to be
8129 // split between the instruction's voffset and immoffset fields) and soffset
8130 // (the offset that is excluded from bounds checking and swizzling, to go in
8131 // the instruction's soffset field).  This function takes the first kind of
8132 // offset and figures out how to split it between voffset and immoffset.
8133 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
8134     SDValue Offset, SelectionDAG &DAG) const {
8135   SDLoc DL(Offset);
8136   const unsigned MaxImm = 4095;
8137   SDValue N0 = Offset;
8138   ConstantSDNode *C1 = nullptr;
8139 
8140   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
8141     N0 = SDValue();
8142   else if (DAG.isBaseWithConstantOffset(N0)) {
8143     C1 = cast<ConstantSDNode>(N0.getOperand(1));
8144     N0 = N0.getOperand(0);
8145   }
8146 
8147   if (C1) {
8148     unsigned ImmOffset = C1->getZExtValue();
8149     // If the immediate value is too big for the immoffset field, put the value
8150     // and -4096 into the immoffset field so that the value that is copied/added
8151     // for the voffset field is a multiple of 4096, and it stands more chance
8152     // of being CSEd with the copy/add for another similar load/store.
8153     // However, do not do that rounding down to a multiple of 4096 if that is a
8154     // negative number, as it appears to be illegal to have a negative offset
8155     // in the vgpr, even if adding the immediate offset makes it positive.
8156     unsigned Overflow = ImmOffset & ~MaxImm;
8157     ImmOffset -= Overflow;
8158     if ((int32_t)Overflow < 0) {
8159       Overflow += ImmOffset;
8160       ImmOffset = 0;
8161     }
8162     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
8163     if (Overflow) {
8164       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
8165       if (!N0)
8166         N0 = OverflowVal;
8167       else {
8168         SDValue Ops[] = { N0, OverflowVal };
8169         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
8170       }
8171     }
8172   }
8173   if (!N0)
8174     N0 = DAG.getConstant(0, DL, MVT::i32);
8175   if (!C1)
8176     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
8177   return {N0, SDValue(C1, 0)};
8178 }
8179 
8180 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
8181 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
8182 // pointed to by Offsets.
8183 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
8184                                         SelectionDAG &DAG, SDValue *Offsets,
8185                                         Align Alignment) const {
8186   SDLoc DL(CombinedOffset);
8187   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
8188     uint32_t Imm = C->getZExtValue();
8189     uint32_t SOffset, ImmOffset;
8190     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
8191                                  Alignment)) {
8192       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
8193       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8194       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8195       return;
8196     }
8197   }
8198   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
8199     SDValue N0 = CombinedOffset.getOperand(0);
8200     SDValue N1 = CombinedOffset.getOperand(1);
8201     uint32_t SOffset, ImmOffset;
8202     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
8203     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
8204                                                 Subtarget, Alignment)) {
8205       Offsets[0] = N0;
8206       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8207       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8208       return;
8209     }
8210   }
8211   Offsets[0] = CombinedOffset;
8212   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
8213   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
8214 }
8215 
8216 // Handle 8 bit and 16 bit buffer loads
8217 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
8218                                                      EVT LoadVT, SDLoc DL,
8219                                                      ArrayRef<SDValue> Ops,
8220                                                      MemSDNode *M) const {
8221   EVT IntVT = LoadVT.changeTypeToInteger();
8222   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
8223          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
8224 
8225   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
8226   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
8227                                                Ops, IntVT,
8228                                                M->getMemOperand());
8229   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
8230   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
8231 
8232   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
8233 }
8234 
8235 // Handle 8 bit and 16 bit buffer stores
8236 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
8237                                                       EVT VDataType, SDLoc DL,
8238                                                       SDValue Ops[],
8239                                                       MemSDNode *M) const {
8240   if (VDataType == MVT::f16)
8241     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
8242 
8243   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
8244   Ops[1] = BufferStoreExt;
8245   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
8246                                  AMDGPUISD::BUFFER_STORE_SHORT;
8247   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
8248   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
8249                                      M->getMemOperand());
8250 }
8251 
8252 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
8253                                  ISD::LoadExtType ExtType, SDValue Op,
8254                                  const SDLoc &SL, EVT VT) {
8255   if (VT.bitsLT(Op.getValueType()))
8256     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
8257 
8258   switch (ExtType) {
8259   case ISD::SEXTLOAD:
8260     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
8261   case ISD::ZEXTLOAD:
8262     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
8263   case ISD::EXTLOAD:
8264     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
8265   case ISD::NON_EXTLOAD:
8266     return Op;
8267   }
8268 
8269   llvm_unreachable("invalid ext type");
8270 }
8271 
8272 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
8273   SelectionDAG &DAG = DCI.DAG;
8274   if (Ld->getAlignment() < 4 || Ld->isDivergent())
8275     return SDValue();
8276 
8277   // FIXME: Constant loads should all be marked invariant.
8278   unsigned AS = Ld->getAddressSpace();
8279   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
8280       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
8281       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
8282     return SDValue();
8283 
8284   // Don't do this early, since it may interfere with adjacent load merging for
8285   // illegal types. We can avoid losing alignment information for exotic types
8286   // pre-legalize.
8287   EVT MemVT = Ld->getMemoryVT();
8288   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
8289       MemVT.getSizeInBits() >= 32)
8290     return SDValue();
8291 
8292   SDLoc SL(Ld);
8293 
8294   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
8295          "unexpected vector extload");
8296 
8297   // TODO: Drop only high part of range.
8298   SDValue Ptr = Ld->getBasePtr();
8299   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
8300                                 MVT::i32, SL, Ld->getChain(), Ptr,
8301                                 Ld->getOffset(),
8302                                 Ld->getPointerInfo(), MVT::i32,
8303                                 Ld->getAlignment(),
8304                                 Ld->getMemOperand()->getFlags(),
8305                                 Ld->getAAInfo(),
8306                                 nullptr); // Drop ranges
8307 
8308   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
8309   if (MemVT.isFloatingPoint()) {
8310     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
8311            "unexpected fp extload");
8312     TruncVT = MemVT.changeTypeToInteger();
8313   }
8314 
8315   SDValue Cvt = NewLoad;
8316   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
8317     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
8318                       DAG.getValueType(TruncVT));
8319   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
8320              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
8321     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
8322   } else {
8323     assert(Ld->getExtensionType() == ISD::EXTLOAD);
8324   }
8325 
8326   EVT VT = Ld->getValueType(0);
8327   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8328 
8329   DCI.AddToWorklist(Cvt.getNode());
8330 
8331   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
8332   // the appropriate extension from the 32-bit load.
8333   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
8334   DCI.AddToWorklist(Cvt.getNode());
8335 
8336   // Handle conversion back to floating point if necessary.
8337   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8338 
8339   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8340 }
8341 
8342 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8343   SDLoc DL(Op);
8344   LoadSDNode *Load = cast<LoadSDNode>(Op);
8345   ISD::LoadExtType ExtType = Load->getExtensionType();
8346   EVT MemVT = Load->getMemoryVT();
8347 
8348   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8349     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8350       return SDValue();
8351 
8352     // FIXME: Copied from PPC
8353     // First, load into 32 bits, then truncate to 1 bit.
8354 
8355     SDValue Chain = Load->getChain();
8356     SDValue BasePtr = Load->getBasePtr();
8357     MachineMemOperand *MMO = Load->getMemOperand();
8358 
8359     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8360 
8361     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8362                                    BasePtr, RealMemVT, MMO);
8363 
8364     if (!MemVT.isVector()) {
8365       SDValue Ops[] = {
8366         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8367         NewLD.getValue(1)
8368       };
8369 
8370       return DAG.getMergeValues(Ops, DL);
8371     }
8372 
8373     SmallVector<SDValue, 3> Elts;
8374     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8375       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8376                                 DAG.getConstant(I, DL, MVT::i32));
8377 
8378       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8379     }
8380 
8381     SDValue Ops[] = {
8382       DAG.getBuildVector(MemVT, DL, Elts),
8383       NewLD.getValue(1)
8384     };
8385 
8386     return DAG.getMergeValues(Ops, DL);
8387   }
8388 
8389   if (!MemVT.isVector())
8390     return SDValue();
8391 
8392   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8393          "Custom lowering for non-i32 vectors hasn't been implemented.");
8394 
8395   unsigned Alignment = Load->getAlignment();
8396   unsigned AS = Load->getAddressSpace();
8397   if (Subtarget->hasLDSMisalignedBug() &&
8398       AS == AMDGPUAS::FLAT_ADDRESS &&
8399       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8400     return SplitVectorLoad(Op, DAG);
8401   }
8402 
8403   MachineFunction &MF = DAG.getMachineFunction();
8404   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8405   // If there is a possibilty that flat instruction access scratch memory
8406   // then we need to use the same legalization rules we use for private.
8407   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8408       !Subtarget->hasMultiDwordFlatScratchAddressing())
8409     AS = MFI->hasFlatScratchInit() ?
8410          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8411 
8412   unsigned NumElements = MemVT.getVectorNumElements();
8413 
8414   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8415       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8416     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8417       if (MemVT.isPow2VectorType())
8418         return SDValue();
8419       return WidenOrSplitVectorLoad(Op, DAG);
8420     }
8421     // Non-uniform loads will be selected to MUBUF instructions, so they
8422     // have the same legalization requirements as global and private
8423     // loads.
8424     //
8425   }
8426 
8427   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8428       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8429       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8430     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8431         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8432         Alignment >= 4 && NumElements < 32) {
8433       if (MemVT.isPow2VectorType())
8434         return SDValue();
8435       return WidenOrSplitVectorLoad(Op, DAG);
8436     }
8437     // Non-uniform loads will be selected to MUBUF instructions, so they
8438     // have the same legalization requirements as global and private
8439     // loads.
8440     //
8441   }
8442   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8443       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8444       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8445       AS == AMDGPUAS::FLAT_ADDRESS) {
8446     if (NumElements > 4)
8447       return SplitVectorLoad(Op, DAG);
8448     // v3 loads not supported on SI.
8449     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8450       return WidenOrSplitVectorLoad(Op, DAG);
8451 
8452     // v3 and v4 loads are supported for private and global memory.
8453     return SDValue();
8454   }
8455   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8456     // Depending on the setting of the private_element_size field in the
8457     // resource descriptor, we can only make private accesses up to a certain
8458     // size.
8459     switch (Subtarget->getMaxPrivateElementSize()) {
8460     case 4: {
8461       SDValue Ops[2];
8462       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8463       return DAG.getMergeValues(Ops, DL);
8464     }
8465     case 8:
8466       if (NumElements > 2)
8467         return SplitVectorLoad(Op, DAG);
8468       return SDValue();
8469     case 16:
8470       // Same as global/flat
8471       if (NumElements > 4)
8472         return SplitVectorLoad(Op, DAG);
8473       // v3 loads not supported on SI.
8474       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8475         return WidenOrSplitVectorLoad(Op, DAG);
8476 
8477       return SDValue();
8478     default:
8479       llvm_unreachable("unsupported private_element_size");
8480     }
8481   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8482     // Use ds_read_b128 or ds_read_b96 when possible.
8483     if (Subtarget->hasDS96AndDS128() &&
8484         ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) ||
8485          MemVT.getStoreSize() == 12) &&
8486         allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8487                                            Load->getAlign()))
8488       return SDValue();
8489 
8490     if (NumElements > 2)
8491       return SplitVectorLoad(Op, DAG);
8492 
8493     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8494     // address is negative, then the instruction is incorrectly treated as
8495     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8496     // loads here to avoid emitting ds_read2_b32. We may re-combine the
8497     // load later in the SILoadStoreOptimizer.
8498     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
8499         NumElements == 2 && MemVT.getStoreSize() == 8 &&
8500         Load->getAlignment() < 8) {
8501       return SplitVectorLoad(Op, DAG);
8502     }
8503   }
8504 
8505   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8506                                       MemVT, *Load->getMemOperand())) {
8507     SDValue Ops[2];
8508     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8509     return DAG.getMergeValues(Ops, DL);
8510   }
8511 
8512   return SDValue();
8513 }
8514 
8515 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8516   EVT VT = Op.getValueType();
8517   if (VT.getSizeInBits() == 128)
8518     return splitTernaryVectorOp(Op, DAG);
8519 
8520   assert(VT.getSizeInBits() == 64);
8521 
8522   SDLoc DL(Op);
8523   SDValue Cond = Op.getOperand(0);
8524 
8525   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8526   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8527 
8528   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8529   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8530 
8531   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8532   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8533 
8534   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8535 
8536   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8537   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8538 
8539   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8540 
8541   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8542   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8543 }
8544 
8545 // Catch division cases where we can use shortcuts with rcp and rsq
8546 // instructions.
8547 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8548                                               SelectionDAG &DAG) const {
8549   SDLoc SL(Op);
8550   SDValue LHS = Op.getOperand(0);
8551   SDValue RHS = Op.getOperand(1);
8552   EVT VT = Op.getValueType();
8553   const SDNodeFlags Flags = Op->getFlags();
8554 
8555   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8556 
8557   // Without !fpmath accuracy information, we can't do more because we don't
8558   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8559   if (!AllowInaccurateRcp)
8560     return SDValue();
8561 
8562   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8563     if (CLHS->isExactlyValue(1.0)) {
8564       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8565       // the CI documentation has a worst case error of 1 ulp.
8566       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8567       // use it as long as we aren't trying to use denormals.
8568       //
8569       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8570 
8571       // 1.0 / sqrt(x) -> rsq(x)
8572 
8573       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8574       // error seems really high at 2^29 ULP.
8575       if (RHS.getOpcode() == ISD::FSQRT)
8576         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8577 
8578       // 1.0 / x -> rcp(x)
8579       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8580     }
8581 
8582     // Same as for 1.0, but expand the sign out of the constant.
8583     if (CLHS->isExactlyValue(-1.0)) {
8584       // -1.0 / x -> rcp (fneg x)
8585       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8586       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8587     }
8588   }
8589 
8590   // Turn into multiply by the reciprocal.
8591   // x / y -> x * (1.0 / y)
8592   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8593   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8594 }
8595 
8596 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8597                                                 SelectionDAG &DAG) const {
8598   SDLoc SL(Op);
8599   SDValue X = Op.getOperand(0);
8600   SDValue Y = Op.getOperand(1);
8601   EVT VT = Op.getValueType();
8602   const SDNodeFlags Flags = Op->getFlags();
8603 
8604   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8605                             DAG.getTarget().Options.UnsafeFPMath;
8606   if (!AllowInaccurateDiv)
8607     return SDValue();
8608 
8609   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8610   SDValue One = DAG.getConstantFP(1.0, SL, VT);
8611 
8612   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8613   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8614 
8615   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8616   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8617   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8618   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8619   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8620   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8621 }
8622 
8623 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8624                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8625                           SDNodeFlags Flags) {
8626   if (GlueChain->getNumValues() <= 1) {
8627     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8628   }
8629 
8630   assert(GlueChain->getNumValues() == 3);
8631 
8632   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8633   switch (Opcode) {
8634   default: llvm_unreachable("no chain equivalent for opcode");
8635   case ISD::FMUL:
8636     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8637     break;
8638   }
8639 
8640   return DAG.getNode(Opcode, SL, VTList,
8641                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8642                      Flags);
8643 }
8644 
8645 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8646                            EVT VT, SDValue A, SDValue B, SDValue C,
8647                            SDValue GlueChain, SDNodeFlags Flags) {
8648   if (GlueChain->getNumValues() <= 1) {
8649     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8650   }
8651 
8652   assert(GlueChain->getNumValues() == 3);
8653 
8654   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8655   switch (Opcode) {
8656   default: llvm_unreachable("no chain equivalent for opcode");
8657   case ISD::FMA:
8658     Opcode = AMDGPUISD::FMA_W_CHAIN;
8659     break;
8660   }
8661 
8662   return DAG.getNode(Opcode, SL, VTList,
8663                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8664                      Flags);
8665 }
8666 
8667 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8668   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8669     return FastLowered;
8670 
8671   SDLoc SL(Op);
8672   SDValue Src0 = Op.getOperand(0);
8673   SDValue Src1 = Op.getOperand(1);
8674 
8675   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8676   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8677 
8678   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8679   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8680 
8681   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8682   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8683 
8684   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8685 }
8686 
8687 // Faster 2.5 ULP division that does not support denormals.
8688 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8689   SDLoc SL(Op);
8690   SDValue LHS = Op.getOperand(1);
8691   SDValue RHS = Op.getOperand(2);
8692 
8693   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8694 
8695   const APFloat K0Val(BitsToFloat(0x6f800000));
8696   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8697 
8698   const APFloat K1Val(BitsToFloat(0x2f800000));
8699   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8700 
8701   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8702 
8703   EVT SetCCVT =
8704     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8705 
8706   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8707 
8708   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8709 
8710   // TODO: Should this propagate fast-math-flags?
8711   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8712 
8713   // rcp does not support denormals.
8714   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8715 
8716   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8717 
8718   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8719 }
8720 
8721 // Returns immediate value for setting the F32 denorm mode when using the
8722 // S_DENORM_MODE instruction.
8723 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8724                                     const SDLoc &SL, const GCNSubtarget *ST) {
8725   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8726   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8727                                 ? FP_DENORM_FLUSH_NONE
8728                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8729 
8730   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8731   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8732 }
8733 
8734 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8735   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8736     return FastLowered;
8737 
8738   // The selection matcher assumes anything with a chain selecting to a
8739   // mayRaiseFPException machine instruction. Since we're introducing a chain
8740   // here, we need to explicitly report nofpexcept for the regular fdiv
8741   // lowering.
8742   SDNodeFlags Flags = Op->getFlags();
8743   Flags.setNoFPExcept(true);
8744 
8745   SDLoc SL(Op);
8746   SDValue LHS = Op.getOperand(0);
8747   SDValue RHS = Op.getOperand(1);
8748 
8749   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8750 
8751   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8752 
8753   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8754                                           {RHS, RHS, LHS}, Flags);
8755   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8756                                         {LHS, RHS, LHS}, Flags);
8757 
8758   // Denominator is scaled to not be denormal, so using rcp is ok.
8759   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8760                                   DenominatorScaled, Flags);
8761   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8762                                      DenominatorScaled, Flags);
8763 
8764   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8765                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8766                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8767   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8768 
8769   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8770 
8771   if (!HasFP32Denormals) {
8772     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8773     // lowering. The chain dependence is insufficient, and we need glue. We do
8774     // not need the glue variants in a strictfp function.
8775 
8776     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8777 
8778     SDNode *EnableDenorm;
8779     if (Subtarget->hasDenormModeInst()) {
8780       const SDValue EnableDenormValue =
8781           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8782 
8783       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8784                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8785     } else {
8786       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8787                                                         SL, MVT::i32);
8788       EnableDenorm =
8789           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8790                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8791     }
8792 
8793     SDValue Ops[3] = {
8794       NegDivScale0,
8795       SDValue(EnableDenorm, 0),
8796       SDValue(EnableDenorm, 1)
8797     };
8798 
8799     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8800   }
8801 
8802   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8803                              ApproxRcp, One, NegDivScale0, Flags);
8804 
8805   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8806                              ApproxRcp, Fma0, Flags);
8807 
8808   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8809                            Fma1, Fma1, Flags);
8810 
8811   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8812                              NumeratorScaled, Mul, Flags);
8813 
8814   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8815                              Fma2, Fma1, Mul, Fma2, Flags);
8816 
8817   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8818                              NumeratorScaled, Fma3, Flags);
8819 
8820   if (!HasFP32Denormals) {
8821     SDNode *DisableDenorm;
8822     if (Subtarget->hasDenormModeInst()) {
8823       const SDValue DisableDenormValue =
8824           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8825 
8826       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8827                                   Fma4.getValue(1), DisableDenormValue,
8828                                   Fma4.getValue(2)).getNode();
8829     } else {
8830       const SDValue DisableDenormValue =
8831           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8832 
8833       DisableDenorm = DAG.getMachineNode(
8834           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8835           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8836     }
8837 
8838     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8839                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8840     DAG.setRoot(OutputChain);
8841   }
8842 
8843   SDValue Scale = NumeratorScaled.getValue(1);
8844   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8845                              {Fma4, Fma1, Fma3, Scale}, Flags);
8846 
8847   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8848 }
8849 
8850 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8851   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
8852     return FastLowered;
8853 
8854   SDLoc SL(Op);
8855   SDValue X = Op.getOperand(0);
8856   SDValue Y = Op.getOperand(1);
8857 
8858   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8859 
8860   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8861 
8862   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8863 
8864   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8865 
8866   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8867 
8868   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8869 
8870   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8871 
8872   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8873 
8874   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8875 
8876   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8877   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8878 
8879   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8880                              NegDivScale0, Mul, DivScale1);
8881 
8882   SDValue Scale;
8883 
8884   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8885     // Workaround a hardware bug on SI where the condition output from div_scale
8886     // is not usable.
8887 
8888     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8889 
8890     // Figure out if the scale to use for div_fmas.
8891     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8892     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8893     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8894     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8895 
8896     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8897     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8898 
8899     SDValue Scale0Hi
8900       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8901     SDValue Scale1Hi
8902       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8903 
8904     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8905     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8906     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8907   } else {
8908     Scale = DivScale1.getValue(1);
8909   }
8910 
8911   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8912                              Fma4, Fma3, Mul, Scale);
8913 
8914   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8915 }
8916 
8917 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8918   EVT VT = Op.getValueType();
8919 
8920   if (VT == MVT::f32)
8921     return LowerFDIV32(Op, DAG);
8922 
8923   if (VT == MVT::f64)
8924     return LowerFDIV64(Op, DAG);
8925 
8926   if (VT == MVT::f16)
8927     return LowerFDIV16(Op, DAG);
8928 
8929   llvm_unreachable("Unexpected type for fdiv");
8930 }
8931 
8932 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8933   SDLoc DL(Op);
8934   StoreSDNode *Store = cast<StoreSDNode>(Op);
8935   EVT VT = Store->getMemoryVT();
8936 
8937   if (VT == MVT::i1) {
8938     return DAG.getTruncStore(Store->getChain(), DL,
8939        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8940        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8941   }
8942 
8943   assert(VT.isVector() &&
8944          Store->getValue().getValueType().getScalarType() == MVT::i32);
8945 
8946   unsigned AS = Store->getAddressSpace();
8947   if (Subtarget->hasLDSMisalignedBug() &&
8948       AS == AMDGPUAS::FLAT_ADDRESS &&
8949       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8950     return SplitVectorStore(Op, DAG);
8951   }
8952 
8953   MachineFunction &MF = DAG.getMachineFunction();
8954   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8955   // If there is a possibilty that flat instruction access scratch memory
8956   // then we need to use the same legalization rules we use for private.
8957   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8958       !Subtarget->hasMultiDwordFlatScratchAddressing())
8959     AS = MFI->hasFlatScratchInit() ?
8960          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8961 
8962   unsigned NumElements = VT.getVectorNumElements();
8963   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8964       AS == AMDGPUAS::FLAT_ADDRESS) {
8965     if (NumElements > 4)
8966       return SplitVectorStore(Op, DAG);
8967     // v3 stores not supported on SI.
8968     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8969       return SplitVectorStore(Op, DAG);
8970 
8971     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8972                                         VT, *Store->getMemOperand()))
8973       return expandUnalignedStore(Store, DAG);
8974 
8975     return SDValue();
8976   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8977     switch (Subtarget->getMaxPrivateElementSize()) {
8978     case 4:
8979       return scalarizeVectorStore(Store, DAG);
8980     case 8:
8981       if (NumElements > 2)
8982         return SplitVectorStore(Op, DAG);
8983       return SDValue();
8984     case 16:
8985       if (NumElements > 4 ||
8986           (NumElements == 3 && !Subtarget->enableFlatScratch()))
8987         return SplitVectorStore(Op, DAG);
8988       return SDValue();
8989     default:
8990       llvm_unreachable("unsupported private_element_size");
8991     }
8992   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8993     // Use ds_write_b128 or ds_write_b96 when possible.
8994     if (Subtarget->hasDS96AndDS128() &&
8995         ((Subtarget->useDS128() && VT.getStoreSize() == 16) ||
8996          (VT.getStoreSize() == 12)) &&
8997         allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
8998                                            Store->getAlign()))
8999       return SDValue();
9000 
9001     if (NumElements > 2)
9002       return SplitVectorStore(Op, DAG);
9003 
9004     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
9005     // address is negative, then the instruction is incorrectly treated as
9006     // out-of-bounds even if base + offsets is in bounds. Split vectorized
9007     // stores here to avoid emitting ds_write2_b32. We may re-combine the
9008     // store later in the SILoadStoreOptimizer.
9009     if (!Subtarget->hasUsableDSOffset() &&
9010         NumElements == 2 && VT.getStoreSize() == 8 &&
9011         Store->getAlignment() < 8) {
9012       return SplitVectorStore(Op, DAG);
9013     }
9014 
9015     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
9016                                         VT, *Store->getMemOperand())) {
9017       if (VT.isVector())
9018         return SplitVectorStore(Op, DAG);
9019       return expandUnalignedStore(Store, DAG);
9020     }
9021 
9022     return SDValue();
9023   } else {
9024     llvm_unreachable("unhandled address space");
9025   }
9026 }
9027 
9028 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
9029   SDLoc DL(Op);
9030   EVT VT = Op.getValueType();
9031   SDValue Arg = Op.getOperand(0);
9032   SDValue TrigVal;
9033 
9034   // Propagate fast-math flags so that the multiply we introduce can be folded
9035   // if Arg is already the result of a multiply by constant.
9036   auto Flags = Op->getFlags();
9037 
9038   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
9039 
9040   if (Subtarget->hasTrigReducedRange()) {
9041     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9042     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
9043   } else {
9044     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9045   }
9046 
9047   switch (Op.getOpcode()) {
9048   case ISD::FCOS:
9049     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
9050   case ISD::FSIN:
9051     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
9052   default:
9053     llvm_unreachable("Wrong trig opcode");
9054   }
9055 }
9056 
9057 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9058   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
9059   assert(AtomicNode->isCompareAndSwap());
9060   unsigned AS = AtomicNode->getAddressSpace();
9061 
9062   // No custom lowering required for local address space
9063   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
9064     return Op;
9065 
9066   // Non-local address space requires custom lowering for atomic compare
9067   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
9068   SDLoc DL(Op);
9069   SDValue ChainIn = Op.getOperand(0);
9070   SDValue Addr = Op.getOperand(1);
9071   SDValue Old = Op.getOperand(2);
9072   SDValue New = Op.getOperand(3);
9073   EVT VT = Op.getValueType();
9074   MVT SimpleVT = VT.getSimpleVT();
9075   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
9076 
9077   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
9078   SDValue Ops[] = { ChainIn, Addr, NewOld };
9079 
9080   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
9081                                  Ops, VT, AtomicNode->getMemOperand());
9082 }
9083 
9084 //===----------------------------------------------------------------------===//
9085 // Custom DAG optimizations
9086 //===----------------------------------------------------------------------===//
9087 
9088 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
9089                                                      DAGCombinerInfo &DCI) const {
9090   EVT VT = N->getValueType(0);
9091   EVT ScalarVT = VT.getScalarType();
9092   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
9093     return SDValue();
9094 
9095   SelectionDAG &DAG = DCI.DAG;
9096   SDLoc DL(N);
9097 
9098   SDValue Src = N->getOperand(0);
9099   EVT SrcVT = Src.getValueType();
9100 
9101   // TODO: We could try to match extracting the higher bytes, which would be
9102   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
9103   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
9104   // about in practice.
9105   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
9106     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
9107       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
9108       DCI.AddToWorklist(Cvt.getNode());
9109 
9110       // For the f16 case, fold to a cast to f32 and then cast back to f16.
9111       if (ScalarVT != MVT::f32) {
9112         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
9113                           DAG.getTargetConstant(0, DL, MVT::i32));
9114       }
9115       return Cvt;
9116     }
9117   }
9118 
9119   return SDValue();
9120 }
9121 
9122 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
9123 
9124 // This is a variant of
9125 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
9126 //
9127 // The normal DAG combiner will do this, but only if the add has one use since
9128 // that would increase the number of instructions.
9129 //
9130 // This prevents us from seeing a constant offset that can be folded into a
9131 // memory instruction's addressing mode. If we know the resulting add offset of
9132 // a pointer can be folded into an addressing offset, we can replace the pointer
9133 // operand with the add of new constant offset. This eliminates one of the uses,
9134 // and may allow the remaining use to also be simplified.
9135 //
9136 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
9137                                                unsigned AddrSpace,
9138                                                EVT MemVT,
9139                                                DAGCombinerInfo &DCI) const {
9140   SDValue N0 = N->getOperand(0);
9141   SDValue N1 = N->getOperand(1);
9142 
9143   // We only do this to handle cases where it's profitable when there are
9144   // multiple uses of the add, so defer to the standard combine.
9145   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
9146       N0->hasOneUse())
9147     return SDValue();
9148 
9149   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
9150   if (!CN1)
9151     return SDValue();
9152 
9153   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9154   if (!CAdd)
9155     return SDValue();
9156 
9157   // If the resulting offset is too large, we can't fold it into the addressing
9158   // mode offset.
9159   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
9160   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
9161 
9162   AddrMode AM;
9163   AM.HasBaseReg = true;
9164   AM.BaseOffs = Offset.getSExtValue();
9165   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
9166     return SDValue();
9167 
9168   SelectionDAG &DAG = DCI.DAG;
9169   SDLoc SL(N);
9170   EVT VT = N->getValueType(0);
9171 
9172   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
9173   SDValue COffset = DAG.getConstant(Offset, SL, VT);
9174 
9175   SDNodeFlags Flags;
9176   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
9177                           (N0.getOpcode() == ISD::OR ||
9178                            N0->getFlags().hasNoUnsignedWrap()));
9179 
9180   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
9181 }
9182 
9183 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
9184 /// by the chain and intrinsic ID. Theoretically we would also need to check the
9185 /// specific intrinsic, but they all place the pointer operand first.
9186 static unsigned getBasePtrIndex(const MemSDNode *N) {
9187   switch (N->getOpcode()) {
9188   case ISD::STORE:
9189   case ISD::INTRINSIC_W_CHAIN:
9190   case ISD::INTRINSIC_VOID:
9191     return 2;
9192   default:
9193     return 1;
9194   }
9195 }
9196 
9197 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
9198                                                   DAGCombinerInfo &DCI) const {
9199   SelectionDAG &DAG = DCI.DAG;
9200   SDLoc SL(N);
9201 
9202   unsigned PtrIdx = getBasePtrIndex(N);
9203   SDValue Ptr = N->getOperand(PtrIdx);
9204 
9205   // TODO: We could also do this for multiplies.
9206   if (Ptr.getOpcode() == ISD::SHL) {
9207     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
9208                                           N->getMemoryVT(), DCI);
9209     if (NewPtr) {
9210       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
9211 
9212       NewOps[PtrIdx] = NewPtr;
9213       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
9214     }
9215   }
9216 
9217   return SDValue();
9218 }
9219 
9220 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
9221   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
9222          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
9223          (Opc == ISD::XOR && Val == 0);
9224 }
9225 
9226 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
9227 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
9228 // integer combine opportunities since most 64-bit operations are decomposed
9229 // this way.  TODO: We won't want this for SALU especially if it is an inline
9230 // immediate.
9231 SDValue SITargetLowering::splitBinaryBitConstantOp(
9232   DAGCombinerInfo &DCI,
9233   const SDLoc &SL,
9234   unsigned Opc, SDValue LHS,
9235   const ConstantSDNode *CRHS) const {
9236   uint64_t Val = CRHS->getZExtValue();
9237   uint32_t ValLo = Lo_32(Val);
9238   uint32_t ValHi = Hi_32(Val);
9239   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9240 
9241     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
9242          bitOpWithConstantIsReducible(Opc, ValHi)) ||
9243         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
9244     // If we need to materialize a 64-bit immediate, it will be split up later
9245     // anyway. Avoid creating the harder to understand 64-bit immediate
9246     // materialization.
9247     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
9248   }
9249 
9250   return SDValue();
9251 }
9252 
9253 // Returns true if argument is a boolean value which is not serialized into
9254 // memory or argument and does not require v_cndmask_b32 to be deserialized.
9255 static bool isBoolSGPR(SDValue V) {
9256   if (V.getValueType() != MVT::i1)
9257     return false;
9258   switch (V.getOpcode()) {
9259   default:
9260     break;
9261   case ISD::SETCC:
9262   case AMDGPUISD::FP_CLASS:
9263     return true;
9264   case ISD::AND:
9265   case ISD::OR:
9266   case ISD::XOR:
9267     return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
9268   }
9269   return false;
9270 }
9271 
9272 // If a constant has all zeroes or all ones within each byte return it.
9273 // Otherwise return 0.
9274 static uint32_t getConstantPermuteMask(uint32_t C) {
9275   // 0xff for any zero byte in the mask
9276   uint32_t ZeroByteMask = 0;
9277   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
9278   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
9279   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
9280   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
9281   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
9282   if ((NonZeroByteMask & C) != NonZeroByteMask)
9283     return 0; // Partial bytes selected.
9284   return C;
9285 }
9286 
9287 // Check if a node selects whole bytes from its operand 0 starting at a byte
9288 // boundary while masking the rest. Returns select mask as in the v_perm_b32
9289 // or -1 if not succeeded.
9290 // Note byte select encoding:
9291 // value 0-3 selects corresponding source byte;
9292 // value 0xc selects zero;
9293 // value 0xff selects 0xff.
9294 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
9295   assert(V.getValueSizeInBits() == 32);
9296 
9297   if (V.getNumOperands() != 2)
9298     return ~0;
9299 
9300   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
9301   if (!N1)
9302     return ~0;
9303 
9304   uint32_t C = N1->getZExtValue();
9305 
9306   switch (V.getOpcode()) {
9307   default:
9308     break;
9309   case ISD::AND:
9310     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9311       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
9312     }
9313     break;
9314 
9315   case ISD::OR:
9316     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9317       return (0x03020100 & ~ConstMask) | ConstMask;
9318     }
9319     break;
9320 
9321   case ISD::SHL:
9322     if (C % 8)
9323       return ~0;
9324 
9325     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
9326 
9327   case ISD::SRL:
9328     if (C % 8)
9329       return ~0;
9330 
9331     return uint32_t(0x0c0c0c0c03020100ull >> C);
9332   }
9333 
9334   return ~0;
9335 }
9336 
9337 SDValue SITargetLowering::performAndCombine(SDNode *N,
9338                                             DAGCombinerInfo &DCI) const {
9339   if (DCI.isBeforeLegalize())
9340     return SDValue();
9341 
9342   SelectionDAG &DAG = DCI.DAG;
9343   EVT VT = N->getValueType(0);
9344   SDValue LHS = N->getOperand(0);
9345   SDValue RHS = N->getOperand(1);
9346 
9347 
9348   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9349   if (VT == MVT::i64 && CRHS) {
9350     if (SDValue Split
9351         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9352       return Split;
9353   }
9354 
9355   if (CRHS && VT == MVT::i32) {
9356     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9357     // nb = number of trailing zeroes in mask
9358     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9359     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9360     uint64_t Mask = CRHS->getZExtValue();
9361     unsigned Bits = countPopulation(Mask);
9362     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9363         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9364       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9365         unsigned Shift = CShift->getZExtValue();
9366         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9367         unsigned Offset = NB + Shift;
9368         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9369           SDLoc SL(N);
9370           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9371                                     LHS->getOperand(0),
9372                                     DAG.getConstant(Offset, SL, MVT::i32),
9373                                     DAG.getConstant(Bits, SL, MVT::i32));
9374           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9375           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9376                                     DAG.getValueType(NarrowVT));
9377           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9378                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9379           return Shl;
9380         }
9381       }
9382     }
9383 
9384     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9385     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9386         isa<ConstantSDNode>(LHS.getOperand(2))) {
9387       uint32_t Sel = getConstantPermuteMask(Mask);
9388       if (!Sel)
9389         return SDValue();
9390 
9391       // Select 0xc for all zero bytes
9392       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9393       SDLoc DL(N);
9394       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9395                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9396     }
9397   }
9398 
9399   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9400   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9401   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9402     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9403     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9404 
9405     SDValue X = LHS.getOperand(0);
9406     SDValue Y = RHS.getOperand(0);
9407     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9408       return SDValue();
9409 
9410     if (LCC == ISD::SETO) {
9411       if (X != LHS.getOperand(1))
9412         return SDValue();
9413 
9414       if (RCC == ISD::SETUNE) {
9415         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9416         if (!C1 || !C1->isInfinity() || C1->isNegative())
9417           return SDValue();
9418 
9419         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9420                               SIInstrFlags::N_SUBNORMAL |
9421                               SIInstrFlags::N_ZERO |
9422                               SIInstrFlags::P_ZERO |
9423                               SIInstrFlags::P_SUBNORMAL |
9424                               SIInstrFlags::P_NORMAL;
9425 
9426         static_assert(((~(SIInstrFlags::S_NAN |
9427                           SIInstrFlags::Q_NAN |
9428                           SIInstrFlags::N_INFINITY |
9429                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9430                       "mask not equal");
9431 
9432         SDLoc DL(N);
9433         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9434                            X, DAG.getConstant(Mask, DL, MVT::i32));
9435       }
9436     }
9437   }
9438 
9439   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9440     std::swap(LHS, RHS);
9441 
9442   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9443       RHS.hasOneUse()) {
9444     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9445     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9446     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9447     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9448     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9449         (RHS.getOperand(0) == LHS.getOperand(0) &&
9450          LHS.getOperand(0) == LHS.getOperand(1))) {
9451       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9452       unsigned NewMask = LCC == ISD::SETO ?
9453         Mask->getZExtValue() & ~OrdMask :
9454         Mask->getZExtValue() & OrdMask;
9455 
9456       SDLoc DL(N);
9457       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9458                          DAG.getConstant(NewMask, DL, MVT::i32));
9459     }
9460   }
9461 
9462   if (VT == MVT::i32 &&
9463       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9464     // and x, (sext cc from i1) => select cc, x, 0
9465     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9466       std::swap(LHS, RHS);
9467     if (isBoolSGPR(RHS.getOperand(0)))
9468       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9469                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9470   }
9471 
9472   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9473   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9474   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9475       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9476     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9477     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9478     if (LHSMask != ~0u && RHSMask != ~0u) {
9479       // Canonicalize the expression in an attempt to have fewer unique masks
9480       // and therefore fewer registers used to hold the masks.
9481       if (LHSMask > RHSMask) {
9482         std::swap(LHSMask, RHSMask);
9483         std::swap(LHS, RHS);
9484       }
9485 
9486       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9487       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9488       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9489       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9490 
9491       // Check of we need to combine values from two sources within a byte.
9492       if (!(LHSUsedLanes & RHSUsedLanes) &&
9493           // If we select high and lower word keep it for SDWA.
9494           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9495           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9496         // Each byte in each mask is either selector mask 0-3, or has higher
9497         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9498         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9499         // mask which is not 0xff wins. By anding both masks we have a correct
9500         // result except that 0x0c shall be corrected to give 0x0c only.
9501         uint32_t Mask = LHSMask & RHSMask;
9502         for (unsigned I = 0; I < 32; I += 8) {
9503           uint32_t ByteSel = 0xff << I;
9504           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9505             Mask &= (0x0c << I) & 0xffffffff;
9506         }
9507 
9508         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9509         // or 0x0c.
9510         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9511         SDLoc DL(N);
9512 
9513         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9514                            LHS.getOperand(0), RHS.getOperand(0),
9515                            DAG.getConstant(Sel, DL, MVT::i32));
9516       }
9517     }
9518   }
9519 
9520   return SDValue();
9521 }
9522 
9523 SDValue SITargetLowering::performOrCombine(SDNode *N,
9524                                            DAGCombinerInfo &DCI) const {
9525   SelectionDAG &DAG = DCI.DAG;
9526   SDValue LHS = N->getOperand(0);
9527   SDValue RHS = N->getOperand(1);
9528 
9529   EVT VT = N->getValueType(0);
9530   if (VT == MVT::i1) {
9531     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9532     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9533         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9534       SDValue Src = LHS.getOperand(0);
9535       if (Src != RHS.getOperand(0))
9536         return SDValue();
9537 
9538       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9539       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9540       if (!CLHS || !CRHS)
9541         return SDValue();
9542 
9543       // Only 10 bits are used.
9544       static const uint32_t MaxMask = 0x3ff;
9545 
9546       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9547       SDLoc DL(N);
9548       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9549                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9550     }
9551 
9552     return SDValue();
9553   }
9554 
9555   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9556   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9557       LHS.getOpcode() == AMDGPUISD::PERM &&
9558       isa<ConstantSDNode>(LHS.getOperand(2))) {
9559     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9560     if (!Sel)
9561       return SDValue();
9562 
9563     Sel |= LHS.getConstantOperandVal(2);
9564     SDLoc DL(N);
9565     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9566                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9567   }
9568 
9569   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9570   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9571   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9572       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9573     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9574     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9575     if (LHSMask != ~0u && RHSMask != ~0u) {
9576       // Canonicalize the expression in an attempt to have fewer unique masks
9577       // and therefore fewer registers used to hold the masks.
9578       if (LHSMask > RHSMask) {
9579         std::swap(LHSMask, RHSMask);
9580         std::swap(LHS, RHS);
9581       }
9582 
9583       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9584       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9585       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9586       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9587 
9588       // Check of we need to combine values from two sources within a byte.
9589       if (!(LHSUsedLanes & RHSUsedLanes) &&
9590           // If we select high and lower word keep it for SDWA.
9591           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9592           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9593         // Kill zero bytes selected by other mask. Zero value is 0xc.
9594         LHSMask &= ~RHSUsedLanes;
9595         RHSMask &= ~LHSUsedLanes;
9596         // Add 4 to each active LHS lane
9597         LHSMask |= LHSUsedLanes & 0x04040404;
9598         // Combine masks
9599         uint32_t Sel = LHSMask | RHSMask;
9600         SDLoc DL(N);
9601 
9602         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9603                            LHS.getOperand(0), RHS.getOperand(0),
9604                            DAG.getConstant(Sel, DL, MVT::i32));
9605       }
9606     }
9607   }
9608 
9609   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9610     return SDValue();
9611 
9612   // TODO: This could be a generic combine with a predicate for extracting the
9613   // high half of an integer being free.
9614 
9615   // (or i64:x, (zero_extend i32:y)) ->
9616   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9617   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9618       RHS.getOpcode() != ISD::ZERO_EXTEND)
9619     std::swap(LHS, RHS);
9620 
9621   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9622     SDValue ExtSrc = RHS.getOperand(0);
9623     EVT SrcVT = ExtSrc.getValueType();
9624     if (SrcVT == MVT::i32) {
9625       SDLoc SL(N);
9626       SDValue LowLHS, HiBits;
9627       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9628       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9629 
9630       DCI.AddToWorklist(LowOr.getNode());
9631       DCI.AddToWorklist(HiBits.getNode());
9632 
9633       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9634                                 LowOr, HiBits);
9635       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9636     }
9637   }
9638 
9639   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9640   if (CRHS) {
9641     if (SDValue Split
9642           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR,
9643                                      N->getOperand(0), CRHS))
9644       return Split;
9645   }
9646 
9647   return SDValue();
9648 }
9649 
9650 SDValue SITargetLowering::performXorCombine(SDNode *N,
9651                                             DAGCombinerInfo &DCI) const {
9652   if (SDValue RV = reassociateScalarOps(N, DCI.DAG))
9653     return RV;
9654 
9655   EVT VT = N->getValueType(0);
9656   if (VT != MVT::i64)
9657     return SDValue();
9658 
9659   SDValue LHS = N->getOperand(0);
9660   SDValue RHS = N->getOperand(1);
9661 
9662   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9663   if (CRHS) {
9664     if (SDValue Split
9665           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9666       return Split;
9667   }
9668 
9669   return SDValue();
9670 }
9671 
9672 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9673                                                    DAGCombinerInfo &DCI) const {
9674   if (!Subtarget->has16BitInsts() ||
9675       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9676     return SDValue();
9677 
9678   EVT VT = N->getValueType(0);
9679   if (VT != MVT::i32)
9680     return SDValue();
9681 
9682   SDValue Src = N->getOperand(0);
9683   if (Src.getValueType() != MVT::i16)
9684     return SDValue();
9685 
9686   return SDValue();
9687 }
9688 
9689 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9690                                                         DAGCombinerInfo &DCI)
9691                                                         const {
9692   SDValue Src = N->getOperand(0);
9693   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9694 
9695   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9696       VTSign->getVT() == MVT::i8) ||
9697       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9698       VTSign->getVT() == MVT::i16)) &&
9699       Src.hasOneUse()) {
9700     auto *M = cast<MemSDNode>(Src);
9701     SDValue Ops[] = {
9702       Src.getOperand(0), // Chain
9703       Src.getOperand(1), // rsrc
9704       Src.getOperand(2), // vindex
9705       Src.getOperand(3), // voffset
9706       Src.getOperand(4), // soffset
9707       Src.getOperand(5), // offset
9708       Src.getOperand(6),
9709       Src.getOperand(7)
9710     };
9711     // replace with BUFFER_LOAD_BYTE/SHORT
9712     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9713                                          Src.getOperand(0).getValueType());
9714     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9715                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9716     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9717                                                           ResList,
9718                                                           Ops, M->getMemoryVT(),
9719                                                           M->getMemOperand());
9720     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9721                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9722   }
9723   return SDValue();
9724 }
9725 
9726 SDValue SITargetLowering::performClassCombine(SDNode *N,
9727                                               DAGCombinerInfo &DCI) const {
9728   SelectionDAG &DAG = DCI.DAG;
9729   SDValue Mask = N->getOperand(1);
9730 
9731   // fp_class x, 0 -> false
9732   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9733     if (CMask->isZero())
9734       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9735   }
9736 
9737   if (N->getOperand(0).isUndef())
9738     return DAG.getUNDEF(MVT::i1);
9739 
9740   return SDValue();
9741 }
9742 
9743 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9744                                             DAGCombinerInfo &DCI) const {
9745   EVT VT = N->getValueType(0);
9746   SDValue N0 = N->getOperand(0);
9747 
9748   if (N0.isUndef())
9749     return N0;
9750 
9751   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9752                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9753     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9754                            N->getFlags());
9755   }
9756 
9757   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9758     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9759                            N0.getOperand(0), N->getFlags());
9760   }
9761 
9762   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9763 }
9764 
9765 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9766                                        unsigned MaxDepth) const {
9767   unsigned Opcode = Op.getOpcode();
9768   if (Opcode == ISD::FCANONICALIZE)
9769     return true;
9770 
9771   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9772     auto F = CFP->getValueAPF();
9773     if (F.isNaN() && F.isSignaling())
9774       return false;
9775     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9776   }
9777 
9778   // If source is a result of another standard FP operation it is already in
9779   // canonical form.
9780   if (MaxDepth == 0)
9781     return false;
9782 
9783   switch (Opcode) {
9784   // These will flush denorms if required.
9785   case ISD::FADD:
9786   case ISD::FSUB:
9787   case ISD::FMUL:
9788   case ISD::FCEIL:
9789   case ISD::FFLOOR:
9790   case ISD::FMA:
9791   case ISD::FMAD:
9792   case ISD::FSQRT:
9793   case ISD::FDIV:
9794   case ISD::FREM:
9795   case ISD::FP_ROUND:
9796   case ISD::FP_EXTEND:
9797   case AMDGPUISD::FMUL_LEGACY:
9798   case AMDGPUISD::FMAD_FTZ:
9799   case AMDGPUISD::RCP:
9800   case AMDGPUISD::RSQ:
9801   case AMDGPUISD::RSQ_CLAMP:
9802   case AMDGPUISD::RCP_LEGACY:
9803   case AMDGPUISD::RCP_IFLAG:
9804   case AMDGPUISD::DIV_SCALE:
9805   case AMDGPUISD::DIV_FMAS:
9806   case AMDGPUISD::DIV_FIXUP:
9807   case AMDGPUISD::FRACT:
9808   case AMDGPUISD::LDEXP:
9809   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9810   case AMDGPUISD::CVT_F32_UBYTE0:
9811   case AMDGPUISD::CVT_F32_UBYTE1:
9812   case AMDGPUISD::CVT_F32_UBYTE2:
9813   case AMDGPUISD::CVT_F32_UBYTE3:
9814     return true;
9815 
9816   // It can/will be lowered or combined as a bit operation.
9817   // Need to check their input recursively to handle.
9818   case ISD::FNEG:
9819   case ISD::FABS:
9820   case ISD::FCOPYSIGN:
9821     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9822 
9823   case ISD::FSIN:
9824   case ISD::FCOS:
9825   case ISD::FSINCOS:
9826     return Op.getValueType().getScalarType() != MVT::f16;
9827 
9828   case ISD::FMINNUM:
9829   case ISD::FMAXNUM:
9830   case ISD::FMINNUM_IEEE:
9831   case ISD::FMAXNUM_IEEE:
9832   case AMDGPUISD::CLAMP:
9833   case AMDGPUISD::FMED3:
9834   case AMDGPUISD::FMAX3:
9835   case AMDGPUISD::FMIN3: {
9836     // FIXME: Shouldn't treat the generic operations different based these.
9837     // However, we aren't really required to flush the result from
9838     // minnum/maxnum..
9839 
9840     // snans will be quieted, so we only need to worry about denormals.
9841     if (Subtarget->supportsMinMaxDenormModes() ||
9842         denormalsEnabledForType(DAG, Op.getValueType()))
9843       return true;
9844 
9845     // Flushing may be required.
9846     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9847     // targets need to check their input recursively.
9848 
9849     // FIXME: Does this apply with clamp? It's implemented with max.
9850     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9851       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9852         return false;
9853     }
9854 
9855     return true;
9856   }
9857   case ISD::SELECT: {
9858     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9859            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9860   }
9861   case ISD::BUILD_VECTOR: {
9862     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9863       SDValue SrcOp = Op.getOperand(i);
9864       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9865         return false;
9866     }
9867 
9868     return true;
9869   }
9870   case ISD::EXTRACT_VECTOR_ELT:
9871   case ISD::EXTRACT_SUBVECTOR: {
9872     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9873   }
9874   case ISD::INSERT_VECTOR_ELT: {
9875     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9876            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9877   }
9878   case ISD::UNDEF:
9879     // Could be anything.
9880     return false;
9881 
9882   case ISD::BITCAST:
9883     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9884   case ISD::TRUNCATE: {
9885     // Hack round the mess we make when legalizing extract_vector_elt
9886     if (Op.getValueType() == MVT::i16) {
9887       SDValue TruncSrc = Op.getOperand(0);
9888       if (TruncSrc.getValueType() == MVT::i32 &&
9889           TruncSrc.getOpcode() == ISD::BITCAST &&
9890           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9891         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9892       }
9893     }
9894     return false;
9895   }
9896   case ISD::INTRINSIC_WO_CHAIN: {
9897     unsigned IntrinsicID
9898       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9899     // TODO: Handle more intrinsics
9900     switch (IntrinsicID) {
9901     case Intrinsic::amdgcn_cvt_pkrtz:
9902     case Intrinsic::amdgcn_cubeid:
9903     case Intrinsic::amdgcn_frexp_mant:
9904     case Intrinsic::amdgcn_fdot2:
9905     case Intrinsic::amdgcn_rcp:
9906     case Intrinsic::amdgcn_rsq:
9907     case Intrinsic::amdgcn_rsq_clamp:
9908     case Intrinsic::amdgcn_rcp_legacy:
9909     case Intrinsic::amdgcn_rsq_legacy:
9910     case Intrinsic::amdgcn_trig_preop:
9911       return true;
9912     default:
9913       break;
9914     }
9915 
9916     LLVM_FALLTHROUGH;
9917   }
9918   default:
9919     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9920            DAG.isKnownNeverSNaN(Op);
9921   }
9922 
9923   llvm_unreachable("invalid operation");
9924 }
9925 
9926 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
9927                                        unsigned MaxDepth) const {
9928   MachineRegisterInfo &MRI = MF.getRegInfo();
9929   MachineInstr *MI = MRI.getVRegDef(Reg);
9930   unsigned Opcode = MI->getOpcode();
9931 
9932   if (Opcode == AMDGPU::G_FCANONICALIZE)
9933     return true;
9934 
9935   Optional<FPValueAndVReg> FCR;
9936   // Constant splat (can be padded with undef) or scalar constant.
9937   if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) {
9938     if (FCR->Value.isSignaling())
9939       return false;
9940     return !FCR->Value.isDenormal() ||
9941            denormalsEnabledForType(MRI.getType(FCR->VReg), MF);
9942   }
9943 
9944   if (MaxDepth == 0)
9945     return false;
9946 
9947   switch (Opcode) {
9948   case AMDGPU::G_FMINNUM_IEEE:
9949   case AMDGPU::G_FMAXNUM_IEEE: {
9950     if (Subtarget->supportsMinMaxDenormModes() ||
9951         denormalsEnabledForType(MRI.getType(Reg), MF))
9952       return true;
9953     for (const MachineOperand &MO : llvm::drop_begin(MI->operands()))
9954       if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1))
9955         return false;
9956     return true;
9957   }
9958   default:
9959     return denormalsEnabledForType(MRI.getType(Reg), MF) &&
9960            isKnownNeverSNaN(Reg, MRI);
9961   }
9962 
9963   llvm_unreachable("invalid operation");
9964 }
9965 
9966 // Constant fold canonicalize.
9967 SDValue SITargetLowering::getCanonicalConstantFP(
9968   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9969   // Flush denormals to 0 if not enabled.
9970   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9971     return DAG.getConstantFP(0.0, SL, VT);
9972 
9973   if (C.isNaN()) {
9974     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9975     if (C.isSignaling()) {
9976       // Quiet a signaling NaN.
9977       // FIXME: Is this supposed to preserve payload bits?
9978       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9979     }
9980 
9981     // Make sure it is the canonical NaN bitpattern.
9982     //
9983     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9984     // immediate?
9985     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9986       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9987   }
9988 
9989   // Already canonical.
9990   return DAG.getConstantFP(C, SL, VT);
9991 }
9992 
9993 static bool vectorEltWillFoldAway(SDValue Op) {
9994   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9995 }
9996 
9997 SDValue SITargetLowering::performFCanonicalizeCombine(
9998   SDNode *N,
9999   DAGCombinerInfo &DCI) const {
10000   SelectionDAG &DAG = DCI.DAG;
10001   SDValue N0 = N->getOperand(0);
10002   EVT VT = N->getValueType(0);
10003 
10004   // fcanonicalize undef -> qnan
10005   if (N0.isUndef()) {
10006     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
10007     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
10008   }
10009 
10010   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
10011     EVT VT = N->getValueType(0);
10012     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
10013   }
10014 
10015   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
10016   //                                                   (fcanonicalize k)
10017   //
10018   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
10019 
10020   // TODO: This could be better with wider vectors that will be split to v2f16,
10021   // and to consider uses since there aren't that many packed operations.
10022   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
10023       isTypeLegal(MVT::v2f16)) {
10024     SDLoc SL(N);
10025     SDValue NewElts[2];
10026     SDValue Lo = N0.getOperand(0);
10027     SDValue Hi = N0.getOperand(1);
10028     EVT EltVT = Lo.getValueType();
10029 
10030     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
10031       for (unsigned I = 0; I != 2; ++I) {
10032         SDValue Op = N0.getOperand(I);
10033         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
10034           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
10035                                               CFP->getValueAPF());
10036         } else if (Op.isUndef()) {
10037           // Handled below based on what the other operand is.
10038           NewElts[I] = Op;
10039         } else {
10040           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
10041         }
10042       }
10043 
10044       // If one half is undef, and one is constant, perfer a splat vector rather
10045       // than the normal qNaN. If it's a register, prefer 0.0 since that's
10046       // cheaper to use and may be free with a packed operation.
10047       if (NewElts[0].isUndef()) {
10048         if (isa<ConstantFPSDNode>(NewElts[1]))
10049           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
10050             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
10051       }
10052 
10053       if (NewElts[1].isUndef()) {
10054         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
10055           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
10056       }
10057 
10058       return DAG.getBuildVector(VT, SL, NewElts);
10059     }
10060   }
10061 
10062   unsigned SrcOpc = N0.getOpcode();
10063 
10064   // If it's free to do so, push canonicalizes further up the source, which may
10065   // find a canonical source.
10066   //
10067   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
10068   // sNaNs.
10069   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
10070     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10071     if (CRHS && N0.hasOneUse()) {
10072       SDLoc SL(N);
10073       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
10074                                    N0.getOperand(0));
10075       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
10076       DCI.AddToWorklist(Canon0.getNode());
10077 
10078       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
10079     }
10080   }
10081 
10082   return isCanonicalized(DAG, N0) ? N0 : SDValue();
10083 }
10084 
10085 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
10086   switch (Opc) {
10087   case ISD::FMAXNUM:
10088   case ISD::FMAXNUM_IEEE:
10089     return AMDGPUISD::FMAX3;
10090   case ISD::SMAX:
10091     return AMDGPUISD::SMAX3;
10092   case ISD::UMAX:
10093     return AMDGPUISD::UMAX3;
10094   case ISD::FMINNUM:
10095   case ISD::FMINNUM_IEEE:
10096     return AMDGPUISD::FMIN3;
10097   case ISD::SMIN:
10098     return AMDGPUISD::SMIN3;
10099   case ISD::UMIN:
10100     return AMDGPUISD::UMIN3;
10101   default:
10102     llvm_unreachable("Not a min/max opcode");
10103   }
10104 }
10105 
10106 SDValue SITargetLowering::performIntMed3ImmCombine(
10107   SelectionDAG &DAG, const SDLoc &SL,
10108   SDValue Op0, SDValue Op1, bool Signed) const {
10109   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
10110   if (!K1)
10111     return SDValue();
10112 
10113   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
10114   if (!K0)
10115     return SDValue();
10116 
10117   if (Signed) {
10118     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
10119       return SDValue();
10120   } else {
10121     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
10122       return SDValue();
10123   }
10124 
10125   EVT VT = K0->getValueType(0);
10126   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
10127   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
10128     return DAG.getNode(Med3Opc, SL, VT,
10129                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
10130   }
10131 
10132   // If there isn't a 16-bit med3 operation, convert to 32-bit.
10133   if (VT == MVT::i16) {
10134     MVT NVT = MVT::i32;
10135     unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
10136 
10137     SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
10138     SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
10139     SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
10140 
10141     SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
10142     return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
10143   }
10144 
10145   return SDValue();
10146 }
10147 
10148 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
10149   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
10150     return C;
10151 
10152   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
10153     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
10154       return C;
10155   }
10156 
10157   return nullptr;
10158 }
10159 
10160 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
10161                                                   const SDLoc &SL,
10162                                                   SDValue Op0,
10163                                                   SDValue Op1) const {
10164   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
10165   if (!K1)
10166     return SDValue();
10167 
10168   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
10169   if (!K0)
10170     return SDValue();
10171 
10172   // Ordered >= (although NaN inputs should have folded away by now).
10173   if (K0->getValueAPF() > K1->getValueAPF())
10174     return SDValue();
10175 
10176   const MachineFunction &MF = DAG.getMachineFunction();
10177   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10178 
10179   // TODO: Check IEEE bit enabled?
10180   EVT VT = Op0.getValueType();
10181   if (Info->getMode().DX10Clamp) {
10182     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
10183     // hardware fmed3 behavior converting to a min.
10184     // FIXME: Should this be allowing -0.0?
10185     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
10186       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
10187   }
10188 
10189   // med3 for f16 is only available on gfx9+, and not available for v2f16.
10190   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
10191     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
10192     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
10193     // then give the other result, which is different from med3 with a NaN
10194     // input.
10195     SDValue Var = Op0.getOperand(0);
10196     if (!DAG.isKnownNeverSNaN(Var))
10197       return SDValue();
10198 
10199     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10200 
10201     if ((!K0->hasOneUse() ||
10202          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
10203         (!K1->hasOneUse() ||
10204          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
10205       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
10206                          Var, SDValue(K0, 0), SDValue(K1, 0));
10207     }
10208   }
10209 
10210   return SDValue();
10211 }
10212 
10213 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
10214                                                DAGCombinerInfo &DCI) const {
10215   SelectionDAG &DAG = DCI.DAG;
10216 
10217   EVT VT = N->getValueType(0);
10218   unsigned Opc = N->getOpcode();
10219   SDValue Op0 = N->getOperand(0);
10220   SDValue Op1 = N->getOperand(1);
10221 
10222   // Only do this if the inner op has one use since this will just increases
10223   // register pressure for no benefit.
10224 
10225   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
10226       !VT.isVector() &&
10227       (VT == MVT::i32 || VT == MVT::f32 ||
10228        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
10229     // max(max(a, b), c) -> max3(a, b, c)
10230     // min(min(a, b), c) -> min3(a, b, c)
10231     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
10232       SDLoc DL(N);
10233       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10234                          DL,
10235                          N->getValueType(0),
10236                          Op0.getOperand(0),
10237                          Op0.getOperand(1),
10238                          Op1);
10239     }
10240 
10241     // Try commuted.
10242     // max(a, max(b, c)) -> max3(a, b, c)
10243     // min(a, min(b, c)) -> min3(a, b, c)
10244     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
10245       SDLoc DL(N);
10246       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10247                          DL,
10248                          N->getValueType(0),
10249                          Op0,
10250                          Op1.getOperand(0),
10251                          Op1.getOperand(1));
10252     }
10253   }
10254 
10255   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
10256   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
10257     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
10258       return Med3;
10259   }
10260 
10261   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
10262     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
10263       return Med3;
10264   }
10265 
10266   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
10267   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
10268        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
10269        (Opc == AMDGPUISD::FMIN_LEGACY &&
10270         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
10271       (VT == MVT::f32 || VT == MVT::f64 ||
10272        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
10273        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
10274       Op0.hasOneUse()) {
10275     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
10276       return Res;
10277   }
10278 
10279   return SDValue();
10280 }
10281 
10282 static bool isClampZeroToOne(SDValue A, SDValue B) {
10283   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
10284     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
10285       // FIXME: Should this be allowing -0.0?
10286       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
10287              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
10288     }
10289   }
10290 
10291   return false;
10292 }
10293 
10294 // FIXME: Should only worry about snans for version with chain.
10295 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
10296                                               DAGCombinerInfo &DCI) const {
10297   EVT VT = N->getValueType(0);
10298   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
10299   // NaNs. With a NaN input, the order of the operands may change the result.
10300 
10301   SelectionDAG &DAG = DCI.DAG;
10302   SDLoc SL(N);
10303 
10304   SDValue Src0 = N->getOperand(0);
10305   SDValue Src1 = N->getOperand(1);
10306   SDValue Src2 = N->getOperand(2);
10307 
10308   if (isClampZeroToOne(Src0, Src1)) {
10309     // const_a, const_b, x -> clamp is safe in all cases including signaling
10310     // nans.
10311     // FIXME: Should this be allowing -0.0?
10312     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
10313   }
10314 
10315   const MachineFunction &MF = DAG.getMachineFunction();
10316   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10317 
10318   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
10319   // handling no dx10-clamp?
10320   if (Info->getMode().DX10Clamp) {
10321     // If NaNs is clamped to 0, we are free to reorder the inputs.
10322 
10323     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10324       std::swap(Src0, Src1);
10325 
10326     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10327       std::swap(Src1, Src2);
10328 
10329     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10330       std::swap(Src0, Src1);
10331 
10332     if (isClampZeroToOne(Src1, Src2))
10333       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10334   }
10335 
10336   return SDValue();
10337 }
10338 
10339 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10340                                                  DAGCombinerInfo &DCI) const {
10341   SDValue Src0 = N->getOperand(0);
10342   SDValue Src1 = N->getOperand(1);
10343   if (Src0.isUndef() && Src1.isUndef())
10344     return DCI.DAG.getUNDEF(N->getValueType(0));
10345   return SDValue();
10346 }
10347 
10348 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10349 // expanded into a set of cmp/select instructions.
10350 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10351                                                 unsigned NumElem,
10352                                                 bool IsDivergentIdx) {
10353   if (UseDivergentRegisterIndexing)
10354     return false;
10355 
10356   unsigned VecSize = EltSize * NumElem;
10357 
10358   // Sub-dword vectors of size 2 dword or less have better implementation.
10359   if (VecSize <= 64 && EltSize < 32)
10360     return false;
10361 
10362   // Always expand the rest of sub-dword instructions, otherwise it will be
10363   // lowered via memory.
10364   if (EltSize < 32)
10365     return true;
10366 
10367   // Always do this if var-idx is divergent, otherwise it will become a loop.
10368   if (IsDivergentIdx)
10369     return true;
10370 
10371   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10372   unsigned NumInsts = NumElem /* Number of compares */ +
10373                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10374   return NumInsts <= 16;
10375 }
10376 
10377 static bool shouldExpandVectorDynExt(SDNode *N) {
10378   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10379   if (isa<ConstantSDNode>(Idx))
10380     return false;
10381 
10382   SDValue Vec = N->getOperand(0);
10383   EVT VecVT = Vec.getValueType();
10384   EVT EltVT = VecVT.getVectorElementType();
10385   unsigned EltSize = EltVT.getSizeInBits();
10386   unsigned NumElem = VecVT.getVectorNumElements();
10387 
10388   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
10389                                                     Idx->isDivergent());
10390 }
10391 
10392 SDValue SITargetLowering::performExtractVectorEltCombine(
10393   SDNode *N, DAGCombinerInfo &DCI) const {
10394   SDValue Vec = N->getOperand(0);
10395   SelectionDAG &DAG = DCI.DAG;
10396 
10397   EVT VecVT = Vec.getValueType();
10398   EVT EltVT = VecVT.getVectorElementType();
10399 
10400   if ((Vec.getOpcode() == ISD::FNEG ||
10401        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10402     SDLoc SL(N);
10403     EVT EltVT = N->getValueType(0);
10404     SDValue Idx = N->getOperand(1);
10405     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10406                               Vec.getOperand(0), Idx);
10407     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10408   }
10409 
10410   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10411   //    =>
10412   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10413   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10414   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10415   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10416     SDLoc SL(N);
10417     EVT EltVT = N->getValueType(0);
10418     SDValue Idx = N->getOperand(1);
10419     unsigned Opc = Vec.getOpcode();
10420 
10421     switch(Opc) {
10422     default:
10423       break;
10424       // TODO: Support other binary operations.
10425     case ISD::FADD:
10426     case ISD::FSUB:
10427     case ISD::FMUL:
10428     case ISD::ADD:
10429     case ISD::UMIN:
10430     case ISD::UMAX:
10431     case ISD::SMIN:
10432     case ISD::SMAX:
10433     case ISD::FMAXNUM:
10434     case ISD::FMINNUM:
10435     case ISD::FMAXNUM_IEEE:
10436     case ISD::FMINNUM_IEEE: {
10437       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10438                                  Vec.getOperand(0), Idx);
10439       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10440                                  Vec.getOperand(1), Idx);
10441 
10442       DCI.AddToWorklist(Elt0.getNode());
10443       DCI.AddToWorklist(Elt1.getNode());
10444       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10445     }
10446     }
10447   }
10448 
10449   unsigned VecSize = VecVT.getSizeInBits();
10450   unsigned EltSize = EltVT.getSizeInBits();
10451 
10452   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10453   if (::shouldExpandVectorDynExt(N)) {
10454     SDLoc SL(N);
10455     SDValue Idx = N->getOperand(1);
10456     SDValue V;
10457     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10458       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10459       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10460       if (I == 0)
10461         V = Elt;
10462       else
10463         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10464     }
10465     return V;
10466   }
10467 
10468   if (!DCI.isBeforeLegalize())
10469     return SDValue();
10470 
10471   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10472   // elements. This exposes more load reduction opportunities by replacing
10473   // multiple small extract_vector_elements with a single 32-bit extract.
10474   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10475   if (isa<MemSDNode>(Vec) &&
10476       EltSize <= 16 &&
10477       EltVT.isByteSized() &&
10478       VecSize > 32 &&
10479       VecSize % 32 == 0 &&
10480       Idx) {
10481     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10482 
10483     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10484     unsigned EltIdx = BitIndex / 32;
10485     unsigned LeftoverBitIdx = BitIndex % 32;
10486     SDLoc SL(N);
10487 
10488     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10489     DCI.AddToWorklist(Cast.getNode());
10490 
10491     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10492                               DAG.getConstant(EltIdx, SL, MVT::i32));
10493     DCI.AddToWorklist(Elt.getNode());
10494     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10495                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10496     DCI.AddToWorklist(Srl.getNode());
10497 
10498     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10499     DCI.AddToWorklist(Trunc.getNode());
10500     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10501   }
10502 
10503   return SDValue();
10504 }
10505 
10506 SDValue
10507 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10508                                                 DAGCombinerInfo &DCI) const {
10509   SDValue Vec = N->getOperand(0);
10510   SDValue Idx = N->getOperand(2);
10511   EVT VecVT = Vec.getValueType();
10512   EVT EltVT = VecVT.getVectorElementType();
10513 
10514   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10515   // => BUILD_VECTOR n x select (e, const-idx)
10516   if (!::shouldExpandVectorDynExt(N))
10517     return SDValue();
10518 
10519   SelectionDAG &DAG = DCI.DAG;
10520   SDLoc SL(N);
10521   SDValue Ins = N->getOperand(1);
10522   EVT IdxVT = Idx.getValueType();
10523 
10524   SmallVector<SDValue, 16> Ops;
10525   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10526     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10527     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10528     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10529     Ops.push_back(V);
10530   }
10531 
10532   return DAG.getBuildVector(VecVT, SL, Ops);
10533 }
10534 
10535 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10536                                           const SDNode *N0,
10537                                           const SDNode *N1) const {
10538   EVT VT = N0->getValueType(0);
10539 
10540   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10541   // support denormals ever.
10542   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10543        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10544         getSubtarget()->hasMadF16())) &&
10545        isOperationLegal(ISD::FMAD, VT))
10546     return ISD::FMAD;
10547 
10548   const TargetOptions &Options = DAG.getTarget().Options;
10549   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10550        (N0->getFlags().hasAllowContract() &&
10551         N1->getFlags().hasAllowContract())) &&
10552       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10553     return ISD::FMA;
10554   }
10555 
10556   return 0;
10557 }
10558 
10559 // For a reassociatable opcode perform:
10560 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10561 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10562                                                SelectionDAG &DAG) const {
10563   EVT VT = N->getValueType(0);
10564   if (VT != MVT::i32 && VT != MVT::i64)
10565     return SDValue();
10566 
10567   if (DAG.isBaseWithConstantOffset(SDValue(N, 0)))
10568     return SDValue();
10569 
10570   unsigned Opc = N->getOpcode();
10571   SDValue Op0 = N->getOperand(0);
10572   SDValue Op1 = N->getOperand(1);
10573 
10574   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10575     return SDValue();
10576 
10577   if (Op0->isDivergent())
10578     std::swap(Op0, Op1);
10579 
10580   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10581     return SDValue();
10582 
10583   SDValue Op2 = Op1.getOperand(1);
10584   Op1 = Op1.getOperand(0);
10585   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10586     return SDValue();
10587 
10588   if (Op1->isDivergent())
10589     std::swap(Op1, Op2);
10590 
10591   SDLoc SL(N);
10592   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10593   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10594 }
10595 
10596 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10597                            EVT VT,
10598                            SDValue N0, SDValue N1, SDValue N2,
10599                            bool Signed) {
10600   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10601   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10602   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10603   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10604 }
10605 
10606 SDValue SITargetLowering::performAddCombine(SDNode *N,
10607                                             DAGCombinerInfo &DCI) const {
10608   SelectionDAG &DAG = DCI.DAG;
10609   EVT VT = N->getValueType(0);
10610   SDLoc SL(N);
10611   SDValue LHS = N->getOperand(0);
10612   SDValue RHS = N->getOperand(1);
10613 
10614   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10615       && Subtarget->hasMad64_32() &&
10616       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10617       VT.getScalarSizeInBits() <= 64) {
10618     if (LHS.getOpcode() != ISD::MUL)
10619       std::swap(LHS, RHS);
10620 
10621     SDValue MulLHS = LHS.getOperand(0);
10622     SDValue MulRHS = LHS.getOperand(1);
10623     SDValue AddRHS = RHS;
10624 
10625     // TODO: Maybe restrict if SGPR inputs.
10626     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10627         numBitsUnsigned(MulRHS, DAG) <= 32) {
10628       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10629       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10630       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10631       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10632     }
10633 
10634     if (numBitsSigned(MulLHS, DAG) <= 32 && numBitsSigned(MulRHS, DAG) <= 32) {
10635       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10636       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10637       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10638       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10639     }
10640 
10641     return SDValue();
10642   }
10643 
10644   if (SDValue V = reassociateScalarOps(N, DAG)) {
10645     return V;
10646   }
10647 
10648   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10649     return SDValue();
10650 
10651   // add x, zext (setcc) => addcarry x, 0, setcc
10652   // add x, sext (setcc) => subcarry x, 0, setcc
10653   unsigned Opc = LHS.getOpcode();
10654   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10655       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10656     std::swap(RHS, LHS);
10657 
10658   Opc = RHS.getOpcode();
10659   switch (Opc) {
10660   default: break;
10661   case ISD::ZERO_EXTEND:
10662   case ISD::SIGN_EXTEND:
10663   case ISD::ANY_EXTEND: {
10664     auto Cond = RHS.getOperand(0);
10665     // If this won't be a real VOPC output, we would still need to insert an
10666     // extra instruction anyway.
10667     if (!isBoolSGPR(Cond))
10668       break;
10669     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10670     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10671     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10672     return DAG.getNode(Opc, SL, VTList, Args);
10673   }
10674   case ISD::ADDCARRY: {
10675     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10676     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10677     if (!C || C->getZExtValue() != 0) break;
10678     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10679     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10680   }
10681   }
10682   return SDValue();
10683 }
10684 
10685 SDValue SITargetLowering::performSubCombine(SDNode *N,
10686                                             DAGCombinerInfo &DCI) const {
10687   SelectionDAG &DAG = DCI.DAG;
10688   EVT VT = N->getValueType(0);
10689 
10690   if (VT != MVT::i32)
10691     return SDValue();
10692 
10693   SDLoc SL(N);
10694   SDValue LHS = N->getOperand(0);
10695   SDValue RHS = N->getOperand(1);
10696 
10697   // sub x, zext (setcc) => subcarry x, 0, setcc
10698   // sub x, sext (setcc) => addcarry x, 0, setcc
10699   unsigned Opc = RHS.getOpcode();
10700   switch (Opc) {
10701   default: break;
10702   case ISD::ZERO_EXTEND:
10703   case ISD::SIGN_EXTEND:
10704   case ISD::ANY_EXTEND: {
10705     auto Cond = RHS.getOperand(0);
10706     // If this won't be a real VOPC output, we would still need to insert an
10707     // extra instruction anyway.
10708     if (!isBoolSGPR(Cond))
10709       break;
10710     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10711     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10712     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10713     return DAG.getNode(Opc, SL, VTList, Args);
10714   }
10715   }
10716 
10717   if (LHS.getOpcode() == ISD::SUBCARRY) {
10718     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10719     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10720     if (!C || !C->isZero())
10721       return SDValue();
10722     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10723     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10724   }
10725   return SDValue();
10726 }
10727 
10728 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10729   DAGCombinerInfo &DCI) const {
10730 
10731   if (N->getValueType(0) != MVT::i32)
10732     return SDValue();
10733 
10734   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10735   if (!C || C->getZExtValue() != 0)
10736     return SDValue();
10737 
10738   SelectionDAG &DAG = DCI.DAG;
10739   SDValue LHS = N->getOperand(0);
10740 
10741   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10742   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10743   unsigned LHSOpc = LHS.getOpcode();
10744   unsigned Opc = N->getOpcode();
10745   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10746       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10747     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10748     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10749   }
10750   return SDValue();
10751 }
10752 
10753 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10754                                              DAGCombinerInfo &DCI) const {
10755   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10756     return SDValue();
10757 
10758   SelectionDAG &DAG = DCI.DAG;
10759   EVT VT = N->getValueType(0);
10760 
10761   SDLoc SL(N);
10762   SDValue LHS = N->getOperand(0);
10763   SDValue RHS = N->getOperand(1);
10764 
10765   // These should really be instruction patterns, but writing patterns with
10766   // source modiifiers is a pain.
10767 
10768   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10769   if (LHS.getOpcode() == ISD::FADD) {
10770     SDValue A = LHS.getOperand(0);
10771     if (A == LHS.getOperand(1)) {
10772       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10773       if (FusedOp != 0) {
10774         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10775         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10776       }
10777     }
10778   }
10779 
10780   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10781   if (RHS.getOpcode() == ISD::FADD) {
10782     SDValue A = RHS.getOperand(0);
10783     if (A == RHS.getOperand(1)) {
10784       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10785       if (FusedOp != 0) {
10786         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10787         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10788       }
10789     }
10790   }
10791 
10792   return SDValue();
10793 }
10794 
10795 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10796                                              DAGCombinerInfo &DCI) const {
10797   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10798     return SDValue();
10799 
10800   SelectionDAG &DAG = DCI.DAG;
10801   SDLoc SL(N);
10802   EVT VT = N->getValueType(0);
10803   assert(!VT.isVector());
10804 
10805   // Try to get the fneg to fold into the source modifier. This undoes generic
10806   // DAG combines and folds them into the mad.
10807   //
10808   // Only do this if we are not trying to support denormals. v_mad_f32 does
10809   // not support denormals ever.
10810   SDValue LHS = N->getOperand(0);
10811   SDValue RHS = N->getOperand(1);
10812   if (LHS.getOpcode() == ISD::FADD) {
10813     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10814     SDValue A = LHS.getOperand(0);
10815     if (A == LHS.getOperand(1)) {
10816       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10817       if (FusedOp != 0){
10818         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10819         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10820 
10821         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10822       }
10823     }
10824   }
10825 
10826   if (RHS.getOpcode() == ISD::FADD) {
10827     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10828 
10829     SDValue A = RHS.getOperand(0);
10830     if (A == RHS.getOperand(1)) {
10831       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10832       if (FusedOp != 0){
10833         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10834         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10835       }
10836     }
10837   }
10838 
10839   return SDValue();
10840 }
10841 
10842 SDValue SITargetLowering::performFMACombine(SDNode *N,
10843                                             DAGCombinerInfo &DCI) const {
10844   SelectionDAG &DAG = DCI.DAG;
10845   EVT VT = N->getValueType(0);
10846   SDLoc SL(N);
10847 
10848   if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
10849     return SDValue();
10850 
10851   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10852   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10853   SDValue Op1 = N->getOperand(0);
10854   SDValue Op2 = N->getOperand(1);
10855   SDValue FMA = N->getOperand(2);
10856 
10857   if (FMA.getOpcode() != ISD::FMA ||
10858       Op1.getOpcode() != ISD::FP_EXTEND ||
10859       Op2.getOpcode() != ISD::FP_EXTEND)
10860     return SDValue();
10861 
10862   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10863   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10864   // is sufficient to allow generaing fdot2.
10865   const TargetOptions &Options = DAG.getTarget().Options;
10866   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10867       (N->getFlags().hasAllowContract() &&
10868        FMA->getFlags().hasAllowContract())) {
10869     Op1 = Op1.getOperand(0);
10870     Op2 = Op2.getOperand(0);
10871     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10872         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10873       return SDValue();
10874 
10875     SDValue Vec1 = Op1.getOperand(0);
10876     SDValue Idx1 = Op1.getOperand(1);
10877     SDValue Vec2 = Op2.getOperand(0);
10878 
10879     SDValue FMAOp1 = FMA.getOperand(0);
10880     SDValue FMAOp2 = FMA.getOperand(1);
10881     SDValue FMAAcc = FMA.getOperand(2);
10882 
10883     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10884         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10885       return SDValue();
10886 
10887     FMAOp1 = FMAOp1.getOperand(0);
10888     FMAOp2 = FMAOp2.getOperand(0);
10889     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10890         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10891       return SDValue();
10892 
10893     SDValue Vec3 = FMAOp1.getOperand(0);
10894     SDValue Vec4 = FMAOp2.getOperand(0);
10895     SDValue Idx2 = FMAOp1.getOperand(1);
10896 
10897     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10898         // Idx1 and Idx2 cannot be the same.
10899         Idx1 == Idx2)
10900       return SDValue();
10901 
10902     if (Vec1 == Vec2 || Vec3 == Vec4)
10903       return SDValue();
10904 
10905     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10906       return SDValue();
10907 
10908     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10909         (Vec1 == Vec4 && Vec2 == Vec3)) {
10910       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10911                          DAG.getTargetConstant(0, SL, MVT::i1));
10912     }
10913   }
10914   return SDValue();
10915 }
10916 
10917 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10918                                               DAGCombinerInfo &DCI) const {
10919   SelectionDAG &DAG = DCI.DAG;
10920   SDLoc SL(N);
10921 
10922   SDValue LHS = N->getOperand(0);
10923   SDValue RHS = N->getOperand(1);
10924   EVT VT = LHS.getValueType();
10925   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10926 
10927   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10928   if (!CRHS) {
10929     CRHS = dyn_cast<ConstantSDNode>(LHS);
10930     if (CRHS) {
10931       std::swap(LHS, RHS);
10932       CC = getSetCCSwappedOperands(CC);
10933     }
10934   }
10935 
10936   if (CRHS) {
10937     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10938         isBoolSGPR(LHS.getOperand(0))) {
10939       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10940       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10941       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10942       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10943       if ((CRHS->isAllOnes() &&
10944            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10945           (CRHS->isZero() &&
10946            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10947         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10948                            DAG.getConstant(-1, SL, MVT::i1));
10949       if ((CRHS->isAllOnes() &&
10950            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10951           (CRHS->isZero() &&
10952            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10953         return LHS.getOperand(0);
10954     }
10955 
10956     const APInt &CRHSVal = CRHS->getAPIntValue();
10957     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10958         LHS.getOpcode() == ISD::SELECT &&
10959         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10960         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10961         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10962         isBoolSGPR(LHS.getOperand(0))) {
10963       // Given CT != FT:
10964       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10965       // setcc (select cc, CT, CF), CF, ne => cc
10966       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10967       // setcc (select cc, CT, CF), CT, eq => cc
10968       const APInt &CT = LHS.getConstantOperandAPInt(1);
10969       const APInt &CF = LHS.getConstantOperandAPInt(2);
10970 
10971       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10972           (CT == CRHSVal && CC == ISD::SETNE))
10973         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10974                            DAG.getConstant(-1, SL, MVT::i1));
10975       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10976           (CT == CRHSVal && CC == ISD::SETEQ))
10977         return LHS.getOperand(0);
10978     }
10979   }
10980 
10981   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10982                                            VT != MVT::f16))
10983     return SDValue();
10984 
10985   // Match isinf/isfinite pattern
10986   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10987   // (fcmp one (fabs x), inf) -> (fp_class x,
10988   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10989   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10990     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10991     if (!CRHS)
10992       return SDValue();
10993 
10994     const APFloat &APF = CRHS->getValueAPF();
10995     if (APF.isInfinity() && !APF.isNegative()) {
10996       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10997                                  SIInstrFlags::N_INFINITY;
10998       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10999                                     SIInstrFlags::P_ZERO |
11000                                     SIInstrFlags::N_NORMAL |
11001                                     SIInstrFlags::P_NORMAL |
11002                                     SIInstrFlags::N_SUBNORMAL |
11003                                     SIInstrFlags::P_SUBNORMAL;
11004       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
11005       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
11006                          DAG.getConstant(Mask, SL, MVT::i32));
11007     }
11008   }
11009 
11010   return SDValue();
11011 }
11012 
11013 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
11014                                                      DAGCombinerInfo &DCI) const {
11015   SelectionDAG &DAG = DCI.DAG;
11016   SDLoc SL(N);
11017   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
11018 
11019   SDValue Src = N->getOperand(0);
11020   SDValue Shift = N->getOperand(0);
11021 
11022   // TODO: Extend type shouldn't matter (assuming legal types).
11023   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
11024     Shift = Shift.getOperand(0);
11025 
11026   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
11027     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
11028     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
11029     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
11030     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
11031     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
11032     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
11033       SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0),
11034                                  SDLoc(Shift.getOperand(0)), MVT::i32);
11035 
11036       unsigned ShiftOffset = 8 * Offset;
11037       if (Shift.getOpcode() == ISD::SHL)
11038         ShiftOffset -= C->getZExtValue();
11039       else
11040         ShiftOffset += C->getZExtValue();
11041 
11042       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
11043         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
11044                            MVT::f32, Shifted);
11045       }
11046     }
11047   }
11048 
11049   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11050   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
11051   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
11052     // We simplified Src. If this node is not dead, visit it again so it is
11053     // folded properly.
11054     if (N->getOpcode() != ISD::DELETED_NODE)
11055       DCI.AddToWorklist(N);
11056     return SDValue(N, 0);
11057   }
11058 
11059   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
11060   if (SDValue DemandedSrc =
11061           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
11062     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
11063 
11064   return SDValue();
11065 }
11066 
11067 SDValue SITargetLowering::performClampCombine(SDNode *N,
11068                                               DAGCombinerInfo &DCI) const {
11069   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
11070   if (!CSrc)
11071     return SDValue();
11072 
11073   const MachineFunction &MF = DCI.DAG.getMachineFunction();
11074   const APFloat &F = CSrc->getValueAPF();
11075   APFloat Zero = APFloat::getZero(F.getSemantics());
11076   if (F < Zero ||
11077       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
11078     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
11079   }
11080 
11081   APFloat One(F.getSemantics(), "1.0");
11082   if (F > One)
11083     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
11084 
11085   return SDValue(CSrc, 0);
11086 }
11087 
11088 
11089 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
11090                                             DAGCombinerInfo &DCI) const {
11091   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
11092     return SDValue();
11093   switch (N->getOpcode()) {
11094   case ISD::ADD:
11095     return performAddCombine(N, DCI);
11096   case ISD::SUB:
11097     return performSubCombine(N, DCI);
11098   case ISD::ADDCARRY:
11099   case ISD::SUBCARRY:
11100     return performAddCarrySubCarryCombine(N, DCI);
11101   case ISD::FADD:
11102     return performFAddCombine(N, DCI);
11103   case ISD::FSUB:
11104     return performFSubCombine(N, DCI);
11105   case ISD::SETCC:
11106     return performSetCCCombine(N, DCI);
11107   case ISD::FMAXNUM:
11108   case ISD::FMINNUM:
11109   case ISD::FMAXNUM_IEEE:
11110   case ISD::FMINNUM_IEEE:
11111   case ISD::SMAX:
11112   case ISD::SMIN:
11113   case ISD::UMAX:
11114   case ISD::UMIN:
11115   case AMDGPUISD::FMIN_LEGACY:
11116   case AMDGPUISD::FMAX_LEGACY:
11117     return performMinMaxCombine(N, DCI);
11118   case ISD::FMA:
11119     return performFMACombine(N, DCI);
11120   case ISD::AND:
11121     return performAndCombine(N, DCI);
11122   case ISD::OR:
11123     return performOrCombine(N, DCI);
11124   case ISD::XOR:
11125     return performXorCombine(N, DCI);
11126   case ISD::ZERO_EXTEND:
11127     return performZeroExtendCombine(N, DCI);
11128   case ISD::SIGN_EXTEND_INREG:
11129     return performSignExtendInRegCombine(N , DCI);
11130   case AMDGPUISD::FP_CLASS:
11131     return performClassCombine(N, DCI);
11132   case ISD::FCANONICALIZE:
11133     return performFCanonicalizeCombine(N, DCI);
11134   case AMDGPUISD::RCP:
11135     return performRcpCombine(N, DCI);
11136   case AMDGPUISD::FRACT:
11137   case AMDGPUISD::RSQ:
11138   case AMDGPUISD::RCP_LEGACY:
11139   case AMDGPUISD::RCP_IFLAG:
11140   case AMDGPUISD::RSQ_CLAMP:
11141   case AMDGPUISD::LDEXP: {
11142     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
11143     SDValue Src = N->getOperand(0);
11144     if (Src.isUndef())
11145       return Src;
11146     break;
11147   }
11148   case ISD::SINT_TO_FP:
11149   case ISD::UINT_TO_FP:
11150     return performUCharToFloatCombine(N, DCI);
11151   case AMDGPUISD::CVT_F32_UBYTE0:
11152   case AMDGPUISD::CVT_F32_UBYTE1:
11153   case AMDGPUISD::CVT_F32_UBYTE2:
11154   case AMDGPUISD::CVT_F32_UBYTE3:
11155     return performCvtF32UByteNCombine(N, DCI);
11156   case AMDGPUISD::FMED3:
11157     return performFMed3Combine(N, DCI);
11158   case AMDGPUISD::CVT_PKRTZ_F16_F32:
11159     return performCvtPkRTZCombine(N, DCI);
11160   case AMDGPUISD::CLAMP:
11161     return performClampCombine(N, DCI);
11162   case ISD::SCALAR_TO_VECTOR: {
11163     SelectionDAG &DAG = DCI.DAG;
11164     EVT VT = N->getValueType(0);
11165 
11166     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
11167     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
11168       SDLoc SL(N);
11169       SDValue Src = N->getOperand(0);
11170       EVT EltVT = Src.getValueType();
11171       if (EltVT == MVT::f16)
11172         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
11173 
11174       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
11175       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
11176     }
11177 
11178     break;
11179   }
11180   case ISD::EXTRACT_VECTOR_ELT:
11181     return performExtractVectorEltCombine(N, DCI);
11182   case ISD::INSERT_VECTOR_ELT:
11183     return performInsertVectorEltCombine(N, DCI);
11184   case ISD::LOAD: {
11185     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
11186       return Widended;
11187     LLVM_FALLTHROUGH;
11188   }
11189   default: {
11190     if (!DCI.isBeforeLegalize()) {
11191       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
11192         return performMemSDNodeCombine(MemNode, DCI);
11193     }
11194 
11195     break;
11196   }
11197   }
11198 
11199   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
11200 }
11201 
11202 /// Helper function for adjustWritemask
11203 static unsigned SubIdx2Lane(unsigned Idx) {
11204   switch (Idx) {
11205   default: return ~0u;
11206   case AMDGPU::sub0: return 0;
11207   case AMDGPU::sub1: return 1;
11208   case AMDGPU::sub2: return 2;
11209   case AMDGPU::sub3: return 3;
11210   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
11211   }
11212 }
11213 
11214 /// Adjust the writemask of MIMG instructions
11215 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
11216                                           SelectionDAG &DAG) const {
11217   unsigned Opcode = Node->getMachineOpcode();
11218 
11219   // Subtract 1 because the vdata output is not a MachineSDNode operand.
11220   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
11221   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
11222     return Node; // not implemented for D16
11223 
11224   SDNode *Users[5] = { nullptr };
11225   unsigned Lane = 0;
11226   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
11227   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
11228   unsigned NewDmask = 0;
11229   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
11230   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
11231   bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
11232                   Node->getConstantOperandVal(LWEIdx))
11233                      ? true
11234                      : false;
11235   unsigned TFCLane = 0;
11236   bool HasChain = Node->getNumValues() > 1;
11237 
11238   if (OldDmask == 0) {
11239     // These are folded out, but on the chance it happens don't assert.
11240     return Node;
11241   }
11242 
11243   unsigned OldBitsSet = countPopulation(OldDmask);
11244   // Work out which is the TFE/LWE lane if that is enabled.
11245   if (UsesTFC) {
11246     TFCLane = OldBitsSet;
11247   }
11248 
11249   // Try to figure out the used register components
11250   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
11251        I != E; ++I) {
11252 
11253     // Don't look at users of the chain.
11254     if (I.getUse().getResNo() != 0)
11255       continue;
11256 
11257     // Abort if we can't understand the usage
11258     if (!I->isMachineOpcode() ||
11259         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
11260       return Node;
11261 
11262     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
11263     // Note that subregs are packed, i.e. Lane==0 is the first bit set
11264     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
11265     // set, etc.
11266     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
11267     if (Lane == ~0u)
11268       return Node;
11269 
11270     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
11271     if (UsesTFC && Lane == TFCLane) {
11272       Users[Lane] = *I;
11273     } else {
11274       // Set which texture component corresponds to the lane.
11275       unsigned Comp;
11276       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
11277         Comp = countTrailingZeros(Dmask);
11278         Dmask &= ~(1 << Comp);
11279       }
11280 
11281       // Abort if we have more than one user per component.
11282       if (Users[Lane])
11283         return Node;
11284 
11285       Users[Lane] = *I;
11286       NewDmask |= 1 << Comp;
11287     }
11288   }
11289 
11290   // Don't allow 0 dmask, as hardware assumes one channel enabled.
11291   bool NoChannels = !NewDmask;
11292   if (NoChannels) {
11293     if (!UsesTFC) {
11294       // No uses of the result and not using TFC. Then do nothing.
11295       return Node;
11296     }
11297     // If the original dmask has one channel - then nothing to do
11298     if (OldBitsSet == 1)
11299       return Node;
11300     // Use an arbitrary dmask - required for the instruction to work
11301     NewDmask = 1;
11302   }
11303   // Abort if there's no change
11304   if (NewDmask == OldDmask)
11305     return Node;
11306 
11307   unsigned BitsSet = countPopulation(NewDmask);
11308 
11309   // Check for TFE or LWE - increase the number of channels by one to account
11310   // for the extra return value
11311   // This will need adjustment for D16 if this is also included in
11312   // adjustWriteMask (this function) but at present D16 are excluded.
11313   unsigned NewChannels = BitsSet + UsesTFC;
11314 
11315   int NewOpcode =
11316       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
11317   assert(NewOpcode != -1 &&
11318          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
11319          "failed to find equivalent MIMG op");
11320 
11321   // Adjust the writemask in the node
11322   SmallVector<SDValue, 12> Ops;
11323   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
11324   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
11325   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11326 
11327   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11328 
11329   MVT ResultVT = NewChannels == 1 ?
11330     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11331                            NewChannels == 5 ? 8 : NewChannels);
11332   SDVTList NewVTList = HasChain ?
11333     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11334 
11335 
11336   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11337                                               NewVTList, Ops);
11338 
11339   if (HasChain) {
11340     // Update chain.
11341     DAG.setNodeMemRefs(NewNode, Node->memoperands());
11342     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11343   }
11344 
11345   if (NewChannels == 1) {
11346     assert(Node->hasNUsesOfValue(1, 0));
11347     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11348                                       SDLoc(Node), Users[Lane]->getValueType(0),
11349                                       SDValue(NewNode, 0));
11350     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11351     return nullptr;
11352   }
11353 
11354   // Update the users of the node with the new indices
11355   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11356     SDNode *User = Users[i];
11357     if (!User) {
11358       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11359       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11360       if (i || !NoChannels)
11361         continue;
11362     } else {
11363       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11364       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11365     }
11366 
11367     switch (Idx) {
11368     default: break;
11369     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11370     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11371     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11372     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11373     }
11374   }
11375 
11376   DAG.RemoveDeadNode(Node);
11377   return nullptr;
11378 }
11379 
11380 static bool isFrameIndexOp(SDValue Op) {
11381   if (Op.getOpcode() == ISD::AssertZext)
11382     Op = Op.getOperand(0);
11383 
11384   return isa<FrameIndexSDNode>(Op);
11385 }
11386 
11387 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11388 /// with frame index operands.
11389 /// LLVM assumes that inputs are to these instructions are registers.
11390 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11391                                                         SelectionDAG &DAG) const {
11392   if (Node->getOpcode() == ISD::CopyToReg) {
11393     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11394     SDValue SrcVal = Node->getOperand(2);
11395 
11396     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11397     // to try understanding copies to physical registers.
11398     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11399       SDLoc SL(Node);
11400       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11401       SDValue VReg = DAG.getRegister(
11402         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11403 
11404       SDNode *Glued = Node->getGluedNode();
11405       SDValue ToVReg
11406         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11407                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11408       SDValue ToResultReg
11409         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11410                            VReg, ToVReg.getValue(1));
11411       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11412       DAG.RemoveDeadNode(Node);
11413       return ToResultReg.getNode();
11414     }
11415   }
11416 
11417   SmallVector<SDValue, 8> Ops;
11418   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11419     if (!isFrameIndexOp(Node->getOperand(i))) {
11420       Ops.push_back(Node->getOperand(i));
11421       continue;
11422     }
11423 
11424     SDLoc DL(Node);
11425     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11426                                      Node->getOperand(i).getValueType(),
11427                                      Node->getOperand(i)), 0));
11428   }
11429 
11430   return DAG.UpdateNodeOperands(Node, Ops);
11431 }
11432 
11433 /// Fold the instructions after selecting them.
11434 /// Returns null if users were already updated.
11435 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11436                                           SelectionDAG &DAG) const {
11437   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11438   unsigned Opcode = Node->getMachineOpcode();
11439 
11440   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11441       !TII->isGather4(Opcode) &&
11442       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11443     return adjustWritemask(Node, DAG);
11444   }
11445 
11446   if (Opcode == AMDGPU::INSERT_SUBREG ||
11447       Opcode == AMDGPU::REG_SEQUENCE) {
11448     legalizeTargetIndependentNode(Node, DAG);
11449     return Node;
11450   }
11451 
11452   switch (Opcode) {
11453   case AMDGPU::V_DIV_SCALE_F32_e64:
11454   case AMDGPU::V_DIV_SCALE_F64_e64: {
11455     // Satisfy the operand register constraint when one of the inputs is
11456     // undefined. Ordinarily each undef value will have its own implicit_def of
11457     // a vreg, so force these to use a single register.
11458     SDValue Src0 = Node->getOperand(1);
11459     SDValue Src1 = Node->getOperand(3);
11460     SDValue Src2 = Node->getOperand(5);
11461 
11462     if ((Src0.isMachineOpcode() &&
11463          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11464         (Src0 == Src1 || Src0 == Src2))
11465       break;
11466 
11467     MVT VT = Src0.getValueType().getSimpleVT();
11468     const TargetRegisterClass *RC =
11469         getRegClassFor(VT, Src0.getNode()->isDivergent());
11470 
11471     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11472     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11473 
11474     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11475                                       UndefReg, Src0, SDValue());
11476 
11477     // src0 must be the same register as src1 or src2, even if the value is
11478     // undefined, so make sure we don't violate this constraint.
11479     if (Src0.isMachineOpcode() &&
11480         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11481       if (Src1.isMachineOpcode() &&
11482           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11483         Src0 = Src1;
11484       else if (Src2.isMachineOpcode() &&
11485                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11486         Src0 = Src2;
11487       else {
11488         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11489         Src0 = UndefReg;
11490         Src1 = UndefReg;
11491       }
11492     } else
11493       break;
11494 
11495     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11496     Ops[1] = Src0;
11497     Ops[3] = Src1;
11498     Ops[5] = Src2;
11499     Ops.push_back(ImpDef.getValue(1));
11500     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11501   }
11502   default:
11503     break;
11504   }
11505 
11506   return Node;
11507 }
11508 
11509 // Any MIMG instructions that use tfe or lwe require an initialization of the
11510 // result register that will be written in the case of a memory access failure.
11511 // The required code is also added to tie this init code to the result of the
11512 // img instruction.
11513 void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
11514   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11515   const SIRegisterInfo &TRI = TII->getRegisterInfo();
11516   MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11517   MachineBasicBlock &MBB = *MI.getParent();
11518 
11519   MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
11520   MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
11521   MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
11522 
11523   if (!TFE && !LWE) // intersect_ray
11524     return;
11525 
11526   unsigned TFEVal = TFE ? TFE->getImm() : 0;
11527   unsigned LWEVal = LWE->getImm();
11528   unsigned D16Val = D16 ? D16->getImm() : 0;
11529 
11530   if (!TFEVal && !LWEVal)
11531     return;
11532 
11533   // At least one of TFE or LWE are non-zero
11534   // We have to insert a suitable initialization of the result value and
11535   // tie this to the dest of the image instruction.
11536 
11537   const DebugLoc &DL = MI.getDebugLoc();
11538 
11539   int DstIdx =
11540       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
11541 
11542   // Calculate which dword we have to initialize to 0.
11543   MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
11544 
11545   // check that dmask operand is found.
11546   assert(MO_Dmask && "Expected dmask operand in instruction");
11547 
11548   unsigned dmask = MO_Dmask->getImm();
11549   // Determine the number of active lanes taking into account the
11550   // Gather4 special case
11551   unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask);
11552 
11553   bool Packed = !Subtarget->hasUnpackedD16VMem();
11554 
11555   unsigned InitIdx =
11556       D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
11557 
11558   // Abandon attempt if the dst size isn't large enough
11559   // - this is in fact an error but this is picked up elsewhere and
11560   // reported correctly.
11561   uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
11562   if (DstSize < InitIdx)
11563     return;
11564 
11565   // Create a register for the intialization value.
11566   Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11567   unsigned NewDst = 0; // Final initialized value will be in here
11568 
11569   // If PRTStrictNull feature is enabled (the default) then initialize
11570   // all the result registers to 0, otherwise just the error indication
11571   // register (VGPRn+1)
11572   unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
11573   unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
11574 
11575   BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
11576   for (; SizeLeft; SizeLeft--, CurrIdx++) {
11577     NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11578     // Initialize dword
11579     Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
11580     BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
11581       .addImm(0);
11582     // Insert into the super-reg
11583     BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
11584       .addReg(PrevDst)
11585       .addReg(SubReg)
11586       .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
11587 
11588     PrevDst = NewDst;
11589   }
11590 
11591   // Add as an implicit operand
11592   MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
11593 
11594   // Tie the just added implicit operand to the dst
11595   MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
11596 }
11597 
11598 /// Assign the register class depending on the number of
11599 /// bits set in the writemask
11600 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11601                                                      SDNode *Node) const {
11602   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11603 
11604   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11605 
11606   if (TII->isVOP3(MI.getOpcode())) {
11607     // Make sure constant bus requirements are respected.
11608     TII->legalizeOperandsVOP3(MRI, MI);
11609 
11610     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11611     // This saves a chain-copy of registers and better ballance register
11612     // use between vgpr and agpr as agpr tuples tend to be big.
11613     if (MI.getDesc().OpInfo) {
11614       unsigned Opc = MI.getOpcode();
11615       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11616       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11617                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11618         if (I == -1)
11619           break;
11620         MachineOperand &Op = MI.getOperand(I);
11621         if (!Op.isReg() || !Op.getReg().isVirtual())
11622           continue;
11623         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11624         if (!TRI->hasAGPRs(RC))
11625           continue;
11626         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11627         if (!Src || !Src->isCopy() ||
11628             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11629           continue;
11630         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11631         // All uses of agpr64 and agpr32 can also accept vgpr except for
11632         // v_accvgpr_read, but we do not produce agpr reads during selection,
11633         // so no use checks are needed.
11634         MRI.setRegClass(Op.getReg(), NewRC);
11635       }
11636     }
11637 
11638     return;
11639   }
11640 
11641   // Replace unused atomics with the no return version.
11642   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11643   if (NoRetAtomicOp != -1) {
11644     if (!Node->hasAnyUseOfValue(0)) {
11645       int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
11646                                                AMDGPU::OpName::cpol);
11647       if (CPolIdx != -1) {
11648         MachineOperand &CPol = MI.getOperand(CPolIdx);
11649         CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC);
11650       }
11651       MI.RemoveOperand(0);
11652       MI.setDesc(TII->get(NoRetAtomicOp));
11653       return;
11654     }
11655 
11656     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11657     // instruction, because the return type of these instructions is a vec2 of
11658     // the memory type, so it can be tied to the input operand.
11659     // This means these instructions always have a use, so we need to add a
11660     // special case to check if the atomic has only one extract_subreg use,
11661     // which itself has no uses.
11662     if ((Node->hasNUsesOfValue(1, 0) &&
11663          Node->use_begin()->isMachineOpcode() &&
11664          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11665          !Node->use_begin()->hasAnyUseOfValue(0))) {
11666       Register Def = MI.getOperand(0).getReg();
11667 
11668       // Change this into a noret atomic.
11669       MI.setDesc(TII->get(NoRetAtomicOp));
11670       MI.RemoveOperand(0);
11671 
11672       // If we only remove the def operand from the atomic instruction, the
11673       // extract_subreg will be left with a use of a vreg without a def.
11674       // So we need to insert an implicit_def to avoid machine verifier
11675       // errors.
11676       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11677               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11678     }
11679     return;
11680   }
11681 
11682   if (TII->isMIMG(MI) && !MI.mayStore())
11683     AddIMGInit(MI);
11684 }
11685 
11686 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11687                               uint64_t Val) {
11688   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11689   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11690 }
11691 
11692 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11693                                                 const SDLoc &DL,
11694                                                 SDValue Ptr) const {
11695   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11696 
11697   // Build the half of the subregister with the constants before building the
11698   // full 128-bit register. If we are building multiple resource descriptors,
11699   // this will allow CSEing of the 2-component register.
11700   const SDValue Ops0[] = {
11701     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11702     buildSMovImm32(DAG, DL, 0),
11703     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11704     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11705     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11706   };
11707 
11708   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11709                                                 MVT::v2i32, Ops0), 0);
11710 
11711   // Combine the constants and the pointer.
11712   const SDValue Ops1[] = {
11713     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11714     Ptr,
11715     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11716     SubRegHi,
11717     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11718   };
11719 
11720   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11721 }
11722 
11723 /// Return a resource descriptor with the 'Add TID' bit enabled
11724 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11725 ///        of the resource descriptor) to create an offset, which is added to
11726 ///        the resource pointer.
11727 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11728                                            SDValue Ptr, uint32_t RsrcDword1,
11729                                            uint64_t RsrcDword2And3) const {
11730   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11731   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11732   if (RsrcDword1) {
11733     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11734                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11735                     0);
11736   }
11737 
11738   SDValue DataLo = buildSMovImm32(DAG, DL,
11739                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11740   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11741 
11742   const SDValue Ops[] = {
11743     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11744     PtrLo,
11745     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11746     PtrHi,
11747     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11748     DataLo,
11749     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11750     DataHi,
11751     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11752   };
11753 
11754   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11755 }
11756 
11757 //===----------------------------------------------------------------------===//
11758 //                         SI Inline Assembly Support
11759 //===----------------------------------------------------------------------===//
11760 
11761 std::pair<unsigned, const TargetRegisterClass *>
11762 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
11763                                                StringRef Constraint,
11764                                                MVT VT) const {
11765   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
11766 
11767   const TargetRegisterClass *RC = nullptr;
11768   if (Constraint.size() == 1) {
11769     const unsigned BitWidth = VT.getSizeInBits();
11770     switch (Constraint[0]) {
11771     default:
11772       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11773     case 's':
11774     case 'r':
11775       switch (BitWidth) {
11776       case 16:
11777         RC = &AMDGPU::SReg_32RegClass;
11778         break;
11779       case 64:
11780         RC = &AMDGPU::SGPR_64RegClass;
11781         break;
11782       default:
11783         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11784         if (!RC)
11785           return std::make_pair(0U, nullptr);
11786         break;
11787       }
11788       break;
11789     case 'v':
11790       switch (BitWidth) {
11791       case 16:
11792         RC = &AMDGPU::VGPR_32RegClass;
11793         break;
11794       default:
11795         RC = TRI->getVGPRClassForBitWidth(BitWidth);
11796         if (!RC)
11797           return std::make_pair(0U, nullptr);
11798         break;
11799       }
11800       break;
11801     case 'a':
11802       if (!Subtarget->hasMAIInsts())
11803         break;
11804       switch (BitWidth) {
11805       case 16:
11806         RC = &AMDGPU::AGPR_32RegClass;
11807         break;
11808       default:
11809         RC = TRI->getAGPRClassForBitWidth(BitWidth);
11810         if (!RC)
11811           return std::make_pair(0U, nullptr);
11812         break;
11813       }
11814       break;
11815     }
11816     // We actually support i128, i16 and f16 as inline parameters
11817     // even if they are not reported as legal
11818     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11819                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11820       return std::make_pair(0U, RC);
11821   }
11822 
11823   if (Constraint.startswith("{") && Constraint.endswith("}")) {
11824     StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
11825     if (RegName.consume_front("v")) {
11826       RC = &AMDGPU::VGPR_32RegClass;
11827     } else if (RegName.consume_front("s")) {
11828       RC = &AMDGPU::SGPR_32RegClass;
11829     } else if (RegName.consume_front("a")) {
11830       RC = &AMDGPU::AGPR_32RegClass;
11831     }
11832 
11833     if (RC) {
11834       uint32_t Idx;
11835       if (RegName.consume_front("[")) {
11836         uint32_t End;
11837         bool Failed = RegName.consumeInteger(10, Idx);
11838         Failed |= !RegName.consume_front(":");
11839         Failed |= RegName.consumeInteger(10, End);
11840         Failed |= !RegName.consume_back("]");
11841         if (!Failed) {
11842           uint32_t Width = (End - Idx + 1) * 32;
11843           MCRegister Reg = RC->getRegister(Idx);
11844           if (SIRegisterInfo::isVGPRClass(RC))
11845             RC = TRI->getVGPRClassForBitWidth(Width);
11846           else if (SIRegisterInfo::isSGPRClass(RC))
11847             RC = TRI->getSGPRClassForBitWidth(Width);
11848           else if (SIRegisterInfo::isAGPRClass(RC))
11849             RC = TRI->getAGPRClassForBitWidth(Width);
11850           if (RC) {
11851             Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC);
11852             return std::make_pair(Reg, RC);
11853           }
11854         }
11855       } else {
11856         bool Failed = RegName.getAsInteger(10, Idx);
11857         if (!Failed && Idx < RC->getNumRegs())
11858           return std::make_pair(RC->getRegister(Idx), RC);
11859       }
11860     }
11861   }
11862 
11863   auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11864   if (Ret.first)
11865     Ret.second = TRI->getPhysRegClass(Ret.first);
11866 
11867   return Ret;
11868 }
11869 
11870 static bool isImmConstraint(StringRef Constraint) {
11871   if (Constraint.size() == 1) {
11872     switch (Constraint[0]) {
11873     default: break;
11874     case 'I':
11875     case 'J':
11876     case 'A':
11877     case 'B':
11878     case 'C':
11879       return true;
11880     }
11881   } else if (Constraint == "DA" ||
11882              Constraint == "DB") {
11883     return true;
11884   }
11885   return false;
11886 }
11887 
11888 SITargetLowering::ConstraintType
11889 SITargetLowering::getConstraintType(StringRef Constraint) const {
11890   if (Constraint.size() == 1) {
11891     switch (Constraint[0]) {
11892     default: break;
11893     case 's':
11894     case 'v':
11895     case 'a':
11896       return C_RegisterClass;
11897     }
11898   }
11899   if (isImmConstraint(Constraint)) {
11900     return C_Other;
11901   }
11902   return TargetLowering::getConstraintType(Constraint);
11903 }
11904 
11905 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11906   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11907     Val = Val & maskTrailingOnes<uint64_t>(Size);
11908   }
11909   return Val;
11910 }
11911 
11912 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11913                                                     std::string &Constraint,
11914                                                     std::vector<SDValue> &Ops,
11915                                                     SelectionDAG &DAG) const {
11916   if (isImmConstraint(Constraint)) {
11917     uint64_t Val;
11918     if (getAsmOperandConstVal(Op, Val) &&
11919         checkAsmConstraintVal(Op, Constraint, Val)) {
11920       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11921       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11922     }
11923   } else {
11924     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11925   }
11926 }
11927 
11928 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11929   unsigned Size = Op.getScalarValueSizeInBits();
11930   if (Size > 64)
11931     return false;
11932 
11933   if (Size == 16 && !Subtarget->has16BitInsts())
11934     return false;
11935 
11936   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11937     Val = C->getSExtValue();
11938     return true;
11939   }
11940   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11941     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11942     return true;
11943   }
11944   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11945     if (Size != 16 || Op.getNumOperands() != 2)
11946       return false;
11947     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11948       return false;
11949     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11950       Val = C->getSExtValue();
11951       return true;
11952     }
11953     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11954       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11955       return true;
11956     }
11957   }
11958 
11959   return false;
11960 }
11961 
11962 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11963                                              const std::string &Constraint,
11964                                              uint64_t Val) const {
11965   if (Constraint.size() == 1) {
11966     switch (Constraint[0]) {
11967     case 'I':
11968       return AMDGPU::isInlinableIntLiteral(Val);
11969     case 'J':
11970       return isInt<16>(Val);
11971     case 'A':
11972       return checkAsmConstraintValA(Op, Val);
11973     case 'B':
11974       return isInt<32>(Val);
11975     case 'C':
11976       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11977              AMDGPU::isInlinableIntLiteral(Val);
11978     default:
11979       break;
11980     }
11981   } else if (Constraint.size() == 2) {
11982     if (Constraint == "DA") {
11983       int64_t HiBits = static_cast<int32_t>(Val >> 32);
11984       int64_t LoBits = static_cast<int32_t>(Val);
11985       return checkAsmConstraintValA(Op, HiBits, 32) &&
11986              checkAsmConstraintValA(Op, LoBits, 32);
11987     }
11988     if (Constraint == "DB") {
11989       return true;
11990     }
11991   }
11992   llvm_unreachable("Invalid asm constraint");
11993 }
11994 
11995 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
11996                                               uint64_t Val,
11997                                               unsigned MaxSize) const {
11998   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
11999   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
12000   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
12001       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
12002       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
12003     return true;
12004   }
12005   return false;
12006 }
12007 
12008 static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
12009   switch (UnalignedClassID) {
12010   case AMDGPU::VReg_64RegClassID:
12011     return AMDGPU::VReg_64_Align2RegClassID;
12012   case AMDGPU::VReg_96RegClassID:
12013     return AMDGPU::VReg_96_Align2RegClassID;
12014   case AMDGPU::VReg_128RegClassID:
12015     return AMDGPU::VReg_128_Align2RegClassID;
12016   case AMDGPU::VReg_160RegClassID:
12017     return AMDGPU::VReg_160_Align2RegClassID;
12018   case AMDGPU::VReg_192RegClassID:
12019     return AMDGPU::VReg_192_Align2RegClassID;
12020   case AMDGPU::VReg_224RegClassID:
12021     return AMDGPU::VReg_224_Align2RegClassID;
12022   case AMDGPU::VReg_256RegClassID:
12023     return AMDGPU::VReg_256_Align2RegClassID;
12024   case AMDGPU::VReg_512RegClassID:
12025     return AMDGPU::VReg_512_Align2RegClassID;
12026   case AMDGPU::VReg_1024RegClassID:
12027     return AMDGPU::VReg_1024_Align2RegClassID;
12028   case AMDGPU::AReg_64RegClassID:
12029     return AMDGPU::AReg_64_Align2RegClassID;
12030   case AMDGPU::AReg_96RegClassID:
12031     return AMDGPU::AReg_96_Align2RegClassID;
12032   case AMDGPU::AReg_128RegClassID:
12033     return AMDGPU::AReg_128_Align2RegClassID;
12034   case AMDGPU::AReg_160RegClassID:
12035     return AMDGPU::AReg_160_Align2RegClassID;
12036   case AMDGPU::AReg_192RegClassID:
12037     return AMDGPU::AReg_192_Align2RegClassID;
12038   case AMDGPU::AReg_256RegClassID:
12039     return AMDGPU::AReg_256_Align2RegClassID;
12040   case AMDGPU::AReg_512RegClassID:
12041     return AMDGPU::AReg_512_Align2RegClassID;
12042   case AMDGPU::AReg_1024RegClassID:
12043     return AMDGPU::AReg_1024_Align2RegClassID;
12044   default:
12045     return -1;
12046   }
12047 }
12048 
12049 // Figure out which registers should be reserved for stack access. Only after
12050 // the function is legalized do we know all of the non-spill stack objects or if
12051 // calls are present.
12052 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
12053   MachineRegisterInfo &MRI = MF.getRegInfo();
12054   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12055   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
12056   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12057   const SIInstrInfo *TII = ST.getInstrInfo();
12058 
12059   if (Info->isEntryFunction()) {
12060     // Callable functions have fixed registers used for stack access.
12061     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
12062   }
12063 
12064   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
12065                              Info->getStackPtrOffsetReg()));
12066   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
12067     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
12068 
12069   // We need to worry about replacing the default register with itself in case
12070   // of MIR testcases missing the MFI.
12071   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
12072     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
12073 
12074   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
12075     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
12076 
12077   Info->limitOccupancy(MF);
12078 
12079   if (ST.isWave32() && !MF.empty()) {
12080     for (auto &MBB : MF) {
12081       for (auto &MI : MBB) {
12082         TII->fixImplicitOperands(MI);
12083       }
12084     }
12085   }
12086 
12087   // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
12088   // classes if required. Ideally the register class constraints would differ
12089   // per-subtarget, but there's no easy way to achieve that right now. This is
12090   // not a problem for VGPRs because the correctly aligned VGPR class is implied
12091   // from using them as the register class for legal types.
12092   if (ST.needsAlignedVGPRs()) {
12093     for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
12094       const Register Reg = Register::index2VirtReg(I);
12095       const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
12096       if (!RC)
12097         continue;
12098       int NewClassID = getAlignedAGPRClassID(RC->getID());
12099       if (NewClassID != -1)
12100         MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
12101     }
12102   }
12103 
12104   TargetLoweringBase::finalizeLowering(MF);
12105 }
12106 
12107 void SITargetLowering::computeKnownBitsForFrameIndex(
12108   const int FI, KnownBits &Known, const MachineFunction &MF) const {
12109   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
12110 
12111   // Set the high bits to zero based on the maximum allowed scratch size per
12112   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
12113   // calculation won't overflow, so assume the sign bit is never set.
12114   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
12115 }
12116 
12117 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
12118                                    KnownBits &Known, unsigned Dim) {
12119   unsigned MaxValue =
12120       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
12121   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
12122 }
12123 
12124 void SITargetLowering::computeKnownBitsForTargetInstr(
12125     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
12126     const MachineRegisterInfo &MRI, unsigned Depth) const {
12127   const MachineInstr *MI = MRI.getVRegDef(R);
12128   switch (MI->getOpcode()) {
12129   case AMDGPU::G_INTRINSIC: {
12130     switch (MI->getIntrinsicID()) {
12131     case Intrinsic::amdgcn_workitem_id_x:
12132       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
12133       break;
12134     case Intrinsic::amdgcn_workitem_id_y:
12135       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
12136       break;
12137     case Intrinsic::amdgcn_workitem_id_z:
12138       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
12139       break;
12140     case Intrinsic::amdgcn_mbcnt_lo:
12141     case Intrinsic::amdgcn_mbcnt_hi: {
12142       // These return at most the wavefront size - 1.
12143       unsigned Size = MRI.getType(R).getSizeInBits();
12144       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
12145       break;
12146     }
12147     case Intrinsic::amdgcn_groupstaticsize: {
12148       // We can report everything over the maximum size as 0. We can't report
12149       // based on the actual size because we don't know if it's accurate or not
12150       // at any given point.
12151       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
12152       break;
12153     }
12154     }
12155     break;
12156   }
12157   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
12158     Known.Zero.setHighBits(24);
12159     break;
12160   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
12161     Known.Zero.setHighBits(16);
12162     break;
12163   }
12164 }
12165 
12166 Align SITargetLowering::computeKnownAlignForTargetInstr(
12167   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
12168   unsigned Depth) const {
12169   const MachineInstr *MI = MRI.getVRegDef(R);
12170   switch (MI->getOpcode()) {
12171   case AMDGPU::G_INTRINSIC:
12172   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
12173     // FIXME: Can this move to generic code? What about the case where the call
12174     // site specifies a lower alignment?
12175     Intrinsic::ID IID = MI->getIntrinsicID();
12176     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
12177     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
12178     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
12179       return *RetAlign;
12180     return Align(1);
12181   }
12182   default:
12183     return Align(1);
12184   }
12185 }
12186 
12187 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12188   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
12189   const Align CacheLineAlign = Align(64);
12190 
12191   // Pre-GFX10 target did not benefit from loop alignment
12192   if (!ML || DisableLoopAlignment ||
12193       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
12194       getSubtarget()->hasInstFwdPrefetchBug())
12195     return PrefAlign;
12196 
12197   // On GFX10 I$ is 4 x 64 bytes cache lines.
12198   // By default prefetcher keeps one cache line behind and reads two ahead.
12199   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
12200   // behind and one ahead.
12201   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
12202   // If loop fits 64 bytes it always spans no more than two cache lines and
12203   // does not need an alignment.
12204   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
12205   // Else if loop is less or equal 192 bytes we need two lines behind.
12206 
12207   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12208   const MachineBasicBlock *Header = ML->getHeader();
12209   if (Header->getAlignment() != PrefAlign)
12210     return Header->getAlignment(); // Already processed.
12211 
12212   unsigned LoopSize = 0;
12213   for (const MachineBasicBlock *MBB : ML->blocks()) {
12214     // If inner loop block is aligned assume in average half of the alignment
12215     // size to be added as nops.
12216     if (MBB != Header)
12217       LoopSize += MBB->getAlignment().value() / 2;
12218 
12219     for (const MachineInstr &MI : *MBB) {
12220       LoopSize += TII->getInstSizeInBytes(MI);
12221       if (LoopSize > 192)
12222         return PrefAlign;
12223     }
12224   }
12225 
12226   if (LoopSize <= 64)
12227     return PrefAlign;
12228 
12229   if (LoopSize <= 128)
12230     return CacheLineAlign;
12231 
12232   // If any of parent loops is surrounded by prefetch instructions do not
12233   // insert new for inner loop, which would reset parent's settings.
12234   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
12235     if (MachineBasicBlock *Exit = P->getExitBlock()) {
12236       auto I = Exit->getFirstNonDebugInstr();
12237       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
12238         return CacheLineAlign;
12239     }
12240   }
12241 
12242   MachineBasicBlock *Pre = ML->getLoopPreheader();
12243   MachineBasicBlock *Exit = ML->getExitBlock();
12244 
12245   if (Pre && Exit) {
12246     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
12247             TII->get(AMDGPU::S_INST_PREFETCH))
12248       .addImm(1); // prefetch 2 lines behind PC
12249 
12250     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
12251             TII->get(AMDGPU::S_INST_PREFETCH))
12252       .addImm(2); // prefetch 1 line behind PC
12253   }
12254 
12255   return CacheLineAlign;
12256 }
12257 
12258 LLVM_ATTRIBUTE_UNUSED
12259 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
12260   assert(N->getOpcode() == ISD::CopyFromReg);
12261   do {
12262     // Follow the chain until we find an INLINEASM node.
12263     N = N->getOperand(0).getNode();
12264     if (N->getOpcode() == ISD::INLINEASM ||
12265         N->getOpcode() == ISD::INLINEASM_BR)
12266       return true;
12267   } while (N->getOpcode() == ISD::CopyFromReg);
12268   return false;
12269 }
12270 
12271 bool SITargetLowering::isSDNodeSourceOfDivergence(
12272     const SDNode *N, FunctionLoweringInfo *FLI,
12273     LegacyDivergenceAnalysis *KDA) const {
12274   switch (N->getOpcode()) {
12275   case ISD::CopyFromReg: {
12276     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
12277     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
12278     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12279     Register Reg = R->getReg();
12280 
12281     // FIXME: Why does this need to consider isLiveIn?
12282     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
12283       return !TRI->isSGPRReg(MRI, Reg);
12284 
12285     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
12286       return KDA->isDivergent(V);
12287 
12288     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
12289     return !TRI->isSGPRReg(MRI, Reg);
12290   }
12291   case ISD::LOAD: {
12292     const LoadSDNode *L = cast<LoadSDNode>(N);
12293     unsigned AS = L->getAddressSpace();
12294     // A flat load may access private memory.
12295     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
12296   }
12297   case ISD::CALLSEQ_END:
12298     return true;
12299   case ISD::INTRINSIC_WO_CHAIN:
12300     return AMDGPU::isIntrinsicSourceOfDivergence(
12301         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
12302   case ISD::INTRINSIC_W_CHAIN:
12303     return AMDGPU::isIntrinsicSourceOfDivergence(
12304         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
12305   case AMDGPUISD::ATOMIC_CMP_SWAP:
12306   case AMDGPUISD::ATOMIC_INC:
12307   case AMDGPUISD::ATOMIC_DEC:
12308   case AMDGPUISD::ATOMIC_LOAD_FMIN:
12309   case AMDGPUISD::ATOMIC_LOAD_FMAX:
12310   case AMDGPUISD::BUFFER_ATOMIC_SWAP:
12311   case AMDGPUISD::BUFFER_ATOMIC_ADD:
12312   case AMDGPUISD::BUFFER_ATOMIC_SUB:
12313   case AMDGPUISD::BUFFER_ATOMIC_SMIN:
12314   case AMDGPUISD::BUFFER_ATOMIC_UMIN:
12315   case AMDGPUISD::BUFFER_ATOMIC_SMAX:
12316   case AMDGPUISD::BUFFER_ATOMIC_UMAX:
12317   case AMDGPUISD::BUFFER_ATOMIC_AND:
12318   case AMDGPUISD::BUFFER_ATOMIC_OR:
12319   case AMDGPUISD::BUFFER_ATOMIC_XOR:
12320   case AMDGPUISD::BUFFER_ATOMIC_INC:
12321   case AMDGPUISD::BUFFER_ATOMIC_DEC:
12322   case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
12323   case AMDGPUISD::BUFFER_ATOMIC_CSUB:
12324   case AMDGPUISD::BUFFER_ATOMIC_FADD:
12325   case AMDGPUISD::BUFFER_ATOMIC_FMIN:
12326   case AMDGPUISD::BUFFER_ATOMIC_FMAX:
12327     // Target-specific read-modify-write atomics are sources of divergence.
12328     return true;
12329   default:
12330     if (auto *A = dyn_cast<AtomicSDNode>(N)) {
12331       // Generic read-modify-write atomics are sources of divergence.
12332       return A->readMem() && A->writeMem();
12333     }
12334     return false;
12335   }
12336 }
12337 
12338 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
12339                                                EVT VT) const {
12340   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
12341   case MVT::f32:
12342     return hasFP32Denormals(DAG.getMachineFunction());
12343   case MVT::f64:
12344   case MVT::f16:
12345     return hasFP64FP16Denormals(DAG.getMachineFunction());
12346   default:
12347     return false;
12348   }
12349 }
12350 
12351 bool SITargetLowering::denormalsEnabledForType(LLT Ty,
12352                                                MachineFunction &MF) const {
12353   switch (Ty.getScalarSizeInBits()) {
12354   case 32:
12355     return hasFP32Denormals(MF);
12356   case 64:
12357   case 16:
12358     return hasFP64FP16Denormals(MF);
12359   default:
12360     return false;
12361   }
12362 }
12363 
12364 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
12365                                                     const SelectionDAG &DAG,
12366                                                     bool SNaN,
12367                                                     unsigned Depth) const {
12368   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
12369     const MachineFunction &MF = DAG.getMachineFunction();
12370     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12371 
12372     if (Info->getMode().DX10Clamp)
12373       return true; // Clamped to 0.
12374     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
12375   }
12376 
12377   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
12378                                                             SNaN, Depth);
12379 }
12380 
12381 // Global FP atomic instructions have a hardcoded FP mode and do not support
12382 // FP32 denormals, and only support v2f16 denormals.
12383 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
12384   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
12385   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
12386   if (&Flt == &APFloat::IEEEsingle())
12387     return DenormMode == DenormalMode::getPreserveSign();
12388   return DenormMode == DenormalMode::getIEEE();
12389 }
12390 
12391 TargetLowering::AtomicExpansionKind
12392 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
12393 
12394   auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) {
12395     OptimizationRemarkEmitter ORE(RMW->getFunction());
12396     LLVMContext &Ctx = RMW->getFunction()->getContext();
12397     SmallVector<StringRef> SSNs;
12398     Ctx.getSyncScopeNames(SSNs);
12399     auto MemScope = SSNs[RMW->getSyncScopeID()].empty()
12400                         ? "system"
12401                         : SSNs[RMW->getSyncScopeID()];
12402     ORE.emit([&]() {
12403       return OptimizationRemark(DEBUG_TYPE, "Passed", RMW)
12404              << "Hardware instruction generated for atomic "
12405              << RMW->getOperationName(RMW->getOperation())
12406              << " operation at memory scope " << MemScope
12407              << " due to an unsafe request.";
12408     });
12409     return Kind;
12410   };
12411 
12412   switch (RMW->getOperation()) {
12413   case AtomicRMWInst::FAdd: {
12414     Type *Ty = RMW->getType();
12415 
12416     // We don't have a way to support 16-bit atomics now, so just leave them
12417     // as-is.
12418     if (Ty->isHalfTy())
12419       return AtomicExpansionKind::None;
12420 
12421     if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
12422       return AtomicExpansionKind::CmpXChg;
12423 
12424     unsigned AS = RMW->getPointerAddressSpace();
12425 
12426     if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) &&
12427          Subtarget->hasAtomicFaddInsts()) {
12428       // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
12429       // floating point atomic instructions. May generate more efficient code,
12430       // but may not respect rounding and denormal modes, and may give incorrect
12431       // results for certain memory destinations.
12432       if (RMW->getFunction()
12433               ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12434               .getValueAsString() != "true")
12435         return AtomicExpansionKind::CmpXChg;
12436 
12437       if (Subtarget->hasGFX90AInsts()) {
12438         if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS)
12439           return AtomicExpansionKind::CmpXChg;
12440 
12441         auto SSID = RMW->getSyncScopeID();
12442         if (SSID == SyncScope::System ||
12443             SSID == RMW->getContext().getOrInsertSyncScopeID("one-as"))
12444           return AtomicExpansionKind::CmpXChg;
12445 
12446         return ReportUnsafeHWInst(AtomicExpansionKind::None);
12447       }
12448 
12449       if (AS == AMDGPUAS::FLAT_ADDRESS)
12450         return AtomicExpansionKind::CmpXChg;
12451 
12452       return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12453                               : AtomicExpansionKind::CmpXChg;
12454     }
12455 
12456     // DS FP atomics do repect the denormal mode, but the rounding mode is fixed
12457     // to round-to-nearest-even.
12458     // The only exception is DS_ADD_F64 which never flushes regardless of mode.
12459     if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) {
12460       if (!Ty->isDoubleTy())
12461         return AtomicExpansionKind::None;
12462 
12463       if (fpModeMatchesGlobalFPAtomicMode(RMW))
12464         return AtomicExpansionKind::None;
12465 
12466       return RMW->getFunction()
12467                          ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12468                          .getValueAsString() == "true"
12469                  ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12470                  : AtomicExpansionKind::CmpXChg;
12471     }
12472 
12473     return AtomicExpansionKind::CmpXChg;
12474   }
12475   default:
12476     break;
12477   }
12478 
12479   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
12480 }
12481 
12482 const TargetRegisterClass *
12483 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
12484   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
12485   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12486   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
12487     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
12488                                                : &AMDGPU::SReg_32RegClass;
12489   if (!TRI->isSGPRClass(RC) && !isDivergent)
12490     return TRI->getEquivalentSGPRClass(RC);
12491   else if (TRI->isSGPRClass(RC) && isDivergent)
12492     return TRI->getEquivalentVGPRClass(RC);
12493 
12494   return RC;
12495 }
12496 
12497 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
12498 // uniform values (as produced by the mask results of control flow intrinsics)
12499 // used outside of divergent blocks. The phi users need to also be treated as
12500 // always uniform.
12501 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
12502                       unsigned WaveSize) {
12503   // FIXME: We asssume we never cast the mask results of a control flow
12504   // intrinsic.
12505   // Early exit if the type won't be consistent as a compile time hack.
12506   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
12507   if (!IT || IT->getBitWidth() != WaveSize)
12508     return false;
12509 
12510   if (!isa<Instruction>(V))
12511     return false;
12512   if (!Visited.insert(V).second)
12513     return false;
12514   bool Result = false;
12515   for (auto U : V->users()) {
12516     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
12517       if (V == U->getOperand(1)) {
12518         switch (Intrinsic->getIntrinsicID()) {
12519         default:
12520           Result = false;
12521           break;
12522         case Intrinsic::amdgcn_if_break:
12523         case Intrinsic::amdgcn_if:
12524         case Intrinsic::amdgcn_else:
12525           Result = true;
12526           break;
12527         }
12528       }
12529       if (V == U->getOperand(0)) {
12530         switch (Intrinsic->getIntrinsicID()) {
12531         default:
12532           Result = false;
12533           break;
12534         case Intrinsic::amdgcn_end_cf:
12535         case Intrinsic::amdgcn_loop:
12536           Result = true;
12537           break;
12538         }
12539       }
12540     } else {
12541       Result = hasCFUser(U, Visited, WaveSize);
12542     }
12543     if (Result)
12544       break;
12545   }
12546   return Result;
12547 }
12548 
12549 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
12550                                                const Value *V) const {
12551   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
12552     if (CI->isInlineAsm()) {
12553       // FIXME: This cannot give a correct answer. This should only trigger in
12554       // the case where inline asm returns mixed SGPR and VGPR results, used
12555       // outside the defining block. We don't have a specific result to
12556       // consider, so this assumes if any value is SGPR, the overall register
12557       // also needs to be SGPR.
12558       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
12559       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
12560           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
12561       for (auto &TC : TargetConstraints) {
12562         if (TC.Type == InlineAsm::isOutput) {
12563           ComputeConstraintToUse(TC, SDValue());
12564           const TargetRegisterClass *RC = getRegForInlineAsmConstraint(
12565               SIRI, TC.ConstraintCode, TC.ConstraintVT).second;
12566           if (RC && SIRI->isSGPRClass(RC))
12567             return true;
12568         }
12569       }
12570     }
12571   }
12572   SmallPtrSet<const Value *, 16> Visited;
12573   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
12574 }
12575 
12576 std::pair<InstructionCost, MVT>
12577 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
12578                                           Type *Ty) const {
12579   std::pair<InstructionCost, MVT> Cost =
12580       TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
12581   auto Size = DL.getTypeSizeInBits(Ty);
12582   // Maximum load or store can handle 8 dwords for scalar and 4 for
12583   // vector ALU. Let's assume anything above 8 dwords is expensive
12584   // even if legal.
12585   if (Size <= 256)
12586     return Cost;
12587 
12588   Cost.first += (Size + 255) / 256;
12589   return Cost;
12590 }
12591 
12592 bool SITargetLowering::hasMemSDNodeUser(SDNode *N) const {
12593   SDNode::use_iterator I = N->use_begin(), E = N->use_end();
12594   for (; I != E; ++I) {
12595     if (MemSDNode *M = dyn_cast<MemSDNode>(*I)) {
12596       if (getBasePtrIndex(M) == I.getOperandNo())
12597         return true;
12598     }
12599   }
12600   return false;
12601 }
12602 
12603 bool SITargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0,
12604                                            SDValue N1) const {
12605   if (!N0.hasOneUse())
12606     return false;
12607   // Take care of the oportunity to keep N0 uniform
12608   if (N0->isDivergent() || !N1->isDivergent())
12609     return true;
12610   // Check if we have a good chance to form the memory access pattern with the
12611   // base and offset
12612   return (DAG.isBaseWithConstantOffset(N0) &&
12613           hasMemSDNodeUser(*N0->use_begin()));
12614 }
12615