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/FloatingPointMode.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
23 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
24 #include "llvm/BinaryFormat/ELF.h"
25 #include "llvm/CodeGen/Analysis.h"
26 #include "llvm/CodeGen/FunctionLoweringInfo.h"
27 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
28 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineLoopInfo.h"
31 #include "llvm/IR/DiagnosticInfo.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/IntrinsicsAMDGPU.h"
34 #include "llvm/IR/IntrinsicsR600.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/KnownBits.h"
37 
38 using namespace llvm;
39 
40 #define DEBUG_TYPE "si-lower"
41 
42 STATISTIC(NumTailCalls, "Number of tail calls");
43 
44 static cl::opt<bool> DisableLoopAlignment(
45   "amdgpu-disable-loop-alignment",
46   cl::desc("Do not align and prefetch loops"),
47   cl::init(false));
48 
49 static cl::opt<bool> UseDivergentRegisterIndexing(
50   "amdgpu-use-divergent-register-indexing",
51   cl::Hidden,
52   cl::desc("Use indirect register addressing for divergent indexes"),
53   cl::init(false));
54 
55 static bool hasFP32Denormals(const MachineFunction &MF) {
56   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
57   return Info->getMode().allFP32Denormals();
58 }
59 
60 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
61   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
62   return Info->getMode().allFP64FP16Denormals();
63 }
64 
65 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
66   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
67   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
68     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
69       return AMDGPU::SGPR0 + Reg;
70     }
71   }
72   llvm_unreachable("Cannot allocate sgpr");
73 }
74 
75 SITargetLowering::SITargetLowering(const TargetMachine &TM,
76                                    const GCNSubtarget &STI)
77     : AMDGPUTargetLowering(TM, STI),
78       Subtarget(&STI) {
79   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
80   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
81 
82   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
83   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
84 
85   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
86 
87   const SIRegisterInfo *TRI = STI.getRegisterInfo();
88   const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class();
89 
90   addRegisterClass(MVT::f64, V64RegClass);
91   addRegisterClass(MVT::v2f32, V64RegClass);
92 
93   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
94   addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96));
95 
96   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
97   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
98 
99   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
100   addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128));
101 
102   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
103   addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160));
104 
105   addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass);
106   addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192));
107 
108   addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass);
109   addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192));
110 
111   addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass);
112   addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224));
113 
114   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
115   addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256));
116 
117   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
118   addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256));
119 
120   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
121   addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512));
122 
123   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
124   addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512));
125 
126   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
127   addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024));
128 
129   if (Subtarget->has16BitInsts()) {
130     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
131     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
132 
133     // Unless there are also VOP3P operations, not operations are really legal.
134     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
135     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
136     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
137     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
138     addRegisterClass(MVT::v8i16, &AMDGPU::SGPR_128RegClass);
139     addRegisterClass(MVT::v8f16, &AMDGPU::SGPR_128RegClass);
140   }
141 
142   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
143   addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024));
144 
145   computeRegisterProperties(Subtarget->getRegisterInfo());
146 
147   // The boolean content concept here is too inflexible. Compares only ever
148   // really produce a 1-bit result. Any copy/extend from these will turn into a
149   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
150   // it's what most targets use.
151   setBooleanContents(ZeroOrOneBooleanContent);
152   setBooleanVectorContents(ZeroOrOneBooleanContent);
153 
154   // We need to custom lower vector stores from local memory
155   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
156   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
157   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
158   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
159   setOperationAction(ISD::LOAD, MVT::v6i32, Custom);
160   setOperationAction(ISD::LOAD, MVT::v7i32, Custom);
161   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
162   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
163   setOperationAction(ISD::LOAD, MVT::i1, Custom);
164   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
165 
166   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
167   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
168   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
169   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
170   setOperationAction(ISD::STORE, MVT::v6i32, Custom);
171   setOperationAction(ISD::STORE, MVT::v7i32, Custom);
172   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
173   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
174   setOperationAction(ISD::STORE, MVT::i1, Custom);
175   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
176 
177   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
178   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
179   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
180   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
181   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
182   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
183   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
184   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
185   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
186   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
187   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
188   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
189   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
190   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
191   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
192   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
193 
194   setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand);
195   setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand);
196   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
197   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
198   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
199   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
200   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
201 
202   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
203   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
204 
205   setOperationAction(ISD::SELECT, MVT::i1, Promote);
206   setOperationAction(ISD::SELECT, MVT::i64, Custom);
207   setOperationAction(ISD::SELECT, MVT::f64, Promote);
208   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
209 
210   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
211   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
212   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
213   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
214   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
215 
216   setOperationAction(ISD::SETCC, MVT::i1, Promote);
217   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
218   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
219   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
220 
221   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
222   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
223   setOperationAction(ISD::TRUNCATE, MVT::v3i32, Expand);
224   setOperationAction(ISD::FP_ROUND, MVT::v3f32, Expand);
225   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
226   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
227   setOperationAction(ISD::TRUNCATE, MVT::v5i32, Expand);
228   setOperationAction(ISD::FP_ROUND, MVT::v5f32, Expand);
229   setOperationAction(ISD::TRUNCATE, MVT::v6i32, Expand);
230   setOperationAction(ISD::FP_ROUND, MVT::v6f32, Expand);
231   setOperationAction(ISD::TRUNCATE, MVT::v7i32, Expand);
232   setOperationAction(ISD::FP_ROUND, MVT::v7f32, Expand);
233   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
234   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
235   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
236   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
237 
238   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
239   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
240   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
241   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
242   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
243   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
244   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
245   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
246 
247   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
248   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
249   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
250   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
251   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
252   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
253 
254   setOperationAction(ISD::UADDO, MVT::i32, Legal);
255   setOperationAction(ISD::USUBO, MVT::i32, Legal);
256 
257   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
258   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
259 
260   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
261   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
262   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
263 
264 #if 0
265   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
266   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
267 #endif
268 
269   // We only support LOAD/STORE and vector manipulation ops for vectors
270   // with > 4 elements.
271   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
272                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
273                   MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32,
274                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
275                   MVT::v8i16, MVT::v8f16, MVT::v16i64, MVT::v16f64,
276                   MVT::v32i32, MVT::v32f32 }) {
277     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
278       switch (Op) {
279       case ISD::LOAD:
280       case ISD::STORE:
281       case ISD::BUILD_VECTOR:
282       case ISD::BITCAST:
283       case ISD::EXTRACT_VECTOR_ELT:
284       case ISD::INSERT_VECTOR_ELT:
285       case ISD::EXTRACT_SUBVECTOR:
286       case ISD::SCALAR_TO_VECTOR:
287         break;
288       case ISD::INSERT_SUBVECTOR:
289       case ISD::CONCAT_VECTORS:
290         setOperationAction(Op, VT, Custom);
291         break;
292       default:
293         setOperationAction(Op, VT, Expand);
294         break;
295       }
296     }
297   }
298 
299   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
300 
301   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
302   // is expanded to avoid having two separate loops in case the index is a VGPR.
303 
304   // Most operations are naturally 32-bit vector operations. We only support
305   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
306   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
307     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
308     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
309 
310     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
311     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
312 
313     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
314     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
315 
316     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
317     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
318   }
319 
320   for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) {
321     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
322     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32);
323 
324     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
325     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32);
326 
327     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
328     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32);
329 
330     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
331     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32);
332   }
333 
334   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
335     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
336     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
337 
338     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
339     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
340 
341     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
342     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
343 
344     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
345     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
346   }
347 
348   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
349     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
350     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
351 
352     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
353     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
354 
355     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
356     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
357 
358     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
359     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
360   }
361 
362   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
363     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
364     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
365 
366     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
367     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
368 
369     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
370     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
371 
372     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
373     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
374   }
375 
376   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
377   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
378   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
379   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
380 
381   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
382   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
383 
384   // Avoid stack access for these.
385   // TODO: Generalize to more vector types.
386   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
387   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
388   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
389   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
390 
391   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
392   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
393   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
394   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
395   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
396   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
397 
398   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
399   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
400   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
401   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
402 
403   // Deal with vec3 vector operations when widened to vec4.
404   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
405   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
406   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
407   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
408 
409   // Deal with vec5/6/7 vector operations when widened to vec8.
410   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
411   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
412   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6i32, Custom);
413   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6f32, Custom);
414   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7i32, Custom);
415   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7f32, Custom);
416   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
417   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
418 
419   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
420   // and output demarshalling
421   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
422   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
423 
424   // We can't return success/failure, only the old value,
425   // let LLVM add the comparison
426   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
427   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
428 
429   if (Subtarget->hasFlatAddressSpace()) {
430     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
431     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
432   }
433 
434   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
435   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
436 
437   // FIXME: This should be narrowed to i32, but that only happens if i64 is
438   // illegal.
439   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
440   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
441   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
442 
443   // On SI this is s_memtime and s_memrealtime on VI.
444   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
445   setOperationAction(ISD::TRAP, MVT::Other, Custom);
446   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
447 
448   if (Subtarget->has16BitInsts()) {
449     setOperationAction(ISD::FPOW, MVT::f16, Promote);
450     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
451     setOperationAction(ISD::FLOG, MVT::f16, Custom);
452     setOperationAction(ISD::FEXP, MVT::f16, Custom);
453     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
454   }
455 
456   if (Subtarget->hasMadMacF32Insts())
457     setOperationAction(ISD::FMAD, MVT::f32, Legal);
458 
459   if (!Subtarget->hasBFI()) {
460     // fcopysign can be done in a single instruction with BFI.
461     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
462     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
463   }
464 
465   if (!Subtarget->hasBCNT(32))
466     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
467 
468   if (!Subtarget->hasBCNT(64))
469     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
470 
471   if (Subtarget->hasFFBH()) {
472     setOperationAction(ISD::CTLZ, MVT::i32, Custom);
473     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
474   }
475 
476   if (Subtarget->hasFFBL()) {
477     setOperationAction(ISD::CTTZ, MVT::i32, Custom);
478     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
479   }
480 
481   // We only really have 32-bit BFE instructions (and 16-bit on VI).
482   //
483   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
484   // effort to match them now. We want this to be false for i64 cases when the
485   // extraction isn't restricted to the upper or lower half. Ideally we would
486   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
487   // span the midpoint are probably relatively rare, so don't worry about them
488   // for now.
489   if (Subtarget->hasBFE())
490     setHasExtractBitsInsn(true);
491 
492   // Clamp modifier on add/sub
493   if (Subtarget->hasIntClamp()) {
494     setOperationAction(ISD::UADDSAT, MVT::i32, Legal);
495     setOperationAction(ISD::USUBSAT, MVT::i32, Legal);
496   }
497 
498   if (Subtarget->hasAddNoCarry()) {
499     setOperationAction(ISD::SADDSAT, MVT::i16, Legal);
500     setOperationAction(ISD::SSUBSAT, MVT::i16, Legal);
501     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
502     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
503   }
504 
505   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
506   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
507   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
508   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
509 
510 
511   // These are really only legal for ieee_mode functions. We should be avoiding
512   // them for functions that don't have ieee_mode enabled, so just say they are
513   // legal.
514   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
515   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
516   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
517   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
518 
519 
520   if (Subtarget->haveRoundOpsF64()) {
521     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
522     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
523     setOperationAction(ISD::FRINT, MVT::f64, Legal);
524   } else {
525     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
526     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
527     setOperationAction(ISD::FRINT, MVT::f64, Custom);
528     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
529   }
530 
531   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
532 
533   setOperationAction(ISD::FSIN, MVT::f32, Custom);
534   setOperationAction(ISD::FCOS, MVT::f32, Custom);
535   setOperationAction(ISD::FDIV, MVT::f32, Custom);
536   setOperationAction(ISD::FDIV, MVT::f64, Custom);
537 
538   if (Subtarget->has16BitInsts()) {
539     setOperationAction(ISD::Constant, MVT::i16, Legal);
540 
541     setOperationAction(ISD::SMIN, MVT::i16, Legal);
542     setOperationAction(ISD::SMAX, MVT::i16, Legal);
543 
544     setOperationAction(ISD::UMIN, MVT::i16, Legal);
545     setOperationAction(ISD::UMAX, MVT::i16, Legal);
546 
547     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
548     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
549 
550     setOperationAction(ISD::ROTR, MVT::i16, Expand);
551     setOperationAction(ISD::ROTL, MVT::i16, Expand);
552 
553     setOperationAction(ISD::SDIV, MVT::i16, Promote);
554     setOperationAction(ISD::UDIV, MVT::i16, Promote);
555     setOperationAction(ISD::SREM, MVT::i16, Promote);
556     setOperationAction(ISD::UREM, MVT::i16, Promote);
557     setOperationAction(ISD::UADDSAT, MVT::i16, Legal);
558     setOperationAction(ISD::USUBSAT, MVT::i16, Legal);
559 
560     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
561 
562     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
563     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
564     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
565     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
566     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
567 
568     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
569 
570     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
571 
572     setOperationAction(ISD::LOAD, MVT::i16, Custom);
573 
574     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
575 
576     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
577     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
578     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
579     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
580 
581     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Custom);
582     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Custom);
583 
584     // F16 - Constant Actions.
585     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
586 
587     // F16 - Load/Store Actions.
588     setOperationAction(ISD::LOAD, MVT::f16, Promote);
589     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
590     setOperationAction(ISD::STORE, MVT::f16, Promote);
591     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
592 
593     // F16 - VOP1 Actions.
594     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
595     setOperationAction(ISD::FCOS, MVT::f16, Custom);
596     setOperationAction(ISD::FSIN, MVT::f16, Custom);
597 
598     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
599     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
600 
601     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
602     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
603     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
604     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
605     setOperationAction(ISD::FROUND, MVT::f16, Custom);
606     setOperationAction(ISD::FPTRUNC_ROUND, MVT::f16, Custom);
607 
608     // F16 - VOP2 Actions.
609     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
610     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
611 
612     setOperationAction(ISD::FDIV, MVT::f16, Custom);
613 
614     // F16 - VOP3 Actions.
615     setOperationAction(ISD::FMA, MVT::f16, Legal);
616     if (STI.hasMadF16())
617       setOperationAction(ISD::FMAD, MVT::f16, Legal);
618 
619     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16, MVT::v8i16,
620                    MVT::v8f16}) {
621       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
622         switch (Op) {
623         case ISD::LOAD:
624         case ISD::STORE:
625         case ISD::BUILD_VECTOR:
626         case ISD::BITCAST:
627         case ISD::EXTRACT_VECTOR_ELT:
628         case ISD::INSERT_VECTOR_ELT:
629         case ISD::INSERT_SUBVECTOR:
630         case ISD::EXTRACT_SUBVECTOR:
631         case ISD::SCALAR_TO_VECTOR:
632           break;
633         case ISD::CONCAT_VECTORS:
634           setOperationAction(Op, VT, Custom);
635           break;
636         default:
637           setOperationAction(Op, VT, Expand);
638           break;
639         }
640       }
641     }
642 
643     // v_perm_b32 can handle either of these.
644     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
645     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
646     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
647 
648     // XXX - Do these do anything? Vector constants turn into build_vector.
649     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
650     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
651 
652     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
653     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
654 
655     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
656     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
657     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
658     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
659 
660     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
661     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
662     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
663     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
664 
665     setOperationAction(ISD::AND, MVT::v2i16, Promote);
666     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
667     setOperationAction(ISD::OR, MVT::v2i16, Promote);
668     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
669     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
670     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
671 
672     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
673     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
674     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
675     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
676 
677     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
678     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
679     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
680     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
681 
682     setOperationAction(ISD::LOAD, MVT::v8i16, Promote);
683     AddPromotedToType(ISD::LOAD, MVT::v8i16, MVT::v4i32);
684     setOperationAction(ISD::LOAD, MVT::v8f16, Promote);
685     AddPromotedToType(ISD::LOAD, MVT::v8f16, MVT::v4i32);
686 
687     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
688     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
689     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
690     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
691 
692     setOperationAction(ISD::STORE, MVT::v8i16, Promote);
693     AddPromotedToType(ISD::STORE, MVT::v8i16, MVT::v4i32);
694     setOperationAction(ISD::STORE, MVT::v8f16, Promote);
695     AddPromotedToType(ISD::STORE, MVT::v8f16, MVT::v4i32);
696 
697     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
698     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
699     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
700     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
701 
702     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
703     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
704     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
705 
706     setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Expand);
707     setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Expand);
708     setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Expand);
709 
710     if (!Subtarget->hasVOP3PInsts()) {
711       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
712       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
713     }
714 
715     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
716     // This isn't really legal, but this avoids the legalizer unrolling it (and
717     // allows matching fneg (fabs x) patterns)
718     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
719 
720     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
721     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
722     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
723     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
724 
725     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
726     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
727     setOperationAction(ISD::FMINNUM_IEEE, MVT::v8f16, Custom);
728     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v8f16, Custom);
729 
730     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
731     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
732     setOperationAction(ISD::FMINNUM, MVT::v8f16, Expand);
733     setOperationAction(ISD::FMAXNUM, MVT::v8f16, Expand);
734 
735     for (MVT Vec16 : { MVT::v8i16, MVT::v8f16 }) {
736       setOperationAction(ISD::BUILD_VECTOR, Vec16, Custom);
737       setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec16, Custom);
738       setOperationAction(ISD::INSERT_VECTOR_ELT, Vec16, Expand);
739       setOperationAction(ISD::SCALAR_TO_VECTOR, Vec16, Expand);
740     }
741   }
742 
743   if (Subtarget->hasVOP3PInsts()) {
744     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
745     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
746     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
747     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
748     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
749     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
750     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
751     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
752     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
753     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
754 
755     setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal);
756     setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal);
757     setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal);
758     setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal);
759 
760     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
761     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
762     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
763 
764     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
765     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
766 
767     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
768 
769     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
770     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
771 
772     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
773     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
774     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f16, Custom);
775     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i16, Custom);
776 
777     for (MVT VT : { MVT::v4i16, MVT::v8i16 }) {
778       // Split vector operations.
779       setOperationAction(ISD::SHL, VT, Custom);
780       setOperationAction(ISD::SRA, VT, Custom);
781       setOperationAction(ISD::SRL, VT, Custom);
782       setOperationAction(ISD::ADD, VT, Custom);
783       setOperationAction(ISD::SUB, VT, Custom);
784       setOperationAction(ISD::MUL, VT, Custom);
785 
786       setOperationAction(ISD::SMIN, VT, Custom);
787       setOperationAction(ISD::SMAX, VT, Custom);
788       setOperationAction(ISD::UMIN, VT, Custom);
789       setOperationAction(ISD::UMAX, VT, Custom);
790 
791       setOperationAction(ISD::UADDSAT, VT, Custom);
792       setOperationAction(ISD::SADDSAT, VT, Custom);
793       setOperationAction(ISD::USUBSAT, VT, Custom);
794       setOperationAction(ISD::SSUBSAT, VT, Custom);
795     }
796 
797     for (MVT VT : { MVT::v4f16, MVT::v8f16 }) {
798       // Split vector operations.
799       setOperationAction(ISD::FADD, VT, Custom);
800       setOperationAction(ISD::FMUL, VT, Custom);
801       setOperationAction(ISD::FMA, VT, Custom);
802       setOperationAction(ISD::FCANONICALIZE, VT, Custom);
803     }
804 
805     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
806     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
807 
808     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
809     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
810 
811     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
812     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
813     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
814 
815     if (Subtarget->hasPackedFP32Ops()) {
816       setOperationAction(ISD::FADD, MVT::v2f32, Legal);
817       setOperationAction(ISD::FMUL, MVT::v2f32, Legal);
818       setOperationAction(ISD::FMA,  MVT::v2f32, Legal);
819       setOperationAction(ISD::FNEG, MVT::v2f32, Legal);
820 
821       for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) {
822         setOperationAction(ISD::FADD, VT, Custom);
823         setOperationAction(ISD::FMUL, VT, Custom);
824         setOperationAction(ISD::FMA, VT, Custom);
825       }
826     }
827   }
828 
829   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
830   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
831 
832   if (Subtarget->has16BitInsts()) {
833     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
834     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
835     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
836     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
837   } else {
838     // Legalization hack.
839     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
840     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
841 
842     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
843     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
844   }
845 
846   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8,
847                   MVT::v8i16, MVT::v8f16 }) {
848     setOperationAction(ISD::SELECT, VT, Custom);
849   }
850 
851   setOperationAction(ISD::SMULO, MVT::i64, Custom);
852   setOperationAction(ISD::UMULO, MVT::i64, Custom);
853 
854   if (Subtarget->hasMad64_32()) {
855     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
856     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
857   }
858 
859   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
860   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
861   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
862   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
863   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
864   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
865   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
866 
867   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
868   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
869   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom);
870   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom);
871   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
872   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
873   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
874   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
875   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
876   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
877   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
878 
879   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
880   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
881   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
882   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom);
883   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom);
884   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
885   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
886   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
887   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
888   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
889 
890   setTargetDAGCombine(ISD::ADD);
891   setTargetDAGCombine(ISD::ADDCARRY);
892   setTargetDAGCombine(ISD::SUB);
893   setTargetDAGCombine(ISD::SUBCARRY);
894   setTargetDAGCombine(ISD::FADD);
895   setTargetDAGCombine(ISD::FSUB);
896   setTargetDAGCombine(ISD::FMINNUM);
897   setTargetDAGCombine(ISD::FMAXNUM);
898   setTargetDAGCombine(ISD::FMINNUM_IEEE);
899   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
900   setTargetDAGCombine(ISD::FMA);
901   setTargetDAGCombine(ISD::SMIN);
902   setTargetDAGCombine(ISD::SMAX);
903   setTargetDAGCombine(ISD::UMIN);
904   setTargetDAGCombine(ISD::UMAX);
905   setTargetDAGCombine(ISD::SETCC);
906   setTargetDAGCombine(ISD::AND);
907   setTargetDAGCombine(ISD::OR);
908   setTargetDAGCombine(ISD::XOR);
909   setTargetDAGCombine(ISD::SINT_TO_FP);
910   setTargetDAGCombine(ISD::UINT_TO_FP);
911   setTargetDAGCombine(ISD::FCANONICALIZE);
912   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
913   setTargetDAGCombine(ISD::ZERO_EXTEND);
914   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
915   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
916   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
917 
918   // All memory operations. Some folding on the pointer operand is done to help
919   // matching the constant offsets in the addressing modes.
920   setTargetDAGCombine(ISD::LOAD);
921   setTargetDAGCombine(ISD::STORE);
922   setTargetDAGCombine(ISD::ATOMIC_LOAD);
923   setTargetDAGCombine(ISD::ATOMIC_STORE);
924   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
925   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
926   setTargetDAGCombine(ISD::ATOMIC_SWAP);
927   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
928   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
929   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
930   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
931   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
932   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
933   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
934   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
935   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
936   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
937   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
938   setTargetDAGCombine(ISD::INTRINSIC_VOID);
939   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
940 
941   // FIXME: In other contexts we pretend this is a per-function property.
942   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
943 
944   setSchedulingPreference(Sched::RegPressure);
945 }
946 
947 const GCNSubtarget *SITargetLowering::getSubtarget() const {
948   return Subtarget;
949 }
950 
951 //===----------------------------------------------------------------------===//
952 // TargetLowering queries
953 //===----------------------------------------------------------------------===//
954 
955 // v_mad_mix* support a conversion from f16 to f32.
956 //
957 // There is only one special case when denormals are enabled we don't currently,
958 // where this is OK to use.
959 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
960                                        EVT DestVT, EVT SrcVT) const {
961   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
962           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
963     DestVT.getScalarType() == MVT::f32 &&
964     SrcVT.getScalarType() == MVT::f16 &&
965     // TODO: This probably only requires no input flushing?
966     !hasFP32Denormals(DAG.getMachineFunction());
967 }
968 
969 bool SITargetLowering::isFPExtFoldable(const MachineInstr &MI, unsigned Opcode,
970                                        LLT DestTy, LLT SrcTy) const {
971   return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) ||
972           (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) &&
973          DestTy.getScalarSizeInBits() == 32 &&
974          SrcTy.getScalarSizeInBits() == 16 &&
975          // TODO: This probably only requires no input flushing?
976          !hasFP32Denormals(*MI.getMF());
977 }
978 
979 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
980   // SI has some legal vector types, but no legal vector operations. Say no
981   // shuffles are legal in order to prefer scalarizing some vector operations.
982   return false;
983 }
984 
985 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
986                                                     CallingConv::ID CC,
987                                                     EVT VT) const {
988   if (CC == CallingConv::AMDGPU_KERNEL)
989     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
990 
991   if (VT.isVector()) {
992     EVT ScalarVT = VT.getScalarType();
993     unsigned Size = ScalarVT.getSizeInBits();
994     if (Size == 16) {
995       if (Subtarget->has16BitInsts())
996         return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
997       return VT.isInteger() ? MVT::i32 : MVT::f32;
998     }
999 
1000     if (Size < 16)
1001       return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
1002     return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
1003   }
1004 
1005   if (VT.getSizeInBits() > 32)
1006     return MVT::i32;
1007 
1008   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1009 }
1010 
1011 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1012                                                          CallingConv::ID CC,
1013                                                          EVT VT) const {
1014   if (CC == CallingConv::AMDGPU_KERNEL)
1015     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1016 
1017   if (VT.isVector()) {
1018     unsigned NumElts = VT.getVectorNumElements();
1019     EVT ScalarVT = VT.getScalarType();
1020     unsigned Size = ScalarVT.getSizeInBits();
1021 
1022     // FIXME: Should probably promote 8-bit vectors to i16.
1023     if (Size == 16 && Subtarget->has16BitInsts())
1024       return (NumElts + 1) / 2;
1025 
1026     if (Size <= 32)
1027       return NumElts;
1028 
1029     if (Size > 32)
1030       return NumElts * ((Size + 31) / 32);
1031   } else if (VT.getSizeInBits() > 32)
1032     return (VT.getSizeInBits() + 31) / 32;
1033 
1034   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1035 }
1036 
1037 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
1038   LLVMContext &Context, CallingConv::ID CC,
1039   EVT VT, EVT &IntermediateVT,
1040   unsigned &NumIntermediates, MVT &RegisterVT) const {
1041   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
1042     unsigned NumElts = VT.getVectorNumElements();
1043     EVT ScalarVT = VT.getScalarType();
1044     unsigned Size = ScalarVT.getSizeInBits();
1045     // FIXME: We should fix the ABI to be the same on targets without 16-bit
1046     // support, but unless we can properly handle 3-vectors, it will be still be
1047     // inconsistent.
1048     if (Size == 16 && Subtarget->has16BitInsts()) {
1049       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
1050       IntermediateVT = RegisterVT;
1051       NumIntermediates = (NumElts + 1) / 2;
1052       return NumIntermediates;
1053     }
1054 
1055     if (Size == 32) {
1056       RegisterVT = ScalarVT.getSimpleVT();
1057       IntermediateVT = RegisterVT;
1058       NumIntermediates = NumElts;
1059       return NumIntermediates;
1060     }
1061 
1062     if (Size < 16 && Subtarget->has16BitInsts()) {
1063       // FIXME: Should probably form v2i16 pieces
1064       RegisterVT = MVT::i16;
1065       IntermediateVT = ScalarVT;
1066       NumIntermediates = NumElts;
1067       return NumIntermediates;
1068     }
1069 
1070 
1071     if (Size != 16 && Size <= 32) {
1072       RegisterVT = MVT::i32;
1073       IntermediateVT = ScalarVT;
1074       NumIntermediates = NumElts;
1075       return NumIntermediates;
1076     }
1077 
1078     if (Size > 32) {
1079       RegisterVT = MVT::i32;
1080       IntermediateVT = RegisterVT;
1081       NumIntermediates = NumElts * ((Size + 31) / 32);
1082       return NumIntermediates;
1083     }
1084   }
1085 
1086   return TargetLowering::getVectorTypeBreakdownForCallingConv(
1087     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
1088 }
1089 
1090 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
1091   assert(DMaskLanes != 0);
1092 
1093   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1094     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
1095     return EVT::getVectorVT(Ty->getContext(),
1096                             EVT::getEVT(VT->getElementType()),
1097                             NumElts);
1098   }
1099 
1100   return EVT::getEVT(Ty);
1101 }
1102 
1103 // Peek through TFE struct returns to only use the data size.
1104 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
1105   auto *ST = dyn_cast<StructType>(Ty);
1106   if (!ST)
1107     return memVTFromImageData(Ty, DMaskLanes);
1108 
1109   // Some intrinsics return an aggregate type - special case to work out the
1110   // correct memVT.
1111   //
1112   // Only limited forms of aggregate type currently expected.
1113   if (ST->getNumContainedTypes() != 2 ||
1114       !ST->getContainedType(1)->isIntegerTy(32))
1115     return EVT();
1116   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
1117 }
1118 
1119 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1120                                           const CallInst &CI,
1121                                           MachineFunction &MF,
1122                                           unsigned IntrID) const {
1123   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1124           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1125     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1126                                                   (Intrinsic::ID)IntrID);
1127     if (Attr.hasFnAttr(Attribute::ReadNone))
1128       return false;
1129 
1130     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1131 
1132     if (RsrcIntr->IsImage) {
1133       Info.ptrVal =
1134           MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1135       Info.align.reset();
1136     } else {
1137       Info.ptrVal =
1138           MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1139     }
1140 
1141     Info.flags = MachineMemOperand::MODereferenceable;
1142     if (Attr.hasFnAttr(Attribute::ReadOnly)) {
1143       unsigned DMaskLanes = 4;
1144 
1145       if (RsrcIntr->IsImage) {
1146         const AMDGPU::ImageDimIntrinsicInfo *Intr
1147           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1148         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1149           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1150 
1151         if (!BaseOpcode->Gather4) {
1152           // If this isn't a gather, we may have excess loaded elements in the
1153           // IR type. Check the dmask for the real number of elements loaded.
1154           unsigned DMask
1155             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1156           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1157         }
1158 
1159         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1160       } else
1161         Info.memVT = EVT::getEVT(CI.getType());
1162 
1163       // FIXME: What does alignment mean for an image?
1164       Info.opc = ISD::INTRINSIC_W_CHAIN;
1165       Info.flags |= MachineMemOperand::MOLoad;
1166     } else if (Attr.hasFnAttr(Attribute::WriteOnly)) {
1167       Info.opc = ISD::INTRINSIC_VOID;
1168 
1169       Type *DataTy = CI.getArgOperand(0)->getType();
1170       if (RsrcIntr->IsImage) {
1171         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1172         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1173         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1174       } else
1175         Info.memVT = EVT::getEVT(DataTy);
1176 
1177       Info.flags |= MachineMemOperand::MOStore;
1178     } else {
1179       // Atomic
1180       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1181                                             ISD::INTRINSIC_W_CHAIN;
1182       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1183       Info.flags = MachineMemOperand::MOLoad |
1184                    MachineMemOperand::MOStore |
1185                    MachineMemOperand::MODereferenceable;
1186 
1187       // XXX - Should this be volatile without known ordering?
1188       Info.flags |= MachineMemOperand::MOVolatile;
1189     }
1190     return true;
1191   }
1192 
1193   switch (IntrID) {
1194   case Intrinsic::amdgcn_atomic_inc:
1195   case Intrinsic::amdgcn_atomic_dec:
1196   case Intrinsic::amdgcn_ds_ordered_add:
1197   case Intrinsic::amdgcn_ds_ordered_swap:
1198   case Intrinsic::amdgcn_ds_fadd:
1199   case Intrinsic::amdgcn_ds_fmin:
1200   case Intrinsic::amdgcn_ds_fmax: {
1201     Info.opc = ISD::INTRINSIC_W_CHAIN;
1202     Info.memVT = MVT::getVT(CI.getType());
1203     Info.ptrVal = CI.getOperand(0);
1204     Info.align.reset();
1205     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1206 
1207     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1208     if (!Vol->isZero())
1209       Info.flags |= MachineMemOperand::MOVolatile;
1210 
1211     return true;
1212   }
1213   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1214     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1215 
1216     Info.opc = ISD::INTRINSIC_W_CHAIN;
1217     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1218     Info.ptrVal =
1219         MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1220     Info.align.reset();
1221     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1222 
1223     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1224     if (!Vol || !Vol->isZero())
1225       Info.flags |= MachineMemOperand::MOVolatile;
1226 
1227     return true;
1228   }
1229   case Intrinsic::amdgcn_ds_append:
1230   case Intrinsic::amdgcn_ds_consume: {
1231     Info.opc = ISD::INTRINSIC_W_CHAIN;
1232     Info.memVT = MVT::getVT(CI.getType());
1233     Info.ptrVal = CI.getOperand(0);
1234     Info.align.reset();
1235     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1236 
1237     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1238     if (!Vol->isZero())
1239       Info.flags |= MachineMemOperand::MOVolatile;
1240 
1241     return true;
1242   }
1243   case Intrinsic::amdgcn_global_atomic_csub: {
1244     Info.opc = ISD::INTRINSIC_W_CHAIN;
1245     Info.memVT = MVT::getVT(CI.getType());
1246     Info.ptrVal = CI.getOperand(0);
1247     Info.align.reset();
1248     Info.flags = MachineMemOperand::MOLoad |
1249                  MachineMemOperand::MOStore |
1250                  MachineMemOperand::MOVolatile;
1251     return true;
1252   }
1253   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1254     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1255     Info.opc = ISD::INTRINSIC_W_CHAIN;
1256     Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1257     Info.ptrVal =
1258         MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1259     Info.align.reset();
1260     Info.flags = MachineMemOperand::MOLoad |
1261                  MachineMemOperand::MODereferenceable;
1262     return true;
1263   }
1264   case Intrinsic::amdgcn_global_atomic_fadd:
1265   case Intrinsic::amdgcn_global_atomic_fmin:
1266   case Intrinsic::amdgcn_global_atomic_fmax:
1267   case Intrinsic::amdgcn_flat_atomic_fadd:
1268   case Intrinsic::amdgcn_flat_atomic_fmin:
1269   case Intrinsic::amdgcn_flat_atomic_fmax: {
1270     Info.opc = ISD::INTRINSIC_W_CHAIN;
1271     Info.memVT = MVT::getVT(CI.getType());
1272     Info.ptrVal = CI.getOperand(0);
1273     Info.align.reset();
1274     Info.flags = MachineMemOperand::MOLoad |
1275                  MachineMemOperand::MOStore |
1276                  MachineMemOperand::MODereferenceable |
1277                  MachineMemOperand::MOVolatile;
1278     return true;
1279   }
1280   case Intrinsic::amdgcn_ds_gws_init:
1281   case Intrinsic::amdgcn_ds_gws_barrier:
1282   case Intrinsic::amdgcn_ds_gws_sema_v:
1283   case Intrinsic::amdgcn_ds_gws_sema_br:
1284   case Intrinsic::amdgcn_ds_gws_sema_p:
1285   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1286     Info.opc = ISD::INTRINSIC_VOID;
1287 
1288     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1289     Info.ptrVal =
1290         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1291 
1292     // This is an abstract access, but we need to specify a type and size.
1293     Info.memVT = MVT::i32;
1294     Info.size = 4;
1295     Info.align = Align(4);
1296 
1297     Info.flags = MachineMemOperand::MOStore;
1298     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1299       Info.flags = MachineMemOperand::MOLoad;
1300     return true;
1301   }
1302   default:
1303     return false;
1304   }
1305 }
1306 
1307 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1308                                             SmallVectorImpl<Value*> &Ops,
1309                                             Type *&AccessTy) const {
1310   switch (II->getIntrinsicID()) {
1311   case Intrinsic::amdgcn_atomic_inc:
1312   case Intrinsic::amdgcn_atomic_dec:
1313   case Intrinsic::amdgcn_ds_ordered_add:
1314   case Intrinsic::amdgcn_ds_ordered_swap:
1315   case Intrinsic::amdgcn_ds_append:
1316   case Intrinsic::amdgcn_ds_consume:
1317   case Intrinsic::amdgcn_ds_fadd:
1318   case Intrinsic::amdgcn_ds_fmin:
1319   case Intrinsic::amdgcn_ds_fmax:
1320   case Intrinsic::amdgcn_global_atomic_fadd:
1321   case Intrinsic::amdgcn_flat_atomic_fadd:
1322   case Intrinsic::amdgcn_flat_atomic_fmin:
1323   case Intrinsic::amdgcn_flat_atomic_fmax:
1324   case Intrinsic::amdgcn_global_atomic_csub: {
1325     Value *Ptr = II->getArgOperand(0);
1326     AccessTy = II->getType();
1327     Ops.push_back(Ptr);
1328     return true;
1329   }
1330   default:
1331     return false;
1332   }
1333 }
1334 
1335 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1336   if (!Subtarget->hasFlatInstOffsets()) {
1337     // Flat instructions do not have offsets, and only have the register
1338     // address.
1339     return AM.BaseOffs == 0 && AM.Scale == 0;
1340   }
1341 
1342   return AM.Scale == 0 &&
1343          (AM.BaseOffs == 0 ||
1344           Subtarget->getInstrInfo()->isLegalFLATOffset(
1345               AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT));
1346 }
1347 
1348 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1349   if (Subtarget->hasFlatGlobalInsts())
1350     return AM.Scale == 0 &&
1351            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1352                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1353                                     SIInstrFlags::FlatGlobal));
1354 
1355   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1356       // Assume the we will use FLAT for all global memory accesses
1357       // on VI.
1358       // FIXME: This assumption is currently wrong.  On VI we still use
1359       // MUBUF instructions for the r + i addressing mode.  As currently
1360       // implemented, the MUBUF instructions only work on buffer < 4GB.
1361       // It may be possible to support > 4GB buffers with MUBUF instructions,
1362       // by setting the stride value in the resource descriptor which would
1363       // increase the size limit to (stride * 4GB).  However, this is risky,
1364       // because it has never been validated.
1365     return isLegalFlatAddressingMode(AM);
1366   }
1367 
1368   return isLegalMUBUFAddressingMode(AM);
1369 }
1370 
1371 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1372   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1373   // additionally can do r + r + i with addr64. 32-bit has more addressing
1374   // mode options. Depending on the resource constant, it can also do
1375   // (i64 r0) + (i32 r1) * (i14 i).
1376   //
1377   // Private arrays end up using a scratch buffer most of the time, so also
1378   // assume those use MUBUF instructions. Scratch loads / stores are currently
1379   // implemented as mubuf instructions with offen bit set, so slightly
1380   // different than the normal addr64.
1381   if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1382     return false;
1383 
1384   // FIXME: Since we can split immediate into soffset and immediate offset,
1385   // would it make sense to allow any immediate?
1386 
1387   switch (AM.Scale) {
1388   case 0: // r + i or just i, depending on HasBaseReg.
1389     return true;
1390   case 1:
1391     return true; // We have r + r or r + i.
1392   case 2:
1393     if (AM.HasBaseReg) {
1394       // Reject 2 * r + r.
1395       return false;
1396     }
1397 
1398     // Allow 2 * r as r + r
1399     // Or  2 * r + i is allowed as r + r + i.
1400     return true;
1401   default: // Don't allow n * r
1402     return false;
1403   }
1404 }
1405 
1406 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1407                                              const AddrMode &AM, Type *Ty,
1408                                              unsigned AS, Instruction *I) const {
1409   // No global is ever allowed as a base.
1410   if (AM.BaseGV)
1411     return false;
1412 
1413   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1414     return isLegalGlobalAddressingMode(AM);
1415 
1416   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1417       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1418       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1419     // If the offset isn't a multiple of 4, it probably isn't going to be
1420     // correctly aligned.
1421     // FIXME: Can we get the real alignment here?
1422     if (AM.BaseOffs % 4 != 0)
1423       return isLegalMUBUFAddressingMode(AM);
1424 
1425     // There are no SMRD extloads, so if we have to do a small type access we
1426     // will use a MUBUF load.
1427     // FIXME?: We also need to do this if unaligned, but we don't know the
1428     // alignment here.
1429     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1430       return isLegalGlobalAddressingMode(AM);
1431 
1432     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1433       // SMRD instructions have an 8-bit, dword offset on SI.
1434       if (!isUInt<8>(AM.BaseOffs / 4))
1435         return false;
1436     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1437       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1438       // in 8-bits, it can use a smaller encoding.
1439       if (!isUInt<32>(AM.BaseOffs / 4))
1440         return false;
1441     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1442       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1443       if (!isUInt<20>(AM.BaseOffs))
1444         return false;
1445     } else
1446       llvm_unreachable("unhandled generation");
1447 
1448     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1449       return true;
1450 
1451     if (AM.Scale == 1 && AM.HasBaseReg)
1452       return true;
1453 
1454     return false;
1455 
1456   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1457     return isLegalMUBUFAddressingMode(AM);
1458   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1459              AS == AMDGPUAS::REGION_ADDRESS) {
1460     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1461     // field.
1462     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1463     // an 8-bit dword offset but we don't know the alignment here.
1464     if (!isUInt<16>(AM.BaseOffs))
1465       return false;
1466 
1467     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1468       return true;
1469 
1470     if (AM.Scale == 1 && AM.HasBaseReg)
1471       return true;
1472 
1473     return false;
1474   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1475              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1476     // For an unknown address space, this usually means that this is for some
1477     // reason being used for pure arithmetic, and not based on some addressing
1478     // computation. We don't have instructions that compute pointers with any
1479     // addressing modes, so treat them as having no offset like flat
1480     // instructions.
1481     return isLegalFlatAddressingMode(AM);
1482   }
1483 
1484   // Assume a user alias of global for unknown address spaces.
1485   return isLegalGlobalAddressingMode(AM);
1486 }
1487 
1488 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1489                                         const MachineFunction &MF) const {
1490   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1491     return (MemVT.getSizeInBits() <= 4 * 32);
1492   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1493     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1494     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1495   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1496     return (MemVT.getSizeInBits() <= 2 * 32);
1497   }
1498   return true;
1499 }
1500 
1501 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1502     unsigned Size, unsigned AddrSpace, Align Alignment,
1503     MachineMemOperand::Flags Flags, bool *IsFast) const {
1504   if (IsFast)
1505     *IsFast = false;
1506 
1507   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1508       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1509     // Check if alignment requirements for ds_read/write instructions are
1510     // disabled.
1511     if (Subtarget->hasUnalignedDSAccessEnabled() &&
1512         !Subtarget->hasLDSMisalignedBug()) {
1513       if (IsFast)
1514         *IsFast = Alignment != Align(2);
1515       return true;
1516     }
1517 
1518     // Either, the alignment requirements are "enabled", or there is an
1519     // unaligned LDS access related hardware bug though alignment requirements
1520     // are "disabled". In either case, we need to check for proper alignment
1521     // requirements.
1522     //
1523     if (Size == 64) {
1524       // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
1525       // can do a 4 byte aligned, 8 byte access in a single operation using
1526       // ds_read2/write2_b32 with adjacent offsets.
1527       bool AlignedBy4 = Alignment >= Align(4);
1528       if (IsFast)
1529         *IsFast = AlignedBy4;
1530 
1531       return AlignedBy4;
1532     }
1533     if (Size == 96) {
1534       // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
1535       // gfx8 and older.
1536       bool AlignedBy16 = Alignment >= Align(16);
1537       if (IsFast)
1538         *IsFast = AlignedBy16;
1539 
1540       return AlignedBy16;
1541     }
1542     if (Size == 128) {
1543       // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
1544       // gfx8 and older, but  we can do a 8 byte aligned, 16 byte access in a
1545       // single operation using ds_read2/write2_b64.
1546       bool AlignedBy8 = Alignment >= Align(8);
1547       if (IsFast)
1548         *IsFast = AlignedBy8;
1549 
1550       return AlignedBy8;
1551     }
1552   }
1553 
1554   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1555     bool AlignedBy4 = Alignment >= Align(4);
1556     if (IsFast)
1557       *IsFast = AlignedBy4;
1558 
1559     return AlignedBy4 ||
1560            Subtarget->enableFlatScratch() ||
1561            Subtarget->hasUnalignedScratchAccess();
1562   }
1563 
1564   // FIXME: We have to be conservative here and assume that flat operations
1565   // will access scratch.  If we had access to the IR function, then we
1566   // could determine if any private memory was used in the function.
1567   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1568       !Subtarget->hasUnalignedScratchAccess()) {
1569     bool AlignedBy4 = Alignment >= Align(4);
1570     if (IsFast)
1571       *IsFast = AlignedBy4;
1572 
1573     return AlignedBy4;
1574   }
1575 
1576   if (Subtarget->hasUnalignedBufferAccessEnabled() &&
1577       !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1578         AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1579     // If we have an uniform constant load, it still requires using a slow
1580     // buffer instruction if unaligned.
1581     if (IsFast) {
1582       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1583       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1584       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1585                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1586         Alignment >= Align(4) : Alignment != Align(2);
1587     }
1588 
1589     return true;
1590   }
1591 
1592   // Smaller than dword value must be aligned.
1593   if (Size < 32)
1594     return false;
1595 
1596   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1597   // byte-address are ignored, thus forcing Dword alignment.
1598   // This applies to private, global, and constant memory.
1599   if (IsFast)
1600     *IsFast = true;
1601 
1602   return Size >= 32 && Alignment >= Align(4);
1603 }
1604 
1605 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1606     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1607     bool *IsFast) const {
1608   if (IsFast)
1609     *IsFast = false;
1610 
1611   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1612   // which isn't a simple VT.
1613   // Until MVT is extended to handle this, simply check for the size and
1614   // rely on the condition below: allow accesses if the size is a multiple of 4.
1615   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1616                            VT.getStoreSize() > 16)) {
1617     return false;
1618   }
1619 
1620   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1621                                             Alignment, Flags, IsFast);
1622 }
1623 
1624 EVT SITargetLowering::getOptimalMemOpType(
1625     const MemOp &Op, const AttributeList &FuncAttributes) const {
1626   // FIXME: Should account for address space here.
1627 
1628   // The default fallback uses the private pointer size as a guess for a type to
1629   // use. Make sure we switch these to 64-bit accesses.
1630 
1631   if (Op.size() >= 16 &&
1632       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1633     return MVT::v4i32;
1634 
1635   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1636     return MVT::v2i32;
1637 
1638   // Use the default.
1639   return MVT::Other;
1640 }
1641 
1642 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1643   const MemSDNode *MemNode = cast<MemSDNode>(N);
1644   return MemNode->getMemOperand()->getFlags() & MONoClobber;
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::FPTRUNC_ROUND: {
4746     unsigned Opc;
4747     SDLoc DL(Op);
4748 
4749     if (Op.getOperand(0)->getValueType(0) != MVT::f32)
4750       return SDValue();
4751 
4752     // Get the rounding mode from the last operand
4753     int RoundMode = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4754     if (RoundMode == (int)RoundingMode::TowardPositive)
4755       Opc = AMDGPUISD::FPTRUNC_ROUND_UPWARD;
4756     else if (RoundMode == (int)RoundingMode::TowardNegative)
4757       Opc = AMDGPUISD::FPTRUNC_ROUND_DOWNWARD;
4758     else
4759       return SDValue();
4760 
4761     return DAG.getNode(Opc, DL, Op.getNode()->getVTList(), Op->getOperand(0));
4762   }
4763   case ISD::TRAP:
4764     return lowerTRAP(Op, DAG);
4765   case ISD::DEBUGTRAP:
4766     return lowerDEBUGTRAP(Op, DAG);
4767   case ISD::FABS:
4768   case ISD::FNEG:
4769   case ISD::FCANONICALIZE:
4770   case ISD::BSWAP:
4771     return splitUnaryVectorOp(Op, DAG);
4772   case ISD::FMINNUM:
4773   case ISD::FMAXNUM:
4774     return lowerFMINNUM_FMAXNUM(Op, DAG);
4775   case ISD::FMA:
4776     return splitTernaryVectorOp(Op, DAG);
4777   case ISD::FP_TO_SINT:
4778   case ISD::FP_TO_UINT:
4779     return LowerFP_TO_INT(Op, DAG);
4780   case ISD::SHL:
4781   case ISD::SRA:
4782   case ISD::SRL:
4783   case ISD::ADD:
4784   case ISD::SUB:
4785   case ISD::MUL:
4786   case ISD::SMIN:
4787   case ISD::SMAX:
4788   case ISD::UMIN:
4789   case ISD::UMAX:
4790   case ISD::FADD:
4791   case ISD::FMUL:
4792   case ISD::FMINNUM_IEEE:
4793   case ISD::FMAXNUM_IEEE:
4794   case ISD::UADDSAT:
4795   case ISD::USUBSAT:
4796   case ISD::SADDSAT:
4797   case ISD::SSUBSAT:
4798     return splitBinaryVectorOp(Op, DAG);
4799   case ISD::SMULO:
4800   case ISD::UMULO:
4801     return lowerXMULO(Op, DAG);
4802   case ISD::SMUL_LOHI:
4803   case ISD::UMUL_LOHI:
4804     return lowerXMUL_LOHI(Op, DAG);
4805   case ISD::DYNAMIC_STACKALLOC:
4806     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4807   }
4808   return SDValue();
4809 }
4810 
4811 // Used for D16: Casts the result of an instruction into the right vector,
4812 // packs values if loads return unpacked values.
4813 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4814                                        const SDLoc &DL,
4815                                        SelectionDAG &DAG, bool Unpacked) {
4816   if (!LoadVT.isVector())
4817     return Result;
4818 
4819   // Cast back to the original packed type or to a larger type that is a
4820   // multiple of 32 bit for D16. Widening the return type is a required for
4821   // legalization.
4822   EVT FittingLoadVT = LoadVT;
4823   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4824     FittingLoadVT =
4825         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4826                          LoadVT.getVectorNumElements() + 1);
4827   }
4828 
4829   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4830     // Truncate to v2i16/v4i16.
4831     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4832 
4833     // Workaround legalizer not scalarizing truncate after vector op
4834     // legalization but not creating intermediate vector trunc.
4835     SmallVector<SDValue, 4> Elts;
4836     DAG.ExtractVectorElements(Result, Elts);
4837     for (SDValue &Elt : Elts)
4838       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4839 
4840     // Pad illegal v1i16/v3fi6 to v4i16
4841     if ((LoadVT.getVectorNumElements() % 2) == 1)
4842       Elts.push_back(DAG.getUNDEF(MVT::i16));
4843 
4844     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4845 
4846     // Bitcast to original type (v2f16/v4f16).
4847     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4848   }
4849 
4850   // Cast back to the original packed type.
4851   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4852 }
4853 
4854 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4855                                               MemSDNode *M,
4856                                               SelectionDAG &DAG,
4857                                               ArrayRef<SDValue> Ops,
4858                                               bool IsIntrinsic) const {
4859   SDLoc DL(M);
4860 
4861   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4862   EVT LoadVT = M->getValueType(0);
4863 
4864   EVT EquivLoadVT = LoadVT;
4865   if (LoadVT.isVector()) {
4866     if (Unpacked) {
4867       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4868                                      LoadVT.getVectorNumElements());
4869     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4870       // Widen v3f16 to legal type
4871       EquivLoadVT =
4872           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4873                            LoadVT.getVectorNumElements() + 1);
4874     }
4875   }
4876 
4877   // Change from v4f16/v2f16 to EquivLoadVT.
4878   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4879 
4880   SDValue Load
4881     = DAG.getMemIntrinsicNode(
4882       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4883       VTList, Ops, M->getMemoryVT(),
4884       M->getMemOperand());
4885 
4886   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4887 
4888   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4889 }
4890 
4891 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4892                                              SelectionDAG &DAG,
4893                                              ArrayRef<SDValue> Ops) const {
4894   SDLoc DL(M);
4895   EVT LoadVT = M->getValueType(0);
4896   EVT EltType = LoadVT.getScalarType();
4897   EVT IntVT = LoadVT.changeTypeToInteger();
4898 
4899   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4900 
4901   unsigned Opc =
4902       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4903 
4904   if (IsD16) {
4905     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4906   }
4907 
4908   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4909   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4910     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4911 
4912   if (isTypeLegal(LoadVT)) {
4913     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4914                                M->getMemOperand(), DAG);
4915   }
4916 
4917   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4918   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4919   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4920                                         M->getMemOperand(), DAG);
4921   return DAG.getMergeValues(
4922       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4923       DL);
4924 }
4925 
4926 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4927                                   SDNode *N, SelectionDAG &DAG) {
4928   EVT VT = N->getValueType(0);
4929   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4930   unsigned CondCode = CD->getZExtValue();
4931   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4932     return DAG.getUNDEF(VT);
4933 
4934   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4935 
4936   SDValue LHS = N->getOperand(1);
4937   SDValue RHS = N->getOperand(2);
4938 
4939   SDLoc DL(N);
4940 
4941   EVT CmpVT = LHS.getValueType();
4942   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4943     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4944       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4945     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4946     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4947   }
4948 
4949   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4950 
4951   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4952   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4953 
4954   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4955                               DAG.getCondCode(CCOpcode));
4956   if (VT.bitsEq(CCVT))
4957     return SetCC;
4958   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4959 }
4960 
4961 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4962                                   SDNode *N, SelectionDAG &DAG) {
4963   EVT VT = N->getValueType(0);
4964   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4965 
4966   unsigned CondCode = CD->getZExtValue();
4967   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4968     return DAG.getUNDEF(VT);
4969 
4970   SDValue Src0 = N->getOperand(1);
4971   SDValue Src1 = N->getOperand(2);
4972   EVT CmpVT = Src0.getValueType();
4973   SDLoc SL(N);
4974 
4975   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4976     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4977     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4978   }
4979 
4980   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4981   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4982   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4983   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4984   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4985                               Src1, DAG.getCondCode(CCOpcode));
4986   if (VT.bitsEq(CCVT))
4987     return SetCC;
4988   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4989 }
4990 
4991 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4992                                     SelectionDAG &DAG) {
4993   EVT VT = N->getValueType(0);
4994   SDValue Src = N->getOperand(1);
4995   SDLoc SL(N);
4996 
4997   if (Src.getOpcode() == ISD::SETCC) {
4998     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4999     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
5000                        Src.getOperand(1), Src.getOperand(2));
5001   }
5002   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
5003     // (ballot 0) -> 0
5004     if (Arg->isZero())
5005       return DAG.getConstant(0, SL, VT);
5006 
5007     // (ballot 1) -> EXEC/EXEC_LO
5008     if (Arg->isOne()) {
5009       Register Exec;
5010       if (VT.getScalarSizeInBits() == 32)
5011         Exec = AMDGPU::EXEC_LO;
5012       else if (VT.getScalarSizeInBits() == 64)
5013         Exec = AMDGPU::EXEC;
5014       else
5015         return SDValue();
5016 
5017       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
5018     }
5019   }
5020 
5021   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
5022   // ISD::SETNE)
5023   return DAG.getNode(
5024       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
5025       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
5026 }
5027 
5028 void SITargetLowering::ReplaceNodeResults(SDNode *N,
5029                                           SmallVectorImpl<SDValue> &Results,
5030                                           SelectionDAG &DAG) const {
5031   switch (N->getOpcode()) {
5032   case ISD::INSERT_VECTOR_ELT: {
5033     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
5034       Results.push_back(Res);
5035     return;
5036   }
5037   case ISD::EXTRACT_VECTOR_ELT: {
5038     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
5039       Results.push_back(Res);
5040     return;
5041   }
5042   case ISD::INTRINSIC_WO_CHAIN: {
5043     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5044     switch (IID) {
5045     case Intrinsic::amdgcn_cvt_pkrtz: {
5046       SDValue Src0 = N->getOperand(1);
5047       SDValue Src1 = N->getOperand(2);
5048       SDLoc SL(N);
5049       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
5050                                 Src0, Src1);
5051       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
5052       return;
5053     }
5054     case Intrinsic::amdgcn_cvt_pknorm_i16:
5055     case Intrinsic::amdgcn_cvt_pknorm_u16:
5056     case Intrinsic::amdgcn_cvt_pk_i16:
5057     case Intrinsic::amdgcn_cvt_pk_u16: {
5058       SDValue Src0 = N->getOperand(1);
5059       SDValue Src1 = N->getOperand(2);
5060       SDLoc SL(N);
5061       unsigned Opcode;
5062 
5063       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
5064         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
5065       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
5066         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
5067       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
5068         Opcode = AMDGPUISD::CVT_PK_I16_I32;
5069       else
5070         Opcode = AMDGPUISD::CVT_PK_U16_U32;
5071 
5072       EVT VT = N->getValueType(0);
5073       if (isTypeLegal(VT))
5074         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
5075       else {
5076         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
5077         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
5078       }
5079       return;
5080     }
5081     }
5082     break;
5083   }
5084   case ISD::INTRINSIC_W_CHAIN: {
5085     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
5086       if (Res.getOpcode() == ISD::MERGE_VALUES) {
5087         // FIXME: Hacky
5088         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
5089           Results.push_back(Res.getOperand(I));
5090         }
5091       } else {
5092         Results.push_back(Res);
5093         Results.push_back(Res.getValue(1));
5094       }
5095       return;
5096     }
5097 
5098     break;
5099   }
5100   case ISD::SELECT: {
5101     SDLoc SL(N);
5102     EVT VT = N->getValueType(0);
5103     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
5104     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
5105     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
5106 
5107     EVT SelectVT = NewVT;
5108     if (NewVT.bitsLT(MVT::i32)) {
5109       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
5110       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
5111       SelectVT = MVT::i32;
5112     }
5113 
5114     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
5115                                     N->getOperand(0), LHS, RHS);
5116 
5117     if (NewVT != SelectVT)
5118       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
5119     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
5120     return;
5121   }
5122   case ISD::FNEG: {
5123     if (N->getValueType(0) != MVT::v2f16)
5124       break;
5125 
5126     SDLoc SL(N);
5127     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5128 
5129     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
5130                              BC,
5131                              DAG.getConstant(0x80008000, SL, MVT::i32));
5132     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5133     return;
5134   }
5135   case ISD::FABS: {
5136     if (N->getValueType(0) != MVT::v2f16)
5137       break;
5138 
5139     SDLoc SL(N);
5140     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5141 
5142     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
5143                              BC,
5144                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
5145     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5146     return;
5147   }
5148   default:
5149     break;
5150   }
5151 }
5152 
5153 /// Helper function for LowerBRCOND
5154 static SDNode *findUser(SDValue Value, unsigned Opcode) {
5155 
5156   SDNode *Parent = Value.getNode();
5157   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
5158        I != E; ++I) {
5159 
5160     if (I.getUse().get() != Value)
5161       continue;
5162 
5163     if (I->getOpcode() == Opcode)
5164       return *I;
5165   }
5166   return nullptr;
5167 }
5168 
5169 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
5170   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
5171     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
5172     case Intrinsic::amdgcn_if:
5173       return AMDGPUISD::IF;
5174     case Intrinsic::amdgcn_else:
5175       return AMDGPUISD::ELSE;
5176     case Intrinsic::amdgcn_loop:
5177       return AMDGPUISD::LOOP;
5178     case Intrinsic::amdgcn_end_cf:
5179       llvm_unreachable("should not occur");
5180     default:
5181       return 0;
5182     }
5183   }
5184 
5185   // break, if_break, else_break are all only used as inputs to loop, not
5186   // directly as branch conditions.
5187   return 0;
5188 }
5189 
5190 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
5191   const Triple &TT = getTargetMachine().getTargetTriple();
5192   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5193           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5194          AMDGPU::shouldEmitConstantsToTextSection(TT);
5195 }
5196 
5197 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
5198   // FIXME: Either avoid relying on address space here or change the default
5199   // address space for functions to avoid the explicit check.
5200   return (GV->getValueType()->isFunctionTy() ||
5201           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
5202          !shouldEmitFixup(GV) &&
5203          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
5204 }
5205 
5206 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
5207   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
5208 }
5209 
5210 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
5211   if (!GV->hasExternalLinkage())
5212     return true;
5213 
5214   const auto OS = getTargetMachine().getTargetTriple().getOS();
5215   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
5216 }
5217 
5218 /// This transforms the control flow intrinsics to get the branch destination as
5219 /// last parameter, also switches branch target with BR if the need arise
5220 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
5221                                       SelectionDAG &DAG) const {
5222   SDLoc DL(BRCOND);
5223 
5224   SDNode *Intr = BRCOND.getOperand(1).getNode();
5225   SDValue Target = BRCOND.getOperand(2);
5226   SDNode *BR = nullptr;
5227   SDNode *SetCC = nullptr;
5228 
5229   if (Intr->getOpcode() == ISD::SETCC) {
5230     // As long as we negate the condition everything is fine
5231     SetCC = Intr;
5232     Intr = SetCC->getOperand(0).getNode();
5233 
5234   } else {
5235     // Get the target from BR if we don't negate the condition
5236     BR = findUser(BRCOND, ISD::BR);
5237     assert(BR && "brcond missing unconditional branch user");
5238     Target = BR->getOperand(1);
5239   }
5240 
5241   unsigned CFNode = isCFIntrinsic(Intr);
5242   if (CFNode == 0) {
5243     // This is a uniform branch so we don't need to legalize.
5244     return BRCOND;
5245   }
5246 
5247   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5248                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5249 
5250   assert(!SetCC ||
5251         (SetCC->getConstantOperandVal(1) == 1 &&
5252          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5253                                                              ISD::SETNE));
5254 
5255   // operands of the new intrinsic call
5256   SmallVector<SDValue, 4> Ops;
5257   if (HaveChain)
5258     Ops.push_back(BRCOND.getOperand(0));
5259 
5260   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5261   Ops.push_back(Target);
5262 
5263   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5264 
5265   // build the new intrinsic call
5266   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5267 
5268   if (!HaveChain) {
5269     SDValue Ops[] =  {
5270       SDValue(Result, 0),
5271       BRCOND.getOperand(0)
5272     };
5273 
5274     Result = DAG.getMergeValues(Ops, DL).getNode();
5275   }
5276 
5277   if (BR) {
5278     // Give the branch instruction our target
5279     SDValue Ops[] = {
5280       BR->getOperand(0),
5281       BRCOND.getOperand(2)
5282     };
5283     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5284     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5285   }
5286 
5287   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5288 
5289   // Copy the intrinsic results to registers
5290   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5291     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5292     if (!CopyToReg)
5293       continue;
5294 
5295     Chain = DAG.getCopyToReg(
5296       Chain, DL,
5297       CopyToReg->getOperand(1),
5298       SDValue(Result, i - 1),
5299       SDValue());
5300 
5301     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5302   }
5303 
5304   // Remove the old intrinsic from the chain
5305   DAG.ReplaceAllUsesOfValueWith(
5306     SDValue(Intr, Intr->getNumValues() - 1),
5307     Intr->getOperand(0));
5308 
5309   return Chain;
5310 }
5311 
5312 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5313                                           SelectionDAG &DAG) const {
5314   MVT VT = Op.getSimpleValueType();
5315   SDLoc DL(Op);
5316   // Checking the depth
5317   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5318     return DAG.getConstant(0, DL, VT);
5319 
5320   MachineFunction &MF = DAG.getMachineFunction();
5321   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5322   // Check for kernel and shader functions
5323   if (Info->isEntryFunction())
5324     return DAG.getConstant(0, DL, VT);
5325 
5326   MachineFrameInfo &MFI = MF.getFrameInfo();
5327   // There is a call to @llvm.returnaddress in this function
5328   MFI.setReturnAddressIsTaken(true);
5329 
5330   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5331   // Get the return address reg and mark it as an implicit live-in
5332   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5333 
5334   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5335 }
5336 
5337 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5338                                             SDValue Op,
5339                                             const SDLoc &DL,
5340                                             EVT VT) const {
5341   return Op.getValueType().bitsLE(VT) ?
5342       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5343     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5344                 DAG.getTargetConstant(0, DL, MVT::i32));
5345 }
5346 
5347 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5348   assert(Op.getValueType() == MVT::f16 &&
5349          "Do not know how to custom lower FP_ROUND for non-f16 type");
5350 
5351   SDValue Src = Op.getOperand(0);
5352   EVT SrcVT = Src.getValueType();
5353   if (SrcVT != MVT::f64)
5354     return Op;
5355 
5356   SDLoc DL(Op);
5357 
5358   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5359   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5360   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5361 }
5362 
5363 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5364                                                SelectionDAG &DAG) const {
5365   EVT VT = Op.getValueType();
5366   const MachineFunction &MF = DAG.getMachineFunction();
5367   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5368   bool IsIEEEMode = Info->getMode().IEEE;
5369 
5370   // FIXME: Assert during selection that this is only selected for
5371   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5372   // mode functions, but this happens to be OK since it's only done in cases
5373   // where there is known no sNaN.
5374   if (IsIEEEMode)
5375     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5376 
5377   if (VT == MVT::v4f16 || VT == MVT::v8f16)
5378     return splitBinaryVectorOp(Op, DAG);
5379   return Op;
5380 }
5381 
5382 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5383   EVT VT = Op.getValueType();
5384   SDLoc SL(Op);
5385   SDValue LHS = Op.getOperand(0);
5386   SDValue RHS = Op.getOperand(1);
5387   bool isSigned = Op.getOpcode() == ISD::SMULO;
5388 
5389   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5390     const APInt &C = RHSC->getAPIntValue();
5391     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5392     if (C.isPowerOf2()) {
5393       // smulo(x, signed_min) is same as umulo(x, signed_min).
5394       bool UseArithShift = isSigned && !C.isMinSignedValue();
5395       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5396       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5397       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5398           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5399                       SL, VT, Result, ShiftAmt),
5400           LHS, ISD::SETNE);
5401       return DAG.getMergeValues({ Result, Overflow }, SL);
5402     }
5403   }
5404 
5405   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5406   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5407                             SL, VT, LHS, RHS);
5408 
5409   SDValue Sign = isSigned
5410     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5411                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5412     : DAG.getConstant(0, SL, VT);
5413   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5414 
5415   return DAG.getMergeValues({ Result, Overflow }, SL);
5416 }
5417 
5418 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const {
5419   if (Op->isDivergent()) {
5420     // Select to V_MAD_[IU]64_[IU]32.
5421     return Op;
5422   }
5423   if (Subtarget->hasSMulHi()) {
5424     // Expand to S_MUL_I32 + S_MUL_HI_[IU]32.
5425     return SDValue();
5426   }
5427   // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to
5428   // calculate the high part, so we might as well do the whole thing with
5429   // V_MAD_[IU]64_[IU]32.
5430   return Op;
5431 }
5432 
5433 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5434   if (!Subtarget->isTrapHandlerEnabled() ||
5435       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5436     return lowerTrapEndpgm(Op, DAG);
5437 
5438   if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) {
5439     switch (*HsaAbiVer) {
5440     case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
5441     case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
5442       return lowerTrapHsaQueuePtr(Op, DAG);
5443     case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
5444     case ELF::ELFABIVERSION_AMDGPU_HSA_V5:
5445       return Subtarget->supportsGetDoorbellID() ?
5446           lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG);
5447     }
5448   }
5449 
5450   llvm_unreachable("Unknown trap handler");
5451 }
5452 
5453 SDValue SITargetLowering::lowerTrapEndpgm(
5454     SDValue Op, SelectionDAG &DAG) const {
5455   SDLoc SL(Op);
5456   SDValue Chain = Op.getOperand(0);
5457   return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5458 }
5459 
5460 SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5461     SDValue Op, SelectionDAG &DAG) const {
5462   SDLoc SL(Op);
5463   SDValue Chain = Op.getOperand(0);
5464 
5465   MachineFunction &MF = DAG.getMachineFunction();
5466   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5467   Register UserSGPR = Info->getQueuePtrUserSGPR();
5468 
5469   SDValue QueuePtr;
5470   if (UserSGPR == AMDGPU::NoRegister) {
5471     // We probably are in a function incorrectly marked with
5472     // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the trap,
5473     // so just use a null pointer.
5474     QueuePtr = DAG.getConstant(0, SL, MVT::i64);
5475   } else {
5476     QueuePtr = CreateLiveInRegister(
5477       DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5478   }
5479 
5480   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5481   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5482                                    QueuePtr, SDValue());
5483 
5484   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5485   SDValue Ops[] = {
5486     ToReg,
5487     DAG.getTargetConstant(TrapID, SL, MVT::i16),
5488     SGPR01,
5489     ToReg.getValue(1)
5490   };
5491   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5492 }
5493 
5494 SDValue SITargetLowering::lowerTrapHsa(
5495     SDValue Op, SelectionDAG &DAG) const {
5496   SDLoc SL(Op);
5497   SDValue Chain = Op.getOperand(0);
5498 
5499   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5500   SDValue Ops[] = {
5501     Chain,
5502     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5503   };
5504   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5505 }
5506 
5507 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5508   SDLoc SL(Op);
5509   SDValue Chain = Op.getOperand(0);
5510   MachineFunction &MF = DAG.getMachineFunction();
5511 
5512   if (!Subtarget->isTrapHandlerEnabled() ||
5513       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5514     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5515                                      "debugtrap handler not supported",
5516                                      Op.getDebugLoc(),
5517                                      DS_Warning);
5518     LLVMContext &Ctx = MF.getFunction().getContext();
5519     Ctx.diagnose(NoTrap);
5520     return Chain;
5521   }
5522 
5523   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5524   SDValue Ops[] = {
5525     Chain,
5526     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5527   };
5528   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5529 }
5530 
5531 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5532                                              SelectionDAG &DAG) const {
5533   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5534   if (Subtarget->hasApertureRegs()) {
5535     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5536         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5537         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5538     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5539         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5540         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5541     unsigned Encoding =
5542         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5543         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5544         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5545 
5546     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5547     SDValue ApertureReg = SDValue(
5548         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5549     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5550     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5551   }
5552 
5553   MachineFunction &MF = DAG.getMachineFunction();
5554   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5555   Register UserSGPR = Info->getQueuePtrUserSGPR();
5556   if (UserSGPR == AMDGPU::NoRegister) {
5557     // We probably are in a function incorrectly marked with
5558     // amdgpu-no-queue-ptr. This is undefined.
5559     return DAG.getUNDEF(MVT::i32);
5560   }
5561 
5562   SDValue QueuePtr = CreateLiveInRegister(
5563     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5564 
5565   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5566   // private_segment_aperture_base_hi.
5567   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5568 
5569   SDValue Ptr =
5570       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5571 
5572   // TODO: Use custom target PseudoSourceValue.
5573   // TODO: We should use the value from the IR intrinsic call, but it might not
5574   // be available and how do we get it?
5575   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5576   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5577                      commonAlignment(Align(64), StructOffset),
5578                      MachineMemOperand::MODereferenceable |
5579                          MachineMemOperand::MOInvariant);
5580 }
5581 
5582 /// Return true if the value is a known valid address, such that a null check is
5583 /// not necessary.
5584 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG,
5585                            const AMDGPUTargetMachine &TM, unsigned AddrSpace) {
5586   if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) ||
5587       isa<BasicBlockSDNode>(Val))
5588     return true;
5589 
5590   if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val))
5591     return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace);
5592 
5593   // TODO: Search through arithmetic, handle arguments and loads
5594   // marked nonnull.
5595   return false;
5596 }
5597 
5598 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5599                                              SelectionDAG &DAG) const {
5600   SDLoc SL(Op);
5601   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5602 
5603   SDValue Src = ASC->getOperand(0);
5604   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5605   unsigned SrcAS = ASC->getSrcAddressSpace();
5606 
5607   const AMDGPUTargetMachine &TM =
5608     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5609 
5610   // flat -> local/private
5611   if (SrcAS == AMDGPUAS::FLAT_ADDRESS) {
5612     unsigned DestAS = ASC->getDestAddressSpace();
5613 
5614     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5615         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5616       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5617 
5618       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5619         return Ptr;
5620 
5621       unsigned NullVal = TM.getNullPointerValue(DestAS);
5622       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5623       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5624 
5625       return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr,
5626                          SegmentNullPtr);
5627     }
5628   }
5629 
5630   // local/private -> flat
5631   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5632     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5633         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5634 
5635       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5636       SDValue CvtPtr =
5637           DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5638       CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr);
5639 
5640       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5641         return CvtPtr;
5642 
5643       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5644       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5645 
5646       SDValue NonNull
5647         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5648 
5649       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr,
5650                          FlatNullPtr);
5651     }
5652   }
5653 
5654   if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5655       Op.getValueType() == MVT::i64) {
5656     const SIMachineFunctionInfo *Info =
5657         DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>();
5658     SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32);
5659     SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi);
5660     return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
5661   }
5662 
5663   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5664       Src.getValueType() == MVT::i64)
5665     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5666 
5667   // global <-> flat are no-ops and never emitted.
5668 
5669   const MachineFunction &MF = DAG.getMachineFunction();
5670   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5671     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5672   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5673 
5674   return DAG.getUNDEF(ASC->getValueType(0));
5675 }
5676 
5677 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5678 // the small vector and inserting them into the big vector. That is better than
5679 // the default expansion of doing it via a stack slot. Even though the use of
5680 // the stack slot would be optimized away afterwards, the stack slot itself
5681 // remains.
5682 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5683                                                 SelectionDAG &DAG) const {
5684   SDValue Vec = Op.getOperand(0);
5685   SDValue Ins = Op.getOperand(1);
5686   SDValue Idx = Op.getOperand(2);
5687   EVT VecVT = Vec.getValueType();
5688   EVT InsVT = Ins.getValueType();
5689   EVT EltVT = VecVT.getVectorElementType();
5690   unsigned InsNumElts = InsVT.getVectorNumElements();
5691   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5692   SDLoc SL(Op);
5693 
5694   for (unsigned I = 0; I != InsNumElts; ++I) {
5695     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5696                               DAG.getConstant(I, SL, MVT::i32));
5697     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5698                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5699   }
5700   return Vec;
5701 }
5702 
5703 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5704                                                  SelectionDAG &DAG) const {
5705   SDValue Vec = Op.getOperand(0);
5706   SDValue InsVal = Op.getOperand(1);
5707   SDValue Idx = Op.getOperand(2);
5708   EVT VecVT = Vec.getValueType();
5709   EVT EltVT = VecVT.getVectorElementType();
5710   unsigned VecSize = VecVT.getSizeInBits();
5711   unsigned EltSize = EltVT.getSizeInBits();
5712 
5713 
5714   assert(VecSize <= 64);
5715 
5716   unsigned NumElts = VecVT.getVectorNumElements();
5717   SDLoc SL(Op);
5718   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5719 
5720   if (NumElts == 4 && EltSize == 16 && KIdx) {
5721     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5722 
5723     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5724                                  DAG.getConstant(0, SL, MVT::i32));
5725     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5726                                  DAG.getConstant(1, SL, MVT::i32));
5727 
5728     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5729     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5730 
5731     unsigned Idx = KIdx->getZExtValue();
5732     bool InsertLo = Idx < 2;
5733     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5734       InsertLo ? LoVec : HiVec,
5735       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5736       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5737 
5738     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5739 
5740     SDValue Concat = InsertLo ?
5741       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5742       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5743 
5744     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5745   }
5746 
5747   if (isa<ConstantSDNode>(Idx))
5748     return SDValue();
5749 
5750   MVT IntVT = MVT::getIntegerVT(VecSize);
5751 
5752   // Avoid stack access for dynamic indexing.
5753   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5754 
5755   // Create a congruent vector with the target value in each element so that
5756   // the required element can be masked and ORed into the target vector.
5757   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5758                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5759 
5760   assert(isPowerOf2_32(EltSize));
5761   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5762 
5763   // Convert vector index to bit-index.
5764   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5765 
5766   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5767   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5768                             DAG.getConstant(0xffff, SL, IntVT),
5769                             ScaledIdx);
5770 
5771   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5772   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5773                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5774 
5775   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5776   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5777 }
5778 
5779 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5780                                                   SelectionDAG &DAG) const {
5781   SDLoc SL(Op);
5782 
5783   EVT ResultVT = Op.getValueType();
5784   SDValue Vec = Op.getOperand(0);
5785   SDValue Idx = Op.getOperand(1);
5786   EVT VecVT = Vec.getValueType();
5787   unsigned VecSize = VecVT.getSizeInBits();
5788   EVT EltVT = VecVT.getVectorElementType();
5789 
5790   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5791 
5792   // Make sure we do any optimizations that will make it easier to fold
5793   // source modifiers before obscuring it with bit operations.
5794 
5795   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5796   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5797     return Combined;
5798 
5799   if (VecSize == 128) {
5800     SDValue Lo, Hi;
5801     EVT LoVT, HiVT;
5802     SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec);
5803     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5804     Lo =
5805         DAG.getBitcast(LoVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5806                                          V2, DAG.getConstant(0, SL, MVT::i32)));
5807     Hi =
5808         DAG.getBitcast(HiVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5809                                          V2, DAG.getConstant(1, SL, MVT::i32)));
5810     EVT IdxVT = Idx.getValueType();
5811     unsigned NElem = VecVT.getVectorNumElements();
5812     assert(isPowerOf2_32(NElem));
5813     SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT);
5814     SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask);
5815     SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT);
5816     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx);
5817   }
5818 
5819   assert(VecSize <= 64);
5820 
5821   unsigned EltSize = EltVT.getSizeInBits();
5822   assert(isPowerOf2_32(EltSize));
5823 
5824   MVT IntVT = MVT::getIntegerVT(VecSize);
5825   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5826 
5827   // Convert vector index to bit-index (* EltSize)
5828   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5829 
5830   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5831   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5832 
5833   if (ResultVT == MVT::f16) {
5834     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5835     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5836   }
5837 
5838   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5839 }
5840 
5841 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5842   assert(Elt % 2 == 0);
5843   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5844 }
5845 
5846 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5847                                               SelectionDAG &DAG) const {
5848   SDLoc SL(Op);
5849   EVT ResultVT = Op.getValueType();
5850   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5851 
5852   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5853   EVT EltVT = PackVT.getVectorElementType();
5854   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5855 
5856   // vector_shuffle <0,1,6,7> lhs, rhs
5857   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5858   //
5859   // vector_shuffle <6,7,2,3> lhs, rhs
5860   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5861   //
5862   // vector_shuffle <6,7,0,1> lhs, rhs
5863   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5864 
5865   // Avoid scalarizing when both halves are reading from consecutive elements.
5866   SmallVector<SDValue, 4> Pieces;
5867   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5868     if (elementPairIsContiguous(SVN->getMask(), I)) {
5869       const int Idx = SVN->getMaskElt(I);
5870       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5871       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5872       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5873                                     PackVT, SVN->getOperand(VecIdx),
5874                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5875       Pieces.push_back(SubVec);
5876     } else {
5877       const int Idx0 = SVN->getMaskElt(I);
5878       const int Idx1 = SVN->getMaskElt(I + 1);
5879       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5880       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5881       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5882       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5883 
5884       SDValue Vec0 = SVN->getOperand(VecIdx0);
5885       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5886                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5887 
5888       SDValue Vec1 = SVN->getOperand(VecIdx1);
5889       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5890                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5891       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5892     }
5893   }
5894 
5895   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5896 }
5897 
5898 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5899                                             SelectionDAG &DAG) const {
5900   SDLoc SL(Op);
5901   EVT VT = Op.getValueType();
5902 
5903   if (VT == MVT::v4i16 || VT == MVT::v4f16 ||
5904       VT == MVT::v8i16 || VT == MVT::v8f16) {
5905     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(),
5906                                   VT.getVectorNumElements() / 2);
5907     MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits());
5908 
5909     // Turn into pair of packed build_vectors.
5910     // TODO: Special case for constants that can be materialized with s_mov_b64.
5911     SmallVector<SDValue, 4> LoOps, HiOps;
5912     for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) {
5913       LoOps.push_back(Op.getOperand(I));
5914       HiOps.push_back(Op.getOperand(I + E));
5915     }
5916     SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps);
5917     SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps);
5918 
5919     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo);
5920     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi);
5921 
5922     SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL,
5923                                        { CastLo, CastHi });
5924     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5925   }
5926 
5927   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5928   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5929 
5930   SDValue Lo = Op.getOperand(0);
5931   SDValue Hi = Op.getOperand(1);
5932 
5933   // Avoid adding defined bits with the zero_extend.
5934   if (Hi.isUndef()) {
5935     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5936     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5937     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5938   }
5939 
5940   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5941   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5942 
5943   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5944                               DAG.getConstant(16, SL, MVT::i32));
5945   if (Lo.isUndef())
5946     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5947 
5948   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5949   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5950 
5951   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5952   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5953 }
5954 
5955 bool
5956 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5957   // We can fold offsets for anything that doesn't require a GOT relocation.
5958   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5959           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5960           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5961          !shouldEmitGOTReloc(GA->getGlobal());
5962 }
5963 
5964 static SDValue
5965 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5966                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5967                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5968   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5969   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5970   // lowered to the following code sequence:
5971   //
5972   // For constant address space:
5973   //   s_getpc_b64 s[0:1]
5974   //   s_add_u32 s0, s0, $symbol
5975   //   s_addc_u32 s1, s1, 0
5976   //
5977   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5978   //   a fixup or relocation is emitted to replace $symbol with a literal
5979   //   constant, which is a pc-relative offset from the encoding of the $symbol
5980   //   operand to the global variable.
5981   //
5982   // For global address space:
5983   //   s_getpc_b64 s[0:1]
5984   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5985   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5986   //
5987   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5988   //   fixups or relocations are emitted to replace $symbol@*@lo and
5989   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5990   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5991   //   operand to the global variable.
5992   //
5993   // What we want here is an offset from the value returned by s_getpc
5994   // (which is the address of the s_add_u32 instruction) to the global
5995   // variable, but since the encoding of $symbol starts 4 bytes after the start
5996   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5997   // small. This requires us to add 4 to the global variable offset in order to
5998   // compute the correct address. Similarly for the s_addc_u32 instruction, the
5999   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
6000   // instruction.
6001   SDValue PtrLo =
6002       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
6003   SDValue PtrHi;
6004   if (GAFlags == SIInstrInfo::MO_NONE) {
6005     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
6006   } else {
6007     PtrHi =
6008         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
6009   }
6010   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
6011 }
6012 
6013 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
6014                                              SDValue Op,
6015                                              SelectionDAG &DAG) const {
6016   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
6017   SDLoc DL(GSD);
6018   EVT PtrVT = Op.getValueType();
6019 
6020   const GlobalValue *GV = GSD->getGlobal();
6021   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
6022        shouldUseLDSConstAddress(GV)) ||
6023       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
6024       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
6025     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
6026         GV->hasExternalLinkage()) {
6027       Type *Ty = GV->getValueType();
6028       // HIP uses an unsized array `extern __shared__ T s[]` or similar
6029       // zero-sized type in other languages to declare the dynamic shared
6030       // memory which size is not known at the compile time. They will be
6031       // allocated by the runtime and placed directly after the static
6032       // allocated ones. They all share the same offset.
6033       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
6034         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
6035         // Adjust alignment for that dynamic shared memory array.
6036         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
6037         return SDValue(
6038             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
6039       }
6040     }
6041     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
6042   }
6043 
6044   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
6045     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
6046                                             SIInstrInfo::MO_ABS32_LO);
6047     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
6048   }
6049 
6050   if (shouldEmitFixup(GV))
6051     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
6052   else if (shouldEmitPCReloc(GV))
6053     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
6054                                    SIInstrInfo::MO_REL32);
6055 
6056   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
6057                                             SIInstrInfo::MO_GOTPCREL32);
6058 
6059   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
6060   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
6061   const DataLayout &DataLayout = DAG.getDataLayout();
6062   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
6063   MachinePointerInfo PtrInfo
6064     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
6065 
6066   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
6067                      MachineMemOperand::MODereferenceable |
6068                          MachineMemOperand::MOInvariant);
6069 }
6070 
6071 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
6072                                    const SDLoc &DL, SDValue V) const {
6073   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
6074   // the destination register.
6075   //
6076   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
6077   // so we will end up with redundant moves to m0.
6078   //
6079   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
6080 
6081   // A Null SDValue creates a glue result.
6082   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
6083                                   V, Chain);
6084   return SDValue(M0, 0);
6085 }
6086 
6087 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
6088                                                  SDValue Op,
6089                                                  MVT VT,
6090                                                  unsigned Offset) const {
6091   SDLoc SL(Op);
6092   SDValue Param = lowerKernargMemParameter(
6093       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
6094   // The local size values will have the hi 16-bits as zero.
6095   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
6096                      DAG.getValueType(VT));
6097 }
6098 
6099 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6100                                         EVT VT) {
6101   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6102                                       "non-hsa intrinsic with hsa target",
6103                                       DL.getDebugLoc());
6104   DAG.getContext()->diagnose(BadIntrin);
6105   return DAG.getUNDEF(VT);
6106 }
6107 
6108 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6109                                          EVT VT) {
6110   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6111                                       "intrinsic not supported on subtarget",
6112                                       DL.getDebugLoc());
6113   DAG.getContext()->diagnose(BadIntrin);
6114   return DAG.getUNDEF(VT);
6115 }
6116 
6117 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
6118                                     ArrayRef<SDValue> Elts) {
6119   assert(!Elts.empty());
6120   MVT Type;
6121   unsigned NumElts = Elts.size();
6122 
6123   if (NumElts <= 8) {
6124     Type = MVT::getVectorVT(MVT::f32, NumElts);
6125   } else {
6126     assert(Elts.size() <= 16);
6127     Type = MVT::v16f32;
6128     NumElts = 16;
6129   }
6130 
6131   SmallVector<SDValue, 16> VecElts(NumElts);
6132   for (unsigned i = 0; i < Elts.size(); ++i) {
6133     SDValue Elt = Elts[i];
6134     if (Elt.getValueType() != MVT::f32)
6135       Elt = DAG.getBitcast(MVT::f32, Elt);
6136     VecElts[i] = Elt;
6137   }
6138   for (unsigned i = Elts.size(); i < NumElts; ++i)
6139     VecElts[i] = DAG.getUNDEF(MVT::f32);
6140 
6141   if (NumElts == 1)
6142     return VecElts[0];
6143   return DAG.getBuildVector(Type, DL, VecElts);
6144 }
6145 
6146 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
6147                               SDValue Src, int ExtraElts) {
6148   EVT SrcVT = Src.getValueType();
6149 
6150   SmallVector<SDValue, 8> Elts;
6151 
6152   if (SrcVT.isVector())
6153     DAG.ExtractVectorElements(Src, Elts);
6154   else
6155     Elts.push_back(Src);
6156 
6157   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
6158   while (ExtraElts--)
6159     Elts.push_back(Undef);
6160 
6161   return DAG.getBuildVector(CastVT, DL, Elts);
6162 }
6163 
6164 // Re-construct the required return value for a image load intrinsic.
6165 // This is more complicated due to the optional use TexFailCtrl which means the required
6166 // return type is an aggregate
6167 static SDValue constructRetValue(SelectionDAG &DAG,
6168                                  MachineSDNode *Result,
6169                                  ArrayRef<EVT> ResultTypes,
6170                                  bool IsTexFail, bool Unpacked, bool IsD16,
6171                                  int DMaskPop, int NumVDataDwords,
6172                                  const SDLoc &DL) {
6173   // Determine the required return type. This is the same regardless of IsTexFail flag
6174   EVT ReqRetVT = ResultTypes[0];
6175   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
6176   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6177     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
6178 
6179   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6180     DMaskPop : (DMaskPop + 1) / 2;
6181 
6182   MVT DataDwordVT = NumDataDwords == 1 ?
6183     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
6184 
6185   MVT MaskPopVT = MaskPopDwords == 1 ?
6186     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
6187 
6188   SDValue Data(Result, 0);
6189   SDValue TexFail;
6190 
6191   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
6192     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
6193     if (MaskPopVT.isVector()) {
6194       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
6195                          SDValue(Result, 0), ZeroIdx);
6196     } else {
6197       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
6198                          SDValue(Result, 0), ZeroIdx);
6199     }
6200   }
6201 
6202   if (DataDwordVT.isVector())
6203     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
6204                           NumDataDwords - MaskPopDwords);
6205 
6206   if (IsD16)
6207     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
6208 
6209   EVT LegalReqRetVT = ReqRetVT;
6210   if (!ReqRetVT.isVector()) {
6211     if (!Data.getValueType().isInteger())
6212       Data = DAG.getNode(ISD::BITCAST, DL,
6213                          Data.getValueType().changeTypeToInteger(), Data);
6214     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
6215   } else {
6216     // We need to widen the return vector to a legal type
6217     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
6218         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
6219       LegalReqRetVT =
6220           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
6221                            ReqRetVT.getVectorNumElements() + 1);
6222     }
6223   }
6224   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
6225 
6226   if (IsTexFail) {
6227     TexFail =
6228         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
6229                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
6230 
6231     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
6232   }
6233 
6234   if (Result->getNumValues() == 1)
6235     return Data;
6236 
6237   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
6238 }
6239 
6240 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
6241                          SDValue *LWE, bool &IsTexFail) {
6242   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
6243 
6244   uint64_t Value = TexFailCtrlConst->getZExtValue();
6245   if (Value) {
6246     IsTexFail = true;
6247   }
6248 
6249   SDLoc DL(TexFailCtrlConst);
6250   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
6251   Value &= ~(uint64_t)0x1;
6252   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
6253   Value &= ~(uint64_t)0x2;
6254 
6255   return Value == 0;
6256 }
6257 
6258 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
6259                                       MVT PackVectorVT,
6260                                       SmallVectorImpl<SDValue> &PackedAddrs,
6261                                       unsigned DimIdx, unsigned EndIdx,
6262                                       unsigned NumGradients) {
6263   SDLoc DL(Op);
6264   for (unsigned I = DimIdx; I < EndIdx; I++) {
6265     SDValue Addr = Op.getOperand(I);
6266 
6267     // Gradients are packed with undef for each coordinate.
6268     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
6269     // 1D: undef,dx/dh; undef,dx/dv
6270     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
6271     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
6272     if (((I + 1) >= EndIdx) ||
6273         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
6274                                          I == DimIdx + NumGradients - 1))) {
6275       if (Addr.getValueType() != MVT::i16)
6276         Addr = DAG.getBitcast(MVT::i16, Addr);
6277       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
6278     } else {
6279       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
6280       I++;
6281     }
6282     Addr = DAG.getBitcast(MVT::f32, Addr);
6283     PackedAddrs.push_back(Addr);
6284   }
6285 }
6286 
6287 SDValue SITargetLowering::lowerImage(SDValue Op,
6288                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
6289                                      SelectionDAG &DAG, bool WithChain) const {
6290   SDLoc DL(Op);
6291   MachineFunction &MF = DAG.getMachineFunction();
6292   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
6293   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
6294       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
6295   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
6296   unsigned IntrOpcode = Intr->BaseOpcode;
6297   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6298 
6299   SmallVector<EVT, 3> ResultTypes(Op->values());
6300   SmallVector<EVT, 3> OrigResultTypes(Op->values());
6301   bool IsD16 = false;
6302   bool IsG16 = false;
6303   bool IsA16 = false;
6304   SDValue VData;
6305   int NumVDataDwords;
6306   bool AdjustRetType = false;
6307 
6308   // Offset of intrinsic arguments
6309   const unsigned ArgOffset = WithChain ? 2 : 1;
6310 
6311   unsigned DMask;
6312   unsigned DMaskLanes = 0;
6313 
6314   if (BaseOpcode->Atomic) {
6315     VData = Op.getOperand(2);
6316 
6317     bool Is64Bit = VData.getValueType() == MVT::i64;
6318     if (BaseOpcode->AtomicX2) {
6319       SDValue VData2 = Op.getOperand(3);
6320       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6321                                  {VData, VData2});
6322       if (Is64Bit)
6323         VData = DAG.getBitcast(MVT::v4i32, VData);
6324 
6325       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6326       DMask = Is64Bit ? 0xf : 0x3;
6327       NumVDataDwords = Is64Bit ? 4 : 2;
6328     } else {
6329       DMask = Is64Bit ? 0x3 : 0x1;
6330       NumVDataDwords = Is64Bit ? 2 : 1;
6331     }
6332   } else {
6333     auto *DMaskConst =
6334         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6335     DMask = DMaskConst->getZExtValue();
6336     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6337 
6338     if (BaseOpcode->Store) {
6339       VData = Op.getOperand(2);
6340 
6341       MVT StoreVT = VData.getSimpleValueType();
6342       if (StoreVT.getScalarType() == MVT::f16) {
6343         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6344           return Op; // D16 is unsupported for this instruction
6345 
6346         IsD16 = true;
6347         VData = handleD16VData(VData, DAG, true);
6348       }
6349 
6350       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6351     } else {
6352       // Work out the num dwords based on the dmask popcount and underlying type
6353       // and whether packing is supported.
6354       MVT LoadVT = ResultTypes[0].getSimpleVT();
6355       if (LoadVT.getScalarType() == MVT::f16) {
6356         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6357           return Op; // D16 is unsupported for this instruction
6358 
6359         IsD16 = true;
6360       }
6361 
6362       // Confirm that the return type is large enough for the dmask specified
6363       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6364           (!LoadVT.isVector() && DMaskLanes > 1))
6365           return Op;
6366 
6367       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6368       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6369       // instructions.
6370       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6371           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6372         NumVDataDwords = (DMaskLanes + 1) / 2;
6373       else
6374         NumVDataDwords = DMaskLanes;
6375 
6376       AdjustRetType = true;
6377     }
6378   }
6379 
6380   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6381   SmallVector<SDValue, 4> VAddrs;
6382 
6383   // Check for 16 bit addresses or derivatives and pack if true.
6384   MVT VAddrVT =
6385       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6386   MVT VAddrScalarVT = VAddrVT.getScalarType();
6387   MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6388   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6389 
6390   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6391   VAddrScalarVT = VAddrVT.getScalarType();
6392   MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6393   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6394 
6395   // Push back extra arguments.
6396   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) {
6397     if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) {
6398       assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument");
6399       // Special handling of bias when A16 is on. Bias is of type half but
6400       // occupies full 32-bit.
6401       SDValue Bias = DAG.getBuildVector(
6402           MVT::v2f16, DL,
6403           {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)});
6404       VAddrs.push_back(Bias);
6405     } else {
6406       assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) &&
6407              "Bias needs to be converted to 16 bit in A16 mode");
6408       VAddrs.push_back(Op.getOperand(ArgOffset + I));
6409     }
6410   }
6411 
6412   if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
6413     // 16 bit gradients are supported, but are tied to the A16 control
6414     // so both gradients and addresses must be 16 bit
6415     LLVM_DEBUG(
6416         dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6417                   "require 16 bit args for both gradients and addresses");
6418     return Op;
6419   }
6420 
6421   if (IsA16) {
6422     if (!ST->hasA16()) {
6423       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6424                            "support 16 bit addresses\n");
6425       return Op;
6426     }
6427   }
6428 
6429   // We've dealt with incorrect input so we know that if IsA16, IsG16
6430   // are set then we have to compress/pack operands (either address,
6431   // gradient or both)
6432   // In the case where a16 and gradients are tied (no G16 support) then we
6433   // have already verified that both IsA16 and IsG16 are true
6434   if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
6435     // Activate g16
6436     const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6437         AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6438     IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6439   }
6440 
6441   // Add gradients (packed or unpacked)
6442   if (IsG16) {
6443     // Pack the gradients
6444     // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6445     packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
6446                               ArgOffset + Intr->GradientStart,
6447                               ArgOffset + Intr->CoordStart, Intr->NumGradients);
6448   } else {
6449     for (unsigned I = ArgOffset + Intr->GradientStart;
6450          I < ArgOffset + Intr->CoordStart; I++)
6451       VAddrs.push_back(Op.getOperand(I));
6452   }
6453 
6454   // Add addresses (packed or unpacked)
6455   if (IsA16) {
6456     packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
6457                               ArgOffset + Intr->CoordStart, VAddrEnd,
6458                               0 /* No gradients */);
6459   } else {
6460     // Add uncompressed address
6461     for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6462       VAddrs.push_back(Op.getOperand(I));
6463   }
6464 
6465   // If the register allocator cannot place the address registers contiguously
6466   // without introducing moves, then using the non-sequential address encoding
6467   // is always preferable, since it saves VALU instructions and is usually a
6468   // wash in terms of code size or even better.
6469   //
6470   // However, we currently have no way of hinting to the register allocator that
6471   // MIMG addresses should be placed contiguously when it is possible to do so,
6472   // so force non-NSA for the common 2-address case as a heuristic.
6473   //
6474   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6475   // allocation when possible.
6476   bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) &&
6477                 VAddrs.size() >= 3 &&
6478                 VAddrs.size() <= (unsigned)ST->getNSAMaxSize();
6479   SDValue VAddr;
6480   if (!UseNSA)
6481     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6482 
6483   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6484   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6485   SDValue Unorm;
6486   if (!BaseOpcode->Sampler) {
6487     Unorm = True;
6488   } else {
6489     auto UnormConst =
6490         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6491 
6492     Unorm = UnormConst->getZExtValue() ? True : False;
6493   }
6494 
6495   SDValue TFE;
6496   SDValue LWE;
6497   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6498   bool IsTexFail = false;
6499   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6500     return Op;
6501 
6502   if (IsTexFail) {
6503     if (!DMaskLanes) {
6504       // Expecting to get an error flag since TFC is on - and dmask is 0
6505       // Force dmask to be at least 1 otherwise the instruction will fail
6506       DMask = 0x1;
6507       DMaskLanes = 1;
6508       NumVDataDwords = 1;
6509     }
6510     NumVDataDwords += 1;
6511     AdjustRetType = true;
6512   }
6513 
6514   // Has something earlier tagged that the return type needs adjusting
6515   // This happens if the instruction is a load or has set TexFailCtrl flags
6516   if (AdjustRetType) {
6517     // NumVDataDwords reflects the true number of dwords required in the return type
6518     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6519       // This is a no-op load. This can be eliminated
6520       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6521       if (isa<MemSDNode>(Op))
6522         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6523       return Undef;
6524     }
6525 
6526     EVT NewVT = NumVDataDwords > 1 ?
6527                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6528                 : MVT::i32;
6529 
6530     ResultTypes[0] = NewVT;
6531     if (ResultTypes.size() == 3) {
6532       // Original result was aggregate type used for TexFailCtrl results
6533       // The actual instruction returns as a vector type which has now been
6534       // created. Remove the aggregate result.
6535       ResultTypes.erase(&ResultTypes[1]);
6536     }
6537   }
6538 
6539   unsigned CPol = cast<ConstantSDNode>(
6540       Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6541   if (BaseOpcode->Atomic)
6542     CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6543   if (CPol & ~AMDGPU::CPol::ALL)
6544     return Op;
6545 
6546   SmallVector<SDValue, 26> Ops;
6547   if (BaseOpcode->Store || BaseOpcode->Atomic)
6548     Ops.push_back(VData); // vdata
6549   if (UseNSA)
6550     append_range(Ops, VAddrs);
6551   else
6552     Ops.push_back(VAddr);
6553   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6554   if (BaseOpcode->Sampler)
6555     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6556   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6557   if (IsGFX10Plus)
6558     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6559   Ops.push_back(Unorm);
6560   Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6561   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6562                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6563   if (IsGFX10Plus)
6564     Ops.push_back(IsA16 ? True : False);
6565   if (!Subtarget->hasGFX90AInsts()) {
6566     Ops.push_back(TFE); //tfe
6567   } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6568     report_fatal_error("TFE is not supported on this GPU");
6569   }
6570   Ops.push_back(LWE); // lwe
6571   if (!IsGFX10Plus)
6572     Ops.push_back(DimInfo->DA ? True : False);
6573   if (BaseOpcode->HasD16)
6574     Ops.push_back(IsD16 ? True : False);
6575   if (isa<MemSDNode>(Op))
6576     Ops.push_back(Op.getOperand(0)); // chain
6577 
6578   int NumVAddrDwords =
6579       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6580   int Opcode = -1;
6581 
6582   if (IsGFX10Plus) {
6583     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6584                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6585                                           : AMDGPU::MIMGEncGfx10Default,
6586                                    NumVDataDwords, NumVAddrDwords);
6587   } else {
6588     if (Subtarget->hasGFX90AInsts()) {
6589       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6590                                      NumVDataDwords, NumVAddrDwords);
6591       if (Opcode == -1)
6592         report_fatal_error(
6593             "requested image instruction is not supported on this GPU");
6594     }
6595     if (Opcode == -1 &&
6596         Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6597       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6598                                      NumVDataDwords, NumVAddrDwords);
6599     if (Opcode == -1)
6600       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6601                                      NumVDataDwords, NumVAddrDwords);
6602   }
6603   assert(Opcode != -1);
6604 
6605   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6606   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6607     MachineMemOperand *MemRef = MemOp->getMemOperand();
6608     DAG.setNodeMemRefs(NewNode, {MemRef});
6609   }
6610 
6611   if (BaseOpcode->AtomicX2) {
6612     SmallVector<SDValue, 1> Elt;
6613     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6614     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6615   }
6616   if (BaseOpcode->Store)
6617     return SDValue(NewNode, 0);
6618   return constructRetValue(DAG, NewNode,
6619                            OrigResultTypes, IsTexFail,
6620                            Subtarget->hasUnpackedD16VMem(), IsD16,
6621                            DMaskLanes, NumVDataDwords, DL);
6622 }
6623 
6624 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6625                                        SDValue Offset, SDValue CachePolicy,
6626                                        SelectionDAG &DAG) const {
6627   MachineFunction &MF = DAG.getMachineFunction();
6628 
6629   const DataLayout &DataLayout = DAG.getDataLayout();
6630   Align Alignment =
6631       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6632 
6633   MachineMemOperand *MMO = MF.getMachineMemOperand(
6634       MachinePointerInfo(),
6635       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6636           MachineMemOperand::MOInvariant,
6637       VT.getStoreSize(), Alignment);
6638 
6639   if (!Offset->isDivergent()) {
6640     SDValue Ops[] = {
6641         Rsrc,
6642         Offset, // Offset
6643         CachePolicy
6644     };
6645 
6646     // Widen vec3 load to vec4.
6647     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6648       EVT WidenedVT =
6649           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6650       auto WidenedOp = DAG.getMemIntrinsicNode(
6651           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6652           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6653       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6654                                    DAG.getVectorIdxConstant(0, DL));
6655       return Subvector;
6656     }
6657 
6658     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6659                                    DAG.getVTList(VT), Ops, VT, MMO);
6660   }
6661 
6662   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6663   // assume that the buffer is unswizzled.
6664   SmallVector<SDValue, 4> Loads;
6665   unsigned NumLoads = 1;
6666   MVT LoadVT = VT.getSimpleVT();
6667   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6668   assert((LoadVT.getScalarType() == MVT::i32 ||
6669           LoadVT.getScalarType() == MVT::f32));
6670 
6671   if (NumElts == 8 || NumElts == 16) {
6672     NumLoads = NumElts / 4;
6673     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6674   }
6675 
6676   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6677   SDValue Ops[] = {
6678       DAG.getEntryNode(),                               // Chain
6679       Rsrc,                                             // rsrc
6680       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6681       {},                                               // voffset
6682       {},                                               // soffset
6683       {},                                               // offset
6684       CachePolicy,                                      // cachepolicy
6685       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6686   };
6687 
6688   // Use the alignment to ensure that the required offsets will fit into the
6689   // immediate offsets.
6690   setBufferOffsets(Offset, DAG, &Ops[3],
6691                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6692 
6693   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6694   for (unsigned i = 0; i < NumLoads; ++i) {
6695     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6696     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6697                                         LoadVT, MMO, DAG));
6698   }
6699 
6700   if (NumElts == 8 || NumElts == 16)
6701     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6702 
6703   return Loads[0];
6704 }
6705 
6706 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6707                                                   SelectionDAG &DAG) const {
6708   MachineFunction &MF = DAG.getMachineFunction();
6709   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6710 
6711   EVT VT = Op.getValueType();
6712   SDLoc DL(Op);
6713   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6714 
6715   // TODO: Should this propagate fast-math-flags?
6716 
6717   switch (IntrinsicID) {
6718   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6719     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6720       return emitNonHSAIntrinsicError(DAG, DL, VT);
6721     return getPreloadedValue(DAG, *MFI, VT,
6722                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6723   }
6724   case Intrinsic::amdgcn_dispatch_ptr:
6725   case Intrinsic::amdgcn_queue_ptr: {
6726     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6727       DiagnosticInfoUnsupported BadIntrin(
6728           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6729           DL.getDebugLoc());
6730       DAG.getContext()->diagnose(BadIntrin);
6731       return DAG.getUNDEF(VT);
6732     }
6733 
6734     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6735       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6736     return getPreloadedValue(DAG, *MFI, VT, RegID);
6737   }
6738   case Intrinsic::amdgcn_implicitarg_ptr: {
6739     if (MFI->isEntryFunction())
6740       return getImplicitArgPtr(DAG, DL);
6741     return getPreloadedValue(DAG, *MFI, VT,
6742                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6743   }
6744   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6745     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6746       // This only makes sense to call in a kernel, so just lower to null.
6747       return DAG.getConstant(0, DL, VT);
6748     }
6749 
6750     return getPreloadedValue(DAG, *MFI, VT,
6751                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6752   }
6753   case Intrinsic::amdgcn_dispatch_id: {
6754     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6755   }
6756   case Intrinsic::amdgcn_rcp:
6757     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6758   case Intrinsic::amdgcn_rsq:
6759     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6760   case Intrinsic::amdgcn_rsq_legacy:
6761     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6762       return emitRemovedIntrinsicError(DAG, DL, VT);
6763     return SDValue();
6764   case Intrinsic::amdgcn_rcp_legacy:
6765     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6766       return emitRemovedIntrinsicError(DAG, DL, VT);
6767     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6768   case Intrinsic::amdgcn_rsq_clamp: {
6769     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6770       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6771 
6772     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6773     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6774     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6775 
6776     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6777     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6778                               DAG.getConstantFP(Max, DL, VT));
6779     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6780                        DAG.getConstantFP(Min, DL, VT));
6781   }
6782   case Intrinsic::r600_read_ngroups_x:
6783     if (Subtarget->isAmdHsaOS())
6784       return emitNonHSAIntrinsicError(DAG, DL, VT);
6785 
6786     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6787                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6788                                     false);
6789   case Intrinsic::r600_read_ngroups_y:
6790     if (Subtarget->isAmdHsaOS())
6791       return emitNonHSAIntrinsicError(DAG, DL, VT);
6792 
6793     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6794                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6795                                     false);
6796   case Intrinsic::r600_read_ngroups_z:
6797     if (Subtarget->isAmdHsaOS())
6798       return emitNonHSAIntrinsicError(DAG, DL, VT);
6799 
6800     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6801                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6802                                     false);
6803   case Intrinsic::r600_read_global_size_x:
6804     if (Subtarget->isAmdHsaOS())
6805       return emitNonHSAIntrinsicError(DAG, DL, VT);
6806 
6807     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6808                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6809                                     Align(4), false);
6810   case Intrinsic::r600_read_global_size_y:
6811     if (Subtarget->isAmdHsaOS())
6812       return emitNonHSAIntrinsicError(DAG, DL, VT);
6813 
6814     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6815                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6816                                     Align(4), false);
6817   case Intrinsic::r600_read_global_size_z:
6818     if (Subtarget->isAmdHsaOS())
6819       return emitNonHSAIntrinsicError(DAG, DL, VT);
6820 
6821     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6822                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6823                                     Align(4), false);
6824   case Intrinsic::r600_read_local_size_x:
6825     if (Subtarget->isAmdHsaOS())
6826       return emitNonHSAIntrinsicError(DAG, DL, VT);
6827 
6828     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6829                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6830   case Intrinsic::r600_read_local_size_y:
6831     if (Subtarget->isAmdHsaOS())
6832       return emitNonHSAIntrinsicError(DAG, DL, VT);
6833 
6834     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6835                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6836   case Intrinsic::r600_read_local_size_z:
6837     if (Subtarget->isAmdHsaOS())
6838       return emitNonHSAIntrinsicError(DAG, DL, VT);
6839 
6840     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6841                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6842   case Intrinsic::amdgcn_workgroup_id_x:
6843     return getPreloadedValue(DAG, *MFI, VT,
6844                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6845   case Intrinsic::amdgcn_workgroup_id_y:
6846     return getPreloadedValue(DAG, *MFI, VT,
6847                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6848   case Intrinsic::amdgcn_workgroup_id_z:
6849     return getPreloadedValue(DAG, *MFI, VT,
6850                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6851   case Intrinsic::amdgcn_workitem_id_x:
6852     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 0) == 0)
6853       return DAG.getConstant(0, DL, MVT::i32);
6854 
6855     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6856                           SDLoc(DAG.getEntryNode()),
6857                           MFI->getArgInfo().WorkItemIDX);
6858   case Intrinsic::amdgcn_workitem_id_y:
6859     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 1) == 0)
6860       return DAG.getConstant(0, DL, MVT::i32);
6861 
6862     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6863                           SDLoc(DAG.getEntryNode()),
6864                           MFI->getArgInfo().WorkItemIDY);
6865   case Intrinsic::amdgcn_workitem_id_z:
6866     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 2) == 0)
6867       return DAG.getConstant(0, DL, MVT::i32);
6868 
6869     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6870                           SDLoc(DAG.getEntryNode()),
6871                           MFI->getArgInfo().WorkItemIDZ);
6872   case Intrinsic::amdgcn_wavefrontsize:
6873     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6874                            SDLoc(Op), MVT::i32);
6875   case Intrinsic::amdgcn_s_buffer_load: {
6876     unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6877     if (CPol & ~AMDGPU::CPol::ALL)
6878       return Op;
6879     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6880                         DAG);
6881   }
6882   case Intrinsic::amdgcn_fdiv_fast:
6883     return lowerFDIV_FAST(Op, DAG);
6884   case Intrinsic::amdgcn_sin:
6885     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6886 
6887   case Intrinsic::amdgcn_cos:
6888     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6889 
6890   case Intrinsic::amdgcn_mul_u24:
6891     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6892   case Intrinsic::amdgcn_mul_i24:
6893     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6894 
6895   case Intrinsic::amdgcn_log_clamp: {
6896     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6897       return SDValue();
6898 
6899     return emitRemovedIntrinsicError(DAG, DL, VT);
6900   }
6901   case Intrinsic::amdgcn_ldexp:
6902     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6903                        Op.getOperand(1), Op.getOperand(2));
6904 
6905   case Intrinsic::amdgcn_fract:
6906     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6907 
6908   case Intrinsic::amdgcn_class:
6909     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6910                        Op.getOperand(1), Op.getOperand(2));
6911   case Intrinsic::amdgcn_div_fmas:
6912     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6913                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6914                        Op.getOperand(4));
6915 
6916   case Intrinsic::amdgcn_div_fixup:
6917     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6918                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6919 
6920   case Intrinsic::amdgcn_div_scale: {
6921     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6922 
6923     // Translate to the operands expected by the machine instruction. The
6924     // first parameter must be the same as the first instruction.
6925     SDValue Numerator = Op.getOperand(1);
6926     SDValue Denominator = Op.getOperand(2);
6927 
6928     // Note this order is opposite of the machine instruction's operations,
6929     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6930     // intrinsic has the numerator as the first operand to match a normal
6931     // division operation.
6932 
6933     SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator;
6934 
6935     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6936                        Denominator, Numerator);
6937   }
6938   case Intrinsic::amdgcn_icmp: {
6939     // There is a Pat that handles this variant, so return it as-is.
6940     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6941         Op.getConstantOperandVal(2) == 0 &&
6942         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6943       return Op;
6944     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6945   }
6946   case Intrinsic::amdgcn_fcmp: {
6947     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6948   }
6949   case Intrinsic::amdgcn_ballot:
6950     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6951   case Intrinsic::amdgcn_fmed3:
6952     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6953                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6954   case Intrinsic::amdgcn_fdot2:
6955     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6956                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6957                        Op.getOperand(4));
6958   case Intrinsic::amdgcn_fmul_legacy:
6959     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6960                        Op.getOperand(1), Op.getOperand(2));
6961   case Intrinsic::amdgcn_sffbh:
6962     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6963   case Intrinsic::amdgcn_sbfe:
6964     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6965                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6966   case Intrinsic::amdgcn_ubfe:
6967     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6968                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6969   case Intrinsic::amdgcn_cvt_pkrtz:
6970   case Intrinsic::amdgcn_cvt_pknorm_i16:
6971   case Intrinsic::amdgcn_cvt_pknorm_u16:
6972   case Intrinsic::amdgcn_cvt_pk_i16:
6973   case Intrinsic::amdgcn_cvt_pk_u16: {
6974     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6975     EVT VT = Op.getValueType();
6976     unsigned Opcode;
6977 
6978     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6979       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6980     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6981       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6982     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6983       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6984     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6985       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6986     else
6987       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6988 
6989     if (isTypeLegal(VT))
6990       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6991 
6992     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6993                                Op.getOperand(1), Op.getOperand(2));
6994     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6995   }
6996   case Intrinsic::amdgcn_fmad_ftz:
6997     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6998                        Op.getOperand(2), Op.getOperand(3));
6999 
7000   case Intrinsic::amdgcn_if_break:
7001     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
7002                                       Op->getOperand(1), Op->getOperand(2)), 0);
7003 
7004   case Intrinsic::amdgcn_groupstaticsize: {
7005     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
7006     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
7007       return Op;
7008 
7009     const Module *M = MF.getFunction().getParent();
7010     const GlobalValue *GV =
7011         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
7012     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
7013                                             SIInstrInfo::MO_ABS32_LO);
7014     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
7015   }
7016   case Intrinsic::amdgcn_is_shared:
7017   case Intrinsic::amdgcn_is_private: {
7018     SDLoc SL(Op);
7019     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
7020       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
7021     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
7022     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
7023                                  Op.getOperand(1));
7024 
7025     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
7026                                 DAG.getConstant(1, SL, MVT::i32));
7027     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
7028   }
7029   case Intrinsic::amdgcn_perm:
7030     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
7031                        Op.getOperand(2), Op.getOperand(3));
7032   case Intrinsic::amdgcn_reloc_constant: {
7033     Module *M = const_cast<Module *>(MF.getFunction().getParent());
7034     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
7035     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
7036     auto RelocSymbol = cast<GlobalVariable>(
7037         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
7038     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
7039                                             SIInstrInfo::MO_ABS32_LO);
7040     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
7041   }
7042   default:
7043     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7044             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7045       return lowerImage(Op, ImageDimIntr, DAG, false);
7046 
7047     return Op;
7048   }
7049 }
7050 
7051 /// Update \p MMO based on the offset inputs to an intrinsic.
7052 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset,
7053                             SDValue SOffset, SDValue Offset,
7054                             SDValue VIndex = SDValue()) {
7055   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
7056       !isa<ConstantSDNode>(Offset)) {
7057     // The combined offset is not known to be constant, so we cannot represent
7058     // it in the MMO. Give up.
7059     MMO->setValue((Value *)nullptr);
7060     return;
7061   }
7062 
7063   if (VIndex && (!isa<ConstantSDNode>(VIndex) ||
7064                  !cast<ConstantSDNode>(VIndex)->isZero())) {
7065     // The strided index component of the address is not known to be zero, so we
7066     // cannot represent it in the MMO. Give up.
7067     MMO->setValue((Value *)nullptr);
7068     return;
7069   }
7070 
7071   MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() +
7072                  cast<ConstantSDNode>(SOffset)->getSExtValue() +
7073                  cast<ConstantSDNode>(Offset)->getSExtValue());
7074 }
7075 
7076 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
7077                                                      SelectionDAG &DAG,
7078                                                      unsigned NewOpcode) const {
7079   SDLoc DL(Op);
7080 
7081   SDValue VData = Op.getOperand(2);
7082   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7083   SDValue Ops[] = {
7084     Op.getOperand(0), // Chain
7085     VData,            // vdata
7086     Op.getOperand(3), // rsrc
7087     DAG.getConstant(0, DL, MVT::i32), // vindex
7088     Offsets.first,    // voffset
7089     Op.getOperand(5), // soffset
7090     Offsets.second,   // offset
7091     Op.getOperand(6), // cachepolicy
7092     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7093   };
7094 
7095   auto *M = cast<MemSDNode>(Op);
7096   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
7097 
7098   EVT MemVT = VData.getValueType();
7099   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7100                                  M->getMemOperand());
7101 }
7102 
7103 // Return a value to use for the idxen operand by examining the vindex operand.
7104 static unsigned getIdxEn(SDValue VIndex) {
7105   if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex))
7106     // No need to set idxen if vindex is known to be zero.
7107     return VIndexC->getZExtValue() != 0;
7108   return 1;
7109 }
7110 
7111 SDValue
7112 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
7113                                                 unsigned NewOpcode) const {
7114   SDLoc DL(Op);
7115 
7116   SDValue VData = Op.getOperand(2);
7117   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7118   SDValue Ops[] = {
7119     Op.getOperand(0), // Chain
7120     VData,            // vdata
7121     Op.getOperand(3), // rsrc
7122     Op.getOperand(4), // vindex
7123     Offsets.first,    // voffset
7124     Op.getOperand(6), // soffset
7125     Offsets.second,   // offset
7126     Op.getOperand(7), // cachepolicy
7127     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7128   };
7129 
7130   auto *M = cast<MemSDNode>(Op);
7131   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7132 
7133   EVT MemVT = VData.getValueType();
7134   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7135                                  M->getMemOperand());
7136 }
7137 
7138 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
7139                                                  SelectionDAG &DAG) const {
7140   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7141   SDLoc DL(Op);
7142 
7143   switch (IntrID) {
7144   case Intrinsic::amdgcn_ds_ordered_add:
7145   case Intrinsic::amdgcn_ds_ordered_swap: {
7146     MemSDNode *M = cast<MemSDNode>(Op);
7147     SDValue Chain = M->getOperand(0);
7148     SDValue M0 = M->getOperand(2);
7149     SDValue Value = M->getOperand(3);
7150     unsigned IndexOperand = M->getConstantOperandVal(7);
7151     unsigned WaveRelease = M->getConstantOperandVal(8);
7152     unsigned WaveDone = M->getConstantOperandVal(9);
7153 
7154     unsigned OrderedCountIndex = IndexOperand & 0x3f;
7155     IndexOperand &= ~0x3f;
7156     unsigned CountDw = 0;
7157 
7158     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
7159       CountDw = (IndexOperand >> 24) & 0xf;
7160       IndexOperand &= ~(0xf << 24);
7161 
7162       if (CountDw < 1 || CountDw > 4) {
7163         report_fatal_error(
7164             "ds_ordered_count: dword count must be between 1 and 4");
7165       }
7166     }
7167 
7168     if (IndexOperand)
7169       report_fatal_error("ds_ordered_count: bad index operand");
7170 
7171     if (WaveDone && !WaveRelease)
7172       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
7173 
7174     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
7175     unsigned ShaderType =
7176         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
7177     unsigned Offset0 = OrderedCountIndex << 2;
7178     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
7179                        (Instruction << 4);
7180 
7181     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
7182       Offset1 |= (CountDw - 1) << 6;
7183 
7184     unsigned Offset = Offset0 | (Offset1 << 8);
7185 
7186     SDValue Ops[] = {
7187       Chain,
7188       Value,
7189       DAG.getTargetConstant(Offset, DL, MVT::i16),
7190       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
7191     };
7192     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
7193                                    M->getVTList(), Ops, M->getMemoryVT(),
7194                                    M->getMemOperand());
7195   }
7196   case Intrinsic::amdgcn_ds_fadd: {
7197     MemSDNode *M = cast<MemSDNode>(Op);
7198     unsigned Opc;
7199     switch (IntrID) {
7200     case Intrinsic::amdgcn_ds_fadd:
7201       Opc = ISD::ATOMIC_LOAD_FADD;
7202       break;
7203     }
7204 
7205     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
7206                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
7207                          M->getMemOperand());
7208   }
7209   case Intrinsic::amdgcn_atomic_inc:
7210   case Intrinsic::amdgcn_atomic_dec:
7211   case Intrinsic::amdgcn_ds_fmin:
7212   case Intrinsic::amdgcn_ds_fmax: {
7213     MemSDNode *M = cast<MemSDNode>(Op);
7214     unsigned Opc;
7215     switch (IntrID) {
7216     case Intrinsic::amdgcn_atomic_inc:
7217       Opc = AMDGPUISD::ATOMIC_INC;
7218       break;
7219     case Intrinsic::amdgcn_atomic_dec:
7220       Opc = AMDGPUISD::ATOMIC_DEC;
7221       break;
7222     case Intrinsic::amdgcn_ds_fmin:
7223       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
7224       break;
7225     case Intrinsic::amdgcn_ds_fmax:
7226       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
7227       break;
7228     default:
7229       llvm_unreachable("Unknown intrinsic!");
7230     }
7231     SDValue Ops[] = {
7232       M->getOperand(0), // Chain
7233       M->getOperand(2), // Ptr
7234       M->getOperand(3)  // Value
7235     };
7236 
7237     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
7238                                    M->getMemoryVT(), M->getMemOperand());
7239   }
7240   case Intrinsic::amdgcn_buffer_load:
7241   case Intrinsic::amdgcn_buffer_load_format: {
7242     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
7243     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7244     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7245     SDValue Ops[] = {
7246       Op.getOperand(0), // Chain
7247       Op.getOperand(2), // rsrc
7248       Op.getOperand(3), // vindex
7249       SDValue(),        // voffset -- will be set by setBufferOffsets
7250       SDValue(),        // soffset -- will be set by setBufferOffsets
7251       SDValue(),        // offset -- will be set by setBufferOffsets
7252       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7253       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7254     };
7255     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
7256 
7257     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
7258         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
7259 
7260     EVT VT = Op.getValueType();
7261     EVT IntVT = VT.changeTypeToInteger();
7262     auto *M = cast<MemSDNode>(Op);
7263     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7264     EVT LoadVT = Op.getValueType();
7265 
7266     if (LoadVT.getScalarType() == MVT::f16)
7267       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
7268                                  M, DAG, Ops);
7269 
7270     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
7271     if (LoadVT.getScalarType() == MVT::i8 ||
7272         LoadVT.getScalarType() == MVT::i16)
7273       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
7274 
7275     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
7276                                M->getMemOperand(), DAG);
7277   }
7278   case Intrinsic::amdgcn_raw_buffer_load:
7279   case Intrinsic::amdgcn_raw_buffer_load_format: {
7280     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
7281 
7282     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7283     SDValue Ops[] = {
7284       Op.getOperand(0), // Chain
7285       Op.getOperand(2), // rsrc
7286       DAG.getConstant(0, DL, MVT::i32), // vindex
7287       Offsets.first,    // voffset
7288       Op.getOperand(4), // soffset
7289       Offsets.second,   // offset
7290       Op.getOperand(5), // cachepolicy, swizzled buffer
7291       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7292     };
7293 
7294     auto *M = cast<MemSDNode>(Op);
7295     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]);
7296     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
7297   }
7298   case Intrinsic::amdgcn_struct_buffer_load:
7299   case Intrinsic::amdgcn_struct_buffer_load_format: {
7300     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
7301 
7302     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7303     SDValue Ops[] = {
7304       Op.getOperand(0), // Chain
7305       Op.getOperand(2), // rsrc
7306       Op.getOperand(3), // vindex
7307       Offsets.first,    // voffset
7308       Op.getOperand(5), // soffset
7309       Offsets.second,   // offset
7310       Op.getOperand(6), // cachepolicy, swizzled buffer
7311       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7312     };
7313 
7314     auto *M = cast<MemSDNode>(Op);
7315     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7316     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7317   }
7318   case Intrinsic::amdgcn_tbuffer_load: {
7319     MemSDNode *M = cast<MemSDNode>(Op);
7320     EVT LoadVT = Op.getValueType();
7321 
7322     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7323     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7324     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7325     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7326     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7327     SDValue Ops[] = {
7328       Op.getOperand(0),  // Chain
7329       Op.getOperand(2),  // rsrc
7330       Op.getOperand(3),  // vindex
7331       Op.getOperand(4),  // voffset
7332       Op.getOperand(5),  // soffset
7333       Op.getOperand(6),  // offset
7334       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7335       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7336       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7337     };
7338 
7339     if (LoadVT.getScalarType() == MVT::f16)
7340       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7341                                  M, DAG, Ops);
7342     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7343                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7344                                DAG);
7345   }
7346   case Intrinsic::amdgcn_raw_tbuffer_load: {
7347     MemSDNode *M = cast<MemSDNode>(Op);
7348     EVT LoadVT = Op.getValueType();
7349     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7350 
7351     SDValue Ops[] = {
7352       Op.getOperand(0),  // Chain
7353       Op.getOperand(2),  // rsrc
7354       DAG.getConstant(0, DL, MVT::i32), // vindex
7355       Offsets.first,     // voffset
7356       Op.getOperand(4),  // soffset
7357       Offsets.second,    // offset
7358       Op.getOperand(5),  // format
7359       Op.getOperand(6),  // cachepolicy, swizzled buffer
7360       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7361     };
7362 
7363     if (LoadVT.getScalarType() == MVT::f16)
7364       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7365                                  M, DAG, Ops);
7366     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7367                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7368                                DAG);
7369   }
7370   case Intrinsic::amdgcn_struct_tbuffer_load: {
7371     MemSDNode *M = cast<MemSDNode>(Op);
7372     EVT LoadVT = Op.getValueType();
7373     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7374 
7375     SDValue Ops[] = {
7376       Op.getOperand(0),  // Chain
7377       Op.getOperand(2),  // rsrc
7378       Op.getOperand(3),  // vindex
7379       Offsets.first,     // voffset
7380       Op.getOperand(5),  // soffset
7381       Offsets.second,    // offset
7382       Op.getOperand(6),  // format
7383       Op.getOperand(7),  // cachepolicy, swizzled buffer
7384       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7385     };
7386 
7387     if (LoadVT.getScalarType() == MVT::f16)
7388       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7389                                  M, DAG, Ops);
7390     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7391                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7392                                DAG);
7393   }
7394   case Intrinsic::amdgcn_buffer_atomic_swap:
7395   case Intrinsic::amdgcn_buffer_atomic_add:
7396   case Intrinsic::amdgcn_buffer_atomic_sub:
7397   case Intrinsic::amdgcn_buffer_atomic_csub:
7398   case Intrinsic::amdgcn_buffer_atomic_smin:
7399   case Intrinsic::amdgcn_buffer_atomic_umin:
7400   case Intrinsic::amdgcn_buffer_atomic_smax:
7401   case Intrinsic::amdgcn_buffer_atomic_umax:
7402   case Intrinsic::amdgcn_buffer_atomic_and:
7403   case Intrinsic::amdgcn_buffer_atomic_or:
7404   case Intrinsic::amdgcn_buffer_atomic_xor:
7405   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7406     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7407     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7408     SDValue Ops[] = {
7409       Op.getOperand(0), // Chain
7410       Op.getOperand(2), // vdata
7411       Op.getOperand(3), // rsrc
7412       Op.getOperand(4), // vindex
7413       SDValue(),        // voffset -- will be set by setBufferOffsets
7414       SDValue(),        // soffset -- will be set by setBufferOffsets
7415       SDValue(),        // offset -- will be set by setBufferOffsets
7416       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7417       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7418     };
7419     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7420 
7421     EVT VT = Op.getValueType();
7422 
7423     auto *M = cast<MemSDNode>(Op);
7424     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7425     unsigned Opcode = 0;
7426 
7427     switch (IntrID) {
7428     case Intrinsic::amdgcn_buffer_atomic_swap:
7429       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7430       break;
7431     case Intrinsic::amdgcn_buffer_atomic_add:
7432       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7433       break;
7434     case Intrinsic::amdgcn_buffer_atomic_sub:
7435       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7436       break;
7437     case Intrinsic::amdgcn_buffer_atomic_csub:
7438       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7439       break;
7440     case Intrinsic::amdgcn_buffer_atomic_smin:
7441       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7442       break;
7443     case Intrinsic::amdgcn_buffer_atomic_umin:
7444       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7445       break;
7446     case Intrinsic::amdgcn_buffer_atomic_smax:
7447       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7448       break;
7449     case Intrinsic::amdgcn_buffer_atomic_umax:
7450       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7451       break;
7452     case Intrinsic::amdgcn_buffer_atomic_and:
7453       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7454       break;
7455     case Intrinsic::amdgcn_buffer_atomic_or:
7456       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7457       break;
7458     case Intrinsic::amdgcn_buffer_atomic_xor:
7459       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7460       break;
7461     case Intrinsic::amdgcn_buffer_atomic_fadd:
7462       if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7463         DiagnosticInfoUnsupported
7464           NoFpRet(DAG.getMachineFunction().getFunction(),
7465                   "return versions of fp atomics not supported",
7466                   DL.getDebugLoc(), DS_Error);
7467         DAG.getContext()->diagnose(NoFpRet);
7468         return SDValue();
7469       }
7470       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7471       break;
7472     default:
7473       llvm_unreachable("unhandled atomic opcode");
7474     }
7475 
7476     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7477                                    M->getMemOperand());
7478   }
7479   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7480     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7481   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7482     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7483   case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7484     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7485   case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7486     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7487   case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7488     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7489   case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7490     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7491   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7492     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7493   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7494     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7495   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7496     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7497   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7498     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7499   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7500     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7501   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7502     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7503   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7504     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7505   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7506     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7507   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7508     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7509   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7510     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7511   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7512     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7513   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7514     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7515   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7516     return lowerStructBufferAtomicIntrin(Op, DAG,
7517                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7518   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7519     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7520   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7521     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7522   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7523     return lowerStructBufferAtomicIntrin(Op, DAG,
7524                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7525   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7526     return lowerStructBufferAtomicIntrin(Op, DAG,
7527                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7528   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7529     return lowerStructBufferAtomicIntrin(Op, DAG,
7530                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7531   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7532     return lowerStructBufferAtomicIntrin(Op, DAG,
7533                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7534   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7535     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7536   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7537     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7538   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7539     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7540   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7541     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7542   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7543     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7544 
7545   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7546     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7547     unsigned IdxEn = getIdxEn(Op.getOperand(5));
7548     SDValue Ops[] = {
7549       Op.getOperand(0), // Chain
7550       Op.getOperand(2), // src
7551       Op.getOperand(3), // cmp
7552       Op.getOperand(4), // rsrc
7553       Op.getOperand(5), // vindex
7554       SDValue(),        // voffset -- will be set by setBufferOffsets
7555       SDValue(),        // soffset -- will be set by setBufferOffsets
7556       SDValue(),        // offset -- will be set by setBufferOffsets
7557       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7558       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7559     };
7560     setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7561 
7562     EVT VT = Op.getValueType();
7563     auto *M = cast<MemSDNode>(Op);
7564     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7565 
7566     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7567                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7568   }
7569   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7570     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7571     SDValue Ops[] = {
7572       Op.getOperand(0), // Chain
7573       Op.getOperand(2), // src
7574       Op.getOperand(3), // cmp
7575       Op.getOperand(4), // rsrc
7576       DAG.getConstant(0, DL, MVT::i32), // vindex
7577       Offsets.first,    // voffset
7578       Op.getOperand(6), // soffset
7579       Offsets.second,   // offset
7580       Op.getOperand(7), // cachepolicy
7581       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7582     };
7583     EVT VT = Op.getValueType();
7584     auto *M = cast<MemSDNode>(Op);
7585     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]);
7586 
7587     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7588                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7589   }
7590   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7591     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7592     SDValue Ops[] = {
7593       Op.getOperand(0), // Chain
7594       Op.getOperand(2), // src
7595       Op.getOperand(3), // cmp
7596       Op.getOperand(4), // rsrc
7597       Op.getOperand(5), // vindex
7598       Offsets.first,    // voffset
7599       Op.getOperand(7), // soffset
7600       Offsets.second,   // offset
7601       Op.getOperand(8), // cachepolicy
7602       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7603     };
7604     EVT VT = Op.getValueType();
7605     auto *M = cast<MemSDNode>(Op);
7606     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7607 
7608     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7609                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7610   }
7611   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7612     MemSDNode *M = cast<MemSDNode>(Op);
7613     SDValue NodePtr = M->getOperand(2);
7614     SDValue RayExtent = M->getOperand(3);
7615     SDValue RayOrigin = M->getOperand(4);
7616     SDValue RayDir = M->getOperand(5);
7617     SDValue RayInvDir = M->getOperand(6);
7618     SDValue TDescr = M->getOperand(7);
7619 
7620     assert(NodePtr.getValueType() == MVT::i32 ||
7621            NodePtr.getValueType() == MVT::i64);
7622     assert(RayDir.getValueType() == MVT::v3f16 ||
7623            RayDir.getValueType() == MVT::v3f32);
7624 
7625     if (!Subtarget->hasGFX10_AEncoding()) {
7626       emitRemovedIntrinsicError(DAG, DL, Op.getValueType());
7627       return SDValue();
7628     }
7629 
7630     const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7631     const bool Is64 = NodePtr.getValueType() == MVT::i64;
7632     const unsigned NumVDataDwords = 4;
7633     const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
7634     const bool UseNSA = Subtarget->hasNSAEncoding() &&
7635                         NumVAddrDwords <= Subtarget->getNSAMaxSize();
7636     const unsigned BaseOpcodes[2][2] = {
7637         {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
7638         {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
7639          AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
7640     int Opcode;
7641     if (UseNSA) {
7642       Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7643                                      AMDGPU::MIMGEncGfx10NSA, NumVDataDwords,
7644                                      NumVAddrDwords);
7645     } else {
7646       Opcode = AMDGPU::getMIMGOpcode(
7647           BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords,
7648           PowerOf2Ceil(NumVAddrDwords));
7649     }
7650     assert(Opcode != -1);
7651 
7652     SmallVector<SDValue, 16> Ops;
7653 
7654     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7655       SmallVector<SDValue, 3> Lanes;
7656       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7657       if (Lanes[0].getValueSizeInBits() == 32) {
7658         for (unsigned I = 0; I < 3; ++I)
7659           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7660       } else {
7661         if (IsAligned) {
7662           Ops.push_back(
7663             DAG.getBitcast(MVT::i32,
7664                            DAG.getBuildVector(MVT::v2f16, DL,
7665                                               { Lanes[0], Lanes[1] })));
7666           Ops.push_back(Lanes[2]);
7667         } else {
7668           SDValue Elt0 = Ops.pop_back_val();
7669           Ops.push_back(
7670             DAG.getBitcast(MVT::i32,
7671                            DAG.getBuildVector(MVT::v2f16, DL,
7672                                               { Elt0, Lanes[0] })));
7673           Ops.push_back(
7674             DAG.getBitcast(MVT::i32,
7675                            DAG.getBuildVector(MVT::v2f16, DL,
7676                                               { Lanes[1], Lanes[2] })));
7677         }
7678       }
7679     };
7680 
7681     if (Is64)
7682       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7683     else
7684       Ops.push_back(NodePtr);
7685 
7686     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7687     packLanes(RayOrigin, true);
7688     packLanes(RayDir, true);
7689     packLanes(RayInvDir, false);
7690 
7691     if (!UseNSA) {
7692       // Build a single vector containing all the operands so far prepared.
7693       if (NumVAddrDwords > 8) {
7694         SDValue Undef = DAG.getUNDEF(MVT::i32);
7695         Ops.append(16 - Ops.size(), Undef);
7696       }
7697       assert(Ops.size() == 8 || Ops.size() == 16);
7698       SDValue MergedOps = DAG.getBuildVector(
7699           Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops);
7700       Ops.clear();
7701       Ops.push_back(MergedOps);
7702     }
7703 
7704     Ops.push_back(TDescr);
7705     if (IsA16)
7706       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7707     Ops.push_back(M->getChain());
7708 
7709     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7710     MachineMemOperand *MemRef = M->getMemOperand();
7711     DAG.setNodeMemRefs(NewNode, {MemRef});
7712     return SDValue(NewNode, 0);
7713   }
7714   case Intrinsic::amdgcn_global_atomic_fadd:
7715     if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7716       DiagnosticInfoUnsupported
7717         NoFpRet(DAG.getMachineFunction().getFunction(),
7718                 "return versions of fp atomics not supported",
7719                 DL.getDebugLoc(), DS_Error);
7720       DAG.getContext()->diagnose(NoFpRet);
7721       return SDValue();
7722     }
7723     LLVM_FALLTHROUGH;
7724   case Intrinsic::amdgcn_global_atomic_fmin:
7725   case Intrinsic::amdgcn_global_atomic_fmax:
7726   case Intrinsic::amdgcn_flat_atomic_fadd:
7727   case Intrinsic::amdgcn_flat_atomic_fmin:
7728   case Intrinsic::amdgcn_flat_atomic_fmax: {
7729     MemSDNode *M = cast<MemSDNode>(Op);
7730     SDValue Ops[] = {
7731       M->getOperand(0), // Chain
7732       M->getOperand(2), // Ptr
7733       M->getOperand(3)  // Value
7734     };
7735     unsigned Opcode = 0;
7736     switch (IntrID) {
7737     case Intrinsic::amdgcn_global_atomic_fadd:
7738     case Intrinsic::amdgcn_flat_atomic_fadd: {
7739       EVT VT = Op.getOperand(3).getValueType();
7740       return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7741                            DAG.getVTList(VT, MVT::Other), Ops,
7742                            M->getMemOperand());
7743     }
7744     case Intrinsic::amdgcn_global_atomic_fmin:
7745     case Intrinsic::amdgcn_flat_atomic_fmin: {
7746       Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7747       break;
7748     }
7749     case Intrinsic::amdgcn_global_atomic_fmax:
7750     case Intrinsic::amdgcn_flat_atomic_fmax: {
7751       Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7752       break;
7753     }
7754     default:
7755       llvm_unreachable("unhandled atomic opcode");
7756     }
7757     return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7758                                    M->getVTList(), Ops, M->getMemoryVT(),
7759                                    M->getMemOperand());
7760   }
7761   default:
7762 
7763     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7764             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7765       return lowerImage(Op, ImageDimIntr, DAG, true);
7766 
7767     return SDValue();
7768   }
7769 }
7770 
7771 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7772 // dwordx4 if on SI.
7773 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7774                                               SDVTList VTList,
7775                                               ArrayRef<SDValue> Ops, EVT MemVT,
7776                                               MachineMemOperand *MMO,
7777                                               SelectionDAG &DAG) const {
7778   EVT VT = VTList.VTs[0];
7779   EVT WidenedVT = VT;
7780   EVT WidenedMemVT = MemVT;
7781   if (!Subtarget->hasDwordx3LoadStores() &&
7782       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7783     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7784                                  WidenedVT.getVectorElementType(), 4);
7785     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7786                                     WidenedMemVT.getVectorElementType(), 4);
7787     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7788   }
7789 
7790   assert(VTList.NumVTs == 2);
7791   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7792 
7793   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7794                                        WidenedMemVT, MMO);
7795   if (WidenedVT != VT) {
7796     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7797                                DAG.getVectorIdxConstant(0, DL));
7798     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7799   }
7800   return NewOp;
7801 }
7802 
7803 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7804                                          bool ImageStore) const {
7805   EVT StoreVT = VData.getValueType();
7806 
7807   // No change for f16 and legal vector D16 types.
7808   if (!StoreVT.isVector())
7809     return VData;
7810 
7811   SDLoc DL(VData);
7812   unsigned NumElements = StoreVT.getVectorNumElements();
7813 
7814   if (Subtarget->hasUnpackedD16VMem()) {
7815     // We need to unpack the packed data to store.
7816     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7817     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7818 
7819     EVT EquivStoreVT =
7820         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7821     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7822     return DAG.UnrollVectorOp(ZExt.getNode());
7823   }
7824 
7825   // The sq block of gfx8.1 does not estimate register use correctly for d16
7826   // image store instructions. The data operand is computed as if it were not a
7827   // d16 image instruction.
7828   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7829     // Bitcast to i16
7830     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7831     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7832 
7833     // Decompose into scalars
7834     SmallVector<SDValue, 4> Elts;
7835     DAG.ExtractVectorElements(IntVData, Elts);
7836 
7837     // Group pairs of i16 into v2i16 and bitcast to i32
7838     SmallVector<SDValue, 4> PackedElts;
7839     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7840       SDValue Pair =
7841           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7842       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7843       PackedElts.push_back(IntPair);
7844     }
7845     if ((NumElements % 2) == 1) {
7846       // Handle v3i16
7847       unsigned I = Elts.size() / 2;
7848       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7849                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7850       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7851       PackedElts.push_back(IntPair);
7852     }
7853 
7854     // Pad using UNDEF
7855     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7856 
7857     // Build final vector
7858     EVT VecVT =
7859         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7860     return DAG.getBuildVector(VecVT, DL, PackedElts);
7861   }
7862 
7863   if (NumElements == 3) {
7864     EVT IntStoreVT =
7865         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7866     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7867 
7868     EVT WidenedStoreVT = EVT::getVectorVT(
7869         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7870     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7871                                          WidenedStoreVT.getStoreSizeInBits());
7872     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7873     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7874   }
7875 
7876   assert(isTypeLegal(StoreVT));
7877   return VData;
7878 }
7879 
7880 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7881                                               SelectionDAG &DAG) const {
7882   SDLoc DL(Op);
7883   SDValue Chain = Op.getOperand(0);
7884   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7885   MachineFunction &MF = DAG.getMachineFunction();
7886 
7887   switch (IntrinsicID) {
7888   case Intrinsic::amdgcn_exp_compr: {
7889     SDValue Src0 = Op.getOperand(4);
7890     SDValue Src1 = Op.getOperand(5);
7891     // Hack around illegal type on SI by directly selecting it.
7892     if (isTypeLegal(Src0.getValueType()))
7893       return SDValue();
7894 
7895     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7896     SDValue Undef = DAG.getUNDEF(MVT::f32);
7897     const SDValue Ops[] = {
7898       Op.getOperand(2), // tgt
7899       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7900       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7901       Undef, // src2
7902       Undef, // src3
7903       Op.getOperand(7), // vm
7904       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7905       Op.getOperand(3), // en
7906       Op.getOperand(0) // Chain
7907     };
7908 
7909     unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7910     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7911   }
7912   case Intrinsic::amdgcn_s_barrier: {
7913     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7914       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7915       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7916       if (WGSize <= ST.getWavefrontSize())
7917         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7918                                           Op.getOperand(0)), 0);
7919     }
7920     return SDValue();
7921   };
7922   case Intrinsic::amdgcn_tbuffer_store: {
7923     SDValue VData = Op.getOperand(2);
7924     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7925     if (IsD16)
7926       VData = handleD16VData(VData, DAG);
7927     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7928     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7929     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7930     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7931     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7932     SDValue Ops[] = {
7933       Chain,
7934       VData,             // vdata
7935       Op.getOperand(3),  // rsrc
7936       Op.getOperand(4),  // vindex
7937       Op.getOperand(5),  // voffset
7938       Op.getOperand(6),  // soffset
7939       Op.getOperand(7),  // offset
7940       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7941       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7942       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7943     };
7944     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7945                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7946     MemSDNode *M = cast<MemSDNode>(Op);
7947     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7948                                    M->getMemoryVT(), M->getMemOperand());
7949   }
7950 
7951   case Intrinsic::amdgcn_struct_tbuffer_store: {
7952     SDValue VData = Op.getOperand(2);
7953     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7954     if (IsD16)
7955       VData = handleD16VData(VData, DAG);
7956     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7957     SDValue Ops[] = {
7958       Chain,
7959       VData,             // vdata
7960       Op.getOperand(3),  // rsrc
7961       Op.getOperand(4),  // vindex
7962       Offsets.first,     // voffset
7963       Op.getOperand(6),  // soffset
7964       Offsets.second,    // offset
7965       Op.getOperand(7),  // format
7966       Op.getOperand(8),  // cachepolicy, swizzled buffer
7967       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7968     };
7969     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7970                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7971     MemSDNode *M = cast<MemSDNode>(Op);
7972     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7973                                    M->getMemoryVT(), M->getMemOperand());
7974   }
7975 
7976   case Intrinsic::amdgcn_raw_tbuffer_store: {
7977     SDValue VData = Op.getOperand(2);
7978     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7979     if (IsD16)
7980       VData = handleD16VData(VData, DAG);
7981     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7982     SDValue Ops[] = {
7983       Chain,
7984       VData,             // vdata
7985       Op.getOperand(3),  // rsrc
7986       DAG.getConstant(0, DL, MVT::i32), // vindex
7987       Offsets.first,     // voffset
7988       Op.getOperand(5),  // soffset
7989       Offsets.second,    // offset
7990       Op.getOperand(6),  // format
7991       Op.getOperand(7),  // cachepolicy, swizzled buffer
7992       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7993     };
7994     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7995                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7996     MemSDNode *M = cast<MemSDNode>(Op);
7997     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7998                                    M->getMemoryVT(), M->getMemOperand());
7999   }
8000 
8001   case Intrinsic::amdgcn_buffer_store:
8002   case Intrinsic::amdgcn_buffer_store_format: {
8003     SDValue VData = Op.getOperand(2);
8004     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8005     if (IsD16)
8006       VData = handleD16VData(VData, DAG);
8007     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
8008     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
8009     unsigned IdxEn = getIdxEn(Op.getOperand(4));
8010     SDValue Ops[] = {
8011       Chain,
8012       VData,
8013       Op.getOperand(3), // rsrc
8014       Op.getOperand(4), // vindex
8015       SDValue(), // voffset -- will be set by setBufferOffsets
8016       SDValue(), // soffset -- will be set by setBufferOffsets
8017       SDValue(), // offset -- will be set by setBufferOffsets
8018       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
8019       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
8020     };
8021     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
8022 
8023     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
8024                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8025     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8026     MemSDNode *M = cast<MemSDNode>(Op);
8027     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8028 
8029     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8030     EVT VDataType = VData.getValueType().getScalarType();
8031     if (VDataType == MVT::i8 || VDataType == MVT::i16)
8032       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8033 
8034     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8035                                    M->getMemoryVT(), M->getMemOperand());
8036   }
8037 
8038   case Intrinsic::amdgcn_raw_buffer_store:
8039   case Intrinsic::amdgcn_raw_buffer_store_format: {
8040     const bool IsFormat =
8041         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
8042 
8043     SDValue VData = Op.getOperand(2);
8044     EVT VDataVT = VData.getValueType();
8045     EVT EltType = VDataVT.getScalarType();
8046     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8047     if (IsD16) {
8048       VData = handleD16VData(VData, DAG);
8049       VDataVT = VData.getValueType();
8050     }
8051 
8052     if (!isTypeLegal(VDataVT)) {
8053       VData =
8054           DAG.getNode(ISD::BITCAST, DL,
8055                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8056     }
8057 
8058     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
8059     SDValue Ops[] = {
8060       Chain,
8061       VData,
8062       Op.getOperand(3), // rsrc
8063       DAG.getConstant(0, DL, MVT::i32), // vindex
8064       Offsets.first,    // voffset
8065       Op.getOperand(5), // soffset
8066       Offsets.second,   // offset
8067       Op.getOperand(6), // cachepolicy, swizzled buffer
8068       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8069     };
8070     unsigned Opc =
8071         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
8072     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8073     MemSDNode *M = cast<MemSDNode>(Op);
8074     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
8075 
8076     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8077     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8078       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
8079 
8080     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8081                                    M->getMemoryVT(), M->getMemOperand());
8082   }
8083 
8084   case Intrinsic::amdgcn_struct_buffer_store:
8085   case Intrinsic::amdgcn_struct_buffer_store_format: {
8086     const bool IsFormat =
8087         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
8088 
8089     SDValue VData = Op.getOperand(2);
8090     EVT VDataVT = VData.getValueType();
8091     EVT EltType = VDataVT.getScalarType();
8092     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8093 
8094     if (IsD16) {
8095       VData = handleD16VData(VData, DAG);
8096       VDataVT = VData.getValueType();
8097     }
8098 
8099     if (!isTypeLegal(VDataVT)) {
8100       VData =
8101           DAG.getNode(ISD::BITCAST, DL,
8102                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8103     }
8104 
8105     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
8106     SDValue Ops[] = {
8107       Chain,
8108       VData,
8109       Op.getOperand(3), // rsrc
8110       Op.getOperand(4), // vindex
8111       Offsets.first,    // voffset
8112       Op.getOperand(6), // soffset
8113       Offsets.second,   // offset
8114       Op.getOperand(7), // cachepolicy, swizzled buffer
8115       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8116     };
8117     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
8118                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8119     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8120     MemSDNode *M = cast<MemSDNode>(Op);
8121     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8122 
8123     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8124     EVT VDataType = VData.getValueType().getScalarType();
8125     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8126       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8127 
8128     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8129                                    M->getMemoryVT(), M->getMemOperand());
8130   }
8131   case Intrinsic::amdgcn_end_cf:
8132     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
8133                                       Op->getOperand(2), Chain), 0);
8134 
8135   default: {
8136     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
8137             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
8138       return lowerImage(Op, ImageDimIntr, DAG, true);
8139 
8140     return Op;
8141   }
8142   }
8143 }
8144 
8145 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
8146 // offset (the offset that is included in bounds checking and swizzling, to be
8147 // split between the instruction's voffset and immoffset fields) and soffset
8148 // (the offset that is excluded from bounds checking and swizzling, to go in
8149 // the instruction's soffset field).  This function takes the first kind of
8150 // offset and figures out how to split it between voffset and immoffset.
8151 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
8152     SDValue Offset, SelectionDAG &DAG) const {
8153   SDLoc DL(Offset);
8154   const unsigned MaxImm = 4095;
8155   SDValue N0 = Offset;
8156   ConstantSDNode *C1 = nullptr;
8157 
8158   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
8159     N0 = SDValue();
8160   else if (DAG.isBaseWithConstantOffset(N0)) {
8161     C1 = cast<ConstantSDNode>(N0.getOperand(1));
8162     N0 = N0.getOperand(0);
8163   }
8164 
8165   if (C1) {
8166     unsigned ImmOffset = C1->getZExtValue();
8167     // If the immediate value is too big for the immoffset field, put the value
8168     // and -4096 into the immoffset field so that the value that is copied/added
8169     // for the voffset field is a multiple of 4096, and it stands more chance
8170     // of being CSEd with the copy/add for another similar load/store.
8171     // However, do not do that rounding down to a multiple of 4096 if that is a
8172     // negative number, as it appears to be illegal to have a negative offset
8173     // in the vgpr, even if adding the immediate offset makes it positive.
8174     unsigned Overflow = ImmOffset & ~MaxImm;
8175     ImmOffset -= Overflow;
8176     if ((int32_t)Overflow < 0) {
8177       Overflow += ImmOffset;
8178       ImmOffset = 0;
8179     }
8180     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
8181     if (Overflow) {
8182       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
8183       if (!N0)
8184         N0 = OverflowVal;
8185       else {
8186         SDValue Ops[] = { N0, OverflowVal };
8187         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
8188       }
8189     }
8190   }
8191   if (!N0)
8192     N0 = DAG.getConstant(0, DL, MVT::i32);
8193   if (!C1)
8194     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
8195   return {N0, SDValue(C1, 0)};
8196 }
8197 
8198 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
8199 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
8200 // pointed to by Offsets.
8201 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
8202                                         SelectionDAG &DAG, SDValue *Offsets,
8203                                         Align Alignment) const {
8204   SDLoc DL(CombinedOffset);
8205   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
8206     uint32_t Imm = C->getZExtValue();
8207     uint32_t SOffset, ImmOffset;
8208     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
8209                                  Alignment)) {
8210       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
8211       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8212       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8213       return;
8214     }
8215   }
8216   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
8217     SDValue N0 = CombinedOffset.getOperand(0);
8218     SDValue N1 = CombinedOffset.getOperand(1);
8219     uint32_t SOffset, ImmOffset;
8220     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
8221     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
8222                                                 Subtarget, Alignment)) {
8223       Offsets[0] = N0;
8224       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8225       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8226       return;
8227     }
8228   }
8229   Offsets[0] = CombinedOffset;
8230   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
8231   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
8232 }
8233 
8234 // Handle 8 bit and 16 bit buffer loads
8235 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
8236                                                      EVT LoadVT, SDLoc DL,
8237                                                      ArrayRef<SDValue> Ops,
8238                                                      MemSDNode *M) const {
8239   EVT IntVT = LoadVT.changeTypeToInteger();
8240   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
8241          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
8242 
8243   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
8244   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
8245                                                Ops, IntVT,
8246                                                M->getMemOperand());
8247   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
8248   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
8249 
8250   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
8251 }
8252 
8253 // Handle 8 bit and 16 bit buffer stores
8254 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
8255                                                       EVT VDataType, SDLoc DL,
8256                                                       SDValue Ops[],
8257                                                       MemSDNode *M) const {
8258   if (VDataType == MVT::f16)
8259     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
8260 
8261   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
8262   Ops[1] = BufferStoreExt;
8263   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
8264                                  AMDGPUISD::BUFFER_STORE_SHORT;
8265   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
8266   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
8267                                      M->getMemOperand());
8268 }
8269 
8270 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
8271                                  ISD::LoadExtType ExtType, SDValue Op,
8272                                  const SDLoc &SL, EVT VT) {
8273   if (VT.bitsLT(Op.getValueType()))
8274     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
8275 
8276   switch (ExtType) {
8277   case ISD::SEXTLOAD:
8278     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
8279   case ISD::ZEXTLOAD:
8280     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
8281   case ISD::EXTLOAD:
8282     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
8283   case ISD::NON_EXTLOAD:
8284     return Op;
8285   }
8286 
8287   llvm_unreachable("invalid ext type");
8288 }
8289 
8290 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
8291   SelectionDAG &DAG = DCI.DAG;
8292   if (Ld->getAlignment() < 4 || Ld->isDivergent())
8293     return SDValue();
8294 
8295   // FIXME: Constant loads should all be marked invariant.
8296   unsigned AS = Ld->getAddressSpace();
8297   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
8298       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
8299       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
8300     return SDValue();
8301 
8302   // Don't do this early, since it may interfere with adjacent load merging for
8303   // illegal types. We can avoid losing alignment information for exotic types
8304   // pre-legalize.
8305   EVT MemVT = Ld->getMemoryVT();
8306   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
8307       MemVT.getSizeInBits() >= 32)
8308     return SDValue();
8309 
8310   SDLoc SL(Ld);
8311 
8312   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
8313          "unexpected vector extload");
8314 
8315   // TODO: Drop only high part of range.
8316   SDValue Ptr = Ld->getBasePtr();
8317   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
8318                                 MVT::i32, SL, Ld->getChain(), Ptr,
8319                                 Ld->getOffset(),
8320                                 Ld->getPointerInfo(), MVT::i32,
8321                                 Ld->getAlignment(),
8322                                 Ld->getMemOperand()->getFlags(),
8323                                 Ld->getAAInfo(),
8324                                 nullptr); // Drop ranges
8325 
8326   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
8327   if (MemVT.isFloatingPoint()) {
8328     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
8329            "unexpected fp extload");
8330     TruncVT = MemVT.changeTypeToInteger();
8331   }
8332 
8333   SDValue Cvt = NewLoad;
8334   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
8335     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
8336                       DAG.getValueType(TruncVT));
8337   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
8338              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
8339     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
8340   } else {
8341     assert(Ld->getExtensionType() == ISD::EXTLOAD);
8342   }
8343 
8344   EVT VT = Ld->getValueType(0);
8345   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8346 
8347   DCI.AddToWorklist(Cvt.getNode());
8348 
8349   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
8350   // the appropriate extension from the 32-bit load.
8351   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
8352   DCI.AddToWorklist(Cvt.getNode());
8353 
8354   // Handle conversion back to floating point if necessary.
8355   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8356 
8357   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8358 }
8359 
8360 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8361   SDLoc DL(Op);
8362   LoadSDNode *Load = cast<LoadSDNode>(Op);
8363   ISD::LoadExtType ExtType = Load->getExtensionType();
8364   EVT MemVT = Load->getMemoryVT();
8365 
8366   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8367     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8368       return SDValue();
8369 
8370     // FIXME: Copied from PPC
8371     // First, load into 32 bits, then truncate to 1 bit.
8372 
8373     SDValue Chain = Load->getChain();
8374     SDValue BasePtr = Load->getBasePtr();
8375     MachineMemOperand *MMO = Load->getMemOperand();
8376 
8377     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8378 
8379     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8380                                    BasePtr, RealMemVT, MMO);
8381 
8382     if (!MemVT.isVector()) {
8383       SDValue Ops[] = {
8384         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8385         NewLD.getValue(1)
8386       };
8387 
8388       return DAG.getMergeValues(Ops, DL);
8389     }
8390 
8391     SmallVector<SDValue, 3> Elts;
8392     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8393       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8394                                 DAG.getConstant(I, DL, MVT::i32));
8395 
8396       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8397     }
8398 
8399     SDValue Ops[] = {
8400       DAG.getBuildVector(MemVT, DL, Elts),
8401       NewLD.getValue(1)
8402     };
8403 
8404     return DAG.getMergeValues(Ops, DL);
8405   }
8406 
8407   if (!MemVT.isVector())
8408     return SDValue();
8409 
8410   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8411          "Custom lowering for non-i32 vectors hasn't been implemented.");
8412 
8413   unsigned Alignment = Load->getAlignment();
8414   unsigned AS = Load->getAddressSpace();
8415   if (Subtarget->hasLDSMisalignedBug() &&
8416       AS == AMDGPUAS::FLAT_ADDRESS &&
8417       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8418     return SplitVectorLoad(Op, DAG);
8419   }
8420 
8421   MachineFunction &MF = DAG.getMachineFunction();
8422   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8423   // If there is a possibilty that flat instruction access scratch memory
8424   // then we need to use the same legalization rules we use for private.
8425   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8426       !Subtarget->hasMultiDwordFlatScratchAddressing())
8427     AS = MFI->hasFlatScratchInit() ?
8428          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8429 
8430   unsigned NumElements = MemVT.getVectorNumElements();
8431 
8432   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8433       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8434     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8435       if (MemVT.isPow2VectorType())
8436         return SDValue();
8437       return WidenOrSplitVectorLoad(Op, DAG);
8438     }
8439     // Non-uniform loads will be selected to MUBUF instructions, so they
8440     // have the same legalization requirements as global and private
8441     // loads.
8442     //
8443   }
8444 
8445   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8446       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8447       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8448     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8449         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8450         Alignment >= 4 && NumElements < 32) {
8451       if (MemVT.isPow2VectorType())
8452         return SDValue();
8453       return WidenOrSplitVectorLoad(Op, DAG);
8454     }
8455     // Non-uniform loads will be selected to MUBUF instructions, so they
8456     // have the same legalization requirements as global and private
8457     // loads.
8458     //
8459   }
8460   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8461       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8462       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8463       AS == AMDGPUAS::FLAT_ADDRESS) {
8464     if (NumElements > 4)
8465       return SplitVectorLoad(Op, DAG);
8466     // v3 loads not supported on SI.
8467     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8468       return WidenOrSplitVectorLoad(Op, DAG);
8469 
8470     // v3 and v4 loads are supported for private and global memory.
8471     return SDValue();
8472   }
8473   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8474     // Depending on the setting of the private_element_size field in the
8475     // resource descriptor, we can only make private accesses up to a certain
8476     // size.
8477     switch (Subtarget->getMaxPrivateElementSize()) {
8478     case 4: {
8479       SDValue Ops[2];
8480       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8481       return DAG.getMergeValues(Ops, DL);
8482     }
8483     case 8:
8484       if (NumElements > 2)
8485         return SplitVectorLoad(Op, DAG);
8486       return SDValue();
8487     case 16:
8488       // Same as global/flat
8489       if (NumElements > 4)
8490         return SplitVectorLoad(Op, DAG);
8491       // v3 loads not supported on SI.
8492       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8493         return WidenOrSplitVectorLoad(Op, DAG);
8494 
8495       return SDValue();
8496     default:
8497       llvm_unreachable("unsupported private_element_size");
8498     }
8499   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8500     // Use ds_read_b128 or ds_read_b96 when possible.
8501     if (Subtarget->hasDS96AndDS128() &&
8502         ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) ||
8503          MemVT.getStoreSize() == 12) &&
8504         allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8505                                            Load->getAlign()))
8506       return SDValue();
8507 
8508     if (NumElements > 2)
8509       return SplitVectorLoad(Op, DAG);
8510 
8511     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8512     // address is negative, then the instruction is incorrectly treated as
8513     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8514     // loads here to avoid emitting ds_read2_b32. We may re-combine the
8515     // load later in the SILoadStoreOptimizer.
8516     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
8517         NumElements == 2 && MemVT.getStoreSize() == 8 &&
8518         Load->getAlignment() < 8) {
8519       return SplitVectorLoad(Op, DAG);
8520     }
8521   }
8522 
8523   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8524                                       MemVT, *Load->getMemOperand())) {
8525     SDValue Ops[2];
8526     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8527     return DAG.getMergeValues(Ops, DL);
8528   }
8529 
8530   return SDValue();
8531 }
8532 
8533 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8534   EVT VT = Op.getValueType();
8535   if (VT.getSizeInBits() == 128)
8536     return splitTernaryVectorOp(Op, DAG);
8537 
8538   assert(VT.getSizeInBits() == 64);
8539 
8540   SDLoc DL(Op);
8541   SDValue Cond = Op.getOperand(0);
8542 
8543   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8544   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8545 
8546   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8547   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8548 
8549   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8550   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8551 
8552   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8553 
8554   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8555   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8556 
8557   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8558 
8559   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8560   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8561 }
8562 
8563 // Catch division cases where we can use shortcuts with rcp and rsq
8564 // instructions.
8565 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8566                                               SelectionDAG &DAG) const {
8567   SDLoc SL(Op);
8568   SDValue LHS = Op.getOperand(0);
8569   SDValue RHS = Op.getOperand(1);
8570   EVT VT = Op.getValueType();
8571   const SDNodeFlags Flags = Op->getFlags();
8572 
8573   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8574 
8575   // Without !fpmath accuracy information, we can't do more because we don't
8576   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8577   if (!AllowInaccurateRcp)
8578     return SDValue();
8579 
8580   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8581     if (CLHS->isExactlyValue(1.0)) {
8582       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8583       // the CI documentation has a worst case error of 1 ulp.
8584       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8585       // use it as long as we aren't trying to use denormals.
8586       //
8587       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8588 
8589       // 1.0 / sqrt(x) -> rsq(x)
8590 
8591       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8592       // error seems really high at 2^29 ULP.
8593       if (RHS.getOpcode() == ISD::FSQRT)
8594         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8595 
8596       // 1.0 / x -> rcp(x)
8597       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8598     }
8599 
8600     // Same as for 1.0, but expand the sign out of the constant.
8601     if (CLHS->isExactlyValue(-1.0)) {
8602       // -1.0 / x -> rcp (fneg x)
8603       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8604       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8605     }
8606   }
8607 
8608   // Turn into multiply by the reciprocal.
8609   // x / y -> x * (1.0 / y)
8610   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8611   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8612 }
8613 
8614 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8615                                                 SelectionDAG &DAG) const {
8616   SDLoc SL(Op);
8617   SDValue X = Op.getOperand(0);
8618   SDValue Y = Op.getOperand(1);
8619   EVT VT = Op.getValueType();
8620   const SDNodeFlags Flags = Op->getFlags();
8621 
8622   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8623                             DAG.getTarget().Options.UnsafeFPMath;
8624   if (!AllowInaccurateDiv)
8625     return SDValue();
8626 
8627   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8628   SDValue One = DAG.getConstantFP(1.0, SL, VT);
8629 
8630   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8631   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8632 
8633   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8634   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8635   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8636   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8637   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8638   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8639 }
8640 
8641 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8642                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8643                           SDNodeFlags Flags) {
8644   if (GlueChain->getNumValues() <= 1) {
8645     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8646   }
8647 
8648   assert(GlueChain->getNumValues() == 3);
8649 
8650   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8651   switch (Opcode) {
8652   default: llvm_unreachable("no chain equivalent for opcode");
8653   case ISD::FMUL:
8654     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8655     break;
8656   }
8657 
8658   return DAG.getNode(Opcode, SL, VTList,
8659                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8660                      Flags);
8661 }
8662 
8663 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8664                            EVT VT, SDValue A, SDValue B, SDValue C,
8665                            SDValue GlueChain, SDNodeFlags Flags) {
8666   if (GlueChain->getNumValues() <= 1) {
8667     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8668   }
8669 
8670   assert(GlueChain->getNumValues() == 3);
8671 
8672   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8673   switch (Opcode) {
8674   default: llvm_unreachable("no chain equivalent for opcode");
8675   case ISD::FMA:
8676     Opcode = AMDGPUISD::FMA_W_CHAIN;
8677     break;
8678   }
8679 
8680   return DAG.getNode(Opcode, SL, VTList,
8681                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8682                      Flags);
8683 }
8684 
8685 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8686   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8687     return FastLowered;
8688 
8689   SDLoc SL(Op);
8690   SDValue Src0 = Op.getOperand(0);
8691   SDValue Src1 = Op.getOperand(1);
8692 
8693   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8694   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8695 
8696   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8697   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8698 
8699   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8700   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8701 
8702   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8703 }
8704 
8705 // Faster 2.5 ULP division that does not support denormals.
8706 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8707   SDLoc SL(Op);
8708   SDValue LHS = Op.getOperand(1);
8709   SDValue RHS = Op.getOperand(2);
8710 
8711   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8712 
8713   const APFloat K0Val(BitsToFloat(0x6f800000));
8714   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8715 
8716   const APFloat K1Val(BitsToFloat(0x2f800000));
8717   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8718 
8719   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8720 
8721   EVT SetCCVT =
8722     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8723 
8724   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8725 
8726   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8727 
8728   // TODO: Should this propagate fast-math-flags?
8729   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8730 
8731   // rcp does not support denormals.
8732   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8733 
8734   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8735 
8736   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8737 }
8738 
8739 // Returns immediate value for setting the F32 denorm mode when using the
8740 // S_DENORM_MODE instruction.
8741 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8742                                     const SDLoc &SL, const GCNSubtarget *ST) {
8743   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8744   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8745                                 ? FP_DENORM_FLUSH_NONE
8746                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8747 
8748   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8749   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8750 }
8751 
8752 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8753   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8754     return FastLowered;
8755 
8756   // The selection matcher assumes anything with a chain selecting to a
8757   // mayRaiseFPException machine instruction. Since we're introducing a chain
8758   // here, we need to explicitly report nofpexcept for the regular fdiv
8759   // lowering.
8760   SDNodeFlags Flags = Op->getFlags();
8761   Flags.setNoFPExcept(true);
8762 
8763   SDLoc SL(Op);
8764   SDValue LHS = Op.getOperand(0);
8765   SDValue RHS = Op.getOperand(1);
8766 
8767   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8768 
8769   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8770 
8771   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8772                                           {RHS, RHS, LHS}, Flags);
8773   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8774                                         {LHS, RHS, LHS}, Flags);
8775 
8776   // Denominator is scaled to not be denormal, so using rcp is ok.
8777   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8778                                   DenominatorScaled, Flags);
8779   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8780                                      DenominatorScaled, Flags);
8781 
8782   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8783                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8784                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8785   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8786 
8787   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8788 
8789   if (!HasFP32Denormals) {
8790     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8791     // lowering. The chain dependence is insufficient, and we need glue. We do
8792     // not need the glue variants in a strictfp function.
8793 
8794     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8795 
8796     SDNode *EnableDenorm;
8797     if (Subtarget->hasDenormModeInst()) {
8798       const SDValue EnableDenormValue =
8799           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8800 
8801       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8802                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8803     } else {
8804       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8805                                                         SL, MVT::i32);
8806       EnableDenorm =
8807           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8808                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8809     }
8810 
8811     SDValue Ops[3] = {
8812       NegDivScale0,
8813       SDValue(EnableDenorm, 0),
8814       SDValue(EnableDenorm, 1)
8815     };
8816 
8817     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8818   }
8819 
8820   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8821                              ApproxRcp, One, NegDivScale0, Flags);
8822 
8823   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8824                              ApproxRcp, Fma0, Flags);
8825 
8826   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8827                            Fma1, Fma1, Flags);
8828 
8829   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8830                              NumeratorScaled, Mul, Flags);
8831 
8832   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8833                              Fma2, Fma1, Mul, Fma2, Flags);
8834 
8835   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8836                              NumeratorScaled, Fma3, Flags);
8837 
8838   if (!HasFP32Denormals) {
8839     SDNode *DisableDenorm;
8840     if (Subtarget->hasDenormModeInst()) {
8841       const SDValue DisableDenormValue =
8842           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8843 
8844       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8845                                   Fma4.getValue(1), DisableDenormValue,
8846                                   Fma4.getValue(2)).getNode();
8847     } else {
8848       const SDValue DisableDenormValue =
8849           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8850 
8851       DisableDenorm = DAG.getMachineNode(
8852           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8853           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8854     }
8855 
8856     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8857                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8858     DAG.setRoot(OutputChain);
8859   }
8860 
8861   SDValue Scale = NumeratorScaled.getValue(1);
8862   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8863                              {Fma4, Fma1, Fma3, Scale}, Flags);
8864 
8865   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8866 }
8867 
8868 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8869   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
8870     return FastLowered;
8871 
8872   SDLoc SL(Op);
8873   SDValue X = Op.getOperand(0);
8874   SDValue Y = Op.getOperand(1);
8875 
8876   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8877 
8878   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8879 
8880   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8881 
8882   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8883 
8884   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8885 
8886   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8887 
8888   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8889 
8890   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8891 
8892   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8893 
8894   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8895   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8896 
8897   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8898                              NegDivScale0, Mul, DivScale1);
8899 
8900   SDValue Scale;
8901 
8902   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8903     // Workaround a hardware bug on SI where the condition output from div_scale
8904     // is not usable.
8905 
8906     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8907 
8908     // Figure out if the scale to use for div_fmas.
8909     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8910     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8911     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8912     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8913 
8914     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8915     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8916 
8917     SDValue Scale0Hi
8918       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8919     SDValue Scale1Hi
8920       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8921 
8922     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8923     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8924     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8925   } else {
8926     Scale = DivScale1.getValue(1);
8927   }
8928 
8929   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8930                              Fma4, Fma3, Mul, Scale);
8931 
8932   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8933 }
8934 
8935 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8936   EVT VT = Op.getValueType();
8937 
8938   if (VT == MVT::f32)
8939     return LowerFDIV32(Op, DAG);
8940 
8941   if (VT == MVT::f64)
8942     return LowerFDIV64(Op, DAG);
8943 
8944   if (VT == MVT::f16)
8945     return LowerFDIV16(Op, DAG);
8946 
8947   llvm_unreachable("Unexpected type for fdiv");
8948 }
8949 
8950 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8951   SDLoc DL(Op);
8952   StoreSDNode *Store = cast<StoreSDNode>(Op);
8953   EVT VT = Store->getMemoryVT();
8954 
8955   if (VT == MVT::i1) {
8956     return DAG.getTruncStore(Store->getChain(), DL,
8957        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8958        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8959   }
8960 
8961   assert(VT.isVector() &&
8962          Store->getValue().getValueType().getScalarType() == MVT::i32);
8963 
8964   unsigned AS = Store->getAddressSpace();
8965   if (Subtarget->hasLDSMisalignedBug() &&
8966       AS == AMDGPUAS::FLAT_ADDRESS &&
8967       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8968     return SplitVectorStore(Op, DAG);
8969   }
8970 
8971   MachineFunction &MF = DAG.getMachineFunction();
8972   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8973   // If there is a possibilty that flat instruction access scratch memory
8974   // then we need to use the same legalization rules we use for private.
8975   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8976       !Subtarget->hasMultiDwordFlatScratchAddressing())
8977     AS = MFI->hasFlatScratchInit() ?
8978          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8979 
8980   unsigned NumElements = VT.getVectorNumElements();
8981   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8982       AS == AMDGPUAS::FLAT_ADDRESS) {
8983     if (NumElements > 4)
8984       return SplitVectorStore(Op, DAG);
8985     // v3 stores not supported on SI.
8986     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8987       return SplitVectorStore(Op, DAG);
8988 
8989     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8990                                         VT, *Store->getMemOperand()))
8991       return expandUnalignedStore(Store, DAG);
8992 
8993     return SDValue();
8994   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8995     switch (Subtarget->getMaxPrivateElementSize()) {
8996     case 4:
8997       return scalarizeVectorStore(Store, DAG);
8998     case 8:
8999       if (NumElements > 2)
9000         return SplitVectorStore(Op, DAG);
9001       return SDValue();
9002     case 16:
9003       if (NumElements > 4 ||
9004           (NumElements == 3 && !Subtarget->enableFlatScratch()))
9005         return SplitVectorStore(Op, DAG);
9006       return SDValue();
9007     default:
9008       llvm_unreachable("unsupported private_element_size");
9009     }
9010   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
9011     // Use ds_write_b128 or ds_write_b96 when possible.
9012     if (Subtarget->hasDS96AndDS128() &&
9013         ((Subtarget->useDS128() && VT.getStoreSize() == 16) ||
9014          (VT.getStoreSize() == 12)) &&
9015         allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
9016                                            Store->getAlign()))
9017       return SDValue();
9018 
9019     if (NumElements > 2)
9020       return SplitVectorStore(Op, DAG);
9021 
9022     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
9023     // address is negative, then the instruction is incorrectly treated as
9024     // out-of-bounds even if base + offsets is in bounds. Split vectorized
9025     // stores here to avoid emitting ds_write2_b32. We may re-combine the
9026     // store later in the SILoadStoreOptimizer.
9027     if (!Subtarget->hasUsableDSOffset() &&
9028         NumElements == 2 && VT.getStoreSize() == 8 &&
9029         Store->getAlignment() < 8) {
9030       return SplitVectorStore(Op, DAG);
9031     }
9032 
9033     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
9034                                         VT, *Store->getMemOperand())) {
9035       if (VT.isVector())
9036         return SplitVectorStore(Op, DAG);
9037       return expandUnalignedStore(Store, DAG);
9038     }
9039 
9040     return SDValue();
9041   } else {
9042     llvm_unreachable("unhandled address space");
9043   }
9044 }
9045 
9046 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
9047   SDLoc DL(Op);
9048   EVT VT = Op.getValueType();
9049   SDValue Arg = Op.getOperand(0);
9050   SDValue TrigVal;
9051 
9052   // Propagate fast-math flags so that the multiply we introduce can be folded
9053   // if Arg is already the result of a multiply by constant.
9054   auto Flags = Op->getFlags();
9055 
9056   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
9057 
9058   if (Subtarget->hasTrigReducedRange()) {
9059     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9060     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
9061   } else {
9062     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9063   }
9064 
9065   switch (Op.getOpcode()) {
9066   case ISD::FCOS:
9067     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
9068   case ISD::FSIN:
9069     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
9070   default:
9071     llvm_unreachable("Wrong trig opcode");
9072   }
9073 }
9074 
9075 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9076   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
9077   assert(AtomicNode->isCompareAndSwap());
9078   unsigned AS = AtomicNode->getAddressSpace();
9079 
9080   // No custom lowering required for local address space
9081   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
9082     return Op;
9083 
9084   // Non-local address space requires custom lowering for atomic compare
9085   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
9086   SDLoc DL(Op);
9087   SDValue ChainIn = Op.getOperand(0);
9088   SDValue Addr = Op.getOperand(1);
9089   SDValue Old = Op.getOperand(2);
9090   SDValue New = Op.getOperand(3);
9091   EVT VT = Op.getValueType();
9092   MVT SimpleVT = VT.getSimpleVT();
9093   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
9094 
9095   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
9096   SDValue Ops[] = { ChainIn, Addr, NewOld };
9097 
9098   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
9099                                  Ops, VT, AtomicNode->getMemOperand());
9100 }
9101 
9102 //===----------------------------------------------------------------------===//
9103 // Custom DAG optimizations
9104 //===----------------------------------------------------------------------===//
9105 
9106 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
9107                                                      DAGCombinerInfo &DCI) const {
9108   EVT VT = N->getValueType(0);
9109   EVT ScalarVT = VT.getScalarType();
9110   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
9111     return SDValue();
9112 
9113   SelectionDAG &DAG = DCI.DAG;
9114   SDLoc DL(N);
9115 
9116   SDValue Src = N->getOperand(0);
9117   EVT SrcVT = Src.getValueType();
9118 
9119   // TODO: We could try to match extracting the higher bytes, which would be
9120   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
9121   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
9122   // about in practice.
9123   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
9124     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
9125       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
9126       DCI.AddToWorklist(Cvt.getNode());
9127 
9128       // For the f16 case, fold to a cast to f32 and then cast back to f16.
9129       if (ScalarVT != MVT::f32) {
9130         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
9131                           DAG.getTargetConstant(0, DL, MVT::i32));
9132       }
9133       return Cvt;
9134     }
9135   }
9136 
9137   return SDValue();
9138 }
9139 
9140 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
9141 
9142 // This is a variant of
9143 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
9144 //
9145 // The normal DAG combiner will do this, but only if the add has one use since
9146 // that would increase the number of instructions.
9147 //
9148 // This prevents us from seeing a constant offset that can be folded into a
9149 // memory instruction's addressing mode. If we know the resulting add offset of
9150 // a pointer can be folded into an addressing offset, we can replace the pointer
9151 // operand with the add of new constant offset. This eliminates one of the uses,
9152 // and may allow the remaining use to also be simplified.
9153 //
9154 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
9155                                                unsigned AddrSpace,
9156                                                EVT MemVT,
9157                                                DAGCombinerInfo &DCI) const {
9158   SDValue N0 = N->getOperand(0);
9159   SDValue N1 = N->getOperand(1);
9160 
9161   // We only do this to handle cases where it's profitable when there are
9162   // multiple uses of the add, so defer to the standard combine.
9163   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
9164       N0->hasOneUse())
9165     return SDValue();
9166 
9167   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
9168   if (!CN1)
9169     return SDValue();
9170 
9171   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9172   if (!CAdd)
9173     return SDValue();
9174 
9175   // If the resulting offset is too large, we can't fold it into the addressing
9176   // mode offset.
9177   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
9178   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
9179 
9180   AddrMode AM;
9181   AM.HasBaseReg = true;
9182   AM.BaseOffs = Offset.getSExtValue();
9183   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
9184     return SDValue();
9185 
9186   SelectionDAG &DAG = DCI.DAG;
9187   SDLoc SL(N);
9188   EVT VT = N->getValueType(0);
9189 
9190   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
9191   SDValue COffset = DAG.getConstant(Offset, SL, VT);
9192 
9193   SDNodeFlags Flags;
9194   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
9195                           (N0.getOpcode() == ISD::OR ||
9196                            N0->getFlags().hasNoUnsignedWrap()));
9197 
9198   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
9199 }
9200 
9201 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
9202 /// by the chain and intrinsic ID. Theoretically we would also need to check the
9203 /// specific intrinsic, but they all place the pointer operand first.
9204 static unsigned getBasePtrIndex(const MemSDNode *N) {
9205   switch (N->getOpcode()) {
9206   case ISD::STORE:
9207   case ISD::INTRINSIC_W_CHAIN:
9208   case ISD::INTRINSIC_VOID:
9209     return 2;
9210   default:
9211     return 1;
9212   }
9213 }
9214 
9215 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
9216                                                   DAGCombinerInfo &DCI) const {
9217   SelectionDAG &DAG = DCI.DAG;
9218   SDLoc SL(N);
9219 
9220   unsigned PtrIdx = getBasePtrIndex(N);
9221   SDValue Ptr = N->getOperand(PtrIdx);
9222 
9223   // TODO: We could also do this for multiplies.
9224   if (Ptr.getOpcode() == ISD::SHL) {
9225     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
9226                                           N->getMemoryVT(), DCI);
9227     if (NewPtr) {
9228       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
9229 
9230       NewOps[PtrIdx] = NewPtr;
9231       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
9232     }
9233   }
9234 
9235   return SDValue();
9236 }
9237 
9238 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
9239   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
9240          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
9241          (Opc == ISD::XOR && Val == 0);
9242 }
9243 
9244 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
9245 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
9246 // integer combine opportunities since most 64-bit operations are decomposed
9247 // this way.  TODO: We won't want this for SALU especially if it is an inline
9248 // immediate.
9249 SDValue SITargetLowering::splitBinaryBitConstantOp(
9250   DAGCombinerInfo &DCI,
9251   const SDLoc &SL,
9252   unsigned Opc, SDValue LHS,
9253   const ConstantSDNode *CRHS) const {
9254   uint64_t Val = CRHS->getZExtValue();
9255   uint32_t ValLo = Lo_32(Val);
9256   uint32_t ValHi = Hi_32(Val);
9257   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9258 
9259     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
9260          bitOpWithConstantIsReducible(Opc, ValHi)) ||
9261         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
9262     // If we need to materialize a 64-bit immediate, it will be split up later
9263     // anyway. Avoid creating the harder to understand 64-bit immediate
9264     // materialization.
9265     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
9266   }
9267 
9268   return SDValue();
9269 }
9270 
9271 // Returns true if argument is a boolean value which is not serialized into
9272 // memory or argument and does not require v_cndmask_b32 to be deserialized.
9273 static bool isBoolSGPR(SDValue V) {
9274   if (V.getValueType() != MVT::i1)
9275     return false;
9276   switch (V.getOpcode()) {
9277   default:
9278     break;
9279   case ISD::SETCC:
9280   case AMDGPUISD::FP_CLASS:
9281     return true;
9282   case ISD::AND:
9283   case ISD::OR:
9284   case ISD::XOR:
9285     return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
9286   }
9287   return false;
9288 }
9289 
9290 // If a constant has all zeroes or all ones within each byte return it.
9291 // Otherwise return 0.
9292 static uint32_t getConstantPermuteMask(uint32_t C) {
9293   // 0xff for any zero byte in the mask
9294   uint32_t ZeroByteMask = 0;
9295   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
9296   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
9297   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
9298   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
9299   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
9300   if ((NonZeroByteMask & C) != NonZeroByteMask)
9301     return 0; // Partial bytes selected.
9302   return C;
9303 }
9304 
9305 // Check if a node selects whole bytes from its operand 0 starting at a byte
9306 // boundary while masking the rest. Returns select mask as in the v_perm_b32
9307 // or -1 if not succeeded.
9308 // Note byte select encoding:
9309 // value 0-3 selects corresponding source byte;
9310 // value 0xc selects zero;
9311 // value 0xff selects 0xff.
9312 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
9313   assert(V.getValueSizeInBits() == 32);
9314 
9315   if (V.getNumOperands() != 2)
9316     return ~0;
9317 
9318   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
9319   if (!N1)
9320     return ~0;
9321 
9322   uint32_t C = N1->getZExtValue();
9323 
9324   switch (V.getOpcode()) {
9325   default:
9326     break;
9327   case ISD::AND:
9328     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9329       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
9330     }
9331     break;
9332 
9333   case ISD::OR:
9334     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9335       return (0x03020100 & ~ConstMask) | ConstMask;
9336     }
9337     break;
9338 
9339   case ISD::SHL:
9340     if (C % 8)
9341       return ~0;
9342 
9343     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
9344 
9345   case ISD::SRL:
9346     if (C % 8)
9347       return ~0;
9348 
9349     return uint32_t(0x0c0c0c0c03020100ull >> C);
9350   }
9351 
9352   return ~0;
9353 }
9354 
9355 SDValue SITargetLowering::performAndCombine(SDNode *N,
9356                                             DAGCombinerInfo &DCI) const {
9357   if (DCI.isBeforeLegalize())
9358     return SDValue();
9359 
9360   SelectionDAG &DAG = DCI.DAG;
9361   EVT VT = N->getValueType(0);
9362   SDValue LHS = N->getOperand(0);
9363   SDValue RHS = N->getOperand(1);
9364 
9365 
9366   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9367   if (VT == MVT::i64 && CRHS) {
9368     if (SDValue Split
9369         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9370       return Split;
9371   }
9372 
9373   if (CRHS && VT == MVT::i32) {
9374     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9375     // nb = number of trailing zeroes in mask
9376     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9377     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9378     uint64_t Mask = CRHS->getZExtValue();
9379     unsigned Bits = countPopulation(Mask);
9380     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9381         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9382       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9383         unsigned Shift = CShift->getZExtValue();
9384         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9385         unsigned Offset = NB + Shift;
9386         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9387           SDLoc SL(N);
9388           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9389                                     LHS->getOperand(0),
9390                                     DAG.getConstant(Offset, SL, MVT::i32),
9391                                     DAG.getConstant(Bits, SL, MVT::i32));
9392           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9393           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9394                                     DAG.getValueType(NarrowVT));
9395           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9396                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9397           return Shl;
9398         }
9399       }
9400     }
9401 
9402     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9403     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9404         isa<ConstantSDNode>(LHS.getOperand(2))) {
9405       uint32_t Sel = getConstantPermuteMask(Mask);
9406       if (!Sel)
9407         return SDValue();
9408 
9409       // Select 0xc for all zero bytes
9410       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9411       SDLoc DL(N);
9412       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9413                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9414     }
9415   }
9416 
9417   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9418   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9419   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9420     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9421     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9422 
9423     SDValue X = LHS.getOperand(0);
9424     SDValue Y = RHS.getOperand(0);
9425     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9426       return SDValue();
9427 
9428     if (LCC == ISD::SETO) {
9429       if (X != LHS.getOperand(1))
9430         return SDValue();
9431 
9432       if (RCC == ISD::SETUNE) {
9433         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9434         if (!C1 || !C1->isInfinity() || C1->isNegative())
9435           return SDValue();
9436 
9437         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9438                               SIInstrFlags::N_SUBNORMAL |
9439                               SIInstrFlags::N_ZERO |
9440                               SIInstrFlags::P_ZERO |
9441                               SIInstrFlags::P_SUBNORMAL |
9442                               SIInstrFlags::P_NORMAL;
9443 
9444         static_assert(((~(SIInstrFlags::S_NAN |
9445                           SIInstrFlags::Q_NAN |
9446                           SIInstrFlags::N_INFINITY |
9447                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9448                       "mask not equal");
9449 
9450         SDLoc DL(N);
9451         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9452                            X, DAG.getConstant(Mask, DL, MVT::i32));
9453       }
9454     }
9455   }
9456 
9457   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9458     std::swap(LHS, RHS);
9459 
9460   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9461       RHS.hasOneUse()) {
9462     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9463     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9464     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9465     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9466     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9467         (RHS.getOperand(0) == LHS.getOperand(0) &&
9468          LHS.getOperand(0) == LHS.getOperand(1))) {
9469       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9470       unsigned NewMask = LCC == ISD::SETO ?
9471         Mask->getZExtValue() & ~OrdMask :
9472         Mask->getZExtValue() & OrdMask;
9473 
9474       SDLoc DL(N);
9475       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9476                          DAG.getConstant(NewMask, DL, MVT::i32));
9477     }
9478   }
9479 
9480   if (VT == MVT::i32 &&
9481       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9482     // and x, (sext cc from i1) => select cc, x, 0
9483     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9484       std::swap(LHS, RHS);
9485     if (isBoolSGPR(RHS.getOperand(0)))
9486       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9487                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9488   }
9489 
9490   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9491   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9492   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9493       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9494     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9495     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9496     if (LHSMask != ~0u && RHSMask != ~0u) {
9497       // Canonicalize the expression in an attempt to have fewer unique masks
9498       // and therefore fewer registers used to hold the masks.
9499       if (LHSMask > RHSMask) {
9500         std::swap(LHSMask, RHSMask);
9501         std::swap(LHS, RHS);
9502       }
9503 
9504       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9505       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9506       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9507       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9508 
9509       // Check of we need to combine values from two sources within a byte.
9510       if (!(LHSUsedLanes & RHSUsedLanes) &&
9511           // If we select high and lower word keep it for SDWA.
9512           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9513           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9514         // Each byte in each mask is either selector mask 0-3, or has higher
9515         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9516         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9517         // mask which is not 0xff wins. By anding both masks we have a correct
9518         // result except that 0x0c shall be corrected to give 0x0c only.
9519         uint32_t Mask = LHSMask & RHSMask;
9520         for (unsigned I = 0; I < 32; I += 8) {
9521           uint32_t ByteSel = 0xff << I;
9522           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9523             Mask &= (0x0c << I) & 0xffffffff;
9524         }
9525 
9526         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9527         // or 0x0c.
9528         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9529         SDLoc DL(N);
9530 
9531         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9532                            LHS.getOperand(0), RHS.getOperand(0),
9533                            DAG.getConstant(Sel, DL, MVT::i32));
9534       }
9535     }
9536   }
9537 
9538   return SDValue();
9539 }
9540 
9541 SDValue SITargetLowering::performOrCombine(SDNode *N,
9542                                            DAGCombinerInfo &DCI) const {
9543   SelectionDAG &DAG = DCI.DAG;
9544   SDValue LHS = N->getOperand(0);
9545   SDValue RHS = N->getOperand(1);
9546 
9547   EVT VT = N->getValueType(0);
9548   if (VT == MVT::i1) {
9549     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9550     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9551         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9552       SDValue Src = LHS.getOperand(0);
9553       if (Src != RHS.getOperand(0))
9554         return SDValue();
9555 
9556       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9557       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9558       if (!CLHS || !CRHS)
9559         return SDValue();
9560 
9561       // Only 10 bits are used.
9562       static const uint32_t MaxMask = 0x3ff;
9563 
9564       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9565       SDLoc DL(N);
9566       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9567                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9568     }
9569 
9570     return SDValue();
9571   }
9572 
9573   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9574   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9575       LHS.getOpcode() == AMDGPUISD::PERM &&
9576       isa<ConstantSDNode>(LHS.getOperand(2))) {
9577     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9578     if (!Sel)
9579       return SDValue();
9580 
9581     Sel |= LHS.getConstantOperandVal(2);
9582     SDLoc DL(N);
9583     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9584                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9585   }
9586 
9587   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9588   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9589   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9590       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9591     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9592     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9593     if (LHSMask != ~0u && RHSMask != ~0u) {
9594       // Canonicalize the expression in an attempt to have fewer unique masks
9595       // and therefore fewer registers used to hold the masks.
9596       if (LHSMask > RHSMask) {
9597         std::swap(LHSMask, RHSMask);
9598         std::swap(LHS, RHS);
9599       }
9600 
9601       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9602       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9603       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9604       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9605 
9606       // Check of we need to combine values from two sources within a byte.
9607       if (!(LHSUsedLanes & RHSUsedLanes) &&
9608           // If we select high and lower word keep it for SDWA.
9609           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9610           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9611         // Kill zero bytes selected by other mask. Zero value is 0xc.
9612         LHSMask &= ~RHSUsedLanes;
9613         RHSMask &= ~LHSUsedLanes;
9614         // Add 4 to each active LHS lane
9615         LHSMask |= LHSUsedLanes & 0x04040404;
9616         // Combine masks
9617         uint32_t Sel = LHSMask | RHSMask;
9618         SDLoc DL(N);
9619 
9620         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9621                            LHS.getOperand(0), RHS.getOperand(0),
9622                            DAG.getConstant(Sel, DL, MVT::i32));
9623       }
9624     }
9625   }
9626 
9627   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9628     return SDValue();
9629 
9630   // TODO: This could be a generic combine with a predicate for extracting the
9631   // high half of an integer being free.
9632 
9633   // (or i64:x, (zero_extend i32:y)) ->
9634   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9635   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9636       RHS.getOpcode() != ISD::ZERO_EXTEND)
9637     std::swap(LHS, RHS);
9638 
9639   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9640     SDValue ExtSrc = RHS.getOperand(0);
9641     EVT SrcVT = ExtSrc.getValueType();
9642     if (SrcVT == MVT::i32) {
9643       SDLoc SL(N);
9644       SDValue LowLHS, HiBits;
9645       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9646       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9647 
9648       DCI.AddToWorklist(LowOr.getNode());
9649       DCI.AddToWorklist(HiBits.getNode());
9650 
9651       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9652                                 LowOr, HiBits);
9653       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9654     }
9655   }
9656 
9657   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9658   if (CRHS) {
9659     if (SDValue Split
9660           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR,
9661                                      N->getOperand(0), CRHS))
9662       return Split;
9663   }
9664 
9665   return SDValue();
9666 }
9667 
9668 SDValue SITargetLowering::performXorCombine(SDNode *N,
9669                                             DAGCombinerInfo &DCI) const {
9670   if (SDValue RV = reassociateScalarOps(N, DCI.DAG))
9671     return RV;
9672 
9673   EVT VT = N->getValueType(0);
9674   if (VT != MVT::i64)
9675     return SDValue();
9676 
9677   SDValue LHS = N->getOperand(0);
9678   SDValue RHS = N->getOperand(1);
9679 
9680   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9681   if (CRHS) {
9682     if (SDValue Split
9683           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9684       return Split;
9685   }
9686 
9687   return SDValue();
9688 }
9689 
9690 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9691                                                    DAGCombinerInfo &DCI) const {
9692   if (!Subtarget->has16BitInsts() ||
9693       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9694     return SDValue();
9695 
9696   EVT VT = N->getValueType(0);
9697   if (VT != MVT::i32)
9698     return SDValue();
9699 
9700   SDValue Src = N->getOperand(0);
9701   if (Src.getValueType() != MVT::i16)
9702     return SDValue();
9703 
9704   return SDValue();
9705 }
9706 
9707 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9708                                                         DAGCombinerInfo &DCI)
9709                                                         const {
9710   SDValue Src = N->getOperand(0);
9711   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9712 
9713   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9714       VTSign->getVT() == MVT::i8) ||
9715       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9716       VTSign->getVT() == MVT::i16)) &&
9717       Src.hasOneUse()) {
9718     auto *M = cast<MemSDNode>(Src);
9719     SDValue Ops[] = {
9720       Src.getOperand(0), // Chain
9721       Src.getOperand(1), // rsrc
9722       Src.getOperand(2), // vindex
9723       Src.getOperand(3), // voffset
9724       Src.getOperand(4), // soffset
9725       Src.getOperand(5), // offset
9726       Src.getOperand(6),
9727       Src.getOperand(7)
9728     };
9729     // replace with BUFFER_LOAD_BYTE/SHORT
9730     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9731                                          Src.getOperand(0).getValueType());
9732     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9733                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9734     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9735                                                           ResList,
9736                                                           Ops, M->getMemoryVT(),
9737                                                           M->getMemOperand());
9738     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9739                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9740   }
9741   return SDValue();
9742 }
9743 
9744 SDValue SITargetLowering::performClassCombine(SDNode *N,
9745                                               DAGCombinerInfo &DCI) const {
9746   SelectionDAG &DAG = DCI.DAG;
9747   SDValue Mask = N->getOperand(1);
9748 
9749   // fp_class x, 0 -> false
9750   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9751     if (CMask->isZero())
9752       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9753   }
9754 
9755   if (N->getOperand(0).isUndef())
9756     return DAG.getUNDEF(MVT::i1);
9757 
9758   return SDValue();
9759 }
9760 
9761 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9762                                             DAGCombinerInfo &DCI) const {
9763   EVT VT = N->getValueType(0);
9764   SDValue N0 = N->getOperand(0);
9765 
9766   if (N0.isUndef())
9767     return N0;
9768 
9769   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9770                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9771     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9772                            N->getFlags());
9773   }
9774 
9775   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9776     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9777                            N0.getOperand(0), N->getFlags());
9778   }
9779 
9780   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9781 }
9782 
9783 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9784                                        unsigned MaxDepth) const {
9785   unsigned Opcode = Op.getOpcode();
9786   if (Opcode == ISD::FCANONICALIZE)
9787     return true;
9788 
9789   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9790     auto F = CFP->getValueAPF();
9791     if (F.isNaN() && F.isSignaling())
9792       return false;
9793     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9794   }
9795 
9796   // If source is a result of another standard FP operation it is already in
9797   // canonical form.
9798   if (MaxDepth == 0)
9799     return false;
9800 
9801   switch (Opcode) {
9802   // These will flush denorms if required.
9803   case ISD::FADD:
9804   case ISD::FSUB:
9805   case ISD::FMUL:
9806   case ISD::FCEIL:
9807   case ISD::FFLOOR:
9808   case ISD::FMA:
9809   case ISD::FMAD:
9810   case ISD::FSQRT:
9811   case ISD::FDIV:
9812   case ISD::FREM:
9813   case ISD::FP_ROUND:
9814   case ISD::FP_EXTEND:
9815   case AMDGPUISD::FMUL_LEGACY:
9816   case AMDGPUISD::FMAD_FTZ:
9817   case AMDGPUISD::RCP:
9818   case AMDGPUISD::RSQ:
9819   case AMDGPUISD::RSQ_CLAMP:
9820   case AMDGPUISD::RCP_LEGACY:
9821   case AMDGPUISD::RCP_IFLAG:
9822   case AMDGPUISD::DIV_SCALE:
9823   case AMDGPUISD::DIV_FMAS:
9824   case AMDGPUISD::DIV_FIXUP:
9825   case AMDGPUISD::FRACT:
9826   case AMDGPUISD::LDEXP:
9827   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9828   case AMDGPUISD::CVT_F32_UBYTE0:
9829   case AMDGPUISD::CVT_F32_UBYTE1:
9830   case AMDGPUISD::CVT_F32_UBYTE2:
9831   case AMDGPUISD::CVT_F32_UBYTE3:
9832     return true;
9833 
9834   // It can/will be lowered or combined as a bit operation.
9835   // Need to check their input recursively to handle.
9836   case ISD::FNEG:
9837   case ISD::FABS:
9838   case ISD::FCOPYSIGN:
9839     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9840 
9841   case ISD::FSIN:
9842   case ISD::FCOS:
9843   case ISD::FSINCOS:
9844     return Op.getValueType().getScalarType() != MVT::f16;
9845 
9846   case ISD::FMINNUM:
9847   case ISD::FMAXNUM:
9848   case ISD::FMINNUM_IEEE:
9849   case ISD::FMAXNUM_IEEE:
9850   case AMDGPUISD::CLAMP:
9851   case AMDGPUISD::FMED3:
9852   case AMDGPUISD::FMAX3:
9853   case AMDGPUISD::FMIN3: {
9854     // FIXME: Shouldn't treat the generic operations different based these.
9855     // However, we aren't really required to flush the result from
9856     // minnum/maxnum..
9857 
9858     // snans will be quieted, so we only need to worry about denormals.
9859     if (Subtarget->supportsMinMaxDenormModes() ||
9860         denormalsEnabledForType(DAG, Op.getValueType()))
9861       return true;
9862 
9863     // Flushing may be required.
9864     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9865     // targets need to check their input recursively.
9866 
9867     // FIXME: Does this apply with clamp? It's implemented with max.
9868     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9869       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9870         return false;
9871     }
9872 
9873     return true;
9874   }
9875   case ISD::SELECT: {
9876     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9877            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9878   }
9879   case ISD::BUILD_VECTOR: {
9880     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9881       SDValue SrcOp = Op.getOperand(i);
9882       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9883         return false;
9884     }
9885 
9886     return true;
9887   }
9888   case ISD::EXTRACT_VECTOR_ELT:
9889   case ISD::EXTRACT_SUBVECTOR: {
9890     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9891   }
9892   case ISD::INSERT_VECTOR_ELT: {
9893     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9894            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9895   }
9896   case ISD::UNDEF:
9897     // Could be anything.
9898     return false;
9899 
9900   case ISD::BITCAST:
9901     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9902   case ISD::TRUNCATE: {
9903     // Hack round the mess we make when legalizing extract_vector_elt
9904     if (Op.getValueType() == MVT::i16) {
9905       SDValue TruncSrc = Op.getOperand(0);
9906       if (TruncSrc.getValueType() == MVT::i32 &&
9907           TruncSrc.getOpcode() == ISD::BITCAST &&
9908           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9909         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9910       }
9911     }
9912     return false;
9913   }
9914   case ISD::INTRINSIC_WO_CHAIN: {
9915     unsigned IntrinsicID
9916       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9917     // TODO: Handle more intrinsics
9918     switch (IntrinsicID) {
9919     case Intrinsic::amdgcn_cvt_pkrtz:
9920     case Intrinsic::amdgcn_cubeid:
9921     case Intrinsic::amdgcn_frexp_mant:
9922     case Intrinsic::amdgcn_fdot2:
9923     case Intrinsic::amdgcn_rcp:
9924     case Intrinsic::amdgcn_rsq:
9925     case Intrinsic::amdgcn_rsq_clamp:
9926     case Intrinsic::amdgcn_rcp_legacy:
9927     case Intrinsic::amdgcn_rsq_legacy:
9928     case Intrinsic::amdgcn_trig_preop:
9929       return true;
9930     default:
9931       break;
9932     }
9933 
9934     LLVM_FALLTHROUGH;
9935   }
9936   default:
9937     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9938            DAG.isKnownNeverSNaN(Op);
9939   }
9940 
9941   llvm_unreachable("invalid operation");
9942 }
9943 
9944 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
9945                                        unsigned MaxDepth) const {
9946   MachineRegisterInfo &MRI = MF.getRegInfo();
9947   MachineInstr *MI = MRI.getVRegDef(Reg);
9948   unsigned Opcode = MI->getOpcode();
9949 
9950   if (Opcode == AMDGPU::G_FCANONICALIZE)
9951     return true;
9952 
9953   Optional<FPValueAndVReg> FCR;
9954   // Constant splat (can be padded with undef) or scalar constant.
9955   if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) {
9956     if (FCR->Value.isSignaling())
9957       return false;
9958     return !FCR->Value.isDenormal() ||
9959            denormalsEnabledForType(MRI.getType(FCR->VReg), MF);
9960   }
9961 
9962   if (MaxDepth == 0)
9963     return false;
9964 
9965   switch (Opcode) {
9966   case AMDGPU::G_FMINNUM_IEEE:
9967   case AMDGPU::G_FMAXNUM_IEEE: {
9968     if (Subtarget->supportsMinMaxDenormModes() ||
9969         denormalsEnabledForType(MRI.getType(Reg), MF))
9970       return true;
9971     for (const MachineOperand &MO : llvm::drop_begin(MI->operands()))
9972       if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1))
9973         return false;
9974     return true;
9975   }
9976   default:
9977     return denormalsEnabledForType(MRI.getType(Reg), MF) &&
9978            isKnownNeverSNaN(Reg, MRI);
9979   }
9980 
9981   llvm_unreachable("invalid operation");
9982 }
9983 
9984 // Constant fold canonicalize.
9985 SDValue SITargetLowering::getCanonicalConstantFP(
9986   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9987   // Flush denormals to 0 if not enabled.
9988   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9989     return DAG.getConstantFP(0.0, SL, VT);
9990 
9991   if (C.isNaN()) {
9992     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9993     if (C.isSignaling()) {
9994       // Quiet a signaling NaN.
9995       // FIXME: Is this supposed to preserve payload bits?
9996       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9997     }
9998 
9999     // Make sure it is the canonical NaN bitpattern.
10000     //
10001     // TODO: Can we use -1 as the canonical NaN value since it's an inline
10002     // immediate?
10003     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
10004       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
10005   }
10006 
10007   // Already canonical.
10008   return DAG.getConstantFP(C, SL, VT);
10009 }
10010 
10011 static bool vectorEltWillFoldAway(SDValue Op) {
10012   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
10013 }
10014 
10015 SDValue SITargetLowering::performFCanonicalizeCombine(
10016   SDNode *N,
10017   DAGCombinerInfo &DCI) const {
10018   SelectionDAG &DAG = DCI.DAG;
10019   SDValue N0 = N->getOperand(0);
10020   EVT VT = N->getValueType(0);
10021 
10022   // fcanonicalize undef -> qnan
10023   if (N0.isUndef()) {
10024     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
10025     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
10026   }
10027 
10028   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
10029     EVT VT = N->getValueType(0);
10030     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
10031   }
10032 
10033   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
10034   //                                                   (fcanonicalize k)
10035   //
10036   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
10037 
10038   // TODO: This could be better with wider vectors that will be split to v2f16,
10039   // and to consider uses since there aren't that many packed operations.
10040   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
10041       isTypeLegal(MVT::v2f16)) {
10042     SDLoc SL(N);
10043     SDValue NewElts[2];
10044     SDValue Lo = N0.getOperand(0);
10045     SDValue Hi = N0.getOperand(1);
10046     EVT EltVT = Lo.getValueType();
10047 
10048     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
10049       for (unsigned I = 0; I != 2; ++I) {
10050         SDValue Op = N0.getOperand(I);
10051         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
10052           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
10053                                               CFP->getValueAPF());
10054         } else if (Op.isUndef()) {
10055           // Handled below based on what the other operand is.
10056           NewElts[I] = Op;
10057         } else {
10058           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
10059         }
10060       }
10061 
10062       // If one half is undef, and one is constant, perfer a splat vector rather
10063       // than the normal qNaN. If it's a register, prefer 0.0 since that's
10064       // cheaper to use and may be free with a packed operation.
10065       if (NewElts[0].isUndef()) {
10066         if (isa<ConstantFPSDNode>(NewElts[1]))
10067           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
10068             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
10069       }
10070 
10071       if (NewElts[1].isUndef()) {
10072         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
10073           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
10074       }
10075 
10076       return DAG.getBuildVector(VT, SL, NewElts);
10077     }
10078   }
10079 
10080   unsigned SrcOpc = N0.getOpcode();
10081 
10082   // If it's free to do so, push canonicalizes further up the source, which may
10083   // find a canonical source.
10084   //
10085   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
10086   // sNaNs.
10087   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
10088     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10089     if (CRHS && N0.hasOneUse()) {
10090       SDLoc SL(N);
10091       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
10092                                    N0.getOperand(0));
10093       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
10094       DCI.AddToWorklist(Canon0.getNode());
10095 
10096       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
10097     }
10098   }
10099 
10100   return isCanonicalized(DAG, N0) ? N0 : SDValue();
10101 }
10102 
10103 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
10104   switch (Opc) {
10105   case ISD::FMAXNUM:
10106   case ISD::FMAXNUM_IEEE:
10107     return AMDGPUISD::FMAX3;
10108   case ISD::SMAX:
10109     return AMDGPUISD::SMAX3;
10110   case ISD::UMAX:
10111     return AMDGPUISD::UMAX3;
10112   case ISD::FMINNUM:
10113   case ISD::FMINNUM_IEEE:
10114     return AMDGPUISD::FMIN3;
10115   case ISD::SMIN:
10116     return AMDGPUISD::SMIN3;
10117   case ISD::UMIN:
10118     return AMDGPUISD::UMIN3;
10119   default:
10120     llvm_unreachable("Not a min/max opcode");
10121   }
10122 }
10123 
10124 SDValue SITargetLowering::performIntMed3ImmCombine(
10125   SelectionDAG &DAG, const SDLoc &SL,
10126   SDValue Op0, SDValue Op1, bool Signed) const {
10127   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
10128   if (!K1)
10129     return SDValue();
10130 
10131   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
10132   if (!K0)
10133     return SDValue();
10134 
10135   if (Signed) {
10136     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
10137       return SDValue();
10138   } else {
10139     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
10140       return SDValue();
10141   }
10142 
10143   EVT VT = K0->getValueType(0);
10144   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
10145   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
10146     return DAG.getNode(Med3Opc, SL, VT,
10147                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
10148   }
10149 
10150   // If there isn't a 16-bit med3 operation, convert to 32-bit.
10151   if (VT == MVT::i16) {
10152     MVT NVT = MVT::i32;
10153     unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
10154 
10155     SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
10156     SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
10157     SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
10158 
10159     SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
10160     return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
10161   }
10162 
10163   return SDValue();
10164 }
10165 
10166 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
10167   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
10168     return C;
10169 
10170   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
10171     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
10172       return C;
10173   }
10174 
10175   return nullptr;
10176 }
10177 
10178 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
10179                                                   const SDLoc &SL,
10180                                                   SDValue Op0,
10181                                                   SDValue Op1) const {
10182   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
10183   if (!K1)
10184     return SDValue();
10185 
10186   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
10187   if (!K0)
10188     return SDValue();
10189 
10190   // Ordered >= (although NaN inputs should have folded away by now).
10191   if (K0->getValueAPF() > K1->getValueAPF())
10192     return SDValue();
10193 
10194   const MachineFunction &MF = DAG.getMachineFunction();
10195   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10196 
10197   // TODO: Check IEEE bit enabled?
10198   EVT VT = Op0.getValueType();
10199   if (Info->getMode().DX10Clamp) {
10200     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
10201     // hardware fmed3 behavior converting to a min.
10202     // FIXME: Should this be allowing -0.0?
10203     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
10204       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
10205   }
10206 
10207   // med3 for f16 is only available on gfx9+, and not available for v2f16.
10208   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
10209     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
10210     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
10211     // then give the other result, which is different from med3 with a NaN
10212     // input.
10213     SDValue Var = Op0.getOperand(0);
10214     if (!DAG.isKnownNeverSNaN(Var))
10215       return SDValue();
10216 
10217     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10218 
10219     if ((!K0->hasOneUse() ||
10220          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
10221         (!K1->hasOneUse() ||
10222          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
10223       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
10224                          Var, SDValue(K0, 0), SDValue(K1, 0));
10225     }
10226   }
10227 
10228   return SDValue();
10229 }
10230 
10231 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
10232                                                DAGCombinerInfo &DCI) const {
10233   SelectionDAG &DAG = DCI.DAG;
10234 
10235   EVT VT = N->getValueType(0);
10236   unsigned Opc = N->getOpcode();
10237   SDValue Op0 = N->getOperand(0);
10238   SDValue Op1 = N->getOperand(1);
10239 
10240   // Only do this if the inner op has one use since this will just increases
10241   // register pressure for no benefit.
10242 
10243   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
10244       !VT.isVector() &&
10245       (VT == MVT::i32 || VT == MVT::f32 ||
10246        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
10247     // max(max(a, b), c) -> max3(a, b, c)
10248     // min(min(a, b), c) -> min3(a, b, c)
10249     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
10250       SDLoc DL(N);
10251       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10252                          DL,
10253                          N->getValueType(0),
10254                          Op0.getOperand(0),
10255                          Op0.getOperand(1),
10256                          Op1);
10257     }
10258 
10259     // Try commuted.
10260     // max(a, max(b, c)) -> max3(a, b, c)
10261     // min(a, min(b, c)) -> min3(a, b, c)
10262     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
10263       SDLoc DL(N);
10264       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10265                          DL,
10266                          N->getValueType(0),
10267                          Op0,
10268                          Op1.getOperand(0),
10269                          Op1.getOperand(1));
10270     }
10271   }
10272 
10273   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
10274   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
10275     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
10276       return Med3;
10277   }
10278 
10279   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
10280     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
10281       return Med3;
10282   }
10283 
10284   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
10285   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
10286        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
10287        (Opc == AMDGPUISD::FMIN_LEGACY &&
10288         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
10289       (VT == MVT::f32 || VT == MVT::f64 ||
10290        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
10291        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
10292       Op0.hasOneUse()) {
10293     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
10294       return Res;
10295   }
10296 
10297   return SDValue();
10298 }
10299 
10300 static bool isClampZeroToOne(SDValue A, SDValue B) {
10301   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
10302     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
10303       // FIXME: Should this be allowing -0.0?
10304       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
10305              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
10306     }
10307   }
10308 
10309   return false;
10310 }
10311 
10312 // FIXME: Should only worry about snans for version with chain.
10313 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
10314                                               DAGCombinerInfo &DCI) const {
10315   EVT VT = N->getValueType(0);
10316   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
10317   // NaNs. With a NaN input, the order of the operands may change the result.
10318 
10319   SelectionDAG &DAG = DCI.DAG;
10320   SDLoc SL(N);
10321 
10322   SDValue Src0 = N->getOperand(0);
10323   SDValue Src1 = N->getOperand(1);
10324   SDValue Src2 = N->getOperand(2);
10325 
10326   if (isClampZeroToOne(Src0, Src1)) {
10327     // const_a, const_b, x -> clamp is safe in all cases including signaling
10328     // nans.
10329     // FIXME: Should this be allowing -0.0?
10330     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
10331   }
10332 
10333   const MachineFunction &MF = DAG.getMachineFunction();
10334   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10335 
10336   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
10337   // handling no dx10-clamp?
10338   if (Info->getMode().DX10Clamp) {
10339     // If NaNs is clamped to 0, we are free to reorder the inputs.
10340 
10341     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10342       std::swap(Src0, Src1);
10343 
10344     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10345       std::swap(Src1, Src2);
10346 
10347     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10348       std::swap(Src0, Src1);
10349 
10350     if (isClampZeroToOne(Src1, Src2))
10351       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10352   }
10353 
10354   return SDValue();
10355 }
10356 
10357 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10358                                                  DAGCombinerInfo &DCI) const {
10359   SDValue Src0 = N->getOperand(0);
10360   SDValue Src1 = N->getOperand(1);
10361   if (Src0.isUndef() && Src1.isUndef())
10362     return DCI.DAG.getUNDEF(N->getValueType(0));
10363   return SDValue();
10364 }
10365 
10366 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10367 // expanded into a set of cmp/select instructions.
10368 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10369                                                 unsigned NumElem,
10370                                                 bool IsDivergentIdx) {
10371   if (UseDivergentRegisterIndexing)
10372     return false;
10373 
10374   unsigned VecSize = EltSize * NumElem;
10375 
10376   // Sub-dword vectors of size 2 dword or less have better implementation.
10377   if (VecSize <= 64 && EltSize < 32)
10378     return false;
10379 
10380   // Always expand the rest of sub-dword instructions, otherwise it will be
10381   // lowered via memory.
10382   if (EltSize < 32)
10383     return true;
10384 
10385   // Always do this if var-idx is divergent, otherwise it will become a loop.
10386   if (IsDivergentIdx)
10387     return true;
10388 
10389   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10390   unsigned NumInsts = NumElem /* Number of compares */ +
10391                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10392   return NumInsts <= 16;
10393 }
10394 
10395 static bool shouldExpandVectorDynExt(SDNode *N) {
10396   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10397   if (isa<ConstantSDNode>(Idx))
10398     return false;
10399 
10400   SDValue Vec = N->getOperand(0);
10401   EVT VecVT = Vec.getValueType();
10402   EVT EltVT = VecVT.getVectorElementType();
10403   unsigned EltSize = EltVT.getSizeInBits();
10404   unsigned NumElem = VecVT.getVectorNumElements();
10405 
10406   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
10407                                                     Idx->isDivergent());
10408 }
10409 
10410 SDValue SITargetLowering::performExtractVectorEltCombine(
10411   SDNode *N, DAGCombinerInfo &DCI) const {
10412   SDValue Vec = N->getOperand(0);
10413   SelectionDAG &DAG = DCI.DAG;
10414 
10415   EVT VecVT = Vec.getValueType();
10416   EVT EltVT = VecVT.getVectorElementType();
10417 
10418   if ((Vec.getOpcode() == ISD::FNEG ||
10419        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10420     SDLoc SL(N);
10421     EVT EltVT = N->getValueType(0);
10422     SDValue Idx = N->getOperand(1);
10423     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10424                               Vec.getOperand(0), Idx);
10425     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10426   }
10427 
10428   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10429   //    =>
10430   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10431   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10432   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10433   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10434     SDLoc SL(N);
10435     EVT EltVT = N->getValueType(0);
10436     SDValue Idx = N->getOperand(1);
10437     unsigned Opc = Vec.getOpcode();
10438 
10439     switch(Opc) {
10440     default:
10441       break;
10442       // TODO: Support other binary operations.
10443     case ISD::FADD:
10444     case ISD::FSUB:
10445     case ISD::FMUL:
10446     case ISD::ADD:
10447     case ISD::UMIN:
10448     case ISD::UMAX:
10449     case ISD::SMIN:
10450     case ISD::SMAX:
10451     case ISD::FMAXNUM:
10452     case ISD::FMINNUM:
10453     case ISD::FMAXNUM_IEEE:
10454     case ISD::FMINNUM_IEEE: {
10455       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10456                                  Vec.getOperand(0), Idx);
10457       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10458                                  Vec.getOperand(1), Idx);
10459 
10460       DCI.AddToWorklist(Elt0.getNode());
10461       DCI.AddToWorklist(Elt1.getNode());
10462       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10463     }
10464     }
10465   }
10466 
10467   unsigned VecSize = VecVT.getSizeInBits();
10468   unsigned EltSize = EltVT.getSizeInBits();
10469 
10470   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10471   if (::shouldExpandVectorDynExt(N)) {
10472     SDLoc SL(N);
10473     SDValue Idx = N->getOperand(1);
10474     SDValue V;
10475     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10476       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10477       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10478       if (I == 0)
10479         V = Elt;
10480       else
10481         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10482     }
10483     return V;
10484   }
10485 
10486   if (!DCI.isBeforeLegalize())
10487     return SDValue();
10488 
10489   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10490   // elements. This exposes more load reduction opportunities by replacing
10491   // multiple small extract_vector_elements with a single 32-bit extract.
10492   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10493   if (isa<MemSDNode>(Vec) &&
10494       EltSize <= 16 &&
10495       EltVT.isByteSized() &&
10496       VecSize > 32 &&
10497       VecSize % 32 == 0 &&
10498       Idx) {
10499     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10500 
10501     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10502     unsigned EltIdx = BitIndex / 32;
10503     unsigned LeftoverBitIdx = BitIndex % 32;
10504     SDLoc SL(N);
10505 
10506     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10507     DCI.AddToWorklist(Cast.getNode());
10508 
10509     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10510                               DAG.getConstant(EltIdx, SL, MVT::i32));
10511     DCI.AddToWorklist(Elt.getNode());
10512     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10513                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10514     DCI.AddToWorklist(Srl.getNode());
10515 
10516     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10517     DCI.AddToWorklist(Trunc.getNode());
10518     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10519   }
10520 
10521   return SDValue();
10522 }
10523 
10524 SDValue
10525 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10526                                                 DAGCombinerInfo &DCI) const {
10527   SDValue Vec = N->getOperand(0);
10528   SDValue Idx = N->getOperand(2);
10529   EVT VecVT = Vec.getValueType();
10530   EVT EltVT = VecVT.getVectorElementType();
10531 
10532   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10533   // => BUILD_VECTOR n x select (e, const-idx)
10534   if (!::shouldExpandVectorDynExt(N))
10535     return SDValue();
10536 
10537   SelectionDAG &DAG = DCI.DAG;
10538   SDLoc SL(N);
10539   SDValue Ins = N->getOperand(1);
10540   EVT IdxVT = Idx.getValueType();
10541 
10542   SmallVector<SDValue, 16> Ops;
10543   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10544     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10545     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10546     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10547     Ops.push_back(V);
10548   }
10549 
10550   return DAG.getBuildVector(VecVT, SL, Ops);
10551 }
10552 
10553 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10554                                           const SDNode *N0,
10555                                           const SDNode *N1) const {
10556   EVT VT = N0->getValueType(0);
10557 
10558   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10559   // support denormals ever.
10560   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10561        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10562         getSubtarget()->hasMadF16())) &&
10563        isOperationLegal(ISD::FMAD, VT))
10564     return ISD::FMAD;
10565 
10566   const TargetOptions &Options = DAG.getTarget().Options;
10567   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10568        (N0->getFlags().hasAllowContract() &&
10569         N1->getFlags().hasAllowContract())) &&
10570       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10571     return ISD::FMA;
10572   }
10573 
10574   return 0;
10575 }
10576 
10577 // For a reassociatable opcode perform:
10578 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10579 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10580                                                SelectionDAG &DAG) const {
10581   EVT VT = N->getValueType(0);
10582   if (VT != MVT::i32 && VT != MVT::i64)
10583     return SDValue();
10584 
10585   if (DAG.isBaseWithConstantOffset(SDValue(N, 0)))
10586     return SDValue();
10587 
10588   unsigned Opc = N->getOpcode();
10589   SDValue Op0 = N->getOperand(0);
10590   SDValue Op1 = N->getOperand(1);
10591 
10592   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10593     return SDValue();
10594 
10595   if (Op0->isDivergent())
10596     std::swap(Op0, Op1);
10597 
10598   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10599     return SDValue();
10600 
10601   SDValue Op2 = Op1.getOperand(1);
10602   Op1 = Op1.getOperand(0);
10603   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10604     return SDValue();
10605 
10606   if (Op1->isDivergent())
10607     std::swap(Op1, Op2);
10608 
10609   SDLoc SL(N);
10610   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10611   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10612 }
10613 
10614 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10615                            EVT VT,
10616                            SDValue N0, SDValue N1, SDValue N2,
10617                            bool Signed) {
10618   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10619   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10620   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10621   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10622 }
10623 
10624 SDValue SITargetLowering::performAddCombine(SDNode *N,
10625                                             DAGCombinerInfo &DCI) const {
10626   SelectionDAG &DAG = DCI.DAG;
10627   EVT VT = N->getValueType(0);
10628   SDLoc SL(N);
10629   SDValue LHS = N->getOperand(0);
10630   SDValue RHS = N->getOperand(1);
10631 
10632   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10633       && Subtarget->hasMad64_32() &&
10634       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10635       VT.getScalarSizeInBits() <= 64) {
10636     if (LHS.getOpcode() != ISD::MUL)
10637       std::swap(LHS, RHS);
10638 
10639     SDValue MulLHS = LHS.getOperand(0);
10640     SDValue MulRHS = LHS.getOperand(1);
10641     SDValue AddRHS = RHS;
10642 
10643     // TODO: Maybe restrict if SGPR inputs.
10644     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10645         numBitsUnsigned(MulRHS, DAG) <= 32) {
10646       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10647       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10648       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10649       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10650     }
10651 
10652     if (numBitsSigned(MulLHS, DAG) <= 32 && numBitsSigned(MulRHS, DAG) <= 32) {
10653       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10654       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10655       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10656       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10657     }
10658 
10659     return SDValue();
10660   }
10661 
10662   if (SDValue V = reassociateScalarOps(N, DAG)) {
10663     return V;
10664   }
10665 
10666   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10667     return SDValue();
10668 
10669   // add x, zext (setcc) => addcarry x, 0, setcc
10670   // add x, sext (setcc) => subcarry x, 0, setcc
10671   unsigned Opc = LHS.getOpcode();
10672   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10673       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10674     std::swap(RHS, LHS);
10675 
10676   Opc = RHS.getOpcode();
10677   switch (Opc) {
10678   default: break;
10679   case ISD::ZERO_EXTEND:
10680   case ISD::SIGN_EXTEND:
10681   case ISD::ANY_EXTEND: {
10682     auto Cond = RHS.getOperand(0);
10683     // If this won't be a real VOPC output, we would still need to insert an
10684     // extra instruction anyway.
10685     if (!isBoolSGPR(Cond))
10686       break;
10687     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10688     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10689     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10690     return DAG.getNode(Opc, SL, VTList, Args);
10691   }
10692   case ISD::ADDCARRY: {
10693     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10694     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10695     if (!C || C->getZExtValue() != 0) break;
10696     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10697     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10698   }
10699   }
10700   return SDValue();
10701 }
10702 
10703 SDValue SITargetLowering::performSubCombine(SDNode *N,
10704                                             DAGCombinerInfo &DCI) const {
10705   SelectionDAG &DAG = DCI.DAG;
10706   EVT VT = N->getValueType(0);
10707 
10708   if (VT != MVT::i32)
10709     return SDValue();
10710 
10711   SDLoc SL(N);
10712   SDValue LHS = N->getOperand(0);
10713   SDValue RHS = N->getOperand(1);
10714 
10715   // sub x, zext (setcc) => subcarry x, 0, setcc
10716   // sub x, sext (setcc) => addcarry x, 0, setcc
10717   unsigned Opc = RHS.getOpcode();
10718   switch (Opc) {
10719   default: break;
10720   case ISD::ZERO_EXTEND:
10721   case ISD::SIGN_EXTEND:
10722   case ISD::ANY_EXTEND: {
10723     auto Cond = RHS.getOperand(0);
10724     // If this won't be a real VOPC output, we would still need to insert an
10725     // extra instruction anyway.
10726     if (!isBoolSGPR(Cond))
10727       break;
10728     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10729     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10730     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10731     return DAG.getNode(Opc, SL, VTList, Args);
10732   }
10733   }
10734 
10735   if (LHS.getOpcode() == ISD::SUBCARRY) {
10736     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10737     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10738     if (!C || !C->isZero())
10739       return SDValue();
10740     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10741     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10742   }
10743   return SDValue();
10744 }
10745 
10746 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10747   DAGCombinerInfo &DCI) const {
10748 
10749   if (N->getValueType(0) != MVT::i32)
10750     return SDValue();
10751 
10752   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10753   if (!C || C->getZExtValue() != 0)
10754     return SDValue();
10755 
10756   SelectionDAG &DAG = DCI.DAG;
10757   SDValue LHS = N->getOperand(0);
10758 
10759   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10760   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10761   unsigned LHSOpc = LHS.getOpcode();
10762   unsigned Opc = N->getOpcode();
10763   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10764       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10765     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10766     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10767   }
10768   return SDValue();
10769 }
10770 
10771 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10772                                              DAGCombinerInfo &DCI) const {
10773   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10774     return SDValue();
10775 
10776   SelectionDAG &DAG = DCI.DAG;
10777   EVT VT = N->getValueType(0);
10778 
10779   SDLoc SL(N);
10780   SDValue LHS = N->getOperand(0);
10781   SDValue RHS = N->getOperand(1);
10782 
10783   // These should really be instruction patterns, but writing patterns with
10784   // source modiifiers is a pain.
10785 
10786   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10787   if (LHS.getOpcode() == ISD::FADD) {
10788     SDValue A = LHS.getOperand(0);
10789     if (A == LHS.getOperand(1)) {
10790       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10791       if (FusedOp != 0) {
10792         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10793         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10794       }
10795     }
10796   }
10797 
10798   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10799   if (RHS.getOpcode() == ISD::FADD) {
10800     SDValue A = RHS.getOperand(0);
10801     if (A == RHS.getOperand(1)) {
10802       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10803       if (FusedOp != 0) {
10804         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10805         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10806       }
10807     }
10808   }
10809 
10810   return SDValue();
10811 }
10812 
10813 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10814                                              DAGCombinerInfo &DCI) const {
10815   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10816     return SDValue();
10817 
10818   SelectionDAG &DAG = DCI.DAG;
10819   SDLoc SL(N);
10820   EVT VT = N->getValueType(0);
10821   assert(!VT.isVector());
10822 
10823   // Try to get the fneg to fold into the source modifier. This undoes generic
10824   // DAG combines and folds them into the mad.
10825   //
10826   // Only do this if we are not trying to support denormals. v_mad_f32 does
10827   // not support denormals ever.
10828   SDValue LHS = N->getOperand(0);
10829   SDValue RHS = N->getOperand(1);
10830   if (LHS.getOpcode() == ISD::FADD) {
10831     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10832     SDValue A = LHS.getOperand(0);
10833     if (A == LHS.getOperand(1)) {
10834       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10835       if (FusedOp != 0){
10836         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10837         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10838 
10839         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10840       }
10841     }
10842   }
10843 
10844   if (RHS.getOpcode() == ISD::FADD) {
10845     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10846 
10847     SDValue A = RHS.getOperand(0);
10848     if (A == RHS.getOperand(1)) {
10849       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10850       if (FusedOp != 0){
10851         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10852         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10853       }
10854     }
10855   }
10856 
10857   return SDValue();
10858 }
10859 
10860 SDValue SITargetLowering::performFMACombine(SDNode *N,
10861                                             DAGCombinerInfo &DCI) const {
10862   SelectionDAG &DAG = DCI.DAG;
10863   EVT VT = N->getValueType(0);
10864   SDLoc SL(N);
10865 
10866   if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
10867     return SDValue();
10868 
10869   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10870   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10871   SDValue Op1 = N->getOperand(0);
10872   SDValue Op2 = N->getOperand(1);
10873   SDValue FMA = N->getOperand(2);
10874 
10875   if (FMA.getOpcode() != ISD::FMA ||
10876       Op1.getOpcode() != ISD::FP_EXTEND ||
10877       Op2.getOpcode() != ISD::FP_EXTEND)
10878     return SDValue();
10879 
10880   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10881   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10882   // is sufficient to allow generaing fdot2.
10883   const TargetOptions &Options = DAG.getTarget().Options;
10884   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10885       (N->getFlags().hasAllowContract() &&
10886        FMA->getFlags().hasAllowContract())) {
10887     Op1 = Op1.getOperand(0);
10888     Op2 = Op2.getOperand(0);
10889     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10890         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10891       return SDValue();
10892 
10893     SDValue Vec1 = Op1.getOperand(0);
10894     SDValue Idx1 = Op1.getOperand(1);
10895     SDValue Vec2 = Op2.getOperand(0);
10896 
10897     SDValue FMAOp1 = FMA.getOperand(0);
10898     SDValue FMAOp2 = FMA.getOperand(1);
10899     SDValue FMAAcc = FMA.getOperand(2);
10900 
10901     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10902         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10903       return SDValue();
10904 
10905     FMAOp1 = FMAOp1.getOperand(0);
10906     FMAOp2 = FMAOp2.getOperand(0);
10907     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10908         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10909       return SDValue();
10910 
10911     SDValue Vec3 = FMAOp1.getOperand(0);
10912     SDValue Vec4 = FMAOp2.getOperand(0);
10913     SDValue Idx2 = FMAOp1.getOperand(1);
10914 
10915     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10916         // Idx1 and Idx2 cannot be the same.
10917         Idx1 == Idx2)
10918       return SDValue();
10919 
10920     if (Vec1 == Vec2 || Vec3 == Vec4)
10921       return SDValue();
10922 
10923     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10924       return SDValue();
10925 
10926     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10927         (Vec1 == Vec4 && Vec2 == Vec3)) {
10928       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10929                          DAG.getTargetConstant(0, SL, MVT::i1));
10930     }
10931   }
10932   return SDValue();
10933 }
10934 
10935 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10936                                               DAGCombinerInfo &DCI) const {
10937   SelectionDAG &DAG = DCI.DAG;
10938   SDLoc SL(N);
10939 
10940   SDValue LHS = N->getOperand(0);
10941   SDValue RHS = N->getOperand(1);
10942   EVT VT = LHS.getValueType();
10943   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10944 
10945   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10946   if (!CRHS) {
10947     CRHS = dyn_cast<ConstantSDNode>(LHS);
10948     if (CRHS) {
10949       std::swap(LHS, RHS);
10950       CC = getSetCCSwappedOperands(CC);
10951     }
10952   }
10953 
10954   if (CRHS) {
10955     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10956         isBoolSGPR(LHS.getOperand(0))) {
10957       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10958       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10959       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10960       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10961       if ((CRHS->isAllOnes() &&
10962            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10963           (CRHS->isZero() &&
10964            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10965         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10966                            DAG.getConstant(-1, SL, MVT::i1));
10967       if ((CRHS->isAllOnes() &&
10968            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10969           (CRHS->isZero() &&
10970            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10971         return LHS.getOperand(0);
10972     }
10973 
10974     const APInt &CRHSVal = CRHS->getAPIntValue();
10975     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10976         LHS.getOpcode() == ISD::SELECT &&
10977         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10978         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10979         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10980         isBoolSGPR(LHS.getOperand(0))) {
10981       // Given CT != FT:
10982       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10983       // setcc (select cc, CT, CF), CF, ne => cc
10984       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10985       // setcc (select cc, CT, CF), CT, eq => cc
10986       const APInt &CT = LHS.getConstantOperandAPInt(1);
10987       const APInt &CF = LHS.getConstantOperandAPInt(2);
10988 
10989       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10990           (CT == CRHSVal && CC == ISD::SETNE))
10991         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10992                            DAG.getConstant(-1, SL, MVT::i1));
10993       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10994           (CT == CRHSVal && CC == ISD::SETEQ))
10995         return LHS.getOperand(0);
10996     }
10997   }
10998 
10999   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
11000                                            VT != MVT::f16))
11001     return SDValue();
11002 
11003   // Match isinf/isfinite pattern
11004   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
11005   // (fcmp one (fabs x), inf) -> (fp_class x,
11006   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
11007   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
11008     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
11009     if (!CRHS)
11010       return SDValue();
11011 
11012     const APFloat &APF = CRHS->getValueAPF();
11013     if (APF.isInfinity() && !APF.isNegative()) {
11014       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
11015                                  SIInstrFlags::N_INFINITY;
11016       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
11017                                     SIInstrFlags::P_ZERO |
11018                                     SIInstrFlags::N_NORMAL |
11019                                     SIInstrFlags::P_NORMAL |
11020                                     SIInstrFlags::N_SUBNORMAL |
11021                                     SIInstrFlags::P_SUBNORMAL;
11022       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
11023       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
11024                          DAG.getConstant(Mask, SL, MVT::i32));
11025     }
11026   }
11027 
11028   return SDValue();
11029 }
11030 
11031 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
11032                                                      DAGCombinerInfo &DCI) const {
11033   SelectionDAG &DAG = DCI.DAG;
11034   SDLoc SL(N);
11035   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
11036 
11037   SDValue Src = N->getOperand(0);
11038   SDValue Shift = N->getOperand(0);
11039 
11040   // TODO: Extend type shouldn't matter (assuming legal types).
11041   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
11042     Shift = Shift.getOperand(0);
11043 
11044   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
11045     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
11046     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
11047     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
11048     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
11049     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
11050     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
11051       SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0),
11052                                  SDLoc(Shift.getOperand(0)), MVT::i32);
11053 
11054       unsigned ShiftOffset = 8 * Offset;
11055       if (Shift.getOpcode() == ISD::SHL)
11056         ShiftOffset -= C->getZExtValue();
11057       else
11058         ShiftOffset += C->getZExtValue();
11059 
11060       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
11061         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
11062                            MVT::f32, Shifted);
11063       }
11064     }
11065   }
11066 
11067   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11068   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
11069   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
11070     // We simplified Src. If this node is not dead, visit it again so it is
11071     // folded properly.
11072     if (N->getOpcode() != ISD::DELETED_NODE)
11073       DCI.AddToWorklist(N);
11074     return SDValue(N, 0);
11075   }
11076 
11077   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
11078   if (SDValue DemandedSrc =
11079           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
11080     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
11081 
11082   return SDValue();
11083 }
11084 
11085 SDValue SITargetLowering::performClampCombine(SDNode *N,
11086                                               DAGCombinerInfo &DCI) const {
11087   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
11088   if (!CSrc)
11089     return SDValue();
11090 
11091   const MachineFunction &MF = DCI.DAG.getMachineFunction();
11092   const APFloat &F = CSrc->getValueAPF();
11093   APFloat Zero = APFloat::getZero(F.getSemantics());
11094   if (F < Zero ||
11095       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
11096     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
11097   }
11098 
11099   APFloat One(F.getSemantics(), "1.0");
11100   if (F > One)
11101     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
11102 
11103   return SDValue(CSrc, 0);
11104 }
11105 
11106 
11107 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
11108                                             DAGCombinerInfo &DCI) const {
11109   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
11110     return SDValue();
11111   switch (N->getOpcode()) {
11112   case ISD::ADD:
11113     return performAddCombine(N, DCI);
11114   case ISD::SUB:
11115     return performSubCombine(N, DCI);
11116   case ISD::ADDCARRY:
11117   case ISD::SUBCARRY:
11118     return performAddCarrySubCarryCombine(N, DCI);
11119   case ISD::FADD:
11120     return performFAddCombine(N, DCI);
11121   case ISD::FSUB:
11122     return performFSubCombine(N, DCI);
11123   case ISD::SETCC:
11124     return performSetCCCombine(N, DCI);
11125   case ISD::FMAXNUM:
11126   case ISD::FMINNUM:
11127   case ISD::FMAXNUM_IEEE:
11128   case ISD::FMINNUM_IEEE:
11129   case ISD::SMAX:
11130   case ISD::SMIN:
11131   case ISD::UMAX:
11132   case ISD::UMIN:
11133   case AMDGPUISD::FMIN_LEGACY:
11134   case AMDGPUISD::FMAX_LEGACY:
11135     return performMinMaxCombine(N, DCI);
11136   case ISD::FMA:
11137     return performFMACombine(N, DCI);
11138   case ISD::AND:
11139     return performAndCombine(N, DCI);
11140   case ISD::OR:
11141     return performOrCombine(N, DCI);
11142   case ISD::XOR:
11143     return performXorCombine(N, DCI);
11144   case ISD::ZERO_EXTEND:
11145     return performZeroExtendCombine(N, DCI);
11146   case ISD::SIGN_EXTEND_INREG:
11147     return performSignExtendInRegCombine(N , DCI);
11148   case AMDGPUISD::FP_CLASS:
11149     return performClassCombine(N, DCI);
11150   case ISD::FCANONICALIZE:
11151     return performFCanonicalizeCombine(N, DCI);
11152   case AMDGPUISD::RCP:
11153     return performRcpCombine(N, DCI);
11154   case AMDGPUISD::FRACT:
11155   case AMDGPUISD::RSQ:
11156   case AMDGPUISD::RCP_LEGACY:
11157   case AMDGPUISD::RCP_IFLAG:
11158   case AMDGPUISD::RSQ_CLAMP:
11159   case AMDGPUISD::LDEXP: {
11160     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
11161     SDValue Src = N->getOperand(0);
11162     if (Src.isUndef())
11163       return Src;
11164     break;
11165   }
11166   case ISD::SINT_TO_FP:
11167   case ISD::UINT_TO_FP:
11168     return performUCharToFloatCombine(N, DCI);
11169   case AMDGPUISD::CVT_F32_UBYTE0:
11170   case AMDGPUISD::CVT_F32_UBYTE1:
11171   case AMDGPUISD::CVT_F32_UBYTE2:
11172   case AMDGPUISD::CVT_F32_UBYTE3:
11173     return performCvtF32UByteNCombine(N, DCI);
11174   case AMDGPUISD::FMED3:
11175     return performFMed3Combine(N, DCI);
11176   case AMDGPUISD::CVT_PKRTZ_F16_F32:
11177     return performCvtPkRTZCombine(N, DCI);
11178   case AMDGPUISD::CLAMP:
11179     return performClampCombine(N, DCI);
11180   case ISD::SCALAR_TO_VECTOR: {
11181     SelectionDAG &DAG = DCI.DAG;
11182     EVT VT = N->getValueType(0);
11183 
11184     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
11185     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
11186       SDLoc SL(N);
11187       SDValue Src = N->getOperand(0);
11188       EVT EltVT = Src.getValueType();
11189       if (EltVT == MVT::f16)
11190         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
11191 
11192       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
11193       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
11194     }
11195 
11196     break;
11197   }
11198   case ISD::EXTRACT_VECTOR_ELT:
11199     return performExtractVectorEltCombine(N, DCI);
11200   case ISD::INSERT_VECTOR_ELT:
11201     return performInsertVectorEltCombine(N, DCI);
11202   case ISD::LOAD: {
11203     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
11204       return Widended;
11205     LLVM_FALLTHROUGH;
11206   }
11207   default: {
11208     if (!DCI.isBeforeLegalize()) {
11209       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
11210         return performMemSDNodeCombine(MemNode, DCI);
11211     }
11212 
11213     break;
11214   }
11215   }
11216 
11217   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
11218 }
11219 
11220 /// Helper function for adjustWritemask
11221 static unsigned SubIdx2Lane(unsigned Idx) {
11222   switch (Idx) {
11223   default: return ~0u;
11224   case AMDGPU::sub0: return 0;
11225   case AMDGPU::sub1: return 1;
11226   case AMDGPU::sub2: return 2;
11227   case AMDGPU::sub3: return 3;
11228   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
11229   }
11230 }
11231 
11232 /// Adjust the writemask of MIMG instructions
11233 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
11234                                           SelectionDAG &DAG) const {
11235   unsigned Opcode = Node->getMachineOpcode();
11236 
11237   // Subtract 1 because the vdata output is not a MachineSDNode operand.
11238   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
11239   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
11240     return Node; // not implemented for D16
11241 
11242   SDNode *Users[5] = { nullptr };
11243   unsigned Lane = 0;
11244   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
11245   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
11246   unsigned NewDmask = 0;
11247   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
11248   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
11249   bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
11250                   Node->getConstantOperandVal(LWEIdx))
11251                      ? true
11252                      : false;
11253   unsigned TFCLane = 0;
11254   bool HasChain = Node->getNumValues() > 1;
11255 
11256   if (OldDmask == 0) {
11257     // These are folded out, but on the chance it happens don't assert.
11258     return Node;
11259   }
11260 
11261   unsigned OldBitsSet = countPopulation(OldDmask);
11262   // Work out which is the TFE/LWE lane if that is enabled.
11263   if (UsesTFC) {
11264     TFCLane = OldBitsSet;
11265   }
11266 
11267   // Try to figure out the used register components
11268   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
11269        I != E; ++I) {
11270 
11271     // Don't look at users of the chain.
11272     if (I.getUse().getResNo() != 0)
11273       continue;
11274 
11275     // Abort if we can't understand the usage
11276     if (!I->isMachineOpcode() ||
11277         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
11278       return Node;
11279 
11280     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
11281     // Note that subregs are packed, i.e. Lane==0 is the first bit set
11282     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
11283     // set, etc.
11284     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
11285     if (Lane == ~0u)
11286       return Node;
11287 
11288     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
11289     if (UsesTFC && Lane == TFCLane) {
11290       Users[Lane] = *I;
11291     } else {
11292       // Set which texture component corresponds to the lane.
11293       unsigned Comp;
11294       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
11295         Comp = countTrailingZeros(Dmask);
11296         Dmask &= ~(1 << Comp);
11297       }
11298 
11299       // Abort if we have more than one user per component.
11300       if (Users[Lane])
11301         return Node;
11302 
11303       Users[Lane] = *I;
11304       NewDmask |= 1 << Comp;
11305     }
11306   }
11307 
11308   // Don't allow 0 dmask, as hardware assumes one channel enabled.
11309   bool NoChannels = !NewDmask;
11310   if (NoChannels) {
11311     if (!UsesTFC) {
11312       // No uses of the result and not using TFC. Then do nothing.
11313       return Node;
11314     }
11315     // If the original dmask has one channel - then nothing to do
11316     if (OldBitsSet == 1)
11317       return Node;
11318     // Use an arbitrary dmask - required for the instruction to work
11319     NewDmask = 1;
11320   }
11321   // Abort if there's no change
11322   if (NewDmask == OldDmask)
11323     return Node;
11324 
11325   unsigned BitsSet = countPopulation(NewDmask);
11326 
11327   // Check for TFE or LWE - increase the number of channels by one to account
11328   // for the extra return value
11329   // This will need adjustment for D16 if this is also included in
11330   // adjustWriteMask (this function) but at present D16 are excluded.
11331   unsigned NewChannels = BitsSet + UsesTFC;
11332 
11333   int NewOpcode =
11334       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
11335   assert(NewOpcode != -1 &&
11336          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
11337          "failed to find equivalent MIMG op");
11338 
11339   // Adjust the writemask in the node
11340   SmallVector<SDValue, 12> Ops;
11341   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
11342   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
11343   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11344 
11345   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11346 
11347   MVT ResultVT = NewChannels == 1 ?
11348     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11349                            NewChannels == 5 ? 8 : NewChannels);
11350   SDVTList NewVTList = HasChain ?
11351     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11352 
11353 
11354   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11355                                               NewVTList, Ops);
11356 
11357   if (HasChain) {
11358     // Update chain.
11359     DAG.setNodeMemRefs(NewNode, Node->memoperands());
11360     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11361   }
11362 
11363   if (NewChannels == 1) {
11364     assert(Node->hasNUsesOfValue(1, 0));
11365     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11366                                       SDLoc(Node), Users[Lane]->getValueType(0),
11367                                       SDValue(NewNode, 0));
11368     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11369     return nullptr;
11370   }
11371 
11372   // Update the users of the node with the new indices
11373   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11374     SDNode *User = Users[i];
11375     if (!User) {
11376       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11377       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11378       if (i || !NoChannels)
11379         continue;
11380     } else {
11381       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11382       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11383     }
11384 
11385     switch (Idx) {
11386     default: break;
11387     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11388     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11389     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11390     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11391     }
11392   }
11393 
11394   DAG.RemoveDeadNode(Node);
11395   return nullptr;
11396 }
11397 
11398 static bool isFrameIndexOp(SDValue Op) {
11399   if (Op.getOpcode() == ISD::AssertZext)
11400     Op = Op.getOperand(0);
11401 
11402   return isa<FrameIndexSDNode>(Op);
11403 }
11404 
11405 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11406 /// with frame index operands.
11407 /// LLVM assumes that inputs are to these instructions are registers.
11408 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11409                                                         SelectionDAG &DAG) const {
11410   if (Node->getOpcode() == ISD::CopyToReg) {
11411     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11412     SDValue SrcVal = Node->getOperand(2);
11413 
11414     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11415     // to try understanding copies to physical registers.
11416     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11417       SDLoc SL(Node);
11418       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11419       SDValue VReg = DAG.getRegister(
11420         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11421 
11422       SDNode *Glued = Node->getGluedNode();
11423       SDValue ToVReg
11424         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11425                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11426       SDValue ToResultReg
11427         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11428                            VReg, ToVReg.getValue(1));
11429       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11430       DAG.RemoveDeadNode(Node);
11431       return ToResultReg.getNode();
11432     }
11433   }
11434 
11435   SmallVector<SDValue, 8> Ops;
11436   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11437     if (!isFrameIndexOp(Node->getOperand(i))) {
11438       Ops.push_back(Node->getOperand(i));
11439       continue;
11440     }
11441 
11442     SDLoc DL(Node);
11443     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11444                                      Node->getOperand(i).getValueType(),
11445                                      Node->getOperand(i)), 0));
11446   }
11447 
11448   return DAG.UpdateNodeOperands(Node, Ops);
11449 }
11450 
11451 /// Fold the instructions after selecting them.
11452 /// Returns null if users were already updated.
11453 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11454                                           SelectionDAG &DAG) const {
11455   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11456   unsigned Opcode = Node->getMachineOpcode();
11457 
11458   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11459       !TII->isGather4(Opcode) &&
11460       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11461     return adjustWritemask(Node, DAG);
11462   }
11463 
11464   if (Opcode == AMDGPU::INSERT_SUBREG ||
11465       Opcode == AMDGPU::REG_SEQUENCE) {
11466     legalizeTargetIndependentNode(Node, DAG);
11467     return Node;
11468   }
11469 
11470   switch (Opcode) {
11471   case AMDGPU::V_DIV_SCALE_F32_e64:
11472   case AMDGPU::V_DIV_SCALE_F64_e64: {
11473     // Satisfy the operand register constraint when one of the inputs is
11474     // undefined. Ordinarily each undef value will have its own implicit_def of
11475     // a vreg, so force these to use a single register.
11476     SDValue Src0 = Node->getOperand(1);
11477     SDValue Src1 = Node->getOperand(3);
11478     SDValue Src2 = Node->getOperand(5);
11479 
11480     if ((Src0.isMachineOpcode() &&
11481          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11482         (Src0 == Src1 || Src0 == Src2))
11483       break;
11484 
11485     MVT VT = Src0.getValueType().getSimpleVT();
11486     const TargetRegisterClass *RC =
11487         getRegClassFor(VT, Src0.getNode()->isDivergent());
11488 
11489     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11490     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11491 
11492     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11493                                       UndefReg, Src0, SDValue());
11494 
11495     // src0 must be the same register as src1 or src2, even if the value is
11496     // undefined, so make sure we don't violate this constraint.
11497     if (Src0.isMachineOpcode() &&
11498         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11499       if (Src1.isMachineOpcode() &&
11500           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11501         Src0 = Src1;
11502       else if (Src2.isMachineOpcode() &&
11503                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11504         Src0 = Src2;
11505       else {
11506         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11507         Src0 = UndefReg;
11508         Src1 = UndefReg;
11509       }
11510     } else
11511       break;
11512 
11513     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11514     Ops[1] = Src0;
11515     Ops[3] = Src1;
11516     Ops[5] = Src2;
11517     Ops.push_back(ImpDef.getValue(1));
11518     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11519   }
11520   default:
11521     break;
11522   }
11523 
11524   return Node;
11525 }
11526 
11527 // Any MIMG instructions that use tfe or lwe require an initialization of the
11528 // result register that will be written in the case of a memory access failure.
11529 // The required code is also added to tie this init code to the result of the
11530 // img instruction.
11531 void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
11532   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11533   const SIRegisterInfo &TRI = TII->getRegisterInfo();
11534   MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11535   MachineBasicBlock &MBB = *MI.getParent();
11536 
11537   MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
11538   MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
11539   MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
11540 
11541   if (!TFE && !LWE) // intersect_ray
11542     return;
11543 
11544   unsigned TFEVal = TFE ? TFE->getImm() : 0;
11545   unsigned LWEVal = LWE->getImm();
11546   unsigned D16Val = D16 ? D16->getImm() : 0;
11547 
11548   if (!TFEVal && !LWEVal)
11549     return;
11550 
11551   // At least one of TFE or LWE are non-zero
11552   // We have to insert a suitable initialization of the result value and
11553   // tie this to the dest of the image instruction.
11554 
11555   const DebugLoc &DL = MI.getDebugLoc();
11556 
11557   int DstIdx =
11558       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
11559 
11560   // Calculate which dword we have to initialize to 0.
11561   MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
11562 
11563   // check that dmask operand is found.
11564   assert(MO_Dmask && "Expected dmask operand in instruction");
11565 
11566   unsigned dmask = MO_Dmask->getImm();
11567   // Determine the number of active lanes taking into account the
11568   // Gather4 special case
11569   unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask);
11570 
11571   bool Packed = !Subtarget->hasUnpackedD16VMem();
11572 
11573   unsigned InitIdx =
11574       D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
11575 
11576   // Abandon attempt if the dst size isn't large enough
11577   // - this is in fact an error but this is picked up elsewhere and
11578   // reported correctly.
11579   uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
11580   if (DstSize < InitIdx)
11581     return;
11582 
11583   // Create a register for the intialization value.
11584   Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11585   unsigned NewDst = 0; // Final initialized value will be in here
11586 
11587   // If PRTStrictNull feature is enabled (the default) then initialize
11588   // all the result registers to 0, otherwise just the error indication
11589   // register (VGPRn+1)
11590   unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
11591   unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
11592 
11593   BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
11594   for (; SizeLeft; SizeLeft--, CurrIdx++) {
11595     NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11596     // Initialize dword
11597     Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
11598     BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
11599       .addImm(0);
11600     // Insert into the super-reg
11601     BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
11602       .addReg(PrevDst)
11603       .addReg(SubReg)
11604       .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
11605 
11606     PrevDst = NewDst;
11607   }
11608 
11609   // Add as an implicit operand
11610   MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
11611 
11612   // Tie the just added implicit operand to the dst
11613   MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
11614 }
11615 
11616 /// Assign the register class depending on the number of
11617 /// bits set in the writemask
11618 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11619                                                      SDNode *Node) const {
11620   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11621 
11622   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11623 
11624   if (TII->isVOP3(MI.getOpcode())) {
11625     // Make sure constant bus requirements are respected.
11626     TII->legalizeOperandsVOP3(MRI, MI);
11627 
11628     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11629     // This saves a chain-copy of registers and better ballance register
11630     // use between vgpr and agpr as agpr tuples tend to be big.
11631     if (MI.getDesc().OpInfo) {
11632       unsigned Opc = MI.getOpcode();
11633       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11634       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11635                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11636         if (I == -1)
11637           break;
11638         MachineOperand &Op = MI.getOperand(I);
11639         if (!Op.isReg() || !Op.getReg().isVirtual())
11640           continue;
11641         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11642         if (!TRI->hasAGPRs(RC))
11643           continue;
11644         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11645         if (!Src || !Src->isCopy() ||
11646             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11647           continue;
11648         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11649         // All uses of agpr64 and agpr32 can also accept vgpr except for
11650         // v_accvgpr_read, but we do not produce agpr reads during selection,
11651         // so no use checks are needed.
11652         MRI.setRegClass(Op.getReg(), NewRC);
11653       }
11654     }
11655 
11656     return;
11657   }
11658 
11659   // Replace unused atomics with the no return version.
11660   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11661   if (NoRetAtomicOp != -1) {
11662     if (!Node->hasAnyUseOfValue(0)) {
11663       int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
11664                                                AMDGPU::OpName::cpol);
11665       if (CPolIdx != -1) {
11666         MachineOperand &CPol = MI.getOperand(CPolIdx);
11667         CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC);
11668       }
11669       MI.RemoveOperand(0);
11670       MI.setDesc(TII->get(NoRetAtomicOp));
11671       return;
11672     }
11673 
11674     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11675     // instruction, because the return type of these instructions is a vec2 of
11676     // the memory type, so it can be tied to the input operand.
11677     // This means these instructions always have a use, so we need to add a
11678     // special case to check if the atomic has only one extract_subreg use,
11679     // which itself has no uses.
11680     if ((Node->hasNUsesOfValue(1, 0) &&
11681          Node->use_begin()->isMachineOpcode() &&
11682          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11683          !Node->use_begin()->hasAnyUseOfValue(0))) {
11684       Register Def = MI.getOperand(0).getReg();
11685 
11686       // Change this into a noret atomic.
11687       MI.setDesc(TII->get(NoRetAtomicOp));
11688       MI.RemoveOperand(0);
11689 
11690       // If we only remove the def operand from the atomic instruction, the
11691       // extract_subreg will be left with a use of a vreg without a def.
11692       // So we need to insert an implicit_def to avoid machine verifier
11693       // errors.
11694       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11695               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11696     }
11697     return;
11698   }
11699 
11700   if (TII->isMIMG(MI) && !MI.mayStore())
11701     AddIMGInit(MI);
11702 }
11703 
11704 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11705                               uint64_t Val) {
11706   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11707   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11708 }
11709 
11710 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11711                                                 const SDLoc &DL,
11712                                                 SDValue Ptr) const {
11713   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11714 
11715   // Build the half of the subregister with the constants before building the
11716   // full 128-bit register. If we are building multiple resource descriptors,
11717   // this will allow CSEing of the 2-component register.
11718   const SDValue Ops0[] = {
11719     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11720     buildSMovImm32(DAG, DL, 0),
11721     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11722     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11723     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11724   };
11725 
11726   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11727                                                 MVT::v2i32, Ops0), 0);
11728 
11729   // Combine the constants and the pointer.
11730   const SDValue Ops1[] = {
11731     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11732     Ptr,
11733     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11734     SubRegHi,
11735     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11736   };
11737 
11738   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11739 }
11740 
11741 /// Return a resource descriptor with the 'Add TID' bit enabled
11742 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11743 ///        of the resource descriptor) to create an offset, which is added to
11744 ///        the resource pointer.
11745 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11746                                            SDValue Ptr, uint32_t RsrcDword1,
11747                                            uint64_t RsrcDword2And3) const {
11748   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11749   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11750   if (RsrcDword1) {
11751     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11752                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11753                     0);
11754   }
11755 
11756   SDValue DataLo = buildSMovImm32(DAG, DL,
11757                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11758   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11759 
11760   const SDValue Ops[] = {
11761     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11762     PtrLo,
11763     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11764     PtrHi,
11765     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11766     DataLo,
11767     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11768     DataHi,
11769     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11770   };
11771 
11772   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11773 }
11774 
11775 //===----------------------------------------------------------------------===//
11776 //                         SI Inline Assembly Support
11777 //===----------------------------------------------------------------------===//
11778 
11779 std::pair<unsigned, const TargetRegisterClass *>
11780 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
11781                                                StringRef Constraint,
11782                                                MVT VT) const {
11783   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
11784 
11785   const TargetRegisterClass *RC = nullptr;
11786   if (Constraint.size() == 1) {
11787     const unsigned BitWidth = VT.getSizeInBits();
11788     switch (Constraint[0]) {
11789     default:
11790       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11791     case 's':
11792     case 'r':
11793       switch (BitWidth) {
11794       case 16:
11795         RC = &AMDGPU::SReg_32RegClass;
11796         break;
11797       case 64:
11798         RC = &AMDGPU::SGPR_64RegClass;
11799         break;
11800       default:
11801         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11802         if (!RC)
11803           return std::make_pair(0U, nullptr);
11804         break;
11805       }
11806       break;
11807     case 'v':
11808       switch (BitWidth) {
11809       case 16:
11810         RC = &AMDGPU::VGPR_32RegClass;
11811         break;
11812       default:
11813         RC = TRI->getVGPRClassForBitWidth(BitWidth);
11814         if (!RC)
11815           return std::make_pair(0U, nullptr);
11816         break;
11817       }
11818       break;
11819     case 'a':
11820       if (!Subtarget->hasMAIInsts())
11821         break;
11822       switch (BitWidth) {
11823       case 16:
11824         RC = &AMDGPU::AGPR_32RegClass;
11825         break;
11826       default:
11827         RC = TRI->getAGPRClassForBitWidth(BitWidth);
11828         if (!RC)
11829           return std::make_pair(0U, nullptr);
11830         break;
11831       }
11832       break;
11833     }
11834     // We actually support i128, i16 and f16 as inline parameters
11835     // even if they are not reported as legal
11836     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11837                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11838       return std::make_pair(0U, RC);
11839   }
11840 
11841   if (Constraint.startswith("{") && Constraint.endswith("}")) {
11842     StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
11843     if (RegName.consume_front("v")) {
11844       RC = &AMDGPU::VGPR_32RegClass;
11845     } else if (RegName.consume_front("s")) {
11846       RC = &AMDGPU::SGPR_32RegClass;
11847     } else if (RegName.consume_front("a")) {
11848       RC = &AMDGPU::AGPR_32RegClass;
11849     }
11850 
11851     if (RC) {
11852       uint32_t Idx;
11853       if (RegName.consume_front("[")) {
11854         uint32_t End;
11855         bool Failed = RegName.consumeInteger(10, Idx);
11856         Failed |= !RegName.consume_front(":");
11857         Failed |= RegName.consumeInteger(10, End);
11858         Failed |= !RegName.consume_back("]");
11859         if (!Failed) {
11860           uint32_t Width = (End - Idx + 1) * 32;
11861           MCRegister Reg = RC->getRegister(Idx);
11862           if (SIRegisterInfo::isVGPRClass(RC))
11863             RC = TRI->getVGPRClassForBitWidth(Width);
11864           else if (SIRegisterInfo::isSGPRClass(RC))
11865             RC = TRI->getSGPRClassForBitWidth(Width);
11866           else if (SIRegisterInfo::isAGPRClass(RC))
11867             RC = TRI->getAGPRClassForBitWidth(Width);
11868           if (RC) {
11869             Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC);
11870             return std::make_pair(Reg, RC);
11871           }
11872         }
11873       } else {
11874         bool Failed = RegName.getAsInteger(10, Idx);
11875         if (!Failed && Idx < RC->getNumRegs())
11876           return std::make_pair(RC->getRegister(Idx), RC);
11877       }
11878     }
11879   }
11880 
11881   auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11882   if (Ret.first)
11883     Ret.second = TRI->getPhysRegClass(Ret.first);
11884 
11885   return Ret;
11886 }
11887 
11888 static bool isImmConstraint(StringRef Constraint) {
11889   if (Constraint.size() == 1) {
11890     switch (Constraint[0]) {
11891     default: break;
11892     case 'I':
11893     case 'J':
11894     case 'A':
11895     case 'B':
11896     case 'C':
11897       return true;
11898     }
11899   } else if (Constraint == "DA" ||
11900              Constraint == "DB") {
11901     return true;
11902   }
11903   return false;
11904 }
11905 
11906 SITargetLowering::ConstraintType
11907 SITargetLowering::getConstraintType(StringRef Constraint) const {
11908   if (Constraint.size() == 1) {
11909     switch (Constraint[0]) {
11910     default: break;
11911     case 's':
11912     case 'v':
11913     case 'a':
11914       return C_RegisterClass;
11915     }
11916   }
11917   if (isImmConstraint(Constraint)) {
11918     return C_Other;
11919   }
11920   return TargetLowering::getConstraintType(Constraint);
11921 }
11922 
11923 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11924   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11925     Val = Val & maskTrailingOnes<uint64_t>(Size);
11926   }
11927   return Val;
11928 }
11929 
11930 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11931                                                     std::string &Constraint,
11932                                                     std::vector<SDValue> &Ops,
11933                                                     SelectionDAG &DAG) const {
11934   if (isImmConstraint(Constraint)) {
11935     uint64_t Val;
11936     if (getAsmOperandConstVal(Op, Val) &&
11937         checkAsmConstraintVal(Op, Constraint, Val)) {
11938       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11939       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11940     }
11941   } else {
11942     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11943   }
11944 }
11945 
11946 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11947   unsigned Size = Op.getScalarValueSizeInBits();
11948   if (Size > 64)
11949     return false;
11950 
11951   if (Size == 16 && !Subtarget->has16BitInsts())
11952     return false;
11953 
11954   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11955     Val = C->getSExtValue();
11956     return true;
11957   }
11958   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11959     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11960     return true;
11961   }
11962   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11963     if (Size != 16 || Op.getNumOperands() != 2)
11964       return false;
11965     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11966       return false;
11967     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11968       Val = C->getSExtValue();
11969       return true;
11970     }
11971     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11972       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11973       return true;
11974     }
11975   }
11976 
11977   return false;
11978 }
11979 
11980 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11981                                              const std::string &Constraint,
11982                                              uint64_t Val) const {
11983   if (Constraint.size() == 1) {
11984     switch (Constraint[0]) {
11985     case 'I':
11986       return AMDGPU::isInlinableIntLiteral(Val);
11987     case 'J':
11988       return isInt<16>(Val);
11989     case 'A':
11990       return checkAsmConstraintValA(Op, Val);
11991     case 'B':
11992       return isInt<32>(Val);
11993     case 'C':
11994       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11995              AMDGPU::isInlinableIntLiteral(Val);
11996     default:
11997       break;
11998     }
11999   } else if (Constraint.size() == 2) {
12000     if (Constraint == "DA") {
12001       int64_t HiBits = static_cast<int32_t>(Val >> 32);
12002       int64_t LoBits = static_cast<int32_t>(Val);
12003       return checkAsmConstraintValA(Op, HiBits, 32) &&
12004              checkAsmConstraintValA(Op, LoBits, 32);
12005     }
12006     if (Constraint == "DB") {
12007       return true;
12008     }
12009   }
12010   llvm_unreachable("Invalid asm constraint");
12011 }
12012 
12013 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
12014                                               uint64_t Val,
12015                                               unsigned MaxSize) const {
12016   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
12017   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
12018   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
12019       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
12020       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
12021     return true;
12022   }
12023   return false;
12024 }
12025 
12026 static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
12027   switch (UnalignedClassID) {
12028   case AMDGPU::VReg_64RegClassID:
12029     return AMDGPU::VReg_64_Align2RegClassID;
12030   case AMDGPU::VReg_96RegClassID:
12031     return AMDGPU::VReg_96_Align2RegClassID;
12032   case AMDGPU::VReg_128RegClassID:
12033     return AMDGPU::VReg_128_Align2RegClassID;
12034   case AMDGPU::VReg_160RegClassID:
12035     return AMDGPU::VReg_160_Align2RegClassID;
12036   case AMDGPU::VReg_192RegClassID:
12037     return AMDGPU::VReg_192_Align2RegClassID;
12038   case AMDGPU::VReg_224RegClassID:
12039     return AMDGPU::VReg_224_Align2RegClassID;
12040   case AMDGPU::VReg_256RegClassID:
12041     return AMDGPU::VReg_256_Align2RegClassID;
12042   case AMDGPU::VReg_512RegClassID:
12043     return AMDGPU::VReg_512_Align2RegClassID;
12044   case AMDGPU::VReg_1024RegClassID:
12045     return AMDGPU::VReg_1024_Align2RegClassID;
12046   case AMDGPU::AReg_64RegClassID:
12047     return AMDGPU::AReg_64_Align2RegClassID;
12048   case AMDGPU::AReg_96RegClassID:
12049     return AMDGPU::AReg_96_Align2RegClassID;
12050   case AMDGPU::AReg_128RegClassID:
12051     return AMDGPU::AReg_128_Align2RegClassID;
12052   case AMDGPU::AReg_160RegClassID:
12053     return AMDGPU::AReg_160_Align2RegClassID;
12054   case AMDGPU::AReg_192RegClassID:
12055     return AMDGPU::AReg_192_Align2RegClassID;
12056   case AMDGPU::AReg_256RegClassID:
12057     return AMDGPU::AReg_256_Align2RegClassID;
12058   case AMDGPU::AReg_512RegClassID:
12059     return AMDGPU::AReg_512_Align2RegClassID;
12060   case AMDGPU::AReg_1024RegClassID:
12061     return AMDGPU::AReg_1024_Align2RegClassID;
12062   default:
12063     return -1;
12064   }
12065 }
12066 
12067 // Figure out which registers should be reserved for stack access. Only after
12068 // the function is legalized do we know all of the non-spill stack objects or if
12069 // calls are present.
12070 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
12071   MachineRegisterInfo &MRI = MF.getRegInfo();
12072   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12073   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
12074   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12075   const SIInstrInfo *TII = ST.getInstrInfo();
12076 
12077   if (Info->isEntryFunction()) {
12078     // Callable functions have fixed registers used for stack access.
12079     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
12080   }
12081 
12082   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
12083                              Info->getStackPtrOffsetReg()));
12084   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
12085     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
12086 
12087   // We need to worry about replacing the default register with itself in case
12088   // of MIR testcases missing the MFI.
12089   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
12090     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
12091 
12092   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
12093     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
12094 
12095   Info->limitOccupancy(MF);
12096 
12097   if (ST.isWave32() && !MF.empty()) {
12098     for (auto &MBB : MF) {
12099       for (auto &MI : MBB) {
12100         TII->fixImplicitOperands(MI);
12101       }
12102     }
12103   }
12104 
12105   // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
12106   // classes if required. Ideally the register class constraints would differ
12107   // per-subtarget, but there's no easy way to achieve that right now. This is
12108   // not a problem for VGPRs because the correctly aligned VGPR class is implied
12109   // from using them as the register class for legal types.
12110   if (ST.needsAlignedVGPRs()) {
12111     for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
12112       const Register Reg = Register::index2VirtReg(I);
12113       const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
12114       if (!RC)
12115         continue;
12116       int NewClassID = getAlignedAGPRClassID(RC->getID());
12117       if (NewClassID != -1)
12118         MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
12119     }
12120   }
12121 
12122   TargetLoweringBase::finalizeLowering(MF);
12123 }
12124 
12125 void SITargetLowering::computeKnownBitsForFrameIndex(
12126   const int FI, KnownBits &Known, const MachineFunction &MF) const {
12127   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
12128 
12129   // Set the high bits to zero based on the maximum allowed scratch size per
12130   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
12131   // calculation won't overflow, so assume the sign bit is never set.
12132   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
12133 }
12134 
12135 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
12136                                    KnownBits &Known, unsigned Dim) {
12137   unsigned MaxValue =
12138       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
12139   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
12140 }
12141 
12142 void SITargetLowering::computeKnownBitsForTargetInstr(
12143     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
12144     const MachineRegisterInfo &MRI, unsigned Depth) const {
12145   const MachineInstr *MI = MRI.getVRegDef(R);
12146   switch (MI->getOpcode()) {
12147   case AMDGPU::G_INTRINSIC: {
12148     switch (MI->getIntrinsicID()) {
12149     case Intrinsic::amdgcn_workitem_id_x:
12150       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
12151       break;
12152     case Intrinsic::amdgcn_workitem_id_y:
12153       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
12154       break;
12155     case Intrinsic::amdgcn_workitem_id_z:
12156       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
12157       break;
12158     case Intrinsic::amdgcn_mbcnt_lo:
12159     case Intrinsic::amdgcn_mbcnt_hi: {
12160       // These return at most the wavefront size - 1.
12161       unsigned Size = MRI.getType(R).getSizeInBits();
12162       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
12163       break;
12164     }
12165     case Intrinsic::amdgcn_groupstaticsize: {
12166       // We can report everything over the maximum size as 0. We can't report
12167       // based on the actual size because we don't know if it's accurate or not
12168       // at any given point.
12169       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
12170       break;
12171     }
12172     }
12173     break;
12174   }
12175   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
12176     Known.Zero.setHighBits(24);
12177     break;
12178   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
12179     Known.Zero.setHighBits(16);
12180     break;
12181   }
12182 }
12183 
12184 Align SITargetLowering::computeKnownAlignForTargetInstr(
12185   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
12186   unsigned Depth) const {
12187   const MachineInstr *MI = MRI.getVRegDef(R);
12188   switch (MI->getOpcode()) {
12189   case AMDGPU::G_INTRINSIC:
12190   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
12191     // FIXME: Can this move to generic code? What about the case where the call
12192     // site specifies a lower alignment?
12193     Intrinsic::ID IID = MI->getIntrinsicID();
12194     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
12195     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
12196     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
12197       return *RetAlign;
12198     return Align(1);
12199   }
12200   default:
12201     return Align(1);
12202   }
12203 }
12204 
12205 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12206   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
12207   const Align CacheLineAlign = Align(64);
12208 
12209   // Pre-GFX10 target did not benefit from loop alignment
12210   if (!ML || DisableLoopAlignment ||
12211       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
12212       getSubtarget()->hasInstFwdPrefetchBug())
12213     return PrefAlign;
12214 
12215   // On GFX10 I$ is 4 x 64 bytes cache lines.
12216   // By default prefetcher keeps one cache line behind and reads two ahead.
12217   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
12218   // behind and one ahead.
12219   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
12220   // If loop fits 64 bytes it always spans no more than two cache lines and
12221   // does not need an alignment.
12222   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
12223   // Else if loop is less or equal 192 bytes we need two lines behind.
12224 
12225   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12226   const MachineBasicBlock *Header = ML->getHeader();
12227   if (Header->getAlignment() != PrefAlign)
12228     return Header->getAlignment(); // Already processed.
12229 
12230   unsigned LoopSize = 0;
12231   for (const MachineBasicBlock *MBB : ML->blocks()) {
12232     // If inner loop block is aligned assume in average half of the alignment
12233     // size to be added as nops.
12234     if (MBB != Header)
12235       LoopSize += MBB->getAlignment().value() / 2;
12236 
12237     for (const MachineInstr &MI : *MBB) {
12238       LoopSize += TII->getInstSizeInBytes(MI);
12239       if (LoopSize > 192)
12240         return PrefAlign;
12241     }
12242   }
12243 
12244   if (LoopSize <= 64)
12245     return PrefAlign;
12246 
12247   if (LoopSize <= 128)
12248     return CacheLineAlign;
12249 
12250   // If any of parent loops is surrounded by prefetch instructions do not
12251   // insert new for inner loop, which would reset parent's settings.
12252   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
12253     if (MachineBasicBlock *Exit = P->getExitBlock()) {
12254       auto I = Exit->getFirstNonDebugInstr();
12255       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
12256         return CacheLineAlign;
12257     }
12258   }
12259 
12260   MachineBasicBlock *Pre = ML->getLoopPreheader();
12261   MachineBasicBlock *Exit = ML->getExitBlock();
12262 
12263   if (Pre && Exit) {
12264     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
12265             TII->get(AMDGPU::S_INST_PREFETCH))
12266       .addImm(1); // prefetch 2 lines behind PC
12267 
12268     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
12269             TII->get(AMDGPU::S_INST_PREFETCH))
12270       .addImm(2); // prefetch 1 line behind PC
12271   }
12272 
12273   return CacheLineAlign;
12274 }
12275 
12276 LLVM_ATTRIBUTE_UNUSED
12277 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
12278   assert(N->getOpcode() == ISD::CopyFromReg);
12279   do {
12280     // Follow the chain until we find an INLINEASM node.
12281     N = N->getOperand(0).getNode();
12282     if (N->getOpcode() == ISD::INLINEASM ||
12283         N->getOpcode() == ISD::INLINEASM_BR)
12284       return true;
12285   } while (N->getOpcode() == ISD::CopyFromReg);
12286   return false;
12287 }
12288 
12289 bool SITargetLowering::isSDNodeSourceOfDivergence(
12290     const SDNode *N, FunctionLoweringInfo *FLI,
12291     LegacyDivergenceAnalysis *KDA) const {
12292   switch (N->getOpcode()) {
12293   case ISD::CopyFromReg: {
12294     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
12295     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
12296     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12297     Register Reg = R->getReg();
12298 
12299     // FIXME: Why does this need to consider isLiveIn?
12300     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
12301       return !TRI->isSGPRReg(MRI, Reg);
12302 
12303     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
12304       return KDA->isDivergent(V);
12305 
12306     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
12307     return !TRI->isSGPRReg(MRI, Reg);
12308   }
12309   case ISD::LOAD: {
12310     const LoadSDNode *L = cast<LoadSDNode>(N);
12311     unsigned AS = L->getAddressSpace();
12312     // A flat load may access private memory.
12313     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
12314   }
12315   case ISD::CALLSEQ_END:
12316     return true;
12317   case ISD::INTRINSIC_WO_CHAIN:
12318     return AMDGPU::isIntrinsicSourceOfDivergence(
12319         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
12320   case ISD::INTRINSIC_W_CHAIN:
12321     return AMDGPU::isIntrinsicSourceOfDivergence(
12322         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
12323   case AMDGPUISD::ATOMIC_CMP_SWAP:
12324   case AMDGPUISD::ATOMIC_INC:
12325   case AMDGPUISD::ATOMIC_DEC:
12326   case AMDGPUISD::ATOMIC_LOAD_FMIN:
12327   case AMDGPUISD::ATOMIC_LOAD_FMAX:
12328   case AMDGPUISD::BUFFER_ATOMIC_SWAP:
12329   case AMDGPUISD::BUFFER_ATOMIC_ADD:
12330   case AMDGPUISD::BUFFER_ATOMIC_SUB:
12331   case AMDGPUISD::BUFFER_ATOMIC_SMIN:
12332   case AMDGPUISD::BUFFER_ATOMIC_UMIN:
12333   case AMDGPUISD::BUFFER_ATOMIC_SMAX:
12334   case AMDGPUISD::BUFFER_ATOMIC_UMAX:
12335   case AMDGPUISD::BUFFER_ATOMIC_AND:
12336   case AMDGPUISD::BUFFER_ATOMIC_OR:
12337   case AMDGPUISD::BUFFER_ATOMIC_XOR:
12338   case AMDGPUISD::BUFFER_ATOMIC_INC:
12339   case AMDGPUISD::BUFFER_ATOMIC_DEC:
12340   case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
12341   case AMDGPUISD::BUFFER_ATOMIC_CSUB:
12342   case AMDGPUISD::BUFFER_ATOMIC_FADD:
12343   case AMDGPUISD::BUFFER_ATOMIC_FMIN:
12344   case AMDGPUISD::BUFFER_ATOMIC_FMAX:
12345     // Target-specific read-modify-write atomics are sources of divergence.
12346     return true;
12347   default:
12348     if (auto *A = dyn_cast<AtomicSDNode>(N)) {
12349       // Generic read-modify-write atomics are sources of divergence.
12350       return A->readMem() && A->writeMem();
12351     }
12352     return false;
12353   }
12354 }
12355 
12356 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
12357                                                EVT VT) const {
12358   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
12359   case MVT::f32:
12360     return hasFP32Denormals(DAG.getMachineFunction());
12361   case MVT::f64:
12362   case MVT::f16:
12363     return hasFP64FP16Denormals(DAG.getMachineFunction());
12364   default:
12365     return false;
12366   }
12367 }
12368 
12369 bool SITargetLowering::denormalsEnabledForType(LLT Ty,
12370                                                MachineFunction &MF) const {
12371   switch (Ty.getScalarSizeInBits()) {
12372   case 32:
12373     return hasFP32Denormals(MF);
12374   case 64:
12375   case 16:
12376     return hasFP64FP16Denormals(MF);
12377   default:
12378     return false;
12379   }
12380 }
12381 
12382 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
12383                                                     const SelectionDAG &DAG,
12384                                                     bool SNaN,
12385                                                     unsigned Depth) const {
12386   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
12387     const MachineFunction &MF = DAG.getMachineFunction();
12388     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12389 
12390     if (Info->getMode().DX10Clamp)
12391       return true; // Clamped to 0.
12392     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
12393   }
12394 
12395   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
12396                                                             SNaN, Depth);
12397 }
12398 
12399 // Global FP atomic instructions have a hardcoded FP mode and do not support
12400 // FP32 denormals, and only support v2f16 denormals.
12401 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
12402   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
12403   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
12404   if (&Flt == &APFloat::IEEEsingle())
12405     return DenormMode == DenormalMode::getPreserveSign();
12406   return DenormMode == DenormalMode::getIEEE();
12407 }
12408 
12409 TargetLowering::AtomicExpansionKind
12410 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
12411 
12412   auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) {
12413     OptimizationRemarkEmitter ORE(RMW->getFunction());
12414     LLVMContext &Ctx = RMW->getFunction()->getContext();
12415     SmallVector<StringRef> SSNs;
12416     Ctx.getSyncScopeNames(SSNs);
12417     auto MemScope = SSNs[RMW->getSyncScopeID()].empty()
12418                         ? "system"
12419                         : SSNs[RMW->getSyncScopeID()];
12420     ORE.emit([&]() {
12421       return OptimizationRemark(DEBUG_TYPE, "Passed", RMW)
12422              << "Hardware instruction generated for atomic "
12423              << RMW->getOperationName(RMW->getOperation())
12424              << " operation at memory scope " << MemScope
12425              << " due to an unsafe request.";
12426     });
12427     return Kind;
12428   };
12429 
12430   switch (RMW->getOperation()) {
12431   case AtomicRMWInst::FAdd: {
12432     Type *Ty = RMW->getType();
12433 
12434     // We don't have a way to support 16-bit atomics now, so just leave them
12435     // as-is.
12436     if (Ty->isHalfTy())
12437       return AtomicExpansionKind::None;
12438 
12439     if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
12440       return AtomicExpansionKind::CmpXChg;
12441 
12442     unsigned AS = RMW->getPointerAddressSpace();
12443 
12444     if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) &&
12445          Subtarget->hasAtomicFaddInsts()) {
12446       // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
12447       // floating point atomic instructions. May generate more efficient code,
12448       // but may not respect rounding and denormal modes, and may give incorrect
12449       // results for certain memory destinations.
12450       if (RMW->getFunction()
12451               ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12452               .getValueAsString() != "true")
12453         return AtomicExpansionKind::CmpXChg;
12454 
12455       if (Subtarget->hasGFX90AInsts()) {
12456         if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS)
12457           return AtomicExpansionKind::CmpXChg;
12458 
12459         auto SSID = RMW->getSyncScopeID();
12460         if (SSID == SyncScope::System ||
12461             SSID == RMW->getContext().getOrInsertSyncScopeID("one-as"))
12462           return AtomicExpansionKind::CmpXChg;
12463 
12464         return ReportUnsafeHWInst(AtomicExpansionKind::None);
12465       }
12466 
12467       if (AS == AMDGPUAS::FLAT_ADDRESS)
12468         return AtomicExpansionKind::CmpXChg;
12469 
12470       return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12471                               : AtomicExpansionKind::CmpXChg;
12472     }
12473 
12474     // DS FP atomics do repect the denormal mode, but the rounding mode is fixed
12475     // to round-to-nearest-even.
12476     // The only exception is DS_ADD_F64 which never flushes regardless of mode.
12477     if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) {
12478       if (!Ty->isDoubleTy())
12479         return AtomicExpansionKind::None;
12480 
12481       if (fpModeMatchesGlobalFPAtomicMode(RMW))
12482         return AtomicExpansionKind::None;
12483 
12484       return RMW->getFunction()
12485                          ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12486                          .getValueAsString() == "true"
12487                  ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12488                  : AtomicExpansionKind::CmpXChg;
12489     }
12490 
12491     return AtomicExpansionKind::CmpXChg;
12492   }
12493   default:
12494     break;
12495   }
12496 
12497   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
12498 }
12499 
12500 const TargetRegisterClass *
12501 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
12502   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
12503   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12504   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
12505     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
12506                                                : &AMDGPU::SReg_32RegClass;
12507   if (!TRI->isSGPRClass(RC) && !isDivergent)
12508     return TRI->getEquivalentSGPRClass(RC);
12509   else if (TRI->isSGPRClass(RC) && isDivergent)
12510     return TRI->getEquivalentVGPRClass(RC);
12511 
12512   return RC;
12513 }
12514 
12515 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
12516 // uniform values (as produced by the mask results of control flow intrinsics)
12517 // used outside of divergent blocks. The phi users need to also be treated as
12518 // always uniform.
12519 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
12520                       unsigned WaveSize) {
12521   // FIXME: We asssume we never cast the mask results of a control flow
12522   // intrinsic.
12523   // Early exit if the type won't be consistent as a compile time hack.
12524   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
12525   if (!IT || IT->getBitWidth() != WaveSize)
12526     return false;
12527 
12528   if (!isa<Instruction>(V))
12529     return false;
12530   if (!Visited.insert(V).second)
12531     return false;
12532   bool Result = false;
12533   for (auto U : V->users()) {
12534     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
12535       if (V == U->getOperand(1)) {
12536         switch (Intrinsic->getIntrinsicID()) {
12537         default:
12538           Result = false;
12539           break;
12540         case Intrinsic::amdgcn_if_break:
12541         case Intrinsic::amdgcn_if:
12542         case Intrinsic::amdgcn_else:
12543           Result = true;
12544           break;
12545         }
12546       }
12547       if (V == U->getOperand(0)) {
12548         switch (Intrinsic->getIntrinsicID()) {
12549         default:
12550           Result = false;
12551           break;
12552         case Intrinsic::amdgcn_end_cf:
12553         case Intrinsic::amdgcn_loop:
12554           Result = true;
12555           break;
12556         }
12557       }
12558     } else {
12559       Result = hasCFUser(U, Visited, WaveSize);
12560     }
12561     if (Result)
12562       break;
12563   }
12564   return Result;
12565 }
12566 
12567 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
12568                                                const Value *V) const {
12569   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
12570     if (CI->isInlineAsm()) {
12571       // FIXME: This cannot give a correct answer. This should only trigger in
12572       // the case where inline asm returns mixed SGPR and VGPR results, used
12573       // outside the defining block. We don't have a specific result to
12574       // consider, so this assumes if any value is SGPR, the overall register
12575       // also needs to be SGPR.
12576       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
12577       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
12578           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
12579       for (auto &TC : TargetConstraints) {
12580         if (TC.Type == InlineAsm::isOutput) {
12581           ComputeConstraintToUse(TC, SDValue());
12582           const TargetRegisterClass *RC = getRegForInlineAsmConstraint(
12583               SIRI, TC.ConstraintCode, TC.ConstraintVT).second;
12584           if (RC && SIRI->isSGPRClass(RC))
12585             return true;
12586         }
12587       }
12588     }
12589   }
12590   SmallPtrSet<const Value *, 16> Visited;
12591   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
12592 }
12593 
12594 std::pair<InstructionCost, MVT>
12595 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
12596                                           Type *Ty) const {
12597   std::pair<InstructionCost, MVT> Cost =
12598       TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
12599   auto Size = DL.getTypeSizeInBits(Ty);
12600   // Maximum load or store can handle 8 dwords for scalar and 4 for
12601   // vector ALU. Let's assume anything above 8 dwords is expensive
12602   // even if legal.
12603   if (Size <= 256)
12604     return Cost;
12605 
12606   Cost.first += (Size + 255) / 256;
12607   return Cost;
12608 }
12609 
12610 bool SITargetLowering::hasMemSDNodeUser(SDNode *N) const {
12611   SDNode::use_iterator I = N->use_begin(), E = N->use_end();
12612   for (; I != E; ++I) {
12613     if (MemSDNode *M = dyn_cast<MemSDNode>(*I)) {
12614       if (getBasePtrIndex(M) == I.getOperandNo())
12615         return true;
12616     }
12617   }
12618   return false;
12619 }
12620 
12621 bool SITargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0,
12622                                            SDValue N1) const {
12623   if (!N0.hasOneUse())
12624     return false;
12625   // Take care of the oportunity to keep N0 uniform
12626   if (N0->isDivergent() || !N1->isDivergent())
12627     return true;
12628   // Check if we have a good chance to form the memory access pattern with the
12629   // base and offset
12630   return (DAG.isBaseWithConstantOffset(N0) &&
12631           hasMemSDNodeUser(*N0->use_begin()));
12632 }
12633 
12634 MachineMemOperand::Flags
12635 SITargetLowering::getTargetMMOFlags(const Instruction &I) const {
12636   // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load.
12637   if (I.getMetadata("amdgpu.noclobber"))
12638     return MONoClobber;
12639   return MachineMemOperand::MONone;
12640 }
12641