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   Info.flags = MachineMemOperand::MONone;
1124   if (CI.hasMetadata(LLVMContext::MD_invariant_load))
1125     Info.flags |= MachineMemOperand::MOInvariant;
1126 
1127   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1128           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1129     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1130                                                   (Intrinsic::ID)IntrID);
1131     if (Attr.hasFnAttr(Attribute::ReadNone))
1132       return false;
1133 
1134     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1135 
1136     if (RsrcIntr->IsImage) {
1137       Info.ptrVal =
1138           MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1139       Info.align.reset();
1140     } else {
1141       Info.ptrVal =
1142           MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1143     }
1144 
1145     Info.flags |= MachineMemOperand::MODereferenceable;
1146     if (Attr.hasFnAttr(Attribute::ReadOnly)) {
1147       unsigned DMaskLanes = 4;
1148 
1149       if (RsrcIntr->IsImage) {
1150         const AMDGPU::ImageDimIntrinsicInfo *Intr
1151           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1152         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1153           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1154 
1155         if (!BaseOpcode->Gather4) {
1156           // If this isn't a gather, we may have excess loaded elements in the
1157           // IR type. Check the dmask for the real number of elements loaded.
1158           unsigned DMask
1159             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1160           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1161         }
1162 
1163         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1164       } else
1165         Info.memVT = EVT::getEVT(CI.getType());
1166 
1167       // FIXME: What does alignment mean for an image?
1168       Info.opc = ISD::INTRINSIC_W_CHAIN;
1169       Info.flags |= MachineMemOperand::MOLoad;
1170     } else if (Attr.hasFnAttr(Attribute::WriteOnly)) {
1171       Info.opc = ISD::INTRINSIC_VOID;
1172 
1173       Type *DataTy = CI.getArgOperand(0)->getType();
1174       if (RsrcIntr->IsImage) {
1175         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1176         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1177         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1178       } else
1179         Info.memVT = EVT::getEVT(DataTy);
1180 
1181       Info.flags |= MachineMemOperand::MOStore;
1182     } else {
1183       // Atomic
1184       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1185                                             ISD::INTRINSIC_W_CHAIN;
1186       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1187       Info.flags |= MachineMemOperand::MOLoad |
1188                     MachineMemOperand::MOStore |
1189                     MachineMemOperand::MODereferenceable;
1190 
1191       // XXX - Should this be volatile without known ordering?
1192       Info.flags |= MachineMemOperand::MOVolatile;
1193     }
1194     return true;
1195   }
1196 
1197   switch (IntrID) {
1198   case Intrinsic::amdgcn_atomic_inc:
1199   case Intrinsic::amdgcn_atomic_dec:
1200   case Intrinsic::amdgcn_ds_ordered_add:
1201   case Intrinsic::amdgcn_ds_ordered_swap:
1202   case Intrinsic::amdgcn_ds_fadd:
1203   case Intrinsic::amdgcn_ds_fmin:
1204   case Intrinsic::amdgcn_ds_fmax: {
1205     Info.opc = ISD::INTRINSIC_W_CHAIN;
1206     Info.memVT = MVT::getVT(CI.getType());
1207     Info.ptrVal = CI.getOperand(0);
1208     Info.align.reset();
1209     Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1210 
1211     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1212     if (!Vol->isZero())
1213       Info.flags |= MachineMemOperand::MOVolatile;
1214 
1215     return true;
1216   }
1217   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1218     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1219 
1220     Info.opc = ISD::INTRINSIC_W_CHAIN;
1221     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1222     Info.ptrVal =
1223         MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1224     Info.align.reset();
1225     Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1226 
1227     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1228     if (!Vol || !Vol->isZero())
1229       Info.flags |= MachineMemOperand::MOVolatile;
1230 
1231     return true;
1232   }
1233   case Intrinsic::amdgcn_ds_append:
1234   case Intrinsic::amdgcn_ds_consume: {
1235     Info.opc = ISD::INTRINSIC_W_CHAIN;
1236     Info.memVT = MVT::getVT(CI.getType());
1237     Info.ptrVal = CI.getOperand(0);
1238     Info.align.reset();
1239     Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1240 
1241     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1242     if (!Vol->isZero())
1243       Info.flags |= MachineMemOperand::MOVolatile;
1244 
1245     return true;
1246   }
1247   case Intrinsic::amdgcn_global_atomic_csub: {
1248     Info.opc = ISD::INTRINSIC_W_CHAIN;
1249     Info.memVT = MVT::getVT(CI.getType());
1250     Info.ptrVal = CI.getOperand(0);
1251     Info.align.reset();
1252     Info.flags |= MachineMemOperand::MOLoad |
1253                   MachineMemOperand::MOStore |
1254                   MachineMemOperand::MOVolatile;
1255     return true;
1256   }
1257   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1258     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1259     Info.opc = ISD::INTRINSIC_W_CHAIN;
1260     Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1261     Info.ptrVal =
1262         MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1263     Info.align.reset();
1264     Info.flags |= MachineMemOperand::MOLoad |
1265                   MachineMemOperand::MODereferenceable;
1266     return true;
1267   }
1268   case Intrinsic::amdgcn_global_atomic_fadd:
1269   case Intrinsic::amdgcn_global_atomic_fmin:
1270   case Intrinsic::amdgcn_global_atomic_fmax:
1271   case Intrinsic::amdgcn_flat_atomic_fadd:
1272   case Intrinsic::amdgcn_flat_atomic_fmin:
1273   case Intrinsic::amdgcn_flat_atomic_fmax:
1274   case Intrinsic::amdgcn_global_atomic_fadd_v2bf16:
1275   case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16: {
1276     Info.opc = ISD::INTRINSIC_W_CHAIN;
1277     Info.memVT = MVT::getVT(CI.getType());
1278     Info.ptrVal = CI.getOperand(0);
1279     Info.align.reset();
1280     Info.flags |= MachineMemOperand::MOLoad |
1281                   MachineMemOperand::MOStore |
1282                   MachineMemOperand::MODereferenceable |
1283                   MachineMemOperand::MOVolatile;
1284     return true;
1285   }
1286   case Intrinsic::amdgcn_ds_gws_init:
1287   case Intrinsic::amdgcn_ds_gws_barrier:
1288   case Intrinsic::amdgcn_ds_gws_sema_v:
1289   case Intrinsic::amdgcn_ds_gws_sema_br:
1290   case Intrinsic::amdgcn_ds_gws_sema_p:
1291   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1292     Info.opc = ISD::INTRINSIC_VOID;
1293 
1294     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1295     Info.ptrVal =
1296         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1297 
1298     // This is an abstract access, but we need to specify a type and size.
1299     Info.memVT = MVT::i32;
1300     Info.size = 4;
1301     Info.align = Align(4);
1302 
1303     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1304       Info.flags |= MachineMemOperand::MOLoad;
1305     else
1306       Info.flags |= MachineMemOperand::MOStore;
1307     return true;
1308   }
1309   default:
1310     return false;
1311   }
1312 }
1313 
1314 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1315                                             SmallVectorImpl<Value*> &Ops,
1316                                             Type *&AccessTy) const {
1317   switch (II->getIntrinsicID()) {
1318   case Intrinsic::amdgcn_atomic_inc:
1319   case Intrinsic::amdgcn_atomic_dec:
1320   case Intrinsic::amdgcn_ds_ordered_add:
1321   case Intrinsic::amdgcn_ds_ordered_swap:
1322   case Intrinsic::amdgcn_ds_append:
1323   case Intrinsic::amdgcn_ds_consume:
1324   case Intrinsic::amdgcn_ds_fadd:
1325   case Intrinsic::amdgcn_ds_fmin:
1326   case Intrinsic::amdgcn_ds_fmax:
1327   case Intrinsic::amdgcn_global_atomic_fadd:
1328   case Intrinsic::amdgcn_flat_atomic_fadd:
1329   case Intrinsic::amdgcn_flat_atomic_fmin:
1330   case Intrinsic::amdgcn_flat_atomic_fmax:
1331   case Intrinsic::amdgcn_global_atomic_fadd_v2bf16:
1332   case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16:
1333   case Intrinsic::amdgcn_global_atomic_csub: {
1334     Value *Ptr = II->getArgOperand(0);
1335     AccessTy = II->getType();
1336     Ops.push_back(Ptr);
1337     return true;
1338   }
1339   default:
1340     return false;
1341   }
1342 }
1343 
1344 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1345   if (!Subtarget->hasFlatInstOffsets()) {
1346     // Flat instructions do not have offsets, and only have the register
1347     // address.
1348     return AM.BaseOffs == 0 && AM.Scale == 0;
1349   }
1350 
1351   return AM.Scale == 0 &&
1352          (AM.BaseOffs == 0 ||
1353           Subtarget->getInstrInfo()->isLegalFLATOffset(
1354               AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT));
1355 }
1356 
1357 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1358   if (Subtarget->hasFlatGlobalInsts())
1359     return AM.Scale == 0 &&
1360            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1361                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1362                                     SIInstrFlags::FlatGlobal));
1363 
1364   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1365       // Assume the we will use FLAT for all global memory accesses
1366       // on VI.
1367       // FIXME: This assumption is currently wrong.  On VI we still use
1368       // MUBUF instructions for the r + i addressing mode.  As currently
1369       // implemented, the MUBUF instructions only work on buffer < 4GB.
1370       // It may be possible to support > 4GB buffers with MUBUF instructions,
1371       // by setting the stride value in the resource descriptor which would
1372       // increase the size limit to (stride * 4GB).  However, this is risky,
1373       // because it has never been validated.
1374     return isLegalFlatAddressingMode(AM);
1375   }
1376 
1377   return isLegalMUBUFAddressingMode(AM);
1378 }
1379 
1380 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1381   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1382   // additionally can do r + r + i with addr64. 32-bit has more addressing
1383   // mode options. Depending on the resource constant, it can also do
1384   // (i64 r0) + (i32 r1) * (i14 i).
1385   //
1386   // Private arrays end up using a scratch buffer most of the time, so also
1387   // assume those use MUBUF instructions. Scratch loads / stores are currently
1388   // implemented as mubuf instructions with offen bit set, so slightly
1389   // different than the normal addr64.
1390   if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1391     return false;
1392 
1393   // FIXME: Since we can split immediate into soffset and immediate offset,
1394   // would it make sense to allow any immediate?
1395 
1396   switch (AM.Scale) {
1397   case 0: // r + i or just i, depending on HasBaseReg.
1398     return true;
1399   case 1:
1400     return true; // We have r + r or r + i.
1401   case 2:
1402     if (AM.HasBaseReg) {
1403       // Reject 2 * r + r.
1404       return false;
1405     }
1406 
1407     // Allow 2 * r as r + r
1408     // Or  2 * r + i is allowed as r + r + i.
1409     return true;
1410   default: // Don't allow n * r
1411     return false;
1412   }
1413 }
1414 
1415 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1416                                              const AddrMode &AM, Type *Ty,
1417                                              unsigned AS, Instruction *I) const {
1418   // No global is ever allowed as a base.
1419   if (AM.BaseGV)
1420     return false;
1421 
1422   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1423     return isLegalGlobalAddressingMode(AM);
1424 
1425   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1426       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1427       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1428     // If the offset isn't a multiple of 4, it probably isn't going to be
1429     // correctly aligned.
1430     // FIXME: Can we get the real alignment here?
1431     if (AM.BaseOffs % 4 != 0)
1432       return isLegalMUBUFAddressingMode(AM);
1433 
1434     // There are no SMRD extloads, so if we have to do a small type access we
1435     // will use a MUBUF load.
1436     // FIXME?: We also need to do this if unaligned, but we don't know the
1437     // alignment here.
1438     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1439       return isLegalGlobalAddressingMode(AM);
1440 
1441     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1442       // SMRD instructions have an 8-bit, dword offset on SI.
1443       if (!isUInt<8>(AM.BaseOffs / 4))
1444         return false;
1445     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1446       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1447       // in 8-bits, it can use a smaller encoding.
1448       if (!isUInt<32>(AM.BaseOffs / 4))
1449         return false;
1450     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1451       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1452       if (!isUInt<20>(AM.BaseOffs))
1453         return false;
1454     } else
1455       llvm_unreachable("unhandled generation");
1456 
1457     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1458       return true;
1459 
1460     if (AM.Scale == 1 && AM.HasBaseReg)
1461       return true;
1462 
1463     return false;
1464 
1465   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1466     return isLegalMUBUFAddressingMode(AM);
1467   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1468              AS == AMDGPUAS::REGION_ADDRESS) {
1469     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1470     // field.
1471     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1472     // an 8-bit dword offset but we don't know the alignment here.
1473     if (!isUInt<16>(AM.BaseOffs))
1474       return false;
1475 
1476     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1477       return true;
1478 
1479     if (AM.Scale == 1 && AM.HasBaseReg)
1480       return true;
1481 
1482     return false;
1483   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1484              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1485     // For an unknown address space, this usually means that this is for some
1486     // reason being used for pure arithmetic, and not based on some addressing
1487     // computation. We don't have instructions that compute pointers with any
1488     // addressing modes, so treat them as having no offset like flat
1489     // instructions.
1490     return isLegalFlatAddressingMode(AM);
1491   }
1492 
1493   // Assume a user alias of global for unknown address spaces.
1494   return isLegalGlobalAddressingMode(AM);
1495 }
1496 
1497 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1498                                         const MachineFunction &MF) const {
1499   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1500     return (MemVT.getSizeInBits() <= 4 * 32);
1501   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1502     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1503     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1504   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1505     return (MemVT.getSizeInBits() <= 2 * 32);
1506   }
1507   return true;
1508 }
1509 
1510 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1511     unsigned Size, unsigned AddrSpace, Align Alignment,
1512     MachineMemOperand::Flags Flags, bool *IsFast) const {
1513   if (IsFast)
1514     *IsFast = false;
1515 
1516   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1517       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1518     // Check if alignment requirements for ds_read/write instructions are
1519     // disabled.
1520     if (Subtarget->hasUnalignedDSAccessEnabled() &&
1521         !Subtarget->hasLDSMisalignedBug()) {
1522       if (IsFast)
1523         *IsFast = Alignment != Align(2);
1524       return true;
1525     }
1526 
1527     // Either, the alignment requirements are "enabled", or there is an
1528     // unaligned LDS access related hardware bug though alignment requirements
1529     // are "disabled". In either case, we need to check for proper alignment
1530     // requirements.
1531     //
1532     if (Size == 64) {
1533       // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
1534       // can do a 4 byte aligned, 8 byte access in a single operation using
1535       // ds_read2/write2_b32 with adjacent offsets.
1536       bool AlignedBy4 = Alignment >= Align(4);
1537       if (IsFast)
1538         *IsFast = AlignedBy4;
1539 
1540       return AlignedBy4;
1541     }
1542     if (Size == 96) {
1543       // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
1544       // gfx8 and older.
1545       bool AlignedBy16 = Alignment >= Align(16);
1546       if (IsFast)
1547         *IsFast = AlignedBy16;
1548 
1549       return AlignedBy16;
1550     }
1551     if (Size == 128) {
1552       // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
1553       // gfx8 and older, but  we can do a 8 byte aligned, 16 byte access in a
1554       // single operation using ds_read2/write2_b64.
1555       bool AlignedBy8 = Alignment >= Align(8);
1556       if (IsFast)
1557         *IsFast = AlignedBy8;
1558 
1559       return AlignedBy8;
1560     }
1561   }
1562 
1563   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1564     bool AlignedBy4 = Alignment >= Align(4);
1565     if (IsFast)
1566       *IsFast = AlignedBy4;
1567 
1568     return AlignedBy4 ||
1569            Subtarget->enableFlatScratch() ||
1570            Subtarget->hasUnalignedScratchAccess();
1571   }
1572 
1573   // FIXME: We have to be conservative here and assume that flat operations
1574   // will access scratch.  If we had access to the IR function, then we
1575   // could determine if any private memory was used in the function.
1576   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1577       !Subtarget->hasUnalignedScratchAccess()) {
1578     bool AlignedBy4 = Alignment >= Align(4);
1579     if (IsFast)
1580       *IsFast = AlignedBy4;
1581 
1582     return AlignedBy4;
1583   }
1584 
1585   if (Subtarget->hasUnalignedBufferAccessEnabled() &&
1586       !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1587         AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1588     // If we have a uniform constant load, it still requires using a slow
1589     // buffer instruction if unaligned.
1590     if (IsFast) {
1591       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1592       // 2-byte alignment is worse than 1 unless doing a 2-byte access.
1593       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1594                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1595         Alignment >= Align(4) : Alignment != Align(2);
1596     }
1597 
1598     return true;
1599   }
1600 
1601   // Smaller than dword value must be aligned.
1602   if (Size < 32)
1603     return false;
1604 
1605   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1606   // byte-address are ignored, thus forcing Dword alignment.
1607   // This applies to private, global, and constant memory.
1608   if (IsFast)
1609     *IsFast = true;
1610 
1611   return Size >= 32 && Alignment >= Align(4);
1612 }
1613 
1614 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1615     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1616     bool *IsFast) const {
1617   if (IsFast)
1618     *IsFast = false;
1619 
1620   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1621   // which isn't a simple VT.
1622   // Until MVT is extended to handle this, simply check for the size and
1623   // rely on the condition below: allow accesses if the size is a multiple of 4.
1624   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1625                            VT.getStoreSize() > 16)) {
1626     return false;
1627   }
1628 
1629   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1630                                             Alignment, Flags, IsFast);
1631 }
1632 
1633 EVT SITargetLowering::getOptimalMemOpType(
1634     const MemOp &Op, const AttributeList &FuncAttributes) const {
1635   // FIXME: Should account for address space here.
1636 
1637   // The default fallback uses the private pointer size as a guess for a type to
1638   // use. Make sure we switch these to 64-bit accesses.
1639 
1640   if (Op.size() >= 16 &&
1641       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1642     return MVT::v4i32;
1643 
1644   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1645     return MVT::v2i32;
1646 
1647   // Use the default.
1648   return MVT::Other;
1649 }
1650 
1651 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1652   const MemSDNode *MemNode = cast<MemSDNode>(N);
1653   return MemNode->getMemOperand()->getFlags() & MONoClobber;
1654 }
1655 
1656 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1657   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1658          AS == AMDGPUAS::PRIVATE_ADDRESS;
1659 }
1660 
1661 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1662                                            unsigned DestAS) const {
1663   // Flat -> private/local is a simple truncate.
1664   // Flat -> global is no-op
1665   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1666     return true;
1667 
1668   const GCNTargetMachine &TM =
1669       static_cast<const GCNTargetMachine &>(getTargetMachine());
1670   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1671 }
1672 
1673 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1674   const MemSDNode *MemNode = cast<MemSDNode>(N);
1675 
1676   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1677 }
1678 
1679 TargetLoweringBase::LegalizeTypeAction
1680 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1681   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1682       VT.getScalarType().bitsLE(MVT::i16))
1683     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1684   return TargetLoweringBase::getPreferredVectorAction(VT);
1685 }
1686 
1687 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1688                                                          Type *Ty) const {
1689   // FIXME: Could be smarter if called for vector constants.
1690   return true;
1691 }
1692 
1693 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1694   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1695     switch (Op) {
1696     case ISD::LOAD:
1697     case ISD::STORE:
1698 
1699     // These operations are done with 32-bit instructions anyway.
1700     case ISD::AND:
1701     case ISD::OR:
1702     case ISD::XOR:
1703     case ISD::SELECT:
1704       // TODO: Extensions?
1705       return true;
1706     default:
1707       return false;
1708     }
1709   }
1710 
1711   // SimplifySetCC uses this function to determine whether or not it should
1712   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1713   if (VT == MVT::i1 && Op == ISD::SETCC)
1714     return false;
1715 
1716   return TargetLowering::isTypeDesirableForOp(Op, VT);
1717 }
1718 
1719 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1720                                                    const SDLoc &SL,
1721                                                    SDValue Chain,
1722                                                    uint64_t Offset) const {
1723   const DataLayout &DL = DAG.getDataLayout();
1724   MachineFunction &MF = DAG.getMachineFunction();
1725   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1726 
1727   const ArgDescriptor *InputPtrReg;
1728   const TargetRegisterClass *RC;
1729   LLT ArgTy;
1730   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1731 
1732   std::tie(InputPtrReg, RC, ArgTy) =
1733       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1734 
1735   // We may not have the kernarg segment argument if we have no kernel
1736   // arguments.
1737   if (!InputPtrReg)
1738     return DAG.getConstant(0, SL, PtrVT);
1739 
1740   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1741   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1742     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1743 
1744   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1745 }
1746 
1747 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1748                                             const SDLoc &SL) const {
1749   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1750                                                FIRST_IMPLICIT);
1751   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1752 }
1753 
1754 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1755                                          const SDLoc &SL, SDValue Val,
1756                                          bool Signed,
1757                                          const ISD::InputArg *Arg) const {
1758   // First, if it is a widened vector, narrow it.
1759   if (VT.isVector() &&
1760       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1761     EVT NarrowedVT =
1762         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1763                          VT.getVectorNumElements());
1764     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1765                       DAG.getConstant(0, SL, MVT::i32));
1766   }
1767 
1768   // Then convert the vector elements or scalar value.
1769   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1770       VT.bitsLT(MemVT)) {
1771     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1772     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1773   }
1774 
1775   if (MemVT.isFloatingPoint())
1776     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1777   else if (Signed)
1778     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1779   else
1780     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1781 
1782   return Val;
1783 }
1784 
1785 SDValue SITargetLowering::lowerKernargMemParameter(
1786     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1787     uint64_t Offset, Align Alignment, bool Signed,
1788     const ISD::InputArg *Arg) const {
1789   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1790 
1791   // Try to avoid using an extload by loading earlier than the argument address,
1792   // and extracting the relevant bits. The load should hopefully be merged with
1793   // the previous argument.
1794   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1795     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1796     int64_t AlignDownOffset = alignDown(Offset, 4);
1797     int64_t OffsetDiff = Offset - AlignDownOffset;
1798 
1799     EVT IntVT = MemVT.changeTypeToInteger();
1800 
1801     // TODO: If we passed in the base kernel offset we could have a better
1802     // alignment than 4, but we don't really need it.
1803     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1804     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1805                                MachineMemOperand::MODereferenceable |
1806                                    MachineMemOperand::MOInvariant);
1807 
1808     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1809     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1810 
1811     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1812     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1813     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1814 
1815 
1816     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1817   }
1818 
1819   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1820   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1821                              MachineMemOperand::MODereferenceable |
1822                                  MachineMemOperand::MOInvariant);
1823 
1824   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1825   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1826 }
1827 
1828 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1829                                               const SDLoc &SL, SDValue Chain,
1830                                               const ISD::InputArg &Arg) const {
1831   MachineFunction &MF = DAG.getMachineFunction();
1832   MachineFrameInfo &MFI = MF.getFrameInfo();
1833 
1834   if (Arg.Flags.isByVal()) {
1835     unsigned Size = Arg.Flags.getByValSize();
1836     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1837     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1838   }
1839 
1840   unsigned ArgOffset = VA.getLocMemOffset();
1841   unsigned ArgSize = VA.getValVT().getStoreSize();
1842 
1843   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1844 
1845   // Create load nodes to retrieve arguments from the stack.
1846   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1847   SDValue ArgValue;
1848 
1849   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1850   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1851   MVT MemVT = VA.getValVT();
1852 
1853   switch (VA.getLocInfo()) {
1854   default:
1855     break;
1856   case CCValAssign::BCvt:
1857     MemVT = VA.getLocVT();
1858     break;
1859   case CCValAssign::SExt:
1860     ExtType = ISD::SEXTLOAD;
1861     break;
1862   case CCValAssign::ZExt:
1863     ExtType = ISD::ZEXTLOAD;
1864     break;
1865   case CCValAssign::AExt:
1866     ExtType = ISD::EXTLOAD;
1867     break;
1868   }
1869 
1870   ArgValue = DAG.getExtLoad(
1871     ExtType, SL, VA.getLocVT(), Chain, FIN,
1872     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1873     MemVT);
1874   return ArgValue;
1875 }
1876 
1877 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1878   const SIMachineFunctionInfo &MFI,
1879   EVT VT,
1880   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1881   const ArgDescriptor *Reg;
1882   const TargetRegisterClass *RC;
1883   LLT Ty;
1884 
1885   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1886   if (!Reg) {
1887     if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) {
1888       // It's possible for a kernarg intrinsic call to appear in a kernel with
1889       // no allocated segment, in which case we do not add the user sgpr
1890       // argument, so just return null.
1891       return DAG.getConstant(0, SDLoc(), VT);
1892     }
1893 
1894     // It's undefined behavior if a function marked with the amdgpu-no-*
1895     // attributes uses the corresponding intrinsic.
1896     return DAG.getUNDEF(VT);
1897   }
1898 
1899   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1900 }
1901 
1902 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1903                                CallingConv::ID CallConv,
1904                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1905                                FunctionType *FType,
1906                                SIMachineFunctionInfo *Info) {
1907   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1908     const ISD::InputArg *Arg = &Ins[I];
1909 
1910     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1911            "vector type argument should have been split");
1912 
1913     // First check if it's a PS input addr.
1914     if (CallConv == CallingConv::AMDGPU_PS &&
1915         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1916       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1917 
1918       // Inconveniently only the first part of the split is marked as isSplit,
1919       // so skip to the end. We only want to increment PSInputNum once for the
1920       // entire split argument.
1921       if (Arg->Flags.isSplit()) {
1922         while (!Arg->Flags.isSplitEnd()) {
1923           assert((!Arg->VT.isVector() ||
1924                   Arg->VT.getScalarSizeInBits() == 16) &&
1925                  "unexpected vector split in ps argument type");
1926           if (!SkipArg)
1927             Splits.push_back(*Arg);
1928           Arg = &Ins[++I];
1929         }
1930       }
1931 
1932       if (SkipArg) {
1933         // We can safely skip PS inputs.
1934         Skipped.set(Arg->getOrigArgIndex());
1935         ++PSInputNum;
1936         continue;
1937       }
1938 
1939       Info->markPSInputAllocated(PSInputNum);
1940       if (Arg->Used)
1941         Info->markPSInputEnabled(PSInputNum);
1942 
1943       ++PSInputNum;
1944     }
1945 
1946     Splits.push_back(*Arg);
1947   }
1948 }
1949 
1950 // Allocate special inputs passed in VGPRs.
1951 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1952                                                       MachineFunction &MF,
1953                                                       const SIRegisterInfo &TRI,
1954                                                       SIMachineFunctionInfo &Info) const {
1955   const LLT S32 = LLT::scalar(32);
1956   MachineRegisterInfo &MRI = MF.getRegInfo();
1957 
1958   if (Info.hasWorkItemIDX()) {
1959     Register Reg = AMDGPU::VGPR0;
1960     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1961 
1962     CCInfo.AllocateReg(Reg);
1963     unsigned Mask = (Subtarget->hasPackedTID() &&
1964                      Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
1965     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1966   }
1967 
1968   if (Info.hasWorkItemIDY()) {
1969     assert(Info.hasWorkItemIDX());
1970     if (Subtarget->hasPackedTID()) {
1971       Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1972                                                         0x3ff << 10));
1973     } else {
1974       unsigned Reg = AMDGPU::VGPR1;
1975       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1976 
1977       CCInfo.AllocateReg(Reg);
1978       Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1979     }
1980   }
1981 
1982   if (Info.hasWorkItemIDZ()) {
1983     assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
1984     if (Subtarget->hasPackedTID()) {
1985       Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1986                                                         0x3ff << 20));
1987     } else {
1988       unsigned Reg = AMDGPU::VGPR2;
1989       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1990 
1991       CCInfo.AllocateReg(Reg);
1992       Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1993     }
1994   }
1995 }
1996 
1997 // Try to allocate a VGPR at the end of the argument list, or if no argument
1998 // VGPRs are left allocating a stack slot.
1999 // If \p Mask is is given it indicates bitfield position in the register.
2000 // If \p Arg is given use it with new ]p Mask instead of allocating new.
2001 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
2002                                          ArgDescriptor Arg = ArgDescriptor()) {
2003   if (Arg.isSet())
2004     return ArgDescriptor::createArg(Arg, Mask);
2005 
2006   ArrayRef<MCPhysReg> ArgVGPRs
2007     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
2008   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
2009   if (RegIdx == ArgVGPRs.size()) {
2010     // Spill to stack required.
2011     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
2012 
2013     return ArgDescriptor::createStack(Offset, Mask);
2014   }
2015 
2016   unsigned Reg = ArgVGPRs[RegIdx];
2017   Reg = CCInfo.AllocateReg(Reg);
2018   assert(Reg != AMDGPU::NoRegister);
2019 
2020   MachineFunction &MF = CCInfo.getMachineFunction();
2021   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
2022   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
2023   return ArgDescriptor::createRegister(Reg, Mask);
2024 }
2025 
2026 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
2027                                              const TargetRegisterClass *RC,
2028                                              unsigned NumArgRegs) {
2029   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
2030   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
2031   if (RegIdx == ArgSGPRs.size())
2032     report_fatal_error("ran out of SGPRs for arguments");
2033 
2034   unsigned Reg = ArgSGPRs[RegIdx];
2035   Reg = CCInfo.AllocateReg(Reg);
2036   assert(Reg != AMDGPU::NoRegister);
2037 
2038   MachineFunction &MF = CCInfo.getMachineFunction();
2039   MF.addLiveIn(Reg, RC);
2040   return ArgDescriptor::createRegister(Reg);
2041 }
2042 
2043 // If this has a fixed position, we still should allocate the register in the
2044 // CCInfo state. Technically we could get away with this for values passed
2045 // outside of the normal argument range.
2046 static void allocateFixedSGPRInputImpl(CCState &CCInfo,
2047                                        const TargetRegisterClass *RC,
2048                                        MCRegister Reg) {
2049   Reg = CCInfo.AllocateReg(Reg);
2050   assert(Reg != AMDGPU::NoRegister);
2051   MachineFunction &MF = CCInfo.getMachineFunction();
2052   MF.addLiveIn(Reg, RC);
2053 }
2054 
2055 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
2056   if (Arg) {
2057     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
2058                                Arg.getRegister());
2059   } else
2060     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
2061 }
2062 
2063 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
2064   if (Arg) {
2065     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
2066                                Arg.getRegister());
2067   } else
2068     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
2069 }
2070 
2071 /// Allocate implicit function VGPR arguments at the end of allocated user
2072 /// arguments.
2073 void SITargetLowering::allocateSpecialInputVGPRs(
2074   CCState &CCInfo, MachineFunction &MF,
2075   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2076   const unsigned Mask = 0x3ff;
2077   ArgDescriptor Arg;
2078 
2079   if (Info.hasWorkItemIDX()) {
2080     Arg = allocateVGPR32Input(CCInfo, Mask);
2081     Info.setWorkItemIDX(Arg);
2082   }
2083 
2084   if (Info.hasWorkItemIDY()) {
2085     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
2086     Info.setWorkItemIDY(Arg);
2087   }
2088 
2089   if (Info.hasWorkItemIDZ())
2090     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
2091 }
2092 
2093 /// Allocate implicit function VGPR arguments in fixed registers.
2094 void SITargetLowering::allocateSpecialInputVGPRsFixed(
2095   CCState &CCInfo, MachineFunction &MF,
2096   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2097   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
2098   if (!Reg)
2099     report_fatal_error("failed to allocated VGPR for implicit arguments");
2100 
2101   const unsigned Mask = 0x3ff;
2102   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2103   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
2104   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
2105 }
2106 
2107 void SITargetLowering::allocateSpecialInputSGPRs(
2108   CCState &CCInfo,
2109   MachineFunction &MF,
2110   const SIRegisterInfo &TRI,
2111   SIMachineFunctionInfo &Info) const {
2112   auto &ArgInfo = Info.getArgInfo();
2113 
2114   // TODO: Unify handling with private memory pointers.
2115   if (Info.hasDispatchPtr())
2116     allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
2117 
2118   if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5)
2119     allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
2120 
2121   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
2122   // constant offset from the kernarg segment.
2123   if (Info.hasImplicitArgPtr())
2124     allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
2125 
2126   if (Info.hasDispatchID())
2127     allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2128 
2129   // flat_scratch_init is not applicable for non-kernel functions.
2130 
2131   if (Info.hasWorkGroupIDX())
2132     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2133 
2134   if (Info.hasWorkGroupIDY())
2135     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2136 
2137   if (Info.hasWorkGroupIDZ())
2138     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2139 }
2140 
2141 // Allocate special inputs passed in user SGPRs.
2142 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2143                                             MachineFunction &MF,
2144                                             const SIRegisterInfo &TRI,
2145                                             SIMachineFunctionInfo &Info) const {
2146   if (Info.hasImplicitBufferPtr()) {
2147     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2148     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2149     CCInfo.AllocateReg(ImplicitBufferPtrReg);
2150   }
2151 
2152   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2153   if (Info.hasPrivateSegmentBuffer()) {
2154     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2155     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2156     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2157   }
2158 
2159   if (Info.hasDispatchPtr()) {
2160     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2161     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2162     CCInfo.AllocateReg(DispatchPtrReg);
2163   }
2164 
2165   if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) {
2166     Register QueuePtrReg = Info.addQueuePtr(TRI);
2167     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2168     CCInfo.AllocateReg(QueuePtrReg);
2169   }
2170 
2171   if (Info.hasKernargSegmentPtr()) {
2172     MachineRegisterInfo &MRI = MF.getRegInfo();
2173     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2174     CCInfo.AllocateReg(InputPtrReg);
2175 
2176     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2177     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2178   }
2179 
2180   if (Info.hasDispatchID()) {
2181     Register DispatchIDReg = Info.addDispatchID(TRI);
2182     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2183     CCInfo.AllocateReg(DispatchIDReg);
2184   }
2185 
2186   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2187     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2188     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2189     CCInfo.AllocateReg(FlatScratchInitReg);
2190   }
2191 
2192   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2193   // these from the dispatch pointer.
2194 }
2195 
2196 // Allocate special input registers that are initialized per-wave.
2197 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2198                                            MachineFunction &MF,
2199                                            SIMachineFunctionInfo &Info,
2200                                            CallingConv::ID CallConv,
2201                                            bool IsShader) const {
2202   if (Info.hasWorkGroupIDX()) {
2203     Register Reg = Info.addWorkGroupIDX();
2204     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2205     CCInfo.AllocateReg(Reg);
2206   }
2207 
2208   if (Info.hasWorkGroupIDY()) {
2209     Register Reg = Info.addWorkGroupIDY();
2210     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2211     CCInfo.AllocateReg(Reg);
2212   }
2213 
2214   if (Info.hasWorkGroupIDZ()) {
2215     Register Reg = Info.addWorkGroupIDZ();
2216     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2217     CCInfo.AllocateReg(Reg);
2218   }
2219 
2220   if (Info.hasWorkGroupInfo()) {
2221     Register Reg = Info.addWorkGroupInfo();
2222     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2223     CCInfo.AllocateReg(Reg);
2224   }
2225 
2226   if (Info.hasPrivateSegmentWaveByteOffset()) {
2227     // Scratch wave offset passed in system SGPR.
2228     unsigned PrivateSegmentWaveByteOffsetReg;
2229 
2230     if (IsShader) {
2231       PrivateSegmentWaveByteOffsetReg =
2232         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2233 
2234       // This is true if the scratch wave byte offset doesn't have a fixed
2235       // location.
2236       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2237         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2238         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2239       }
2240     } else
2241       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2242 
2243     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2244     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2245   }
2246 }
2247 
2248 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2249                                      MachineFunction &MF,
2250                                      const SIRegisterInfo &TRI,
2251                                      SIMachineFunctionInfo &Info) {
2252   // Now that we've figured out where the scratch register inputs are, see if
2253   // should reserve the arguments and use them directly.
2254   MachineFrameInfo &MFI = MF.getFrameInfo();
2255   bool HasStackObjects = MFI.hasStackObjects();
2256   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2257 
2258   // Record that we know we have non-spill stack objects so we don't need to
2259   // check all stack objects later.
2260   if (HasStackObjects)
2261     Info.setHasNonSpillStackObjects(true);
2262 
2263   // Everything live out of a block is spilled with fast regalloc, so it's
2264   // almost certain that spilling will be required.
2265   if (TM.getOptLevel() == CodeGenOpt::None)
2266     HasStackObjects = true;
2267 
2268   // For now assume stack access is needed in any callee functions, so we need
2269   // the scratch registers to pass in.
2270   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2271 
2272   if (!ST.enableFlatScratch()) {
2273     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2274       // If we have stack objects, we unquestionably need the private buffer
2275       // resource. For the Code Object V2 ABI, this will be the first 4 user
2276       // SGPR inputs. We can reserve those and use them directly.
2277 
2278       Register PrivateSegmentBufferReg =
2279           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2280       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2281     } else {
2282       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2283       // We tentatively reserve the last registers (skipping the last registers
2284       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2285       // we'll replace these with the ones immediately after those which were
2286       // really allocated. In the prologue copies will be inserted from the
2287       // argument to these reserved registers.
2288 
2289       // Without HSA, relocations are used for the scratch pointer and the
2290       // buffer resource setup is always inserted in the prologue. Scratch wave
2291       // offset is still in an input SGPR.
2292       Info.setScratchRSrcReg(ReservedBufferReg);
2293     }
2294   }
2295 
2296   MachineRegisterInfo &MRI = MF.getRegInfo();
2297 
2298   // For entry functions we have to set up the stack pointer if we use it,
2299   // whereas non-entry functions get this "for free". This means there is no
2300   // intrinsic advantage to using S32 over S34 in cases where we do not have
2301   // calls but do need a frame pointer (i.e. if we are requested to have one
2302   // because frame pointer elimination is disabled). To keep things simple we
2303   // only ever use S32 as the call ABI stack pointer, and so using it does not
2304   // imply we need a separate frame pointer.
2305   //
2306   // Try to use s32 as the SP, but move it if it would interfere with input
2307   // arguments. This won't work with calls though.
2308   //
2309   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2310   // registers.
2311   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2312     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2313   } else {
2314     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2315 
2316     if (MFI.hasCalls())
2317       report_fatal_error("call in graphics shader with too many input SGPRs");
2318 
2319     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2320       if (!MRI.isLiveIn(Reg)) {
2321         Info.setStackPtrOffsetReg(Reg);
2322         break;
2323       }
2324     }
2325 
2326     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2327       report_fatal_error("failed to find register for SP");
2328   }
2329 
2330   // hasFP should be accurate for entry functions even before the frame is
2331   // finalized, because it does not rely on the known stack size, only
2332   // properties like whether variable sized objects are present.
2333   if (ST.getFrameLowering()->hasFP(MF)) {
2334     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2335   }
2336 }
2337 
2338 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2339   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2340   return !Info->isEntryFunction();
2341 }
2342 
2343 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2344 
2345 }
2346 
2347 void SITargetLowering::insertCopiesSplitCSR(
2348   MachineBasicBlock *Entry,
2349   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2350   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2351 
2352   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2353   if (!IStart)
2354     return;
2355 
2356   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2357   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2358   MachineBasicBlock::iterator MBBI = Entry->begin();
2359   for (const MCPhysReg *I = IStart; *I; ++I) {
2360     const TargetRegisterClass *RC = nullptr;
2361     if (AMDGPU::SReg_64RegClass.contains(*I))
2362       RC = &AMDGPU::SGPR_64RegClass;
2363     else if (AMDGPU::SReg_32RegClass.contains(*I))
2364       RC = &AMDGPU::SGPR_32RegClass;
2365     else
2366       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2367 
2368     Register NewVR = MRI->createVirtualRegister(RC);
2369     // Create copy from CSR to a virtual register.
2370     Entry->addLiveIn(*I);
2371     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2372       .addReg(*I);
2373 
2374     // Insert the copy-back instructions right before the terminator.
2375     for (auto *Exit : Exits)
2376       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2377               TII->get(TargetOpcode::COPY), *I)
2378         .addReg(NewVR);
2379   }
2380 }
2381 
2382 SDValue SITargetLowering::LowerFormalArguments(
2383     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2384     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2385     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2386   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2387 
2388   MachineFunction &MF = DAG.getMachineFunction();
2389   const Function &Fn = MF.getFunction();
2390   FunctionType *FType = MF.getFunction().getFunctionType();
2391   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2392 
2393   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2394     DiagnosticInfoUnsupported NoGraphicsHSA(
2395         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2396     DAG.getContext()->diagnose(NoGraphicsHSA);
2397     return DAG.getEntryNode();
2398   }
2399 
2400   Info->allocateModuleLDSGlobal(Fn.getParent());
2401 
2402   SmallVector<ISD::InputArg, 16> Splits;
2403   SmallVector<CCValAssign, 16> ArgLocs;
2404   BitVector Skipped(Ins.size());
2405   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2406                  *DAG.getContext());
2407 
2408   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2409   bool IsKernel = AMDGPU::isKernel(CallConv);
2410   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2411 
2412   if (IsGraphics) {
2413     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2414            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2415            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2416            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2417            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2418            !Info->hasWorkItemIDZ());
2419   }
2420 
2421   if (CallConv == CallingConv::AMDGPU_PS) {
2422     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2423 
2424     // At least one interpolation mode must be enabled or else the GPU will
2425     // hang.
2426     //
2427     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2428     // set PSInputAddr, the user wants to enable some bits after the compilation
2429     // based on run-time states. Since we can't know what the final PSInputEna
2430     // will look like, so we shouldn't do anything here and the user should take
2431     // responsibility for the correct programming.
2432     //
2433     // Otherwise, the following restrictions apply:
2434     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2435     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2436     //   enabled too.
2437     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2438         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2439       CCInfo.AllocateReg(AMDGPU::VGPR0);
2440       CCInfo.AllocateReg(AMDGPU::VGPR1);
2441       Info->markPSInputAllocated(0);
2442       Info->markPSInputEnabled(0);
2443     }
2444     if (Subtarget->isAmdPalOS()) {
2445       // For isAmdPalOS, the user does not enable some bits after compilation
2446       // based on run-time states; the register values being generated here are
2447       // the final ones set in hardware. Therefore we need to apply the
2448       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2449       // a bit is set in PSInputAddr but not PSInputEnable is where the
2450       // frontend set up an input arg for a particular interpolation mode, but
2451       // nothing uses that input arg. Really we should have an earlier pass
2452       // that removes such an arg.)
2453       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2454       if ((PsInputBits & 0x7F) == 0 ||
2455           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2456         Info->markPSInputEnabled(
2457             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2458     }
2459   } else if (IsKernel) {
2460     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2461   } else {
2462     Splits.append(Ins.begin(), Ins.end());
2463   }
2464 
2465   if (IsEntryFunc) {
2466     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2467     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2468   } else if (!IsGraphics) {
2469     // For the fixed ABI, pass workitem IDs in the last argument register.
2470     allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2471   }
2472 
2473   if (IsKernel) {
2474     analyzeFormalArgumentsCompute(CCInfo, Ins);
2475   } else {
2476     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2477     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2478   }
2479 
2480   SmallVector<SDValue, 16> Chains;
2481 
2482   // FIXME: This is the minimum kernel argument alignment. We should improve
2483   // this to the maximum alignment of the arguments.
2484   //
2485   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2486   // kern arg offset.
2487   const Align KernelArgBaseAlign = Align(16);
2488 
2489   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2490     const ISD::InputArg &Arg = Ins[i];
2491     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2492       InVals.push_back(DAG.getUNDEF(Arg.VT));
2493       continue;
2494     }
2495 
2496     CCValAssign &VA = ArgLocs[ArgIdx++];
2497     MVT VT = VA.getLocVT();
2498 
2499     if (IsEntryFunc && VA.isMemLoc()) {
2500       VT = Ins[i].VT;
2501       EVT MemVT = VA.getLocVT();
2502 
2503       const uint64_t Offset = VA.getLocMemOffset();
2504       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2505 
2506       if (Arg.Flags.isByRef()) {
2507         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2508 
2509         const GCNTargetMachine &TM =
2510             static_cast<const GCNTargetMachine &>(getTargetMachine());
2511         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2512                                     Arg.Flags.getPointerAddrSpace())) {
2513           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2514                                      Arg.Flags.getPointerAddrSpace());
2515         }
2516 
2517         InVals.push_back(Ptr);
2518         continue;
2519       }
2520 
2521       SDValue Arg = lowerKernargMemParameter(
2522         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2523       Chains.push_back(Arg.getValue(1));
2524 
2525       auto *ParamTy =
2526         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2527       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2528           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2529                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2530         // On SI local pointers are just offsets into LDS, so they are always
2531         // less than 16-bits.  On CI and newer they could potentially be
2532         // real pointers, so we can't guarantee their size.
2533         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2534                           DAG.getValueType(MVT::i16));
2535       }
2536 
2537       InVals.push_back(Arg);
2538       continue;
2539     } else if (!IsEntryFunc && VA.isMemLoc()) {
2540       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2541       InVals.push_back(Val);
2542       if (!Arg.Flags.isByVal())
2543         Chains.push_back(Val.getValue(1));
2544       continue;
2545     }
2546 
2547     assert(VA.isRegLoc() && "Parameter must be in a register!");
2548 
2549     Register Reg = VA.getLocReg();
2550     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2551     EVT ValVT = VA.getValVT();
2552 
2553     Reg = MF.addLiveIn(Reg, RC);
2554     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2555 
2556     if (Arg.Flags.isSRet()) {
2557       // The return object should be reasonably addressable.
2558 
2559       // FIXME: This helps when the return is a real sret. If it is a
2560       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2561       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2562       unsigned NumBits
2563         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2564       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2565         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2566     }
2567 
2568     // If this is an 8 or 16-bit value, it is really passed promoted
2569     // to 32 bits. Insert an assert[sz]ext to capture this, then
2570     // truncate to the right size.
2571     switch (VA.getLocInfo()) {
2572     case CCValAssign::Full:
2573       break;
2574     case CCValAssign::BCvt:
2575       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2576       break;
2577     case CCValAssign::SExt:
2578       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2579                         DAG.getValueType(ValVT));
2580       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2581       break;
2582     case CCValAssign::ZExt:
2583       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2584                         DAG.getValueType(ValVT));
2585       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2586       break;
2587     case CCValAssign::AExt:
2588       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2589       break;
2590     default:
2591       llvm_unreachable("Unknown loc info!");
2592     }
2593 
2594     InVals.push_back(Val);
2595   }
2596 
2597   // Start adding system SGPRs.
2598   if (IsEntryFunc) {
2599     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2600   } else {
2601     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2602     if (!IsGraphics)
2603       allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2604   }
2605 
2606   auto &ArgUsageInfo =
2607     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2608   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2609 
2610   unsigned StackArgSize = CCInfo.getNextStackOffset();
2611   Info->setBytesInStackArgArea(StackArgSize);
2612 
2613   return Chains.empty() ? Chain :
2614     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2615 }
2616 
2617 // TODO: If return values can't fit in registers, we should return as many as
2618 // possible in registers before passing on stack.
2619 bool SITargetLowering::CanLowerReturn(
2620   CallingConv::ID CallConv,
2621   MachineFunction &MF, bool IsVarArg,
2622   const SmallVectorImpl<ISD::OutputArg> &Outs,
2623   LLVMContext &Context) const {
2624   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2625   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2626   // for shaders. Vector types should be explicitly handled by CC.
2627   if (AMDGPU::isEntryFunctionCC(CallConv))
2628     return true;
2629 
2630   SmallVector<CCValAssign, 16> RVLocs;
2631   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2632   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2633 }
2634 
2635 SDValue
2636 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2637                               bool isVarArg,
2638                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2639                               const SmallVectorImpl<SDValue> &OutVals,
2640                               const SDLoc &DL, SelectionDAG &DAG) const {
2641   MachineFunction &MF = DAG.getMachineFunction();
2642   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2643 
2644   if (AMDGPU::isKernel(CallConv)) {
2645     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2646                                              OutVals, DL, DAG);
2647   }
2648 
2649   bool IsShader = AMDGPU::isShader(CallConv);
2650 
2651   Info->setIfReturnsVoid(Outs.empty());
2652   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2653 
2654   // CCValAssign - represent the assignment of the return value to a location.
2655   SmallVector<CCValAssign, 48> RVLocs;
2656   SmallVector<ISD::OutputArg, 48> Splits;
2657 
2658   // CCState - Info about the registers and stack slots.
2659   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2660                  *DAG.getContext());
2661 
2662   // Analyze outgoing return values.
2663   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2664 
2665   SDValue Flag;
2666   SmallVector<SDValue, 48> RetOps;
2667   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2668 
2669   // Copy the result values into the output registers.
2670   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2671        ++I, ++RealRVLocIdx) {
2672     CCValAssign &VA = RVLocs[I];
2673     assert(VA.isRegLoc() && "Can only return in registers!");
2674     // TODO: Partially return in registers if return values don't fit.
2675     SDValue Arg = OutVals[RealRVLocIdx];
2676 
2677     // Copied from other backends.
2678     switch (VA.getLocInfo()) {
2679     case CCValAssign::Full:
2680       break;
2681     case CCValAssign::BCvt:
2682       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2683       break;
2684     case CCValAssign::SExt:
2685       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2686       break;
2687     case CCValAssign::ZExt:
2688       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2689       break;
2690     case CCValAssign::AExt:
2691       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2692       break;
2693     default:
2694       llvm_unreachable("Unknown loc info!");
2695     }
2696 
2697     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2698     Flag = Chain.getValue(1);
2699     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2700   }
2701 
2702   // FIXME: Does sret work properly?
2703   if (!Info->isEntryFunction()) {
2704     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2705     const MCPhysReg *I =
2706       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2707     if (I) {
2708       for (; *I; ++I) {
2709         if (AMDGPU::SReg_64RegClass.contains(*I))
2710           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2711         else if (AMDGPU::SReg_32RegClass.contains(*I))
2712           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2713         else
2714           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2715       }
2716     }
2717   }
2718 
2719   // Update chain and glue.
2720   RetOps[0] = Chain;
2721   if (Flag.getNode())
2722     RetOps.push_back(Flag);
2723 
2724   unsigned Opc = AMDGPUISD::ENDPGM;
2725   if (!IsWaveEnd)
2726     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2727   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2728 }
2729 
2730 SDValue SITargetLowering::LowerCallResult(
2731     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2732     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2733     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2734     SDValue ThisVal) const {
2735   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2736 
2737   // Assign locations to each value returned by this call.
2738   SmallVector<CCValAssign, 16> RVLocs;
2739   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2740                  *DAG.getContext());
2741   CCInfo.AnalyzeCallResult(Ins, RetCC);
2742 
2743   // Copy all of the result registers out of their specified physreg.
2744   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2745     CCValAssign VA = RVLocs[i];
2746     SDValue Val;
2747 
2748     if (VA.isRegLoc()) {
2749       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2750       Chain = Val.getValue(1);
2751       InFlag = Val.getValue(2);
2752     } else if (VA.isMemLoc()) {
2753       report_fatal_error("TODO: return values in memory");
2754     } else
2755       llvm_unreachable("unknown argument location type");
2756 
2757     switch (VA.getLocInfo()) {
2758     case CCValAssign::Full:
2759       break;
2760     case CCValAssign::BCvt:
2761       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2762       break;
2763     case CCValAssign::ZExt:
2764       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2765                         DAG.getValueType(VA.getValVT()));
2766       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2767       break;
2768     case CCValAssign::SExt:
2769       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2770                         DAG.getValueType(VA.getValVT()));
2771       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2772       break;
2773     case CCValAssign::AExt:
2774       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2775       break;
2776     default:
2777       llvm_unreachable("Unknown loc info!");
2778     }
2779 
2780     InVals.push_back(Val);
2781   }
2782 
2783   return Chain;
2784 }
2785 
2786 // Add code to pass special inputs required depending on used features separate
2787 // from the explicit user arguments present in the IR.
2788 void SITargetLowering::passSpecialInputs(
2789     CallLoweringInfo &CLI,
2790     CCState &CCInfo,
2791     const SIMachineFunctionInfo &Info,
2792     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2793     SmallVectorImpl<SDValue> &MemOpChains,
2794     SDValue Chain) const {
2795   // If we don't have a call site, this was a call inserted by
2796   // legalization. These can never use special inputs.
2797   if (!CLI.CB)
2798     return;
2799 
2800   SelectionDAG &DAG = CLI.DAG;
2801   const SDLoc &DL = CLI.DL;
2802   const Function &F = DAG.getMachineFunction().getFunction();
2803 
2804   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2805   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2806 
2807   const AMDGPUFunctionArgInfo *CalleeArgInfo
2808     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2809   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2810     auto &ArgUsageInfo =
2811       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2812     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2813   }
2814 
2815   // TODO: Unify with private memory register handling. This is complicated by
2816   // the fact that at least in kernels, the input argument is not necessarily
2817   // in the same location as the input.
2818   static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
2819                              StringLiteral> ImplicitAttrs[] = {
2820     {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"},
2821     {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" },
2822     {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"},
2823     {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"},
2824     {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"},
2825     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"},
2826     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"}
2827   };
2828 
2829   for (auto Attr : ImplicitAttrs) {
2830     const ArgDescriptor *OutgoingArg;
2831     const TargetRegisterClass *ArgRC;
2832     LLT ArgTy;
2833 
2834     AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first;
2835 
2836     // If the callee does not use the attribute value, skip copying the value.
2837     if (CLI.CB->hasFnAttr(Attr.second))
2838       continue;
2839 
2840     std::tie(OutgoingArg, ArgRC, ArgTy) =
2841         CalleeArgInfo->getPreloadedValue(InputID);
2842     if (!OutgoingArg)
2843       continue;
2844 
2845     const ArgDescriptor *IncomingArg;
2846     const TargetRegisterClass *IncomingArgRC;
2847     LLT Ty;
2848     std::tie(IncomingArg, IncomingArgRC, Ty) =
2849         CallerArgInfo.getPreloadedValue(InputID);
2850     assert(IncomingArgRC == ArgRC);
2851 
2852     // All special arguments are ints for now.
2853     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2854     SDValue InputReg;
2855 
2856     if (IncomingArg) {
2857       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2858     } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
2859       // The implicit arg ptr is special because it doesn't have a corresponding
2860       // input for kernels, and is computed from the kernarg segment pointer.
2861       InputReg = getImplicitArgPtr(DAG, DL);
2862     } else {
2863       // We may have proven the input wasn't needed, although the ABI is
2864       // requiring it. We just need to allocate the register appropriately.
2865       InputReg = DAG.getUNDEF(ArgVT);
2866     }
2867 
2868     if (OutgoingArg->isRegister()) {
2869       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2870       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2871         report_fatal_error("failed to allocate implicit input argument");
2872     } else {
2873       unsigned SpecialArgOffset =
2874           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2875       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2876                                               SpecialArgOffset);
2877       MemOpChains.push_back(ArgStore);
2878     }
2879   }
2880 
2881   // Pack workitem IDs into a single register or pass it as is if already
2882   // packed.
2883   const ArgDescriptor *OutgoingArg;
2884   const TargetRegisterClass *ArgRC;
2885   LLT Ty;
2886 
2887   std::tie(OutgoingArg, ArgRC, Ty) =
2888       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2889   if (!OutgoingArg)
2890     std::tie(OutgoingArg, ArgRC, Ty) =
2891         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2892   if (!OutgoingArg)
2893     std::tie(OutgoingArg, ArgRC, Ty) =
2894         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2895   if (!OutgoingArg)
2896     return;
2897 
2898   const ArgDescriptor *IncomingArgX = std::get<0>(
2899       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2900   const ArgDescriptor *IncomingArgY = std::get<0>(
2901       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2902   const ArgDescriptor *IncomingArgZ = std::get<0>(
2903       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2904 
2905   SDValue InputReg;
2906   SDLoc SL;
2907 
2908   const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
2909   const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
2910   const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
2911 
2912   // If incoming ids are not packed we need to pack them.
2913   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
2914       NeedWorkItemIDX) {
2915     if (Subtarget->getMaxWorkitemID(F, 0) != 0) {
2916       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2917     } else {
2918       InputReg = DAG.getConstant(0, DL, MVT::i32);
2919     }
2920   }
2921 
2922   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
2923       NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) {
2924     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2925     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2926                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2927     InputReg = InputReg.getNode() ?
2928                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2929   }
2930 
2931   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
2932       NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) {
2933     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2934     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2935                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2936     InputReg = InputReg.getNode() ?
2937                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2938   }
2939 
2940   if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
2941     if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) {
2942       // We're in a situation where the outgoing function requires the workitem
2943       // ID, but the calling function does not have it (e.g a graphics function
2944       // calling a C calling convention function). This is illegal, but we need
2945       // to produce something.
2946       InputReg = DAG.getUNDEF(MVT::i32);
2947     } else {
2948       // Workitem ids are already packed, any of present incoming arguments
2949       // will carry all required fields.
2950       ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2951         IncomingArgX ? *IncomingArgX :
2952         IncomingArgY ? *IncomingArgY :
2953         *IncomingArgZ, ~0u);
2954       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2955     }
2956   }
2957 
2958   if (OutgoingArg->isRegister()) {
2959     if (InputReg)
2960       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2961 
2962     CCInfo.AllocateReg(OutgoingArg->getRegister());
2963   } else {
2964     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2965     if (InputReg) {
2966       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2967                                               SpecialArgOffset);
2968       MemOpChains.push_back(ArgStore);
2969     }
2970   }
2971 }
2972 
2973 static bool canGuaranteeTCO(CallingConv::ID CC) {
2974   return CC == CallingConv::Fast;
2975 }
2976 
2977 /// Return true if we might ever do TCO for calls with this calling convention.
2978 static bool mayTailCallThisCC(CallingConv::ID CC) {
2979   switch (CC) {
2980   case CallingConv::C:
2981   case CallingConv::AMDGPU_Gfx:
2982     return true;
2983   default:
2984     return canGuaranteeTCO(CC);
2985   }
2986 }
2987 
2988 bool SITargetLowering::isEligibleForTailCallOptimization(
2989     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2990     const SmallVectorImpl<ISD::OutputArg> &Outs,
2991     const SmallVectorImpl<SDValue> &OutVals,
2992     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2993   if (!mayTailCallThisCC(CalleeCC))
2994     return false;
2995 
2996   // For a divergent call target, we need to do a waterfall loop over the
2997   // possible callees which precludes us from using a simple jump.
2998   if (Callee->isDivergent())
2999     return false;
3000 
3001   MachineFunction &MF = DAG.getMachineFunction();
3002   const Function &CallerF = MF.getFunction();
3003   CallingConv::ID CallerCC = CallerF.getCallingConv();
3004   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3005   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3006 
3007   // Kernels aren't callable, and don't have a live in return address so it
3008   // doesn't make sense to do a tail call with entry functions.
3009   if (!CallerPreserved)
3010     return false;
3011 
3012   bool CCMatch = CallerCC == CalleeCC;
3013 
3014   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3015     if (canGuaranteeTCO(CalleeCC) && CCMatch)
3016       return true;
3017     return false;
3018   }
3019 
3020   // TODO: Can we handle var args?
3021   if (IsVarArg)
3022     return false;
3023 
3024   for (const Argument &Arg : CallerF.args()) {
3025     if (Arg.hasByValAttr())
3026       return false;
3027   }
3028 
3029   LLVMContext &Ctx = *DAG.getContext();
3030 
3031   // Check that the call results are passed in the same way.
3032   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
3033                                   CCAssignFnForCall(CalleeCC, IsVarArg),
3034                                   CCAssignFnForCall(CallerCC, IsVarArg)))
3035     return false;
3036 
3037   // The callee has to preserve all registers the caller needs to preserve.
3038   if (!CCMatch) {
3039     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3040     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3041       return false;
3042   }
3043 
3044   // Nothing more to check if the callee is taking no arguments.
3045   if (Outs.empty())
3046     return true;
3047 
3048   SmallVector<CCValAssign, 16> ArgLocs;
3049   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
3050 
3051   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
3052 
3053   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
3054   // If the stack arguments for this call do not fit into our own save area then
3055   // the call cannot be made tail.
3056   // TODO: Is this really necessary?
3057   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3058     return false;
3059 
3060   const MachineRegisterInfo &MRI = MF.getRegInfo();
3061   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
3062 }
3063 
3064 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3065   if (!CI->isTailCall())
3066     return false;
3067 
3068   const Function *ParentFn = CI->getParent()->getParent();
3069   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
3070     return false;
3071   return true;
3072 }
3073 
3074 // The wave scratch offset register is used as the global base pointer.
3075 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
3076                                     SmallVectorImpl<SDValue> &InVals) const {
3077   SelectionDAG &DAG = CLI.DAG;
3078   const SDLoc &DL = CLI.DL;
3079   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3080   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3081   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3082   SDValue Chain = CLI.Chain;
3083   SDValue Callee = CLI.Callee;
3084   bool &IsTailCall = CLI.IsTailCall;
3085   CallingConv::ID CallConv = CLI.CallConv;
3086   bool IsVarArg = CLI.IsVarArg;
3087   bool IsSibCall = false;
3088   bool IsThisReturn = false;
3089   MachineFunction &MF = DAG.getMachineFunction();
3090 
3091   if (Callee.isUndef() || isNullConstant(Callee)) {
3092     if (!CLI.IsTailCall) {
3093       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
3094         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
3095     }
3096 
3097     return Chain;
3098   }
3099 
3100   if (IsVarArg) {
3101     return lowerUnhandledCall(CLI, InVals,
3102                               "unsupported call to variadic function ");
3103   }
3104 
3105   if (!CLI.CB)
3106     report_fatal_error("unsupported libcall legalization");
3107 
3108   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
3109     return lowerUnhandledCall(CLI, InVals,
3110                               "unsupported required tail call to function ");
3111   }
3112 
3113   if (AMDGPU::isShader(CallConv)) {
3114     // Note the issue is with the CC of the called function, not of the call
3115     // itself.
3116     return lowerUnhandledCall(CLI, InVals,
3117                               "unsupported call to a shader function ");
3118   }
3119 
3120   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
3121       CallConv != CallingConv::AMDGPU_Gfx) {
3122     // Only allow calls with specific calling conventions.
3123     return lowerUnhandledCall(CLI, InVals,
3124                               "unsupported calling convention for call from "
3125                               "graphics shader of function ");
3126   }
3127 
3128   if (IsTailCall) {
3129     IsTailCall = isEligibleForTailCallOptimization(
3130       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3131     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
3132       report_fatal_error("failed to perform tail call elimination on a call "
3133                          "site marked musttail");
3134     }
3135 
3136     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3137 
3138     // A sibling call is one where we're under the usual C ABI and not planning
3139     // to change that but can still do a tail call:
3140     if (!TailCallOpt && IsTailCall)
3141       IsSibCall = true;
3142 
3143     if (IsTailCall)
3144       ++NumTailCalls;
3145   }
3146 
3147   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3148   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3149   SmallVector<SDValue, 8> MemOpChains;
3150 
3151   // Analyze operands of the call, assigning locations to each operand.
3152   SmallVector<CCValAssign, 16> ArgLocs;
3153   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3154   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3155 
3156   if (CallConv != CallingConv::AMDGPU_Gfx) {
3157     // With a fixed ABI, allocate fixed registers before user arguments.
3158     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3159   }
3160 
3161   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3162 
3163   // Get a count of how many bytes are to be pushed on the stack.
3164   unsigned NumBytes = CCInfo.getNextStackOffset();
3165 
3166   if (IsSibCall) {
3167     // Since we're not changing the ABI to make this a tail call, the memory
3168     // operands are already available in the caller's incoming argument space.
3169     NumBytes = 0;
3170   }
3171 
3172   // FPDiff is the byte offset of the call's argument area from the callee's.
3173   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3174   // by this amount for a tail call. In a sibling call it must be 0 because the
3175   // caller will deallocate the entire stack and the callee still expects its
3176   // arguments to begin at SP+0. Completely unused for non-tail calls.
3177   int32_t FPDiff = 0;
3178   MachineFrameInfo &MFI = MF.getFrameInfo();
3179 
3180   // Adjust the stack pointer for the new arguments...
3181   // These operations are automatically eliminated by the prolog/epilog pass
3182   if (!IsSibCall) {
3183     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3184 
3185     if (!Subtarget->enableFlatScratch()) {
3186       SmallVector<SDValue, 4> CopyFromChains;
3187 
3188       // In the HSA case, this should be an identity copy.
3189       SDValue ScratchRSrcReg
3190         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3191       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3192       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3193       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3194     }
3195   }
3196 
3197   MVT PtrVT = MVT::i32;
3198 
3199   // Walk the register/memloc assignments, inserting copies/loads.
3200   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3201     CCValAssign &VA = ArgLocs[i];
3202     SDValue Arg = OutVals[i];
3203 
3204     // Promote the value if needed.
3205     switch (VA.getLocInfo()) {
3206     case CCValAssign::Full:
3207       break;
3208     case CCValAssign::BCvt:
3209       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3210       break;
3211     case CCValAssign::ZExt:
3212       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3213       break;
3214     case CCValAssign::SExt:
3215       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3216       break;
3217     case CCValAssign::AExt:
3218       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3219       break;
3220     case CCValAssign::FPExt:
3221       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3222       break;
3223     default:
3224       llvm_unreachable("Unknown loc info!");
3225     }
3226 
3227     if (VA.isRegLoc()) {
3228       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3229     } else {
3230       assert(VA.isMemLoc());
3231 
3232       SDValue DstAddr;
3233       MachinePointerInfo DstInfo;
3234 
3235       unsigned LocMemOffset = VA.getLocMemOffset();
3236       int32_t Offset = LocMemOffset;
3237 
3238       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3239       MaybeAlign Alignment;
3240 
3241       if (IsTailCall) {
3242         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3243         unsigned OpSize = Flags.isByVal() ?
3244           Flags.getByValSize() : VA.getValVT().getStoreSize();
3245 
3246         // FIXME: We can have better than the minimum byval required alignment.
3247         Alignment =
3248             Flags.isByVal()
3249                 ? Flags.getNonZeroByValAlign()
3250                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3251 
3252         Offset = Offset + FPDiff;
3253         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3254 
3255         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3256         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3257 
3258         // Make sure any stack arguments overlapping with where we're storing
3259         // are loaded before this eventual operation. Otherwise they'll be
3260         // clobbered.
3261 
3262         // FIXME: Why is this really necessary? This seems to just result in a
3263         // lot of code to copy the stack and write them back to the same
3264         // locations, which are supposed to be immutable?
3265         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3266       } else {
3267         // Stores to the argument stack area are relative to the stack pointer.
3268         SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3269                                         MVT::i32);
3270         DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3271         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3272         Alignment =
3273             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3274       }
3275 
3276       if (Outs[i].Flags.isByVal()) {
3277         SDValue SizeNode =
3278             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3279         SDValue Cpy =
3280             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3281                           Outs[i].Flags.getNonZeroByValAlign(),
3282                           /*isVol = */ false, /*AlwaysInline = */ true,
3283                           /*isTailCall = */ false, DstInfo,
3284                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3285 
3286         MemOpChains.push_back(Cpy);
3287       } else {
3288         SDValue Store =
3289             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3290         MemOpChains.push_back(Store);
3291       }
3292     }
3293   }
3294 
3295   if (!MemOpChains.empty())
3296     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3297 
3298   // Build a sequence of copy-to-reg nodes chained together with token chain
3299   // and flag operands which copy the outgoing args into the appropriate regs.
3300   SDValue InFlag;
3301   for (auto &RegToPass : RegsToPass) {
3302     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3303                              RegToPass.second, InFlag);
3304     InFlag = Chain.getValue(1);
3305   }
3306 
3307 
3308   // We don't usually want to end the call-sequence here because we would tidy
3309   // the frame up *after* the call, however in the ABI-changing tail-call case
3310   // we've carefully laid out the parameters so that when sp is reset they'll be
3311   // in the correct location.
3312   if (IsTailCall && !IsSibCall) {
3313     Chain = DAG.getCALLSEQ_END(Chain,
3314                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3315                                DAG.getTargetConstant(0, DL, MVT::i32),
3316                                InFlag, DL);
3317     InFlag = Chain.getValue(1);
3318   }
3319 
3320   std::vector<SDValue> Ops;
3321   Ops.push_back(Chain);
3322   Ops.push_back(Callee);
3323   // Add a redundant copy of the callee global which will not be legalized, as
3324   // we need direct access to the callee later.
3325   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3326     const GlobalValue *GV = GSD->getGlobal();
3327     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3328   } else {
3329     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3330   }
3331 
3332   if (IsTailCall) {
3333     // Each tail call may have to adjust the stack by a different amount, so
3334     // this information must travel along with the operation for eventual
3335     // consumption by emitEpilogue.
3336     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3337   }
3338 
3339   // Add argument registers to the end of the list so that they are known live
3340   // into the call.
3341   for (auto &RegToPass : RegsToPass) {
3342     Ops.push_back(DAG.getRegister(RegToPass.first,
3343                                   RegToPass.second.getValueType()));
3344   }
3345 
3346   // Add a register mask operand representing the call-preserved registers.
3347 
3348   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3349   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3350   assert(Mask && "Missing call preserved mask for calling convention");
3351   Ops.push_back(DAG.getRegisterMask(Mask));
3352 
3353   if (InFlag.getNode())
3354     Ops.push_back(InFlag);
3355 
3356   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3357 
3358   // If we're doing a tall call, use a TC_RETURN here rather than an
3359   // actual call instruction.
3360   if (IsTailCall) {
3361     MFI.setHasTailCall();
3362     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3363   }
3364 
3365   // Returns a chain and a flag for retval copy to use.
3366   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3367   Chain = Call.getValue(0);
3368   InFlag = Call.getValue(1);
3369 
3370   uint64_t CalleePopBytes = NumBytes;
3371   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3372                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3373                              InFlag, DL);
3374   if (!Ins.empty())
3375     InFlag = Chain.getValue(1);
3376 
3377   // Handle result values, copying them out of physregs into vregs that we
3378   // return.
3379   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3380                          InVals, IsThisReturn,
3381                          IsThisReturn ? OutVals[0] : SDValue());
3382 }
3383 
3384 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3385 // except for applying the wave size scale to the increment amount.
3386 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3387     SDValue Op, SelectionDAG &DAG) const {
3388   const MachineFunction &MF = DAG.getMachineFunction();
3389   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3390 
3391   SDLoc dl(Op);
3392   EVT VT = Op.getValueType();
3393   SDValue Tmp1 = Op;
3394   SDValue Tmp2 = Op.getValue(1);
3395   SDValue Tmp3 = Op.getOperand(2);
3396   SDValue Chain = Tmp1.getOperand(0);
3397 
3398   Register SPReg = Info->getStackPtrOffsetReg();
3399 
3400   // Chain the dynamic stack allocation so that it doesn't modify the stack
3401   // pointer when other instructions are using the stack.
3402   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3403 
3404   SDValue Size  = Tmp2.getOperand(1);
3405   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3406   Chain = SP.getValue(1);
3407   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3408   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3409   const TargetFrameLowering *TFL = ST.getFrameLowering();
3410   unsigned Opc =
3411     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3412     ISD::ADD : ISD::SUB;
3413 
3414   SDValue ScaledSize = DAG.getNode(
3415       ISD::SHL, dl, VT, Size,
3416       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3417 
3418   Align StackAlign = TFL->getStackAlign();
3419   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3420   if (Alignment && *Alignment > StackAlign) {
3421     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3422                        DAG.getConstant(-(uint64_t)Alignment->value()
3423                                            << ST.getWavefrontSizeLog2(),
3424                                        dl, VT));
3425   }
3426 
3427   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3428   Tmp2 = DAG.getCALLSEQ_END(
3429       Chain, DAG.getIntPtrConstant(0, dl, true),
3430       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3431 
3432   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3433 }
3434 
3435 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3436                                                   SelectionDAG &DAG) const {
3437   // We only handle constant sizes here to allow non-entry block, static sized
3438   // allocas. A truly dynamic value is more difficult to support because we
3439   // don't know if the size value is uniform or not. If the size isn't uniform,
3440   // we would need to do a wave reduction to get the maximum size to know how
3441   // much to increment the uniform stack pointer.
3442   SDValue Size = Op.getOperand(1);
3443   if (isa<ConstantSDNode>(Size))
3444       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3445 
3446   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3447 }
3448 
3449 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3450                                              const MachineFunction &MF) const {
3451   Register Reg = StringSwitch<Register>(RegName)
3452     .Case("m0", AMDGPU::M0)
3453     .Case("exec", AMDGPU::EXEC)
3454     .Case("exec_lo", AMDGPU::EXEC_LO)
3455     .Case("exec_hi", AMDGPU::EXEC_HI)
3456     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3457     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3458     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3459     .Default(Register());
3460 
3461   if (Reg == AMDGPU::NoRegister) {
3462     report_fatal_error(Twine("invalid register name \""
3463                              + StringRef(RegName)  + "\"."));
3464 
3465   }
3466 
3467   if (!Subtarget->hasFlatScrRegister() &&
3468        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3469     report_fatal_error(Twine("invalid register \""
3470                              + StringRef(RegName)  + "\" for subtarget."));
3471   }
3472 
3473   switch (Reg) {
3474   case AMDGPU::M0:
3475   case AMDGPU::EXEC_LO:
3476   case AMDGPU::EXEC_HI:
3477   case AMDGPU::FLAT_SCR_LO:
3478   case AMDGPU::FLAT_SCR_HI:
3479     if (VT.getSizeInBits() == 32)
3480       return Reg;
3481     break;
3482   case AMDGPU::EXEC:
3483   case AMDGPU::FLAT_SCR:
3484     if (VT.getSizeInBits() == 64)
3485       return Reg;
3486     break;
3487   default:
3488     llvm_unreachable("missing register type checking");
3489   }
3490 
3491   report_fatal_error(Twine("invalid type for register \""
3492                            + StringRef(RegName) + "\"."));
3493 }
3494 
3495 // If kill is not the last instruction, split the block so kill is always a
3496 // proper terminator.
3497 MachineBasicBlock *
3498 SITargetLowering::splitKillBlock(MachineInstr &MI,
3499                                  MachineBasicBlock *BB) const {
3500   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3501   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3502   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3503   return SplitBB;
3504 }
3505 
3506 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3507 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3508 // be the first instruction in the remainder block.
3509 //
3510 /// \returns { LoopBody, Remainder }
3511 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3512 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3513   MachineFunction *MF = MBB.getParent();
3514   MachineBasicBlock::iterator I(&MI);
3515 
3516   // To insert the loop we need to split the block. Move everything after this
3517   // point to a new block, and insert a new empty block between the two.
3518   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3519   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3520   MachineFunction::iterator MBBI(MBB);
3521   ++MBBI;
3522 
3523   MF->insert(MBBI, LoopBB);
3524   MF->insert(MBBI, RemainderBB);
3525 
3526   LoopBB->addSuccessor(LoopBB);
3527   LoopBB->addSuccessor(RemainderBB);
3528 
3529   // Move the rest of the block into a new block.
3530   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3531 
3532   if (InstInLoop) {
3533     auto Next = std::next(I);
3534 
3535     // Move instruction to loop body.
3536     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3537 
3538     // Move the rest of the block.
3539     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3540   } else {
3541     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3542   }
3543 
3544   MBB.addSuccessor(LoopBB);
3545 
3546   return std::make_pair(LoopBB, RemainderBB);
3547 }
3548 
3549 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3550 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3551   MachineBasicBlock *MBB = MI.getParent();
3552   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3553   auto I = MI.getIterator();
3554   auto E = std::next(I);
3555 
3556   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3557     .addImm(0);
3558 
3559   MIBundleBuilder Bundler(*MBB, I, E);
3560   finalizeBundle(*MBB, Bundler.begin());
3561 }
3562 
3563 MachineBasicBlock *
3564 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3565                                          MachineBasicBlock *BB) const {
3566   const DebugLoc &DL = MI.getDebugLoc();
3567 
3568   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3569 
3570   MachineBasicBlock *LoopBB;
3571   MachineBasicBlock *RemainderBB;
3572   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3573 
3574   // Apparently kill flags are only valid if the def is in the same block?
3575   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3576     Src->setIsKill(false);
3577 
3578   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3579 
3580   MachineBasicBlock::iterator I = LoopBB->end();
3581 
3582   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3583     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3584 
3585   // Clear TRAP_STS.MEM_VIOL
3586   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3587     .addImm(0)
3588     .addImm(EncodedReg);
3589 
3590   bundleInstWithWaitcnt(MI);
3591 
3592   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3593 
3594   // Load and check TRAP_STS.MEM_VIOL
3595   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3596     .addImm(EncodedReg);
3597 
3598   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3599   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3600     .addReg(Reg, RegState::Kill)
3601     .addImm(0);
3602   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3603     .addMBB(LoopBB);
3604 
3605   return RemainderBB;
3606 }
3607 
3608 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3609 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3610 // will only do one iteration. In the worst case, this will loop 64 times.
3611 //
3612 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3613 static MachineBasicBlock::iterator
3614 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3615                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3616                        const DebugLoc &DL, const MachineOperand &Idx,
3617                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3618                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3619                        Register &SGPRIdxReg) {
3620 
3621   MachineFunction *MF = OrigBB.getParent();
3622   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3623   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3624   MachineBasicBlock::iterator I = LoopBB.begin();
3625 
3626   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3627   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3628   Register NewExec = MRI.createVirtualRegister(BoolRC);
3629   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3630   Register CondReg = MRI.createVirtualRegister(BoolRC);
3631 
3632   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3633     .addReg(InitReg)
3634     .addMBB(&OrigBB)
3635     .addReg(ResultReg)
3636     .addMBB(&LoopBB);
3637 
3638   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3639     .addReg(InitSaveExecReg)
3640     .addMBB(&OrigBB)
3641     .addReg(NewExec)
3642     .addMBB(&LoopBB);
3643 
3644   // Read the next variant <- also loop target.
3645   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3646       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3647 
3648   // Compare the just read M0 value to all possible Idx values.
3649   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3650       .addReg(CurrentIdxReg)
3651       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3652 
3653   // Update EXEC, save the original EXEC value to VCC.
3654   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3655                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3656           NewExec)
3657     .addReg(CondReg, RegState::Kill);
3658 
3659   MRI.setSimpleHint(NewExec, CondReg);
3660 
3661   if (UseGPRIdxMode) {
3662     if (Offset == 0) {
3663       SGPRIdxReg = CurrentIdxReg;
3664     } else {
3665       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3666       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3667           .addReg(CurrentIdxReg, RegState::Kill)
3668           .addImm(Offset);
3669     }
3670   } else {
3671     // Move index from VCC into M0
3672     if (Offset == 0) {
3673       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3674         .addReg(CurrentIdxReg, RegState::Kill);
3675     } else {
3676       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3677         .addReg(CurrentIdxReg, RegState::Kill)
3678         .addImm(Offset);
3679     }
3680   }
3681 
3682   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3683   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3684   MachineInstr *InsertPt =
3685     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3686                                                   : AMDGPU::S_XOR_B64_term), Exec)
3687       .addReg(Exec)
3688       .addReg(NewExec);
3689 
3690   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3691   // s_cbranch_scc0?
3692 
3693   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3694   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3695     .addMBB(&LoopBB);
3696 
3697   return InsertPt->getIterator();
3698 }
3699 
3700 // This has slightly sub-optimal regalloc when the source vector is killed by
3701 // the read. The register allocator does not understand that the kill is
3702 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3703 // subregister from it, using 1 more VGPR than necessary. This was saved when
3704 // this was expanded after register allocation.
3705 static MachineBasicBlock::iterator
3706 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3707                unsigned InitResultReg, unsigned PhiReg, int Offset,
3708                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3709   MachineFunction *MF = MBB.getParent();
3710   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3711   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3712   MachineRegisterInfo &MRI = MF->getRegInfo();
3713   const DebugLoc &DL = MI.getDebugLoc();
3714   MachineBasicBlock::iterator I(&MI);
3715 
3716   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3717   Register DstReg = MI.getOperand(0).getReg();
3718   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3719   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3720   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3721   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3722 
3723   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3724 
3725   // Save the EXEC mask
3726   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3727     .addReg(Exec);
3728 
3729   MachineBasicBlock *LoopBB;
3730   MachineBasicBlock *RemainderBB;
3731   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3732 
3733   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3734 
3735   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3736                                       InitResultReg, DstReg, PhiReg, TmpExec,
3737                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3738 
3739   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3740   MachineFunction::iterator MBBI(LoopBB);
3741   ++MBBI;
3742   MF->insert(MBBI, LandingPad);
3743   LoopBB->removeSuccessor(RemainderBB);
3744   LandingPad->addSuccessor(RemainderBB);
3745   LoopBB->addSuccessor(LandingPad);
3746   MachineBasicBlock::iterator First = LandingPad->begin();
3747   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3748     .addReg(SaveExec);
3749 
3750   return InsPt;
3751 }
3752 
3753 // Returns subreg index, offset
3754 static std::pair<unsigned, int>
3755 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3756                             const TargetRegisterClass *SuperRC,
3757                             unsigned VecReg,
3758                             int Offset) {
3759   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3760 
3761   // Skip out of bounds offsets, or else we would end up using an undefined
3762   // register.
3763   if (Offset >= NumElts || Offset < 0)
3764     return std::make_pair(AMDGPU::sub0, Offset);
3765 
3766   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3767 }
3768 
3769 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3770                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3771                                  int Offset) {
3772   MachineBasicBlock *MBB = MI.getParent();
3773   const DebugLoc &DL = MI.getDebugLoc();
3774   MachineBasicBlock::iterator I(&MI);
3775 
3776   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3777 
3778   assert(Idx->getReg() != AMDGPU::NoRegister);
3779 
3780   if (Offset == 0) {
3781     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3782   } else {
3783     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3784         .add(*Idx)
3785         .addImm(Offset);
3786   }
3787 }
3788 
3789 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3790                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3791                                    int Offset) {
3792   MachineBasicBlock *MBB = MI.getParent();
3793   const DebugLoc &DL = MI.getDebugLoc();
3794   MachineBasicBlock::iterator I(&MI);
3795 
3796   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3797 
3798   if (Offset == 0)
3799     return Idx->getReg();
3800 
3801   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3802   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3803       .add(*Idx)
3804       .addImm(Offset);
3805   return Tmp;
3806 }
3807 
3808 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3809                                           MachineBasicBlock &MBB,
3810                                           const GCNSubtarget &ST) {
3811   const SIInstrInfo *TII = ST.getInstrInfo();
3812   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3813   MachineFunction *MF = MBB.getParent();
3814   MachineRegisterInfo &MRI = MF->getRegInfo();
3815 
3816   Register Dst = MI.getOperand(0).getReg();
3817   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3818   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3819   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3820 
3821   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3822   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3823 
3824   unsigned SubReg;
3825   std::tie(SubReg, Offset)
3826     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3827 
3828   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3829 
3830   // Check for a SGPR index.
3831   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3832     MachineBasicBlock::iterator I(&MI);
3833     const DebugLoc &DL = MI.getDebugLoc();
3834 
3835     if (UseGPRIdxMode) {
3836       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3837       // to avoid interfering with other uses, so probably requires a new
3838       // optimization pass.
3839       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3840 
3841       const MCInstrDesc &GPRIDXDesc =
3842           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3843       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3844           .addReg(SrcReg)
3845           .addReg(Idx)
3846           .addImm(SubReg);
3847     } else {
3848       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3849 
3850       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3851         .addReg(SrcReg, 0, SubReg)
3852         .addReg(SrcReg, RegState::Implicit);
3853     }
3854 
3855     MI.eraseFromParent();
3856 
3857     return &MBB;
3858   }
3859 
3860   // Control flow needs to be inserted if indexing with a VGPR.
3861   const DebugLoc &DL = MI.getDebugLoc();
3862   MachineBasicBlock::iterator I(&MI);
3863 
3864   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3865   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3866 
3867   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3868 
3869   Register SGPRIdxReg;
3870   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3871                               UseGPRIdxMode, SGPRIdxReg);
3872 
3873   MachineBasicBlock *LoopBB = InsPt->getParent();
3874 
3875   if (UseGPRIdxMode) {
3876     const MCInstrDesc &GPRIDXDesc =
3877         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3878 
3879     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3880         .addReg(SrcReg)
3881         .addReg(SGPRIdxReg)
3882         .addImm(SubReg);
3883   } else {
3884     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3885       .addReg(SrcReg, 0, SubReg)
3886       .addReg(SrcReg, RegState::Implicit);
3887   }
3888 
3889   MI.eraseFromParent();
3890 
3891   return LoopBB;
3892 }
3893 
3894 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3895                                           MachineBasicBlock &MBB,
3896                                           const GCNSubtarget &ST) {
3897   const SIInstrInfo *TII = ST.getInstrInfo();
3898   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3899   MachineFunction *MF = MBB.getParent();
3900   MachineRegisterInfo &MRI = MF->getRegInfo();
3901 
3902   Register Dst = MI.getOperand(0).getReg();
3903   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3904   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3905   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3906   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3907   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3908   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3909 
3910   // This can be an immediate, but will be folded later.
3911   assert(Val->getReg());
3912 
3913   unsigned SubReg;
3914   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3915                                                          SrcVec->getReg(),
3916                                                          Offset);
3917   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3918 
3919   if (Idx->getReg() == AMDGPU::NoRegister) {
3920     MachineBasicBlock::iterator I(&MI);
3921     const DebugLoc &DL = MI.getDebugLoc();
3922 
3923     assert(Offset == 0);
3924 
3925     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3926         .add(*SrcVec)
3927         .add(*Val)
3928         .addImm(SubReg);
3929 
3930     MI.eraseFromParent();
3931     return &MBB;
3932   }
3933 
3934   // Check for a SGPR index.
3935   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3936     MachineBasicBlock::iterator I(&MI);
3937     const DebugLoc &DL = MI.getDebugLoc();
3938 
3939     if (UseGPRIdxMode) {
3940       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3941 
3942       const MCInstrDesc &GPRIDXDesc =
3943           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3944       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3945           .addReg(SrcVec->getReg())
3946           .add(*Val)
3947           .addReg(Idx)
3948           .addImm(SubReg);
3949     } else {
3950       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3951 
3952       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3953           TRI.getRegSizeInBits(*VecRC), 32, false);
3954       BuildMI(MBB, I, DL, MovRelDesc, Dst)
3955           .addReg(SrcVec->getReg())
3956           .add(*Val)
3957           .addImm(SubReg);
3958     }
3959     MI.eraseFromParent();
3960     return &MBB;
3961   }
3962 
3963   // Control flow needs to be inserted if indexing with a VGPR.
3964   if (Val->isReg())
3965     MRI.clearKillFlags(Val->getReg());
3966 
3967   const DebugLoc &DL = MI.getDebugLoc();
3968 
3969   Register PhiReg = MRI.createVirtualRegister(VecRC);
3970 
3971   Register SGPRIdxReg;
3972   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
3973                               UseGPRIdxMode, SGPRIdxReg);
3974   MachineBasicBlock *LoopBB = InsPt->getParent();
3975 
3976   if (UseGPRIdxMode) {
3977     const MCInstrDesc &GPRIDXDesc =
3978         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3979 
3980     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3981         .addReg(PhiReg)
3982         .add(*Val)
3983         .addReg(SGPRIdxReg)
3984         .addImm(AMDGPU::sub0);
3985   } else {
3986     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3987         TRI.getRegSizeInBits(*VecRC), 32, false);
3988     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3989         .addReg(PhiReg)
3990         .add(*Val)
3991         .addImm(AMDGPU::sub0);
3992   }
3993 
3994   MI.eraseFromParent();
3995   return LoopBB;
3996 }
3997 
3998 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3999   MachineInstr &MI, MachineBasicBlock *BB) const {
4000 
4001   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4002   MachineFunction *MF = BB->getParent();
4003   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
4004 
4005   switch (MI.getOpcode()) {
4006   case AMDGPU::S_UADDO_PSEUDO:
4007   case AMDGPU::S_USUBO_PSEUDO: {
4008     const DebugLoc &DL = MI.getDebugLoc();
4009     MachineOperand &Dest0 = MI.getOperand(0);
4010     MachineOperand &Dest1 = MI.getOperand(1);
4011     MachineOperand &Src0 = MI.getOperand(2);
4012     MachineOperand &Src1 = MI.getOperand(3);
4013 
4014     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
4015                        ? AMDGPU::S_ADD_I32
4016                        : AMDGPU::S_SUB_I32;
4017     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
4018 
4019     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
4020         .addImm(1)
4021         .addImm(0);
4022 
4023     MI.eraseFromParent();
4024     return BB;
4025   }
4026   case AMDGPU::S_ADD_U64_PSEUDO:
4027   case AMDGPU::S_SUB_U64_PSEUDO: {
4028     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4029     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4030     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4031     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
4032     const DebugLoc &DL = MI.getDebugLoc();
4033 
4034     MachineOperand &Dest = MI.getOperand(0);
4035     MachineOperand &Src0 = MI.getOperand(1);
4036     MachineOperand &Src1 = MI.getOperand(2);
4037 
4038     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4039     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4040 
4041     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
4042         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4043     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
4044         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4045 
4046     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
4047         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4048     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
4049         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4050 
4051     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
4052 
4053     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
4054     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
4055     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
4056     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
4057     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4058         .addReg(DestSub0)
4059         .addImm(AMDGPU::sub0)
4060         .addReg(DestSub1)
4061         .addImm(AMDGPU::sub1);
4062     MI.eraseFromParent();
4063     return BB;
4064   }
4065   case AMDGPU::V_ADD_U64_PSEUDO:
4066   case AMDGPU::V_SUB_U64_PSEUDO: {
4067     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4068     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4069     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4070     const DebugLoc &DL = MI.getDebugLoc();
4071 
4072     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
4073 
4074     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4075 
4076     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4077     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4078 
4079     Register CarryReg = MRI.createVirtualRegister(CarryRC);
4080     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
4081 
4082     MachineOperand &Dest = MI.getOperand(0);
4083     MachineOperand &Src0 = MI.getOperand(1);
4084     MachineOperand &Src1 = MI.getOperand(2);
4085 
4086     const TargetRegisterClass *Src0RC = Src0.isReg()
4087                                             ? MRI.getRegClass(Src0.getReg())
4088                                             : &AMDGPU::VReg_64RegClass;
4089     const TargetRegisterClass *Src1RC = Src1.isReg()
4090                                             ? MRI.getRegClass(Src1.getReg())
4091                                             : &AMDGPU::VReg_64RegClass;
4092 
4093     const TargetRegisterClass *Src0SubRC =
4094         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
4095     const TargetRegisterClass *Src1SubRC =
4096         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
4097 
4098     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
4099         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
4100     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
4101         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
4102 
4103     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
4104         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
4105     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
4106         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
4107 
4108     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
4109     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
4110                                .addReg(CarryReg, RegState::Define)
4111                                .add(SrcReg0Sub0)
4112                                .add(SrcReg1Sub0)
4113                                .addImm(0); // clamp bit
4114 
4115     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
4116     MachineInstr *HiHalf =
4117         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4118             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4119             .add(SrcReg0Sub1)
4120             .add(SrcReg1Sub1)
4121             .addReg(CarryReg, RegState::Kill)
4122             .addImm(0); // clamp bit
4123 
4124     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4125         .addReg(DestSub0)
4126         .addImm(AMDGPU::sub0)
4127         .addReg(DestSub1)
4128         .addImm(AMDGPU::sub1);
4129     TII->legalizeOperands(*LoHalf);
4130     TII->legalizeOperands(*HiHalf);
4131     MI.eraseFromParent();
4132     return BB;
4133   }
4134   case AMDGPU::S_ADD_CO_PSEUDO:
4135   case AMDGPU::S_SUB_CO_PSEUDO: {
4136     // This pseudo has a chance to be selected
4137     // only from uniform add/subcarry node. All the VGPR operands
4138     // therefore assumed to be splat vectors.
4139     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4140     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4141     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4142     MachineBasicBlock::iterator MII = MI;
4143     const DebugLoc &DL = MI.getDebugLoc();
4144     MachineOperand &Dest = MI.getOperand(0);
4145     MachineOperand &CarryDest = MI.getOperand(1);
4146     MachineOperand &Src0 = MI.getOperand(2);
4147     MachineOperand &Src1 = MI.getOperand(3);
4148     MachineOperand &Src2 = MI.getOperand(4);
4149     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4150                        ? AMDGPU::S_ADDC_U32
4151                        : AMDGPU::S_SUBB_U32;
4152     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4153       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4154       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4155           .addReg(Src0.getReg());
4156       Src0.setReg(RegOp0);
4157     }
4158     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4159       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4160       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4161           .addReg(Src1.getReg());
4162       Src1.setReg(RegOp1);
4163     }
4164     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4165     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4166       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4167           .addReg(Src2.getReg());
4168       Src2.setReg(RegOp2);
4169     }
4170 
4171     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4172     unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC);
4173     assert(WaveSize == 64 || WaveSize == 32);
4174 
4175     if (WaveSize == 64) {
4176       if (ST.hasScalarCompareEq64()) {
4177         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4178             .addReg(Src2.getReg())
4179             .addImm(0);
4180       } else {
4181         const TargetRegisterClass *SubRC =
4182             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4183         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4184             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4185         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4186             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4187         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4188 
4189         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4190             .add(Src2Sub0)
4191             .add(Src2Sub1);
4192 
4193         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4194             .addReg(Src2_32, RegState::Kill)
4195             .addImm(0);
4196       }
4197     } else {
4198       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4199           .addReg(Src2.getReg())
4200           .addImm(0);
4201     }
4202 
4203     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4204 
4205     unsigned SelOpc =
4206         (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
4207 
4208     BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg())
4209         .addImm(-1)
4210         .addImm(0);
4211 
4212     MI.eraseFromParent();
4213     return BB;
4214   }
4215   case AMDGPU::SI_INIT_M0: {
4216     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4217             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4218         .add(MI.getOperand(0));
4219     MI.eraseFromParent();
4220     return BB;
4221   }
4222   case AMDGPU::GET_GROUPSTATICSIZE: {
4223     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4224            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4225     DebugLoc DL = MI.getDebugLoc();
4226     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4227         .add(MI.getOperand(0))
4228         .addImm(MFI->getLDSSize());
4229     MI.eraseFromParent();
4230     return BB;
4231   }
4232   case AMDGPU::SI_INDIRECT_SRC_V1:
4233   case AMDGPU::SI_INDIRECT_SRC_V2:
4234   case AMDGPU::SI_INDIRECT_SRC_V4:
4235   case AMDGPU::SI_INDIRECT_SRC_V8:
4236   case AMDGPU::SI_INDIRECT_SRC_V16:
4237   case AMDGPU::SI_INDIRECT_SRC_V32:
4238     return emitIndirectSrc(MI, *BB, *getSubtarget());
4239   case AMDGPU::SI_INDIRECT_DST_V1:
4240   case AMDGPU::SI_INDIRECT_DST_V2:
4241   case AMDGPU::SI_INDIRECT_DST_V4:
4242   case AMDGPU::SI_INDIRECT_DST_V8:
4243   case AMDGPU::SI_INDIRECT_DST_V16:
4244   case AMDGPU::SI_INDIRECT_DST_V32:
4245     return emitIndirectDst(MI, *BB, *getSubtarget());
4246   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4247   case AMDGPU::SI_KILL_I1_PSEUDO:
4248     return splitKillBlock(MI, BB);
4249   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4250     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4251     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4252     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4253 
4254     Register Dst = MI.getOperand(0).getReg();
4255     Register Src0 = MI.getOperand(1).getReg();
4256     Register Src1 = MI.getOperand(2).getReg();
4257     const DebugLoc &DL = MI.getDebugLoc();
4258     Register SrcCond = MI.getOperand(3).getReg();
4259 
4260     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4261     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4262     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4263     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4264 
4265     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4266       .addReg(SrcCond);
4267     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4268       .addImm(0)
4269       .addReg(Src0, 0, AMDGPU::sub0)
4270       .addImm(0)
4271       .addReg(Src1, 0, AMDGPU::sub0)
4272       .addReg(SrcCondCopy);
4273     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4274       .addImm(0)
4275       .addReg(Src0, 0, AMDGPU::sub1)
4276       .addImm(0)
4277       .addReg(Src1, 0, AMDGPU::sub1)
4278       .addReg(SrcCondCopy);
4279 
4280     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4281       .addReg(DstLo)
4282       .addImm(AMDGPU::sub0)
4283       .addReg(DstHi)
4284       .addImm(AMDGPU::sub1);
4285     MI.eraseFromParent();
4286     return BB;
4287   }
4288   case AMDGPU::SI_BR_UNDEF: {
4289     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4290     const DebugLoc &DL = MI.getDebugLoc();
4291     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4292                            .add(MI.getOperand(0));
4293     Br->getOperand(1).setIsUndef(true); // read undef SCC
4294     MI.eraseFromParent();
4295     return BB;
4296   }
4297   case AMDGPU::ADJCALLSTACKUP:
4298   case AMDGPU::ADJCALLSTACKDOWN: {
4299     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4300     MachineInstrBuilder MIB(*MF, &MI);
4301     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4302        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4303     return BB;
4304   }
4305   case AMDGPU::SI_CALL_ISEL: {
4306     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4307     const DebugLoc &DL = MI.getDebugLoc();
4308 
4309     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4310 
4311     MachineInstrBuilder MIB;
4312     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4313 
4314     for (const MachineOperand &MO : MI.operands())
4315       MIB.add(MO);
4316 
4317     MIB.cloneMemRefs(MI);
4318     MI.eraseFromParent();
4319     return BB;
4320   }
4321   case AMDGPU::V_ADD_CO_U32_e32:
4322   case AMDGPU::V_SUB_CO_U32_e32:
4323   case AMDGPU::V_SUBREV_CO_U32_e32: {
4324     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4325     const DebugLoc &DL = MI.getDebugLoc();
4326     unsigned Opc = MI.getOpcode();
4327 
4328     bool NeedClampOperand = false;
4329     if (TII->pseudoToMCOpcode(Opc) == -1) {
4330       Opc = AMDGPU::getVOPe64(Opc);
4331       NeedClampOperand = true;
4332     }
4333 
4334     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4335     if (TII->isVOP3(*I)) {
4336       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4337       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4338       I.addReg(TRI->getVCC(), RegState::Define);
4339     }
4340     I.add(MI.getOperand(1))
4341      .add(MI.getOperand(2));
4342     if (NeedClampOperand)
4343       I.addImm(0); // clamp bit for e64 encoding
4344 
4345     TII->legalizeOperands(*I);
4346 
4347     MI.eraseFromParent();
4348     return BB;
4349   }
4350   case AMDGPU::V_ADDC_U32_e32:
4351   case AMDGPU::V_SUBB_U32_e32:
4352   case AMDGPU::V_SUBBREV_U32_e32:
4353     // These instructions have an implicit use of vcc which counts towards the
4354     // constant bus limit.
4355     TII->legalizeOperands(MI);
4356     return BB;
4357   case AMDGPU::DS_GWS_INIT:
4358   case AMDGPU::DS_GWS_SEMA_BR:
4359   case AMDGPU::DS_GWS_BARRIER:
4360     if (Subtarget->needsAlignedVGPRs()) {
4361       // Add implicit aligned super-reg to force alignment on the data operand.
4362       const DebugLoc &DL = MI.getDebugLoc();
4363       MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4364       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
4365       MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0);
4366       Register DataReg = Op->getReg();
4367       bool IsAGPR = TRI->isAGPR(MRI, DataReg);
4368       Register Undef = MRI.createVirtualRegister(
4369           IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass);
4370       BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef);
4371       Register NewVR =
4372           MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass
4373                                            : &AMDGPU::VReg_64_Align2RegClass);
4374       BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR)
4375           .addReg(DataReg, 0, Op->getSubReg())
4376           .addImm(AMDGPU::sub0)
4377           .addReg(Undef)
4378           .addImm(AMDGPU::sub1);
4379       Op->setReg(NewVR);
4380       Op->setSubReg(AMDGPU::sub0);
4381       MI.addOperand(MachineOperand::CreateReg(NewVR, false, true));
4382     }
4383     LLVM_FALLTHROUGH;
4384   case AMDGPU::DS_GWS_SEMA_V:
4385   case AMDGPU::DS_GWS_SEMA_P:
4386   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4387     // A s_waitcnt 0 is required to be the instruction immediately following.
4388     if (getSubtarget()->hasGWSAutoReplay()) {
4389       bundleInstWithWaitcnt(MI);
4390       return BB;
4391     }
4392 
4393     return emitGWSMemViolTestLoop(MI, BB);
4394   case AMDGPU::S_SETREG_B32: {
4395     // Try to optimize cases that only set the denormal mode or rounding mode.
4396     //
4397     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4398     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4399     // instead.
4400     //
4401     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4402     // allow you to have a no side effect instruction in the output of a
4403     // sideeffecting pattern.
4404     unsigned ID, Offset, Width;
4405     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4406     if (ID != AMDGPU::Hwreg::ID_MODE)
4407       return BB;
4408 
4409     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4410     const unsigned SetMask = WidthMask << Offset;
4411 
4412     if (getSubtarget()->hasDenormModeInst()) {
4413       unsigned SetDenormOp = 0;
4414       unsigned SetRoundOp = 0;
4415 
4416       // The dedicated instructions can only set the whole denorm or round mode
4417       // at once, not a subset of bits in either.
4418       if (SetMask ==
4419           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4420         // If this fully sets both the round and denorm mode, emit the two
4421         // dedicated instructions for these.
4422         SetRoundOp = AMDGPU::S_ROUND_MODE;
4423         SetDenormOp = AMDGPU::S_DENORM_MODE;
4424       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4425         SetRoundOp = AMDGPU::S_ROUND_MODE;
4426       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4427         SetDenormOp = AMDGPU::S_DENORM_MODE;
4428       }
4429 
4430       if (SetRoundOp || SetDenormOp) {
4431         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4432         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4433         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4434           unsigned ImmVal = Def->getOperand(1).getImm();
4435           if (SetRoundOp) {
4436             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4437                 .addImm(ImmVal & 0xf);
4438 
4439             // If we also have the denorm mode, get just the denorm mode bits.
4440             ImmVal >>= 4;
4441           }
4442 
4443           if (SetDenormOp) {
4444             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4445                 .addImm(ImmVal & 0xf);
4446           }
4447 
4448           MI.eraseFromParent();
4449           return BB;
4450         }
4451       }
4452     }
4453 
4454     // If only FP bits are touched, used the no side effects pseudo.
4455     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4456                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4457       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4458 
4459     return BB;
4460   }
4461   default:
4462     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4463   }
4464 }
4465 
4466 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4467   return isTypeLegal(VT.getScalarType());
4468 }
4469 
4470 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4471   // This currently forces unfolding various combinations of fsub into fma with
4472   // free fneg'd operands. As long as we have fast FMA (controlled by
4473   // isFMAFasterThanFMulAndFAdd), we should perform these.
4474 
4475   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4476   // most of these combines appear to be cycle neutral but save on instruction
4477   // count / code size.
4478   return true;
4479 }
4480 
4481 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; }
4482 
4483 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4484                                          EVT VT) const {
4485   if (!VT.isVector()) {
4486     return MVT::i1;
4487   }
4488   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4489 }
4490 
4491 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4492   // TODO: Should i16 be used always if legal? For now it would force VALU
4493   // shifts.
4494   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4495 }
4496 
4497 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4498   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4499              ? Ty.changeElementSize(16)
4500              : Ty.changeElementSize(32);
4501 }
4502 
4503 // Answering this is somewhat tricky and depends on the specific device which
4504 // have different rates for fma or all f64 operations.
4505 //
4506 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4507 // regardless of which device (although the number of cycles differs between
4508 // devices), so it is always profitable for f64.
4509 //
4510 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4511 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4512 // which we can always do even without fused FP ops since it returns the same
4513 // result as the separate operations and since it is always full
4514 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4515 // however does not support denormals, so we do report fma as faster if we have
4516 // a fast fma device and require denormals.
4517 //
4518 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4519                                                   EVT VT) const {
4520   VT = VT.getScalarType();
4521 
4522   switch (VT.getSimpleVT().SimpleTy) {
4523   case MVT::f32: {
4524     // If mad is not available this depends only on if f32 fma is full rate.
4525     if (!Subtarget->hasMadMacF32Insts())
4526       return Subtarget->hasFastFMAF32();
4527 
4528     // Otherwise f32 mad is always full rate and returns the same result as
4529     // the separate operations so should be preferred over fma.
4530     // However does not support denormals.
4531     if (hasFP32Denormals(MF))
4532       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4533 
4534     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4535     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4536   }
4537   case MVT::f64:
4538     return true;
4539   case MVT::f16:
4540     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4541   default:
4542     break;
4543   }
4544 
4545   return false;
4546 }
4547 
4548 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4549                                                   LLT Ty) const {
4550   switch (Ty.getScalarSizeInBits()) {
4551   case 16:
4552     return isFMAFasterThanFMulAndFAdd(MF, MVT::f16);
4553   case 32:
4554     return isFMAFasterThanFMulAndFAdd(MF, MVT::f32);
4555   case 64:
4556     return isFMAFasterThanFMulAndFAdd(MF, MVT::f64);
4557   default:
4558     break;
4559   }
4560 
4561   return false;
4562 }
4563 
4564 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const {
4565   if (!Ty.isScalar())
4566     return false;
4567 
4568   if (Ty.getScalarSizeInBits() == 16)
4569     return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF());
4570   if (Ty.getScalarSizeInBits() == 32)
4571     return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF());
4572 
4573   return false;
4574 }
4575 
4576 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4577                                    const SDNode *N) const {
4578   // TODO: Check future ftz flag
4579   // v_mad_f32/v_mac_f32 do not support denormals.
4580   EVT VT = N->getValueType(0);
4581   if (VT == MVT::f32)
4582     return Subtarget->hasMadMacF32Insts() &&
4583            !hasFP32Denormals(DAG.getMachineFunction());
4584   if (VT == MVT::f16) {
4585     return Subtarget->hasMadF16() &&
4586            !hasFP64FP16Denormals(DAG.getMachineFunction());
4587   }
4588 
4589   return false;
4590 }
4591 
4592 //===----------------------------------------------------------------------===//
4593 // Custom DAG Lowering Operations
4594 //===----------------------------------------------------------------------===//
4595 
4596 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4597 // wider vector type is legal.
4598 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4599                                              SelectionDAG &DAG) const {
4600   unsigned Opc = Op.getOpcode();
4601   EVT VT = Op.getValueType();
4602   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4603 
4604   SDValue Lo, Hi;
4605   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4606 
4607   SDLoc SL(Op);
4608   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4609                              Op->getFlags());
4610   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4611                              Op->getFlags());
4612 
4613   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4614 }
4615 
4616 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4617 // wider vector type is legal.
4618 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4619                                               SelectionDAG &DAG) const {
4620   unsigned Opc = Op.getOpcode();
4621   EVT VT = Op.getValueType();
4622   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4623          VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8f32 ||
4624          VT == MVT::v16f32 || VT == MVT::v32f32);
4625 
4626   SDValue Lo0, Hi0;
4627   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4628   SDValue Lo1, Hi1;
4629   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4630 
4631   SDLoc SL(Op);
4632 
4633   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4634                              Op->getFlags());
4635   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4636                              Op->getFlags());
4637 
4638   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4639 }
4640 
4641 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4642                                               SelectionDAG &DAG) const {
4643   unsigned Opc = Op.getOpcode();
4644   EVT VT = Op.getValueType();
4645   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 ||
4646          VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v8f32 ||
4647          VT == MVT::v16f32 || VT == MVT::v32f32);
4648 
4649   SDValue Lo0, Hi0;
4650   SDValue Op0 = Op.getOperand(0);
4651   std::tie(Lo0, Hi0) = Op0.getValueType().isVector()
4652                          ? DAG.SplitVectorOperand(Op.getNode(), 0)
4653                          : std::make_pair(Op0, Op0);
4654   SDValue Lo1, Hi1;
4655   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4656   SDValue Lo2, Hi2;
4657   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4658 
4659   SDLoc SL(Op);
4660   auto ResVT = DAG.GetSplitDestVTs(VT);
4661 
4662   SDValue OpLo = DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2,
4663                              Op->getFlags());
4664   SDValue OpHi = DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2,
4665                              Op->getFlags());
4666 
4667   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4668 }
4669 
4670 
4671 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4672   switch (Op.getOpcode()) {
4673   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4674   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4675   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4676   case ISD::LOAD: {
4677     SDValue Result = LowerLOAD(Op, DAG);
4678     assert((!Result.getNode() ||
4679             Result.getNode()->getNumValues() == 2) &&
4680            "Load should return a value and a chain");
4681     return Result;
4682   }
4683 
4684   case ISD::FSIN:
4685   case ISD::FCOS:
4686     return LowerTrig(Op, DAG);
4687   case ISD::SELECT: return LowerSELECT(Op, DAG);
4688   case ISD::FDIV: return LowerFDIV(Op, DAG);
4689   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4690   case ISD::STORE: return LowerSTORE(Op, DAG);
4691   case ISD::GlobalAddress: {
4692     MachineFunction &MF = DAG.getMachineFunction();
4693     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4694     return LowerGlobalAddress(MFI, Op, DAG);
4695   }
4696   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4697   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4698   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4699   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4700   case ISD::INSERT_SUBVECTOR:
4701     return lowerINSERT_SUBVECTOR(Op, DAG);
4702   case ISD::INSERT_VECTOR_ELT:
4703     return lowerINSERT_VECTOR_ELT(Op, DAG);
4704   case ISD::EXTRACT_VECTOR_ELT:
4705     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4706   case ISD::VECTOR_SHUFFLE:
4707     return lowerVECTOR_SHUFFLE(Op, DAG);
4708   case ISD::BUILD_VECTOR:
4709     return lowerBUILD_VECTOR(Op, DAG);
4710   case ISD::FP_ROUND:
4711     return lowerFP_ROUND(Op, DAG);
4712   case ISD::FPTRUNC_ROUND: {
4713     unsigned Opc;
4714     SDLoc DL(Op);
4715 
4716     if (Op.getOperand(0)->getValueType(0) != MVT::f32)
4717       return SDValue();
4718 
4719     // Get the rounding mode from the last operand
4720     int RoundMode = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4721     if (RoundMode == (int)RoundingMode::TowardPositive)
4722       Opc = AMDGPUISD::FPTRUNC_ROUND_UPWARD;
4723     else if (RoundMode == (int)RoundingMode::TowardNegative)
4724       Opc = AMDGPUISD::FPTRUNC_ROUND_DOWNWARD;
4725     else
4726       return SDValue();
4727 
4728     return DAG.getNode(Opc, DL, Op.getNode()->getVTList(), Op->getOperand(0));
4729   }
4730   case ISD::TRAP:
4731     return lowerTRAP(Op, DAG);
4732   case ISD::DEBUGTRAP:
4733     return lowerDEBUGTRAP(Op, DAG);
4734   case ISD::FABS:
4735   case ISD::FNEG:
4736   case ISD::FCANONICALIZE:
4737   case ISD::BSWAP:
4738     return splitUnaryVectorOp(Op, DAG);
4739   case ISD::FMINNUM:
4740   case ISD::FMAXNUM:
4741     return lowerFMINNUM_FMAXNUM(Op, DAG);
4742   case ISD::FMA:
4743     return splitTernaryVectorOp(Op, DAG);
4744   case ISD::FP_TO_SINT:
4745   case ISD::FP_TO_UINT:
4746     return LowerFP_TO_INT(Op, DAG);
4747   case ISD::SHL:
4748   case ISD::SRA:
4749   case ISD::SRL:
4750   case ISD::ADD:
4751   case ISD::SUB:
4752   case ISD::MUL:
4753   case ISD::SMIN:
4754   case ISD::SMAX:
4755   case ISD::UMIN:
4756   case ISD::UMAX:
4757   case ISD::FADD:
4758   case ISD::FMUL:
4759   case ISD::FMINNUM_IEEE:
4760   case ISD::FMAXNUM_IEEE:
4761   case ISD::UADDSAT:
4762   case ISD::USUBSAT:
4763   case ISD::SADDSAT:
4764   case ISD::SSUBSAT:
4765     return splitBinaryVectorOp(Op, DAG);
4766   case ISD::SMULO:
4767   case ISD::UMULO:
4768     return lowerXMULO(Op, DAG);
4769   case ISD::SMUL_LOHI:
4770   case ISD::UMUL_LOHI:
4771     return lowerXMUL_LOHI(Op, DAG);
4772   case ISD::DYNAMIC_STACKALLOC:
4773     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4774   }
4775   return SDValue();
4776 }
4777 
4778 // Used for D16: Casts the result of an instruction into the right vector,
4779 // packs values if loads return unpacked values.
4780 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4781                                        const SDLoc &DL,
4782                                        SelectionDAG &DAG, bool Unpacked) {
4783   if (!LoadVT.isVector())
4784     return Result;
4785 
4786   // Cast back to the original packed type or to a larger type that is a
4787   // multiple of 32 bit for D16. Widening the return type is a required for
4788   // legalization.
4789   EVT FittingLoadVT = LoadVT;
4790   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4791     FittingLoadVT =
4792         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4793                          LoadVT.getVectorNumElements() + 1);
4794   }
4795 
4796   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4797     // Truncate to v2i16/v4i16.
4798     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4799 
4800     // Workaround legalizer not scalarizing truncate after vector op
4801     // legalization but not creating intermediate vector trunc.
4802     SmallVector<SDValue, 4> Elts;
4803     DAG.ExtractVectorElements(Result, Elts);
4804     for (SDValue &Elt : Elts)
4805       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4806 
4807     // Pad illegal v1i16/v3fi6 to v4i16
4808     if ((LoadVT.getVectorNumElements() % 2) == 1)
4809       Elts.push_back(DAG.getUNDEF(MVT::i16));
4810 
4811     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4812 
4813     // Bitcast to original type (v2f16/v4f16).
4814     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4815   }
4816 
4817   // Cast back to the original packed type.
4818   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4819 }
4820 
4821 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4822                                               MemSDNode *M,
4823                                               SelectionDAG &DAG,
4824                                               ArrayRef<SDValue> Ops,
4825                                               bool IsIntrinsic) const {
4826   SDLoc DL(M);
4827 
4828   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4829   EVT LoadVT = M->getValueType(0);
4830 
4831   EVT EquivLoadVT = LoadVT;
4832   if (LoadVT.isVector()) {
4833     if (Unpacked) {
4834       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4835                                      LoadVT.getVectorNumElements());
4836     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4837       // Widen v3f16 to legal type
4838       EquivLoadVT =
4839           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4840                            LoadVT.getVectorNumElements() + 1);
4841     }
4842   }
4843 
4844   // Change from v4f16/v2f16 to EquivLoadVT.
4845   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4846 
4847   SDValue Load
4848     = DAG.getMemIntrinsicNode(
4849       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4850       VTList, Ops, M->getMemoryVT(),
4851       M->getMemOperand());
4852 
4853   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4854 
4855   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4856 }
4857 
4858 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4859                                              SelectionDAG &DAG,
4860                                              ArrayRef<SDValue> Ops) const {
4861   SDLoc DL(M);
4862   EVT LoadVT = M->getValueType(0);
4863   EVT EltType = LoadVT.getScalarType();
4864   EVT IntVT = LoadVT.changeTypeToInteger();
4865 
4866   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4867 
4868   unsigned Opc =
4869       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4870 
4871   if (IsD16) {
4872     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4873   }
4874 
4875   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4876   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4877     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4878 
4879   if (isTypeLegal(LoadVT)) {
4880     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4881                                M->getMemOperand(), DAG);
4882   }
4883 
4884   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4885   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4886   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4887                                         M->getMemOperand(), DAG);
4888   return DAG.getMergeValues(
4889       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4890       DL);
4891 }
4892 
4893 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4894                                   SDNode *N, SelectionDAG &DAG) {
4895   EVT VT = N->getValueType(0);
4896   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4897   unsigned CondCode = CD->getZExtValue();
4898   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4899     return DAG.getUNDEF(VT);
4900 
4901   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4902 
4903   SDValue LHS = N->getOperand(1);
4904   SDValue RHS = N->getOperand(2);
4905 
4906   SDLoc DL(N);
4907 
4908   EVT CmpVT = LHS.getValueType();
4909   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4910     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4911       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4912     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4913     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4914   }
4915 
4916   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4917 
4918   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4919   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4920 
4921   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4922                               DAG.getCondCode(CCOpcode));
4923   if (VT.bitsEq(CCVT))
4924     return SetCC;
4925   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4926 }
4927 
4928 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4929                                   SDNode *N, SelectionDAG &DAG) {
4930   EVT VT = N->getValueType(0);
4931   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4932 
4933   unsigned CondCode = CD->getZExtValue();
4934   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4935     return DAG.getUNDEF(VT);
4936 
4937   SDValue Src0 = N->getOperand(1);
4938   SDValue Src1 = N->getOperand(2);
4939   EVT CmpVT = Src0.getValueType();
4940   SDLoc SL(N);
4941 
4942   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4943     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4944     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4945   }
4946 
4947   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4948   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4949   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4950   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4951   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4952                               Src1, DAG.getCondCode(CCOpcode));
4953   if (VT.bitsEq(CCVT))
4954     return SetCC;
4955   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4956 }
4957 
4958 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4959                                     SelectionDAG &DAG) {
4960   EVT VT = N->getValueType(0);
4961   SDValue Src = N->getOperand(1);
4962   SDLoc SL(N);
4963 
4964   if (Src.getOpcode() == ISD::SETCC) {
4965     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4966     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4967                        Src.getOperand(1), Src.getOperand(2));
4968   }
4969   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4970     // (ballot 0) -> 0
4971     if (Arg->isZero())
4972       return DAG.getConstant(0, SL, VT);
4973 
4974     // (ballot 1) -> EXEC/EXEC_LO
4975     if (Arg->isOne()) {
4976       Register Exec;
4977       if (VT.getScalarSizeInBits() == 32)
4978         Exec = AMDGPU::EXEC_LO;
4979       else if (VT.getScalarSizeInBits() == 64)
4980         Exec = AMDGPU::EXEC;
4981       else
4982         return SDValue();
4983 
4984       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4985     }
4986   }
4987 
4988   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4989   // ISD::SETNE)
4990   return DAG.getNode(
4991       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4992       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4993 }
4994 
4995 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4996                                           SmallVectorImpl<SDValue> &Results,
4997                                           SelectionDAG &DAG) const {
4998   switch (N->getOpcode()) {
4999   case ISD::INSERT_VECTOR_ELT: {
5000     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
5001       Results.push_back(Res);
5002     return;
5003   }
5004   case ISD::EXTRACT_VECTOR_ELT: {
5005     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
5006       Results.push_back(Res);
5007     return;
5008   }
5009   case ISD::INTRINSIC_WO_CHAIN: {
5010     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5011     switch (IID) {
5012     case Intrinsic::amdgcn_cvt_pkrtz: {
5013       SDValue Src0 = N->getOperand(1);
5014       SDValue Src1 = N->getOperand(2);
5015       SDLoc SL(N);
5016       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
5017                                 Src0, Src1);
5018       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
5019       return;
5020     }
5021     case Intrinsic::amdgcn_cvt_pknorm_i16:
5022     case Intrinsic::amdgcn_cvt_pknorm_u16:
5023     case Intrinsic::amdgcn_cvt_pk_i16:
5024     case Intrinsic::amdgcn_cvt_pk_u16: {
5025       SDValue Src0 = N->getOperand(1);
5026       SDValue Src1 = N->getOperand(2);
5027       SDLoc SL(N);
5028       unsigned Opcode;
5029 
5030       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
5031         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
5032       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
5033         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
5034       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
5035         Opcode = AMDGPUISD::CVT_PK_I16_I32;
5036       else
5037         Opcode = AMDGPUISD::CVT_PK_U16_U32;
5038 
5039       EVT VT = N->getValueType(0);
5040       if (isTypeLegal(VT))
5041         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
5042       else {
5043         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
5044         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
5045       }
5046       return;
5047     }
5048     }
5049     break;
5050   }
5051   case ISD::INTRINSIC_W_CHAIN: {
5052     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
5053       if (Res.getOpcode() == ISD::MERGE_VALUES) {
5054         // FIXME: Hacky
5055         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
5056           Results.push_back(Res.getOperand(I));
5057         }
5058       } else {
5059         Results.push_back(Res);
5060         Results.push_back(Res.getValue(1));
5061       }
5062       return;
5063     }
5064 
5065     break;
5066   }
5067   case ISD::SELECT: {
5068     SDLoc SL(N);
5069     EVT VT = N->getValueType(0);
5070     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
5071     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
5072     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
5073 
5074     EVT SelectVT = NewVT;
5075     if (NewVT.bitsLT(MVT::i32)) {
5076       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
5077       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
5078       SelectVT = MVT::i32;
5079     }
5080 
5081     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
5082                                     N->getOperand(0), LHS, RHS);
5083 
5084     if (NewVT != SelectVT)
5085       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
5086     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
5087     return;
5088   }
5089   case ISD::FNEG: {
5090     if (N->getValueType(0) != MVT::v2f16)
5091       break;
5092 
5093     SDLoc SL(N);
5094     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5095 
5096     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
5097                              BC,
5098                              DAG.getConstant(0x80008000, SL, MVT::i32));
5099     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5100     return;
5101   }
5102   case ISD::FABS: {
5103     if (N->getValueType(0) != MVT::v2f16)
5104       break;
5105 
5106     SDLoc SL(N);
5107     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5108 
5109     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
5110                              BC,
5111                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
5112     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5113     return;
5114   }
5115   default:
5116     break;
5117   }
5118 }
5119 
5120 /// Helper function for LowerBRCOND
5121 static SDNode *findUser(SDValue Value, unsigned Opcode) {
5122 
5123   SDNode *Parent = Value.getNode();
5124   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
5125        I != E; ++I) {
5126 
5127     if (I.getUse().get() != Value)
5128       continue;
5129 
5130     if (I->getOpcode() == Opcode)
5131       return *I;
5132   }
5133   return nullptr;
5134 }
5135 
5136 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
5137   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
5138     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
5139     case Intrinsic::amdgcn_if:
5140       return AMDGPUISD::IF;
5141     case Intrinsic::amdgcn_else:
5142       return AMDGPUISD::ELSE;
5143     case Intrinsic::amdgcn_loop:
5144       return AMDGPUISD::LOOP;
5145     case Intrinsic::amdgcn_end_cf:
5146       llvm_unreachable("should not occur");
5147     default:
5148       return 0;
5149     }
5150   }
5151 
5152   // break, if_break, else_break are all only used as inputs to loop, not
5153   // directly as branch conditions.
5154   return 0;
5155 }
5156 
5157 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
5158   const Triple &TT = getTargetMachine().getTargetTriple();
5159   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5160           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5161          AMDGPU::shouldEmitConstantsToTextSection(TT);
5162 }
5163 
5164 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
5165   // FIXME: Either avoid relying on address space here or change the default
5166   // address space for functions to avoid the explicit check.
5167   return (GV->getValueType()->isFunctionTy() ||
5168           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
5169          !shouldEmitFixup(GV) &&
5170          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
5171 }
5172 
5173 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
5174   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
5175 }
5176 
5177 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
5178   if (!GV->hasExternalLinkage())
5179     return true;
5180 
5181   const auto OS = getTargetMachine().getTargetTriple().getOS();
5182   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
5183 }
5184 
5185 /// This transforms the control flow intrinsics to get the branch destination as
5186 /// last parameter, also switches branch target with BR if the need arise
5187 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
5188                                       SelectionDAG &DAG) const {
5189   SDLoc DL(BRCOND);
5190 
5191   SDNode *Intr = BRCOND.getOperand(1).getNode();
5192   SDValue Target = BRCOND.getOperand(2);
5193   SDNode *BR = nullptr;
5194   SDNode *SetCC = nullptr;
5195 
5196   if (Intr->getOpcode() == ISD::SETCC) {
5197     // As long as we negate the condition everything is fine
5198     SetCC = Intr;
5199     Intr = SetCC->getOperand(0).getNode();
5200 
5201   } else {
5202     // Get the target from BR if we don't negate the condition
5203     BR = findUser(BRCOND, ISD::BR);
5204     assert(BR && "brcond missing unconditional branch user");
5205     Target = BR->getOperand(1);
5206   }
5207 
5208   unsigned CFNode = isCFIntrinsic(Intr);
5209   if (CFNode == 0) {
5210     // This is a uniform branch so we don't need to legalize.
5211     return BRCOND;
5212   }
5213 
5214   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5215                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5216 
5217   assert(!SetCC ||
5218         (SetCC->getConstantOperandVal(1) == 1 &&
5219          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5220                                                              ISD::SETNE));
5221 
5222   // operands of the new intrinsic call
5223   SmallVector<SDValue, 4> Ops;
5224   if (HaveChain)
5225     Ops.push_back(BRCOND.getOperand(0));
5226 
5227   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5228   Ops.push_back(Target);
5229 
5230   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5231 
5232   // build the new intrinsic call
5233   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5234 
5235   if (!HaveChain) {
5236     SDValue Ops[] =  {
5237       SDValue(Result, 0),
5238       BRCOND.getOperand(0)
5239     };
5240 
5241     Result = DAG.getMergeValues(Ops, DL).getNode();
5242   }
5243 
5244   if (BR) {
5245     // Give the branch instruction our target
5246     SDValue Ops[] = {
5247       BR->getOperand(0),
5248       BRCOND.getOperand(2)
5249     };
5250     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5251     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5252   }
5253 
5254   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5255 
5256   // Copy the intrinsic results to registers
5257   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5258     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5259     if (!CopyToReg)
5260       continue;
5261 
5262     Chain = DAG.getCopyToReg(
5263       Chain, DL,
5264       CopyToReg->getOperand(1),
5265       SDValue(Result, i - 1),
5266       SDValue());
5267 
5268     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5269   }
5270 
5271   // Remove the old intrinsic from the chain
5272   DAG.ReplaceAllUsesOfValueWith(
5273     SDValue(Intr, Intr->getNumValues() - 1),
5274     Intr->getOperand(0));
5275 
5276   return Chain;
5277 }
5278 
5279 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5280                                           SelectionDAG &DAG) const {
5281   MVT VT = Op.getSimpleValueType();
5282   SDLoc DL(Op);
5283   // Checking the depth
5284   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5285     return DAG.getConstant(0, DL, VT);
5286 
5287   MachineFunction &MF = DAG.getMachineFunction();
5288   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5289   // Check for kernel and shader functions
5290   if (Info->isEntryFunction())
5291     return DAG.getConstant(0, DL, VT);
5292 
5293   MachineFrameInfo &MFI = MF.getFrameInfo();
5294   // There is a call to @llvm.returnaddress in this function
5295   MFI.setReturnAddressIsTaken(true);
5296 
5297   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5298   // Get the return address reg and mark it as an implicit live-in
5299   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5300 
5301   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5302 }
5303 
5304 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5305                                             SDValue Op,
5306                                             const SDLoc &DL,
5307                                             EVT VT) const {
5308   return Op.getValueType().bitsLE(VT) ?
5309       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5310     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5311                 DAG.getTargetConstant(0, DL, MVT::i32));
5312 }
5313 
5314 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5315   assert(Op.getValueType() == MVT::f16 &&
5316          "Do not know how to custom lower FP_ROUND for non-f16 type");
5317 
5318   SDValue Src = Op.getOperand(0);
5319   EVT SrcVT = Src.getValueType();
5320   if (SrcVT != MVT::f64)
5321     return Op;
5322 
5323   SDLoc DL(Op);
5324 
5325   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5326   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5327   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5328 }
5329 
5330 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5331                                                SelectionDAG &DAG) const {
5332   EVT VT = Op.getValueType();
5333   const MachineFunction &MF = DAG.getMachineFunction();
5334   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5335   bool IsIEEEMode = Info->getMode().IEEE;
5336 
5337   // FIXME: Assert during selection that this is only selected for
5338   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5339   // mode functions, but this happens to be OK since it's only done in cases
5340   // where there is known no sNaN.
5341   if (IsIEEEMode)
5342     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5343 
5344   if (VT == MVT::v4f16 || VT == MVT::v8f16)
5345     return splitBinaryVectorOp(Op, DAG);
5346   return Op;
5347 }
5348 
5349 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5350   EVT VT = Op.getValueType();
5351   SDLoc SL(Op);
5352   SDValue LHS = Op.getOperand(0);
5353   SDValue RHS = Op.getOperand(1);
5354   bool isSigned = Op.getOpcode() == ISD::SMULO;
5355 
5356   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5357     const APInt &C = RHSC->getAPIntValue();
5358     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5359     if (C.isPowerOf2()) {
5360       // smulo(x, signed_min) is same as umulo(x, signed_min).
5361       bool UseArithShift = isSigned && !C.isMinSignedValue();
5362       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5363       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5364       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5365           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5366                       SL, VT, Result, ShiftAmt),
5367           LHS, ISD::SETNE);
5368       return DAG.getMergeValues({ Result, Overflow }, SL);
5369     }
5370   }
5371 
5372   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5373   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5374                             SL, VT, LHS, RHS);
5375 
5376   SDValue Sign = isSigned
5377     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5378                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5379     : DAG.getConstant(0, SL, VT);
5380   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5381 
5382   return DAG.getMergeValues({ Result, Overflow }, SL);
5383 }
5384 
5385 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const {
5386   if (Op->isDivergent()) {
5387     // Select to V_MAD_[IU]64_[IU]32.
5388     return Op;
5389   }
5390   if (Subtarget->hasSMulHi()) {
5391     // Expand to S_MUL_I32 + S_MUL_HI_[IU]32.
5392     return SDValue();
5393   }
5394   // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to
5395   // calculate the high part, so we might as well do the whole thing with
5396   // V_MAD_[IU]64_[IU]32.
5397   return Op;
5398 }
5399 
5400 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5401   if (!Subtarget->isTrapHandlerEnabled() ||
5402       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5403     return lowerTrapEndpgm(Op, DAG);
5404 
5405   if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) {
5406     switch (*HsaAbiVer) {
5407     case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
5408     case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
5409       return lowerTrapHsaQueuePtr(Op, DAG);
5410     case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
5411     case ELF::ELFABIVERSION_AMDGPU_HSA_V5:
5412       return Subtarget->supportsGetDoorbellID() ?
5413           lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG);
5414     }
5415   }
5416 
5417   llvm_unreachable("Unknown trap handler");
5418 }
5419 
5420 SDValue SITargetLowering::lowerTrapEndpgm(
5421     SDValue Op, SelectionDAG &DAG) const {
5422   SDLoc SL(Op);
5423   SDValue Chain = Op.getOperand(0);
5424   return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5425 }
5426 
5427 SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5428     SDValue Op, SelectionDAG &DAG) const {
5429   SDLoc SL(Op);
5430   SDValue Chain = Op.getOperand(0);
5431 
5432   MachineFunction &MF = DAG.getMachineFunction();
5433   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5434   Register UserSGPR = Info->getQueuePtrUserSGPR();
5435 
5436   SDValue QueuePtr;
5437   if (UserSGPR == AMDGPU::NoRegister) {
5438     // We probably are in a function incorrectly marked with
5439     // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the trap,
5440     // so just use a null pointer.
5441     QueuePtr = DAG.getConstant(0, SL, MVT::i64);
5442   } else {
5443     QueuePtr = CreateLiveInRegister(
5444       DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5445   }
5446 
5447   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5448   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5449                                    QueuePtr, SDValue());
5450 
5451   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5452   SDValue Ops[] = {
5453     ToReg,
5454     DAG.getTargetConstant(TrapID, SL, MVT::i16),
5455     SGPR01,
5456     ToReg.getValue(1)
5457   };
5458   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5459 }
5460 
5461 SDValue SITargetLowering::lowerTrapHsa(
5462     SDValue Op, SelectionDAG &DAG) const {
5463   SDLoc SL(Op);
5464   SDValue Chain = Op.getOperand(0);
5465 
5466   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5467   SDValue Ops[] = {
5468     Chain,
5469     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5470   };
5471   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5472 }
5473 
5474 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5475   SDLoc SL(Op);
5476   SDValue Chain = Op.getOperand(0);
5477   MachineFunction &MF = DAG.getMachineFunction();
5478 
5479   if (!Subtarget->isTrapHandlerEnabled() ||
5480       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5481     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5482                                      "debugtrap handler not supported",
5483                                      Op.getDebugLoc(),
5484                                      DS_Warning);
5485     LLVMContext &Ctx = MF.getFunction().getContext();
5486     Ctx.diagnose(NoTrap);
5487     return Chain;
5488   }
5489 
5490   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5491   SDValue Ops[] = {
5492     Chain,
5493     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5494   };
5495   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5496 }
5497 
5498 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5499                                              SelectionDAG &DAG) const {
5500   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5501   if (Subtarget->hasApertureRegs()) {
5502     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5503         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5504         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5505     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5506         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5507         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5508     unsigned Encoding =
5509         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5510         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5511         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5512 
5513     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5514     SDValue ApertureReg = SDValue(
5515         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5516     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5517     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5518   }
5519 
5520   MachineFunction &MF = DAG.getMachineFunction();
5521   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5522   Register UserSGPR = Info->getQueuePtrUserSGPR();
5523   if (UserSGPR == AMDGPU::NoRegister) {
5524     // We probably are in a function incorrectly marked with
5525     // amdgpu-no-queue-ptr. This is undefined.
5526     return DAG.getUNDEF(MVT::i32);
5527   }
5528 
5529   SDValue QueuePtr = CreateLiveInRegister(
5530     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5531 
5532   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5533   // private_segment_aperture_base_hi.
5534   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5535 
5536   SDValue Ptr =
5537       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5538 
5539   // TODO: Use custom target PseudoSourceValue.
5540   // TODO: We should use the value from the IR intrinsic call, but it might not
5541   // be available and how do we get it?
5542   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5543   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5544                      commonAlignment(Align(64), StructOffset),
5545                      MachineMemOperand::MODereferenceable |
5546                          MachineMemOperand::MOInvariant);
5547 }
5548 
5549 /// Return true if the value is a known valid address, such that a null check is
5550 /// not necessary.
5551 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG,
5552                            const AMDGPUTargetMachine &TM, unsigned AddrSpace) {
5553   if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) ||
5554       isa<BasicBlockSDNode>(Val))
5555     return true;
5556 
5557   if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val))
5558     return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace);
5559 
5560   // TODO: Search through arithmetic, handle arguments and loads
5561   // marked nonnull.
5562   return false;
5563 }
5564 
5565 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5566                                              SelectionDAG &DAG) const {
5567   SDLoc SL(Op);
5568   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5569 
5570   SDValue Src = ASC->getOperand(0);
5571   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5572   unsigned SrcAS = ASC->getSrcAddressSpace();
5573 
5574   const AMDGPUTargetMachine &TM =
5575     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5576 
5577   // flat -> local/private
5578   if (SrcAS == AMDGPUAS::FLAT_ADDRESS) {
5579     unsigned DestAS = ASC->getDestAddressSpace();
5580 
5581     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5582         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5583       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5584 
5585       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5586         return Ptr;
5587 
5588       unsigned NullVal = TM.getNullPointerValue(DestAS);
5589       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5590       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5591 
5592       return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr,
5593                          SegmentNullPtr);
5594     }
5595   }
5596 
5597   // local/private -> flat
5598   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5599     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5600         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5601 
5602       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5603       SDValue CvtPtr =
5604           DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5605       CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr);
5606 
5607       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5608         return CvtPtr;
5609 
5610       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5611       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5612 
5613       SDValue NonNull
5614         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5615 
5616       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr,
5617                          FlatNullPtr);
5618     }
5619   }
5620 
5621   if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5622       Op.getValueType() == MVT::i64) {
5623     const SIMachineFunctionInfo *Info =
5624         DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>();
5625     SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32);
5626     SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi);
5627     return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
5628   }
5629 
5630   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5631       Src.getValueType() == MVT::i64)
5632     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5633 
5634   // global <-> flat are no-ops and never emitted.
5635 
5636   const MachineFunction &MF = DAG.getMachineFunction();
5637   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5638     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5639   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5640 
5641   return DAG.getUNDEF(ASC->getValueType(0));
5642 }
5643 
5644 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5645 // the small vector and inserting them into the big vector. That is better than
5646 // the default expansion of doing it via a stack slot. Even though the use of
5647 // the stack slot would be optimized away afterwards, the stack slot itself
5648 // remains.
5649 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5650                                                 SelectionDAG &DAG) const {
5651   SDValue Vec = Op.getOperand(0);
5652   SDValue Ins = Op.getOperand(1);
5653   SDValue Idx = Op.getOperand(2);
5654   EVT VecVT = Vec.getValueType();
5655   EVT InsVT = Ins.getValueType();
5656   EVT EltVT = VecVT.getVectorElementType();
5657   unsigned InsNumElts = InsVT.getVectorNumElements();
5658   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5659   SDLoc SL(Op);
5660 
5661   for (unsigned I = 0; I != InsNumElts; ++I) {
5662     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5663                               DAG.getConstant(I, SL, MVT::i32));
5664     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5665                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5666   }
5667   return Vec;
5668 }
5669 
5670 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5671                                                  SelectionDAG &DAG) const {
5672   SDValue Vec = Op.getOperand(0);
5673   SDValue InsVal = Op.getOperand(1);
5674   SDValue Idx = Op.getOperand(2);
5675   EVT VecVT = Vec.getValueType();
5676   EVT EltVT = VecVT.getVectorElementType();
5677   unsigned VecSize = VecVT.getSizeInBits();
5678   unsigned EltSize = EltVT.getSizeInBits();
5679 
5680 
5681   assert(VecSize <= 64);
5682 
5683   unsigned NumElts = VecVT.getVectorNumElements();
5684   SDLoc SL(Op);
5685   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5686 
5687   if (NumElts == 4 && EltSize == 16 && KIdx) {
5688     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5689 
5690     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5691                                  DAG.getConstant(0, SL, MVT::i32));
5692     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5693                                  DAG.getConstant(1, SL, MVT::i32));
5694 
5695     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5696     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5697 
5698     unsigned Idx = KIdx->getZExtValue();
5699     bool InsertLo = Idx < 2;
5700     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5701       InsertLo ? LoVec : HiVec,
5702       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5703       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5704 
5705     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5706 
5707     SDValue Concat = InsertLo ?
5708       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5709       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5710 
5711     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5712   }
5713 
5714   if (isa<ConstantSDNode>(Idx))
5715     return SDValue();
5716 
5717   MVT IntVT = MVT::getIntegerVT(VecSize);
5718 
5719   // Avoid stack access for dynamic indexing.
5720   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5721 
5722   // Create a congruent vector with the target value in each element so that
5723   // the required element can be masked and ORed into the target vector.
5724   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5725                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5726 
5727   assert(isPowerOf2_32(EltSize));
5728   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5729 
5730   // Convert vector index to bit-index.
5731   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5732 
5733   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5734   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5735                             DAG.getConstant(0xffff, SL, IntVT),
5736                             ScaledIdx);
5737 
5738   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5739   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5740                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5741 
5742   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5743   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5744 }
5745 
5746 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5747                                                   SelectionDAG &DAG) const {
5748   SDLoc SL(Op);
5749 
5750   EVT ResultVT = Op.getValueType();
5751   SDValue Vec = Op.getOperand(0);
5752   SDValue Idx = Op.getOperand(1);
5753   EVT VecVT = Vec.getValueType();
5754   unsigned VecSize = VecVT.getSizeInBits();
5755   EVT EltVT = VecVT.getVectorElementType();
5756 
5757   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5758 
5759   // Make sure we do any optimizations that will make it easier to fold
5760   // source modifiers before obscuring it with bit operations.
5761 
5762   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5763   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5764     return Combined;
5765 
5766   if (VecSize == 128) {
5767     SDValue Lo, Hi;
5768     EVT LoVT, HiVT;
5769     SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec);
5770     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5771     Lo =
5772         DAG.getBitcast(LoVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5773                                          V2, DAG.getConstant(0, SL, MVT::i32)));
5774     Hi =
5775         DAG.getBitcast(HiVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5776                                          V2, DAG.getConstant(1, SL, MVT::i32)));
5777     EVT IdxVT = Idx.getValueType();
5778     unsigned NElem = VecVT.getVectorNumElements();
5779     assert(isPowerOf2_32(NElem));
5780     SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT);
5781     SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask);
5782     SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT);
5783     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx);
5784   }
5785 
5786   assert(VecSize <= 64);
5787 
5788   unsigned EltSize = EltVT.getSizeInBits();
5789   assert(isPowerOf2_32(EltSize));
5790 
5791   MVT IntVT = MVT::getIntegerVT(VecSize);
5792   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5793 
5794   // Convert vector index to bit-index (* EltSize)
5795   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5796 
5797   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5798   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5799 
5800   if (ResultVT == MVT::f16) {
5801     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5802     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5803   }
5804 
5805   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5806 }
5807 
5808 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5809   assert(Elt % 2 == 0);
5810   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5811 }
5812 
5813 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5814                                               SelectionDAG &DAG) const {
5815   SDLoc SL(Op);
5816   EVT ResultVT = Op.getValueType();
5817   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5818 
5819   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5820   EVT EltVT = PackVT.getVectorElementType();
5821   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5822 
5823   // vector_shuffle <0,1,6,7> lhs, rhs
5824   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5825   //
5826   // vector_shuffle <6,7,2,3> lhs, rhs
5827   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5828   //
5829   // vector_shuffle <6,7,0,1> lhs, rhs
5830   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5831 
5832   // Avoid scalarizing when both halves are reading from consecutive elements.
5833   SmallVector<SDValue, 4> Pieces;
5834   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5835     if (elementPairIsContiguous(SVN->getMask(), I)) {
5836       const int Idx = SVN->getMaskElt(I);
5837       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5838       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5839       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5840                                     PackVT, SVN->getOperand(VecIdx),
5841                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5842       Pieces.push_back(SubVec);
5843     } else {
5844       const int Idx0 = SVN->getMaskElt(I);
5845       const int Idx1 = SVN->getMaskElt(I + 1);
5846       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5847       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5848       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5849       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5850 
5851       SDValue Vec0 = SVN->getOperand(VecIdx0);
5852       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5853                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5854 
5855       SDValue Vec1 = SVN->getOperand(VecIdx1);
5856       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5857                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5858       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5859     }
5860   }
5861 
5862   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5863 }
5864 
5865 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5866                                             SelectionDAG &DAG) const {
5867   SDLoc SL(Op);
5868   EVT VT = Op.getValueType();
5869 
5870   if (VT == MVT::v4i16 || VT == MVT::v4f16 ||
5871       VT == MVT::v8i16 || VT == MVT::v8f16) {
5872     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(),
5873                                   VT.getVectorNumElements() / 2);
5874     MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits());
5875 
5876     // Turn into pair of packed build_vectors.
5877     // TODO: Special case for constants that can be materialized with s_mov_b64.
5878     SmallVector<SDValue, 4> LoOps, HiOps;
5879     for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) {
5880       LoOps.push_back(Op.getOperand(I));
5881       HiOps.push_back(Op.getOperand(I + E));
5882     }
5883     SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps);
5884     SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps);
5885 
5886     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo);
5887     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi);
5888 
5889     SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL,
5890                                        { CastLo, CastHi });
5891     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5892   }
5893 
5894   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5895   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5896 
5897   SDValue Lo = Op.getOperand(0);
5898   SDValue Hi = Op.getOperand(1);
5899 
5900   // Avoid adding defined bits with the zero_extend.
5901   if (Hi.isUndef()) {
5902     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5903     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5904     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5905   }
5906 
5907   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5908   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5909 
5910   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5911                               DAG.getConstant(16, SL, MVT::i32));
5912   if (Lo.isUndef())
5913     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5914 
5915   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5916   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5917 
5918   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5919   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5920 }
5921 
5922 bool
5923 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5924   // We can fold offsets for anything that doesn't require a GOT relocation.
5925   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5926           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5927           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5928          !shouldEmitGOTReloc(GA->getGlobal());
5929 }
5930 
5931 static SDValue
5932 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5933                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5934                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5935   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5936   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5937   // lowered to the following code sequence:
5938   //
5939   // For constant address space:
5940   //   s_getpc_b64 s[0:1]
5941   //   s_add_u32 s0, s0, $symbol
5942   //   s_addc_u32 s1, s1, 0
5943   //
5944   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5945   //   a fixup or relocation is emitted to replace $symbol with a literal
5946   //   constant, which is a pc-relative offset from the encoding of the $symbol
5947   //   operand to the global variable.
5948   //
5949   // For global address space:
5950   //   s_getpc_b64 s[0:1]
5951   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5952   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5953   //
5954   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5955   //   fixups or relocations are emitted to replace $symbol@*@lo and
5956   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5957   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5958   //   operand to the global variable.
5959   //
5960   // What we want here is an offset from the value returned by s_getpc
5961   // (which is the address of the s_add_u32 instruction) to the global
5962   // variable, but since the encoding of $symbol starts 4 bytes after the start
5963   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5964   // small. This requires us to add 4 to the global variable offset in order to
5965   // compute the correct address. Similarly for the s_addc_u32 instruction, the
5966   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
5967   // instruction.
5968   SDValue PtrLo =
5969       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5970   SDValue PtrHi;
5971   if (GAFlags == SIInstrInfo::MO_NONE) {
5972     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5973   } else {
5974     PtrHi =
5975         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
5976   }
5977   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5978 }
5979 
5980 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5981                                              SDValue Op,
5982                                              SelectionDAG &DAG) const {
5983   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5984   SDLoc DL(GSD);
5985   EVT PtrVT = Op.getValueType();
5986 
5987   const GlobalValue *GV = GSD->getGlobal();
5988   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5989        shouldUseLDSConstAddress(GV)) ||
5990       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5991       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
5992     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5993         GV->hasExternalLinkage()) {
5994       Type *Ty = GV->getValueType();
5995       // HIP uses an unsized array `extern __shared__ T s[]` or similar
5996       // zero-sized type in other languages to declare the dynamic shared
5997       // memory which size is not known at the compile time. They will be
5998       // allocated by the runtime and placed directly after the static
5999       // allocated ones. They all share the same offset.
6000       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
6001         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
6002         // Adjust alignment for that dynamic shared memory array.
6003         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
6004         return SDValue(
6005             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
6006       }
6007     }
6008     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
6009   }
6010 
6011   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
6012     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
6013                                             SIInstrInfo::MO_ABS32_LO);
6014     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
6015   }
6016 
6017   if (shouldEmitFixup(GV))
6018     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
6019   else if (shouldEmitPCReloc(GV))
6020     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
6021                                    SIInstrInfo::MO_REL32);
6022 
6023   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
6024                                             SIInstrInfo::MO_GOTPCREL32);
6025 
6026   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
6027   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
6028   const DataLayout &DataLayout = DAG.getDataLayout();
6029   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
6030   MachinePointerInfo PtrInfo
6031     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
6032 
6033   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
6034                      MachineMemOperand::MODereferenceable |
6035                          MachineMemOperand::MOInvariant);
6036 }
6037 
6038 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
6039                                    const SDLoc &DL, SDValue V) const {
6040   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
6041   // the destination register.
6042   //
6043   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
6044   // so we will end up with redundant moves to m0.
6045   //
6046   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
6047 
6048   // A Null SDValue creates a glue result.
6049   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
6050                                   V, Chain);
6051   return SDValue(M0, 0);
6052 }
6053 
6054 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
6055                                                  SDValue Op,
6056                                                  MVT VT,
6057                                                  unsigned Offset) const {
6058   SDLoc SL(Op);
6059   SDValue Param = lowerKernargMemParameter(
6060       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
6061   // The local size values will have the hi 16-bits as zero.
6062   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
6063                      DAG.getValueType(VT));
6064 }
6065 
6066 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6067                                         EVT VT) {
6068   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6069                                       "non-hsa intrinsic with hsa target",
6070                                       DL.getDebugLoc());
6071   DAG.getContext()->diagnose(BadIntrin);
6072   return DAG.getUNDEF(VT);
6073 }
6074 
6075 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6076                                          EVT VT) {
6077   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6078                                       "intrinsic not supported on subtarget",
6079                                       DL.getDebugLoc());
6080   DAG.getContext()->diagnose(BadIntrin);
6081   return DAG.getUNDEF(VT);
6082 }
6083 
6084 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
6085                                     ArrayRef<SDValue> Elts) {
6086   assert(!Elts.empty());
6087   MVT Type;
6088   unsigned NumElts = Elts.size();
6089 
6090   if (NumElts <= 8) {
6091     Type = MVT::getVectorVT(MVT::f32, NumElts);
6092   } else {
6093     assert(Elts.size() <= 16);
6094     Type = MVT::v16f32;
6095     NumElts = 16;
6096   }
6097 
6098   SmallVector<SDValue, 16> VecElts(NumElts);
6099   for (unsigned i = 0; i < Elts.size(); ++i) {
6100     SDValue Elt = Elts[i];
6101     if (Elt.getValueType() != MVT::f32)
6102       Elt = DAG.getBitcast(MVT::f32, Elt);
6103     VecElts[i] = Elt;
6104   }
6105   for (unsigned i = Elts.size(); i < NumElts; ++i)
6106     VecElts[i] = DAG.getUNDEF(MVT::f32);
6107 
6108   if (NumElts == 1)
6109     return VecElts[0];
6110   return DAG.getBuildVector(Type, DL, VecElts);
6111 }
6112 
6113 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
6114                               SDValue Src, int ExtraElts) {
6115   EVT SrcVT = Src.getValueType();
6116 
6117   SmallVector<SDValue, 8> Elts;
6118 
6119   if (SrcVT.isVector())
6120     DAG.ExtractVectorElements(Src, Elts);
6121   else
6122     Elts.push_back(Src);
6123 
6124   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
6125   while (ExtraElts--)
6126     Elts.push_back(Undef);
6127 
6128   return DAG.getBuildVector(CastVT, DL, Elts);
6129 }
6130 
6131 // Re-construct the required return value for a image load intrinsic.
6132 // This is more complicated due to the optional use TexFailCtrl which means the required
6133 // return type is an aggregate
6134 static SDValue constructRetValue(SelectionDAG &DAG,
6135                                  MachineSDNode *Result,
6136                                  ArrayRef<EVT> ResultTypes,
6137                                  bool IsTexFail, bool Unpacked, bool IsD16,
6138                                  int DMaskPop, int NumVDataDwords,
6139                                  const SDLoc &DL) {
6140   // Determine the required return type. This is the same regardless of IsTexFail flag
6141   EVT ReqRetVT = ResultTypes[0];
6142   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
6143   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6144     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
6145 
6146   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6147     DMaskPop : (DMaskPop + 1) / 2;
6148 
6149   MVT DataDwordVT = NumDataDwords == 1 ?
6150     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
6151 
6152   MVT MaskPopVT = MaskPopDwords == 1 ?
6153     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
6154 
6155   SDValue Data(Result, 0);
6156   SDValue TexFail;
6157 
6158   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
6159     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
6160     if (MaskPopVT.isVector()) {
6161       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
6162                          SDValue(Result, 0), ZeroIdx);
6163     } else {
6164       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
6165                          SDValue(Result, 0), ZeroIdx);
6166     }
6167   }
6168 
6169   if (DataDwordVT.isVector())
6170     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
6171                           NumDataDwords - MaskPopDwords);
6172 
6173   if (IsD16)
6174     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
6175 
6176   EVT LegalReqRetVT = ReqRetVT;
6177   if (!ReqRetVT.isVector()) {
6178     if (!Data.getValueType().isInteger())
6179       Data = DAG.getNode(ISD::BITCAST, DL,
6180                          Data.getValueType().changeTypeToInteger(), Data);
6181     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
6182   } else {
6183     // We need to widen the return vector to a legal type
6184     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
6185         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
6186       LegalReqRetVT =
6187           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
6188                            ReqRetVT.getVectorNumElements() + 1);
6189     }
6190   }
6191   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
6192 
6193   if (IsTexFail) {
6194     TexFail =
6195         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
6196                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
6197 
6198     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
6199   }
6200 
6201   if (Result->getNumValues() == 1)
6202     return Data;
6203 
6204   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
6205 }
6206 
6207 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
6208                          SDValue *LWE, bool &IsTexFail) {
6209   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
6210 
6211   uint64_t Value = TexFailCtrlConst->getZExtValue();
6212   if (Value) {
6213     IsTexFail = true;
6214   }
6215 
6216   SDLoc DL(TexFailCtrlConst);
6217   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
6218   Value &= ~(uint64_t)0x1;
6219   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
6220   Value &= ~(uint64_t)0x2;
6221 
6222   return Value == 0;
6223 }
6224 
6225 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
6226                                       MVT PackVectorVT,
6227                                       SmallVectorImpl<SDValue> &PackedAddrs,
6228                                       unsigned DimIdx, unsigned EndIdx,
6229                                       unsigned NumGradients) {
6230   SDLoc DL(Op);
6231   for (unsigned I = DimIdx; I < EndIdx; I++) {
6232     SDValue Addr = Op.getOperand(I);
6233 
6234     // Gradients are packed with undef for each coordinate.
6235     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
6236     // 1D: undef,dx/dh; undef,dx/dv
6237     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
6238     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
6239     if (((I + 1) >= EndIdx) ||
6240         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
6241                                          I == DimIdx + NumGradients - 1))) {
6242       if (Addr.getValueType() != MVT::i16)
6243         Addr = DAG.getBitcast(MVT::i16, Addr);
6244       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
6245     } else {
6246       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
6247       I++;
6248     }
6249     Addr = DAG.getBitcast(MVT::f32, Addr);
6250     PackedAddrs.push_back(Addr);
6251   }
6252 }
6253 
6254 SDValue SITargetLowering::lowerImage(SDValue Op,
6255                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
6256                                      SelectionDAG &DAG, bool WithChain) const {
6257   SDLoc DL(Op);
6258   MachineFunction &MF = DAG.getMachineFunction();
6259   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
6260   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
6261       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
6262   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
6263   unsigned IntrOpcode = Intr->BaseOpcode;
6264   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6265 
6266   SmallVector<EVT, 3> ResultTypes(Op->values());
6267   SmallVector<EVT, 3> OrigResultTypes(Op->values());
6268   bool IsD16 = false;
6269   bool IsG16 = false;
6270   bool IsA16 = false;
6271   SDValue VData;
6272   int NumVDataDwords;
6273   bool AdjustRetType = false;
6274 
6275   // Offset of intrinsic arguments
6276   const unsigned ArgOffset = WithChain ? 2 : 1;
6277 
6278   unsigned DMask;
6279   unsigned DMaskLanes = 0;
6280 
6281   if (BaseOpcode->Atomic) {
6282     VData = Op.getOperand(2);
6283 
6284     bool Is64Bit = VData.getValueType() == MVT::i64;
6285     if (BaseOpcode->AtomicX2) {
6286       SDValue VData2 = Op.getOperand(3);
6287       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6288                                  {VData, VData2});
6289       if (Is64Bit)
6290         VData = DAG.getBitcast(MVT::v4i32, VData);
6291 
6292       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6293       DMask = Is64Bit ? 0xf : 0x3;
6294       NumVDataDwords = Is64Bit ? 4 : 2;
6295     } else {
6296       DMask = Is64Bit ? 0x3 : 0x1;
6297       NumVDataDwords = Is64Bit ? 2 : 1;
6298     }
6299   } else {
6300     auto *DMaskConst =
6301         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6302     DMask = DMaskConst->getZExtValue();
6303     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6304 
6305     if (BaseOpcode->Store) {
6306       VData = Op.getOperand(2);
6307 
6308       MVT StoreVT = VData.getSimpleValueType();
6309       if (StoreVT.getScalarType() == MVT::f16) {
6310         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6311           return Op; // D16 is unsupported for this instruction
6312 
6313         IsD16 = true;
6314         VData = handleD16VData(VData, DAG, true);
6315       }
6316 
6317       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6318     } else {
6319       // Work out the num dwords based on the dmask popcount and underlying type
6320       // and whether packing is supported.
6321       MVT LoadVT = ResultTypes[0].getSimpleVT();
6322       if (LoadVT.getScalarType() == MVT::f16) {
6323         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6324           return Op; // D16 is unsupported for this instruction
6325 
6326         IsD16 = true;
6327       }
6328 
6329       // Confirm that the return type is large enough for the dmask specified
6330       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6331           (!LoadVT.isVector() && DMaskLanes > 1))
6332           return Op;
6333 
6334       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6335       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6336       // instructions.
6337       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6338           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6339         NumVDataDwords = (DMaskLanes + 1) / 2;
6340       else
6341         NumVDataDwords = DMaskLanes;
6342 
6343       AdjustRetType = true;
6344     }
6345   }
6346 
6347   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6348   SmallVector<SDValue, 4> VAddrs;
6349 
6350   // Check for 16 bit addresses or derivatives and pack if true.
6351   MVT VAddrVT =
6352       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6353   MVT VAddrScalarVT = VAddrVT.getScalarType();
6354   MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6355   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6356 
6357   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6358   VAddrScalarVT = VAddrVT.getScalarType();
6359   MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6360   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6361 
6362   // Push back extra arguments.
6363   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) {
6364     if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) {
6365       assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument");
6366       // Special handling of bias when A16 is on. Bias is of type half but
6367       // occupies full 32-bit.
6368       SDValue Bias = DAG.getBuildVector(
6369           MVT::v2f16, DL,
6370           {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)});
6371       VAddrs.push_back(Bias);
6372     } else {
6373       assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) &&
6374              "Bias needs to be converted to 16 bit in A16 mode");
6375       VAddrs.push_back(Op.getOperand(ArgOffset + I));
6376     }
6377   }
6378 
6379   if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
6380     // 16 bit gradients are supported, but are tied to the A16 control
6381     // so both gradients and addresses must be 16 bit
6382     LLVM_DEBUG(
6383         dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6384                   "require 16 bit args for both gradients and addresses");
6385     return Op;
6386   }
6387 
6388   if (IsA16) {
6389     if (!ST->hasA16()) {
6390       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6391                            "support 16 bit addresses\n");
6392       return Op;
6393     }
6394   }
6395 
6396   // We've dealt with incorrect input so we know that if IsA16, IsG16
6397   // are set then we have to compress/pack operands (either address,
6398   // gradient or both)
6399   // In the case where a16 and gradients are tied (no G16 support) then we
6400   // have already verified that both IsA16 and IsG16 are true
6401   if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
6402     // Activate g16
6403     const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6404         AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6405     IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6406   }
6407 
6408   // Add gradients (packed or unpacked)
6409   if (IsG16) {
6410     // Pack the gradients
6411     // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6412     packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
6413                               ArgOffset + Intr->GradientStart,
6414                               ArgOffset + Intr->CoordStart, Intr->NumGradients);
6415   } else {
6416     for (unsigned I = ArgOffset + Intr->GradientStart;
6417          I < ArgOffset + Intr->CoordStart; I++)
6418       VAddrs.push_back(Op.getOperand(I));
6419   }
6420 
6421   // Add addresses (packed or unpacked)
6422   if (IsA16) {
6423     packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
6424                               ArgOffset + Intr->CoordStart, VAddrEnd,
6425                               0 /* No gradients */);
6426   } else {
6427     // Add uncompressed address
6428     for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6429       VAddrs.push_back(Op.getOperand(I));
6430   }
6431 
6432   // If the register allocator cannot place the address registers contiguously
6433   // without introducing moves, then using the non-sequential address encoding
6434   // is always preferable, since it saves VALU instructions and is usually a
6435   // wash in terms of code size or even better.
6436   //
6437   // However, we currently have no way of hinting to the register allocator that
6438   // MIMG addresses should be placed contiguously when it is possible to do so,
6439   // so force non-NSA for the common 2-address case as a heuristic.
6440   //
6441   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6442   // allocation when possible.
6443   bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) &&
6444                 VAddrs.size() >= 3 &&
6445                 VAddrs.size() <= (unsigned)ST->getNSAMaxSize();
6446   SDValue VAddr;
6447   if (!UseNSA)
6448     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6449 
6450   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6451   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6452   SDValue Unorm;
6453   if (!BaseOpcode->Sampler) {
6454     Unorm = True;
6455   } else {
6456     auto UnormConst =
6457         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6458 
6459     Unorm = UnormConst->getZExtValue() ? True : False;
6460   }
6461 
6462   SDValue TFE;
6463   SDValue LWE;
6464   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6465   bool IsTexFail = false;
6466   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6467     return Op;
6468 
6469   if (IsTexFail) {
6470     if (!DMaskLanes) {
6471       // Expecting to get an error flag since TFC is on - and dmask is 0
6472       // Force dmask to be at least 1 otherwise the instruction will fail
6473       DMask = 0x1;
6474       DMaskLanes = 1;
6475       NumVDataDwords = 1;
6476     }
6477     NumVDataDwords += 1;
6478     AdjustRetType = true;
6479   }
6480 
6481   // Has something earlier tagged that the return type needs adjusting
6482   // This happens if the instruction is a load or has set TexFailCtrl flags
6483   if (AdjustRetType) {
6484     // NumVDataDwords reflects the true number of dwords required in the return type
6485     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6486       // This is a no-op load. This can be eliminated
6487       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6488       if (isa<MemSDNode>(Op))
6489         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6490       return Undef;
6491     }
6492 
6493     EVT NewVT = NumVDataDwords > 1 ?
6494                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6495                 : MVT::i32;
6496 
6497     ResultTypes[0] = NewVT;
6498     if (ResultTypes.size() == 3) {
6499       // Original result was aggregate type used for TexFailCtrl results
6500       // The actual instruction returns as a vector type which has now been
6501       // created. Remove the aggregate result.
6502       ResultTypes.erase(&ResultTypes[1]);
6503     }
6504   }
6505 
6506   unsigned CPol = cast<ConstantSDNode>(
6507       Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6508   if (BaseOpcode->Atomic)
6509     CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6510   if (CPol & ~AMDGPU::CPol::ALL)
6511     return Op;
6512 
6513   SmallVector<SDValue, 26> Ops;
6514   if (BaseOpcode->Store || BaseOpcode->Atomic)
6515     Ops.push_back(VData); // vdata
6516   if (UseNSA)
6517     append_range(Ops, VAddrs);
6518   else
6519     Ops.push_back(VAddr);
6520   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6521   if (BaseOpcode->Sampler)
6522     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6523   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6524   if (IsGFX10Plus)
6525     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6526   Ops.push_back(Unorm);
6527   Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6528   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6529                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6530   if (IsGFX10Plus)
6531     Ops.push_back(IsA16 ? True : False);
6532   if (!Subtarget->hasGFX90AInsts()) {
6533     Ops.push_back(TFE); //tfe
6534   } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6535     report_fatal_error("TFE is not supported on this GPU");
6536   }
6537   Ops.push_back(LWE); // lwe
6538   if (!IsGFX10Plus)
6539     Ops.push_back(DimInfo->DA ? True : False);
6540   if (BaseOpcode->HasD16)
6541     Ops.push_back(IsD16 ? True : False);
6542   if (isa<MemSDNode>(Op))
6543     Ops.push_back(Op.getOperand(0)); // chain
6544 
6545   int NumVAddrDwords =
6546       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6547   int Opcode = -1;
6548 
6549   if (IsGFX10Plus) {
6550     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6551                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6552                                           : AMDGPU::MIMGEncGfx10Default,
6553                                    NumVDataDwords, NumVAddrDwords);
6554   } else {
6555     if (Subtarget->hasGFX90AInsts()) {
6556       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6557                                      NumVDataDwords, NumVAddrDwords);
6558       if (Opcode == -1)
6559         report_fatal_error(
6560             "requested image instruction is not supported on this GPU");
6561     }
6562     if (Opcode == -1 &&
6563         Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6564       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6565                                      NumVDataDwords, NumVAddrDwords);
6566     if (Opcode == -1)
6567       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6568                                      NumVDataDwords, NumVAddrDwords);
6569   }
6570   assert(Opcode != -1);
6571 
6572   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6573   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6574     MachineMemOperand *MemRef = MemOp->getMemOperand();
6575     DAG.setNodeMemRefs(NewNode, {MemRef});
6576   }
6577 
6578   if (BaseOpcode->AtomicX2) {
6579     SmallVector<SDValue, 1> Elt;
6580     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6581     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6582   }
6583   if (BaseOpcode->Store)
6584     return SDValue(NewNode, 0);
6585   return constructRetValue(DAG, NewNode,
6586                            OrigResultTypes, IsTexFail,
6587                            Subtarget->hasUnpackedD16VMem(), IsD16,
6588                            DMaskLanes, NumVDataDwords, DL);
6589 }
6590 
6591 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6592                                        SDValue Offset, SDValue CachePolicy,
6593                                        SelectionDAG &DAG) const {
6594   MachineFunction &MF = DAG.getMachineFunction();
6595 
6596   const DataLayout &DataLayout = DAG.getDataLayout();
6597   Align Alignment =
6598       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6599 
6600   MachineMemOperand *MMO = MF.getMachineMemOperand(
6601       MachinePointerInfo(),
6602       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6603           MachineMemOperand::MOInvariant,
6604       VT.getStoreSize(), Alignment);
6605 
6606   if (!Offset->isDivergent()) {
6607     SDValue Ops[] = {
6608         Rsrc,
6609         Offset, // Offset
6610         CachePolicy
6611     };
6612 
6613     // Widen vec3 load to vec4.
6614     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6615       EVT WidenedVT =
6616           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6617       auto WidenedOp = DAG.getMemIntrinsicNode(
6618           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6619           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6620       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6621                                    DAG.getVectorIdxConstant(0, DL));
6622       return Subvector;
6623     }
6624 
6625     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6626                                    DAG.getVTList(VT), Ops, VT, MMO);
6627   }
6628 
6629   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6630   // assume that the buffer is unswizzled.
6631   SmallVector<SDValue, 4> Loads;
6632   unsigned NumLoads = 1;
6633   MVT LoadVT = VT.getSimpleVT();
6634   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6635   assert((LoadVT.getScalarType() == MVT::i32 ||
6636           LoadVT.getScalarType() == MVT::f32));
6637 
6638   if (NumElts == 8 || NumElts == 16) {
6639     NumLoads = NumElts / 4;
6640     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6641   }
6642 
6643   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6644   SDValue Ops[] = {
6645       DAG.getEntryNode(),                               // Chain
6646       Rsrc,                                             // rsrc
6647       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6648       {},                                               // voffset
6649       {},                                               // soffset
6650       {},                                               // offset
6651       CachePolicy,                                      // cachepolicy
6652       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6653   };
6654 
6655   // Use the alignment to ensure that the required offsets will fit into the
6656   // immediate offsets.
6657   setBufferOffsets(Offset, DAG, &Ops[3],
6658                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6659 
6660   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6661   for (unsigned i = 0; i < NumLoads; ++i) {
6662     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6663     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6664                                         LoadVT, MMO, DAG));
6665   }
6666 
6667   if (NumElts == 8 || NumElts == 16)
6668     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6669 
6670   return Loads[0];
6671 }
6672 
6673 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6674                                                   SelectionDAG &DAG) const {
6675   MachineFunction &MF = DAG.getMachineFunction();
6676   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6677 
6678   EVT VT = Op.getValueType();
6679   SDLoc DL(Op);
6680   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6681 
6682   // TODO: Should this propagate fast-math-flags?
6683 
6684   switch (IntrinsicID) {
6685   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6686     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6687       return emitNonHSAIntrinsicError(DAG, DL, VT);
6688     return getPreloadedValue(DAG, *MFI, VT,
6689                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6690   }
6691   case Intrinsic::amdgcn_dispatch_ptr:
6692   case Intrinsic::amdgcn_queue_ptr: {
6693     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6694       DiagnosticInfoUnsupported BadIntrin(
6695           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6696           DL.getDebugLoc());
6697       DAG.getContext()->diagnose(BadIntrin);
6698       return DAG.getUNDEF(VT);
6699     }
6700 
6701     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6702       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6703     return getPreloadedValue(DAG, *MFI, VT, RegID);
6704   }
6705   case Intrinsic::amdgcn_implicitarg_ptr: {
6706     if (MFI->isEntryFunction())
6707       return getImplicitArgPtr(DAG, DL);
6708     return getPreloadedValue(DAG, *MFI, VT,
6709                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6710   }
6711   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6712     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6713       // This only makes sense to call in a kernel, so just lower to null.
6714       return DAG.getConstant(0, DL, VT);
6715     }
6716 
6717     return getPreloadedValue(DAG, *MFI, VT,
6718                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6719   }
6720   case Intrinsic::amdgcn_dispatch_id: {
6721     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6722   }
6723   case Intrinsic::amdgcn_rcp:
6724     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6725   case Intrinsic::amdgcn_rsq:
6726     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6727   case Intrinsic::amdgcn_rsq_legacy:
6728     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6729       return emitRemovedIntrinsicError(DAG, DL, VT);
6730     return SDValue();
6731   case Intrinsic::amdgcn_rcp_legacy:
6732     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6733       return emitRemovedIntrinsicError(DAG, DL, VT);
6734     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6735   case Intrinsic::amdgcn_rsq_clamp: {
6736     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6737       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6738 
6739     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6740     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6741     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6742 
6743     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6744     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6745                               DAG.getConstantFP(Max, DL, VT));
6746     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6747                        DAG.getConstantFP(Min, DL, VT));
6748   }
6749   case Intrinsic::r600_read_ngroups_x:
6750     if (Subtarget->isAmdHsaOS())
6751       return emitNonHSAIntrinsicError(DAG, DL, VT);
6752 
6753     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6754                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6755                                     false);
6756   case Intrinsic::r600_read_ngroups_y:
6757     if (Subtarget->isAmdHsaOS())
6758       return emitNonHSAIntrinsicError(DAG, DL, VT);
6759 
6760     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6761                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6762                                     false);
6763   case Intrinsic::r600_read_ngroups_z:
6764     if (Subtarget->isAmdHsaOS())
6765       return emitNonHSAIntrinsicError(DAG, DL, VT);
6766 
6767     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6768                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6769                                     false);
6770   case Intrinsic::r600_read_global_size_x:
6771     if (Subtarget->isAmdHsaOS())
6772       return emitNonHSAIntrinsicError(DAG, DL, VT);
6773 
6774     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6775                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6776                                     Align(4), false);
6777   case Intrinsic::r600_read_global_size_y:
6778     if (Subtarget->isAmdHsaOS())
6779       return emitNonHSAIntrinsicError(DAG, DL, VT);
6780 
6781     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6782                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6783                                     Align(4), false);
6784   case Intrinsic::r600_read_global_size_z:
6785     if (Subtarget->isAmdHsaOS())
6786       return emitNonHSAIntrinsicError(DAG, DL, VT);
6787 
6788     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6789                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6790                                     Align(4), false);
6791   case Intrinsic::r600_read_local_size_x:
6792     if (Subtarget->isAmdHsaOS())
6793       return emitNonHSAIntrinsicError(DAG, DL, VT);
6794 
6795     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6796                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6797   case Intrinsic::r600_read_local_size_y:
6798     if (Subtarget->isAmdHsaOS())
6799       return emitNonHSAIntrinsicError(DAG, DL, VT);
6800 
6801     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6802                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6803   case Intrinsic::r600_read_local_size_z:
6804     if (Subtarget->isAmdHsaOS())
6805       return emitNonHSAIntrinsicError(DAG, DL, VT);
6806 
6807     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6808                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6809   case Intrinsic::amdgcn_workgroup_id_x:
6810     return getPreloadedValue(DAG, *MFI, VT,
6811                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6812   case Intrinsic::amdgcn_workgroup_id_y:
6813     return getPreloadedValue(DAG, *MFI, VT,
6814                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6815   case Intrinsic::amdgcn_workgroup_id_z:
6816     return getPreloadedValue(DAG, *MFI, VT,
6817                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6818   case Intrinsic::amdgcn_workitem_id_x:
6819     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 0) == 0)
6820       return DAG.getConstant(0, DL, MVT::i32);
6821 
6822     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6823                           SDLoc(DAG.getEntryNode()),
6824                           MFI->getArgInfo().WorkItemIDX);
6825   case Intrinsic::amdgcn_workitem_id_y:
6826     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 1) == 0)
6827       return DAG.getConstant(0, DL, MVT::i32);
6828 
6829     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6830                           SDLoc(DAG.getEntryNode()),
6831                           MFI->getArgInfo().WorkItemIDY);
6832   case Intrinsic::amdgcn_workitem_id_z:
6833     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 2) == 0)
6834       return DAG.getConstant(0, DL, MVT::i32);
6835 
6836     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6837                           SDLoc(DAG.getEntryNode()),
6838                           MFI->getArgInfo().WorkItemIDZ);
6839   case Intrinsic::amdgcn_wavefrontsize:
6840     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6841                            SDLoc(Op), MVT::i32);
6842   case Intrinsic::amdgcn_s_buffer_load: {
6843     unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6844     if (CPol & ~AMDGPU::CPol::ALL)
6845       return Op;
6846     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6847                         DAG);
6848   }
6849   case Intrinsic::amdgcn_fdiv_fast:
6850     return lowerFDIV_FAST(Op, DAG);
6851   case Intrinsic::amdgcn_sin:
6852     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6853 
6854   case Intrinsic::amdgcn_cos:
6855     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6856 
6857   case Intrinsic::amdgcn_mul_u24:
6858     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6859   case Intrinsic::amdgcn_mul_i24:
6860     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6861 
6862   case Intrinsic::amdgcn_log_clamp: {
6863     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6864       return SDValue();
6865 
6866     return emitRemovedIntrinsicError(DAG, DL, VT);
6867   }
6868   case Intrinsic::amdgcn_ldexp:
6869     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6870                        Op.getOperand(1), Op.getOperand(2));
6871 
6872   case Intrinsic::amdgcn_fract:
6873     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6874 
6875   case Intrinsic::amdgcn_class:
6876     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6877                        Op.getOperand(1), Op.getOperand(2));
6878   case Intrinsic::amdgcn_div_fmas:
6879     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6880                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6881                        Op.getOperand(4));
6882 
6883   case Intrinsic::amdgcn_div_fixup:
6884     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6885                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6886 
6887   case Intrinsic::amdgcn_div_scale: {
6888     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6889 
6890     // Translate to the operands expected by the machine instruction. The
6891     // first parameter must be the same as the first instruction.
6892     SDValue Numerator = Op.getOperand(1);
6893     SDValue Denominator = Op.getOperand(2);
6894 
6895     // Note this order is opposite of the machine instruction's operations,
6896     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6897     // intrinsic has the numerator as the first operand to match a normal
6898     // division operation.
6899 
6900     SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator;
6901 
6902     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6903                        Denominator, Numerator);
6904   }
6905   case Intrinsic::amdgcn_icmp: {
6906     // There is a Pat that handles this variant, so return it as-is.
6907     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6908         Op.getConstantOperandVal(2) == 0 &&
6909         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6910       return Op;
6911     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6912   }
6913   case Intrinsic::amdgcn_fcmp: {
6914     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6915   }
6916   case Intrinsic::amdgcn_ballot:
6917     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6918   case Intrinsic::amdgcn_fmed3:
6919     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6920                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6921   case Intrinsic::amdgcn_fdot2:
6922     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6923                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6924                        Op.getOperand(4));
6925   case Intrinsic::amdgcn_fmul_legacy:
6926     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6927                        Op.getOperand(1), Op.getOperand(2));
6928   case Intrinsic::amdgcn_sffbh:
6929     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6930   case Intrinsic::amdgcn_sbfe:
6931     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6932                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6933   case Intrinsic::amdgcn_ubfe:
6934     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6935                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6936   case Intrinsic::amdgcn_cvt_pkrtz:
6937   case Intrinsic::amdgcn_cvt_pknorm_i16:
6938   case Intrinsic::amdgcn_cvt_pknorm_u16:
6939   case Intrinsic::amdgcn_cvt_pk_i16:
6940   case Intrinsic::amdgcn_cvt_pk_u16: {
6941     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6942     EVT VT = Op.getValueType();
6943     unsigned Opcode;
6944 
6945     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6946       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6947     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6948       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6949     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6950       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6951     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6952       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6953     else
6954       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6955 
6956     if (isTypeLegal(VT))
6957       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6958 
6959     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6960                                Op.getOperand(1), Op.getOperand(2));
6961     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6962   }
6963   case Intrinsic::amdgcn_fmad_ftz:
6964     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6965                        Op.getOperand(2), Op.getOperand(3));
6966 
6967   case Intrinsic::amdgcn_if_break:
6968     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6969                                       Op->getOperand(1), Op->getOperand(2)), 0);
6970 
6971   case Intrinsic::amdgcn_groupstaticsize: {
6972     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6973     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6974       return Op;
6975 
6976     const Module *M = MF.getFunction().getParent();
6977     const GlobalValue *GV =
6978         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6979     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6980                                             SIInstrInfo::MO_ABS32_LO);
6981     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6982   }
6983   case Intrinsic::amdgcn_is_shared:
6984   case Intrinsic::amdgcn_is_private: {
6985     SDLoc SL(Op);
6986     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6987       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6988     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6989     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6990                                  Op.getOperand(1));
6991 
6992     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6993                                 DAG.getConstant(1, SL, MVT::i32));
6994     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6995   }
6996   case Intrinsic::amdgcn_perm:
6997     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
6998                        Op.getOperand(2), Op.getOperand(3));
6999   case Intrinsic::amdgcn_reloc_constant: {
7000     Module *M = const_cast<Module *>(MF.getFunction().getParent());
7001     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
7002     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
7003     auto RelocSymbol = cast<GlobalVariable>(
7004         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
7005     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
7006                                             SIInstrInfo::MO_ABS32_LO);
7007     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
7008   }
7009   default:
7010     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7011             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7012       return lowerImage(Op, ImageDimIntr, DAG, false);
7013 
7014     return Op;
7015   }
7016 }
7017 
7018 /// Update \p MMO based on the offset inputs to an intrinsic.
7019 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset,
7020                             SDValue SOffset, SDValue Offset,
7021                             SDValue VIndex = SDValue()) {
7022   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
7023       !isa<ConstantSDNode>(Offset)) {
7024     // The combined offset is not known to be constant, so we cannot represent
7025     // it in the MMO. Give up.
7026     MMO->setValue((Value *)nullptr);
7027     return;
7028   }
7029 
7030   if (VIndex && (!isa<ConstantSDNode>(VIndex) ||
7031                  !cast<ConstantSDNode>(VIndex)->isZero())) {
7032     // The strided index component of the address is not known to be zero, so we
7033     // cannot represent it in the MMO. Give up.
7034     MMO->setValue((Value *)nullptr);
7035     return;
7036   }
7037 
7038   MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() +
7039                  cast<ConstantSDNode>(SOffset)->getSExtValue() +
7040                  cast<ConstantSDNode>(Offset)->getSExtValue());
7041 }
7042 
7043 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
7044                                                      SelectionDAG &DAG,
7045                                                      unsigned NewOpcode) const {
7046   SDLoc DL(Op);
7047 
7048   SDValue VData = Op.getOperand(2);
7049   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7050   SDValue Ops[] = {
7051     Op.getOperand(0), // Chain
7052     VData,            // vdata
7053     Op.getOperand(3), // rsrc
7054     DAG.getConstant(0, DL, MVT::i32), // vindex
7055     Offsets.first,    // voffset
7056     Op.getOperand(5), // soffset
7057     Offsets.second,   // offset
7058     Op.getOperand(6), // cachepolicy
7059     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7060   };
7061 
7062   auto *M = cast<MemSDNode>(Op);
7063   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
7064 
7065   EVT MemVT = VData.getValueType();
7066   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7067                                  M->getMemOperand());
7068 }
7069 
7070 // Return a value to use for the idxen operand by examining the vindex operand.
7071 static unsigned getIdxEn(SDValue VIndex) {
7072   if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex))
7073     // No need to set idxen if vindex is known to be zero.
7074     return VIndexC->getZExtValue() != 0;
7075   return 1;
7076 }
7077 
7078 SDValue
7079 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
7080                                                 unsigned NewOpcode) const {
7081   SDLoc DL(Op);
7082 
7083   SDValue VData = Op.getOperand(2);
7084   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7085   SDValue Ops[] = {
7086     Op.getOperand(0), // Chain
7087     VData,            // vdata
7088     Op.getOperand(3), // rsrc
7089     Op.getOperand(4), // vindex
7090     Offsets.first,    // voffset
7091     Op.getOperand(6), // soffset
7092     Offsets.second,   // offset
7093     Op.getOperand(7), // cachepolicy
7094     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7095   };
7096 
7097   auto *M = cast<MemSDNode>(Op);
7098   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7099 
7100   EVT MemVT = VData.getValueType();
7101   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7102                                  M->getMemOperand());
7103 }
7104 
7105 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
7106                                                  SelectionDAG &DAG) const {
7107   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7108   SDLoc DL(Op);
7109 
7110   switch (IntrID) {
7111   case Intrinsic::amdgcn_ds_ordered_add:
7112   case Intrinsic::amdgcn_ds_ordered_swap: {
7113     MemSDNode *M = cast<MemSDNode>(Op);
7114     SDValue Chain = M->getOperand(0);
7115     SDValue M0 = M->getOperand(2);
7116     SDValue Value = M->getOperand(3);
7117     unsigned IndexOperand = M->getConstantOperandVal(7);
7118     unsigned WaveRelease = M->getConstantOperandVal(8);
7119     unsigned WaveDone = M->getConstantOperandVal(9);
7120 
7121     unsigned OrderedCountIndex = IndexOperand & 0x3f;
7122     IndexOperand &= ~0x3f;
7123     unsigned CountDw = 0;
7124 
7125     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
7126       CountDw = (IndexOperand >> 24) & 0xf;
7127       IndexOperand &= ~(0xf << 24);
7128 
7129       if (CountDw < 1 || CountDw > 4) {
7130         report_fatal_error(
7131             "ds_ordered_count: dword count must be between 1 and 4");
7132       }
7133     }
7134 
7135     if (IndexOperand)
7136       report_fatal_error("ds_ordered_count: bad index operand");
7137 
7138     if (WaveDone && !WaveRelease)
7139       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
7140 
7141     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
7142     unsigned ShaderType =
7143         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
7144     unsigned Offset0 = OrderedCountIndex << 2;
7145     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
7146                        (Instruction << 4);
7147 
7148     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
7149       Offset1 |= (CountDw - 1) << 6;
7150 
7151     unsigned Offset = Offset0 | (Offset1 << 8);
7152 
7153     SDValue Ops[] = {
7154       Chain,
7155       Value,
7156       DAG.getTargetConstant(Offset, DL, MVT::i16),
7157       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
7158     };
7159     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
7160                                    M->getVTList(), Ops, M->getMemoryVT(),
7161                                    M->getMemOperand());
7162   }
7163   case Intrinsic::amdgcn_ds_fadd: {
7164     MemSDNode *M = cast<MemSDNode>(Op);
7165     unsigned Opc;
7166     switch (IntrID) {
7167     case Intrinsic::amdgcn_ds_fadd:
7168       Opc = ISD::ATOMIC_LOAD_FADD;
7169       break;
7170     }
7171 
7172     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
7173                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
7174                          M->getMemOperand());
7175   }
7176   case Intrinsic::amdgcn_atomic_inc:
7177   case Intrinsic::amdgcn_atomic_dec:
7178   case Intrinsic::amdgcn_ds_fmin:
7179   case Intrinsic::amdgcn_ds_fmax: {
7180     MemSDNode *M = cast<MemSDNode>(Op);
7181     unsigned Opc;
7182     switch (IntrID) {
7183     case Intrinsic::amdgcn_atomic_inc:
7184       Opc = AMDGPUISD::ATOMIC_INC;
7185       break;
7186     case Intrinsic::amdgcn_atomic_dec:
7187       Opc = AMDGPUISD::ATOMIC_DEC;
7188       break;
7189     case Intrinsic::amdgcn_ds_fmin:
7190       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
7191       break;
7192     case Intrinsic::amdgcn_ds_fmax:
7193       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
7194       break;
7195     default:
7196       llvm_unreachable("Unknown intrinsic!");
7197     }
7198     SDValue Ops[] = {
7199       M->getOperand(0), // Chain
7200       M->getOperand(2), // Ptr
7201       M->getOperand(3)  // Value
7202     };
7203 
7204     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
7205                                    M->getMemoryVT(), M->getMemOperand());
7206   }
7207   case Intrinsic::amdgcn_buffer_load:
7208   case Intrinsic::amdgcn_buffer_load_format: {
7209     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
7210     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7211     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7212     SDValue Ops[] = {
7213       Op.getOperand(0), // Chain
7214       Op.getOperand(2), // rsrc
7215       Op.getOperand(3), // vindex
7216       SDValue(),        // voffset -- will be set by setBufferOffsets
7217       SDValue(),        // soffset -- will be set by setBufferOffsets
7218       SDValue(),        // offset -- will be set by setBufferOffsets
7219       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7220       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7221     };
7222     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
7223 
7224     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
7225         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
7226 
7227     EVT VT = Op.getValueType();
7228     EVT IntVT = VT.changeTypeToInteger();
7229     auto *M = cast<MemSDNode>(Op);
7230     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7231     EVT LoadVT = Op.getValueType();
7232 
7233     if (LoadVT.getScalarType() == MVT::f16)
7234       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
7235                                  M, DAG, Ops);
7236 
7237     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
7238     if (LoadVT.getScalarType() == MVT::i8 ||
7239         LoadVT.getScalarType() == MVT::i16)
7240       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
7241 
7242     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
7243                                M->getMemOperand(), DAG);
7244   }
7245   case Intrinsic::amdgcn_raw_buffer_load:
7246   case Intrinsic::amdgcn_raw_buffer_load_format: {
7247     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
7248 
7249     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7250     SDValue Ops[] = {
7251       Op.getOperand(0), // Chain
7252       Op.getOperand(2), // rsrc
7253       DAG.getConstant(0, DL, MVT::i32), // vindex
7254       Offsets.first,    // voffset
7255       Op.getOperand(4), // soffset
7256       Offsets.second,   // offset
7257       Op.getOperand(5), // cachepolicy, swizzled buffer
7258       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7259     };
7260 
7261     auto *M = cast<MemSDNode>(Op);
7262     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]);
7263     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
7264   }
7265   case Intrinsic::amdgcn_struct_buffer_load:
7266   case Intrinsic::amdgcn_struct_buffer_load_format: {
7267     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
7268 
7269     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7270     SDValue Ops[] = {
7271       Op.getOperand(0), // Chain
7272       Op.getOperand(2), // rsrc
7273       Op.getOperand(3), // vindex
7274       Offsets.first,    // voffset
7275       Op.getOperand(5), // soffset
7276       Offsets.second,   // offset
7277       Op.getOperand(6), // cachepolicy, swizzled buffer
7278       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7279     };
7280 
7281     auto *M = cast<MemSDNode>(Op);
7282     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7283     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7284   }
7285   case Intrinsic::amdgcn_tbuffer_load: {
7286     MemSDNode *M = cast<MemSDNode>(Op);
7287     EVT LoadVT = Op.getValueType();
7288 
7289     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7290     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7291     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7292     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7293     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7294     SDValue Ops[] = {
7295       Op.getOperand(0),  // Chain
7296       Op.getOperand(2),  // rsrc
7297       Op.getOperand(3),  // vindex
7298       Op.getOperand(4),  // voffset
7299       Op.getOperand(5),  // soffset
7300       Op.getOperand(6),  // offset
7301       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7302       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7303       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7304     };
7305 
7306     if (LoadVT.getScalarType() == MVT::f16)
7307       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7308                                  M, DAG, Ops);
7309     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7310                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7311                                DAG);
7312   }
7313   case Intrinsic::amdgcn_raw_tbuffer_load: {
7314     MemSDNode *M = cast<MemSDNode>(Op);
7315     EVT LoadVT = Op.getValueType();
7316     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7317 
7318     SDValue Ops[] = {
7319       Op.getOperand(0),  // Chain
7320       Op.getOperand(2),  // rsrc
7321       DAG.getConstant(0, DL, MVT::i32), // vindex
7322       Offsets.first,     // voffset
7323       Op.getOperand(4),  // soffset
7324       Offsets.second,    // offset
7325       Op.getOperand(5),  // format
7326       Op.getOperand(6),  // cachepolicy, swizzled buffer
7327       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7328     };
7329 
7330     if (LoadVT.getScalarType() == MVT::f16)
7331       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7332                                  M, DAG, Ops);
7333     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7334                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7335                                DAG);
7336   }
7337   case Intrinsic::amdgcn_struct_tbuffer_load: {
7338     MemSDNode *M = cast<MemSDNode>(Op);
7339     EVT LoadVT = Op.getValueType();
7340     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7341 
7342     SDValue Ops[] = {
7343       Op.getOperand(0),  // Chain
7344       Op.getOperand(2),  // rsrc
7345       Op.getOperand(3),  // vindex
7346       Offsets.first,     // voffset
7347       Op.getOperand(5),  // soffset
7348       Offsets.second,    // offset
7349       Op.getOperand(6),  // format
7350       Op.getOperand(7),  // cachepolicy, swizzled buffer
7351       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7352     };
7353 
7354     if (LoadVT.getScalarType() == MVT::f16)
7355       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7356                                  M, DAG, Ops);
7357     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7358                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7359                                DAG);
7360   }
7361   case Intrinsic::amdgcn_buffer_atomic_swap:
7362   case Intrinsic::amdgcn_buffer_atomic_add:
7363   case Intrinsic::amdgcn_buffer_atomic_sub:
7364   case Intrinsic::amdgcn_buffer_atomic_csub:
7365   case Intrinsic::amdgcn_buffer_atomic_smin:
7366   case Intrinsic::amdgcn_buffer_atomic_umin:
7367   case Intrinsic::amdgcn_buffer_atomic_smax:
7368   case Intrinsic::amdgcn_buffer_atomic_umax:
7369   case Intrinsic::amdgcn_buffer_atomic_and:
7370   case Intrinsic::amdgcn_buffer_atomic_or:
7371   case Intrinsic::amdgcn_buffer_atomic_xor:
7372   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7373     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7374     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7375     SDValue Ops[] = {
7376       Op.getOperand(0), // Chain
7377       Op.getOperand(2), // vdata
7378       Op.getOperand(3), // rsrc
7379       Op.getOperand(4), // vindex
7380       SDValue(),        // voffset -- will be set by setBufferOffsets
7381       SDValue(),        // soffset -- will be set by setBufferOffsets
7382       SDValue(),        // offset -- will be set by setBufferOffsets
7383       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7384       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7385     };
7386     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7387 
7388     EVT VT = Op.getValueType();
7389 
7390     auto *M = cast<MemSDNode>(Op);
7391     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7392     unsigned Opcode = 0;
7393 
7394     switch (IntrID) {
7395     case Intrinsic::amdgcn_buffer_atomic_swap:
7396       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7397       break;
7398     case Intrinsic::amdgcn_buffer_atomic_add:
7399       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7400       break;
7401     case Intrinsic::amdgcn_buffer_atomic_sub:
7402       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7403       break;
7404     case Intrinsic::amdgcn_buffer_atomic_csub:
7405       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7406       break;
7407     case Intrinsic::amdgcn_buffer_atomic_smin:
7408       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7409       break;
7410     case Intrinsic::amdgcn_buffer_atomic_umin:
7411       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7412       break;
7413     case Intrinsic::amdgcn_buffer_atomic_smax:
7414       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7415       break;
7416     case Intrinsic::amdgcn_buffer_atomic_umax:
7417       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7418       break;
7419     case Intrinsic::amdgcn_buffer_atomic_and:
7420       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7421       break;
7422     case Intrinsic::amdgcn_buffer_atomic_or:
7423       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7424       break;
7425     case Intrinsic::amdgcn_buffer_atomic_xor:
7426       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7427       break;
7428     case Intrinsic::amdgcn_buffer_atomic_fadd:
7429       if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7430         DiagnosticInfoUnsupported
7431           NoFpRet(DAG.getMachineFunction().getFunction(),
7432                   "return versions of fp atomics not supported",
7433                   DL.getDebugLoc(), DS_Error);
7434         DAG.getContext()->diagnose(NoFpRet);
7435         return SDValue();
7436       }
7437       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7438       break;
7439     default:
7440       llvm_unreachable("unhandled atomic opcode");
7441     }
7442 
7443     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7444                                    M->getMemOperand());
7445   }
7446   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7447     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7448   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7449     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7450   case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7451     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7452   case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7453     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7454   case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7455     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7456   case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7457     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7458   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7459     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7460   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7461     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7462   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7463     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7464   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7465     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7466   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7467     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7468   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7469     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7470   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7471     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7472   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7473     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7474   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7475     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7476   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7477     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7478   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7479     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7480   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7481     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7482   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7483     return lowerStructBufferAtomicIntrin(Op, DAG,
7484                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7485   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7486     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7487   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7488     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7489   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7490     return lowerStructBufferAtomicIntrin(Op, DAG,
7491                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7492   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7493     return lowerStructBufferAtomicIntrin(Op, DAG,
7494                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7495   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7496     return lowerStructBufferAtomicIntrin(Op, DAG,
7497                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7498   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7499     return lowerStructBufferAtomicIntrin(Op, DAG,
7500                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7501   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7502     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7503   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7504     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7505   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7506     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7507   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7508     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7509   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7510     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7511 
7512   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7513     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7514     unsigned IdxEn = getIdxEn(Op.getOperand(5));
7515     SDValue Ops[] = {
7516       Op.getOperand(0), // Chain
7517       Op.getOperand(2), // src
7518       Op.getOperand(3), // cmp
7519       Op.getOperand(4), // rsrc
7520       Op.getOperand(5), // vindex
7521       SDValue(),        // voffset -- will be set by setBufferOffsets
7522       SDValue(),        // soffset -- will be set by setBufferOffsets
7523       SDValue(),        // offset -- will be set by setBufferOffsets
7524       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7525       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7526     };
7527     setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7528 
7529     EVT VT = Op.getValueType();
7530     auto *M = cast<MemSDNode>(Op);
7531     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7532 
7533     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7534                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7535   }
7536   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7537     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7538     SDValue Ops[] = {
7539       Op.getOperand(0), // Chain
7540       Op.getOperand(2), // src
7541       Op.getOperand(3), // cmp
7542       Op.getOperand(4), // rsrc
7543       DAG.getConstant(0, DL, MVT::i32), // vindex
7544       Offsets.first,    // voffset
7545       Op.getOperand(6), // soffset
7546       Offsets.second,   // offset
7547       Op.getOperand(7), // cachepolicy
7548       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7549     };
7550     EVT VT = Op.getValueType();
7551     auto *M = cast<MemSDNode>(Op);
7552     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]);
7553 
7554     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7555                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7556   }
7557   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7558     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7559     SDValue Ops[] = {
7560       Op.getOperand(0), // Chain
7561       Op.getOperand(2), // src
7562       Op.getOperand(3), // cmp
7563       Op.getOperand(4), // rsrc
7564       Op.getOperand(5), // vindex
7565       Offsets.first,    // voffset
7566       Op.getOperand(7), // soffset
7567       Offsets.second,   // offset
7568       Op.getOperand(8), // cachepolicy
7569       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7570     };
7571     EVT VT = Op.getValueType();
7572     auto *M = cast<MemSDNode>(Op);
7573     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7574 
7575     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7576                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7577   }
7578   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7579     MemSDNode *M = cast<MemSDNode>(Op);
7580     SDValue NodePtr = M->getOperand(2);
7581     SDValue RayExtent = M->getOperand(3);
7582     SDValue RayOrigin = M->getOperand(4);
7583     SDValue RayDir = M->getOperand(5);
7584     SDValue RayInvDir = M->getOperand(6);
7585     SDValue TDescr = M->getOperand(7);
7586 
7587     assert(NodePtr.getValueType() == MVT::i32 ||
7588            NodePtr.getValueType() == MVT::i64);
7589     assert(RayDir.getValueType() == MVT::v3f16 ||
7590            RayDir.getValueType() == MVT::v3f32);
7591 
7592     if (!Subtarget->hasGFX10_AEncoding()) {
7593       emitRemovedIntrinsicError(DAG, DL, Op.getValueType());
7594       return SDValue();
7595     }
7596 
7597     const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7598     const bool Is64 = NodePtr.getValueType() == MVT::i64;
7599     const unsigned NumVDataDwords = 4;
7600     const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
7601     const bool UseNSA = Subtarget->hasNSAEncoding() &&
7602                         NumVAddrDwords <= Subtarget->getNSAMaxSize();
7603     const unsigned BaseOpcodes[2][2] = {
7604         {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
7605         {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
7606          AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
7607     int Opcode;
7608     if (UseNSA) {
7609       Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7610                                      AMDGPU::MIMGEncGfx10NSA, NumVDataDwords,
7611                                      NumVAddrDwords);
7612     } else {
7613       Opcode = AMDGPU::getMIMGOpcode(
7614           BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords,
7615           PowerOf2Ceil(NumVAddrDwords));
7616     }
7617     assert(Opcode != -1);
7618 
7619     SmallVector<SDValue, 16> Ops;
7620 
7621     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7622       SmallVector<SDValue, 3> Lanes;
7623       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7624       if (Lanes[0].getValueSizeInBits() == 32) {
7625         for (unsigned I = 0; I < 3; ++I)
7626           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7627       } else {
7628         if (IsAligned) {
7629           Ops.push_back(
7630             DAG.getBitcast(MVT::i32,
7631                            DAG.getBuildVector(MVT::v2f16, DL,
7632                                               { Lanes[0], Lanes[1] })));
7633           Ops.push_back(Lanes[2]);
7634         } else {
7635           SDValue Elt0 = Ops.pop_back_val();
7636           Ops.push_back(
7637             DAG.getBitcast(MVT::i32,
7638                            DAG.getBuildVector(MVT::v2f16, DL,
7639                                               { Elt0, Lanes[0] })));
7640           Ops.push_back(
7641             DAG.getBitcast(MVT::i32,
7642                            DAG.getBuildVector(MVT::v2f16, DL,
7643                                               { Lanes[1], Lanes[2] })));
7644         }
7645       }
7646     };
7647 
7648     if (Is64)
7649       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7650     else
7651       Ops.push_back(NodePtr);
7652 
7653     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7654     packLanes(RayOrigin, true);
7655     packLanes(RayDir, true);
7656     packLanes(RayInvDir, false);
7657 
7658     if (!UseNSA) {
7659       // Build a single vector containing all the operands so far prepared.
7660       if (NumVAddrDwords > 8) {
7661         SDValue Undef = DAG.getUNDEF(MVT::i32);
7662         Ops.append(16 - Ops.size(), Undef);
7663       }
7664       assert(Ops.size() == 8 || Ops.size() == 16);
7665       SDValue MergedOps = DAG.getBuildVector(
7666           Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops);
7667       Ops.clear();
7668       Ops.push_back(MergedOps);
7669     }
7670 
7671     Ops.push_back(TDescr);
7672     if (IsA16)
7673       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7674     Ops.push_back(M->getChain());
7675 
7676     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7677     MachineMemOperand *MemRef = M->getMemOperand();
7678     DAG.setNodeMemRefs(NewNode, {MemRef});
7679     return SDValue(NewNode, 0);
7680   }
7681   case Intrinsic::amdgcn_global_atomic_fadd:
7682     if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7683       DiagnosticInfoUnsupported
7684         NoFpRet(DAG.getMachineFunction().getFunction(),
7685                 "return versions of fp atomics not supported",
7686                 DL.getDebugLoc(), DS_Error);
7687       DAG.getContext()->diagnose(NoFpRet);
7688       return SDValue();
7689     }
7690     LLVM_FALLTHROUGH;
7691   case Intrinsic::amdgcn_global_atomic_fmin:
7692   case Intrinsic::amdgcn_global_atomic_fmax:
7693   case Intrinsic::amdgcn_flat_atomic_fadd:
7694   case Intrinsic::amdgcn_flat_atomic_fmin:
7695   case Intrinsic::amdgcn_flat_atomic_fmax: {
7696     MemSDNode *M = cast<MemSDNode>(Op);
7697     SDValue Ops[] = {
7698       M->getOperand(0), // Chain
7699       M->getOperand(2), // Ptr
7700       M->getOperand(3)  // Value
7701     };
7702     unsigned Opcode = 0;
7703     switch (IntrID) {
7704     case Intrinsic::amdgcn_global_atomic_fadd:
7705     case Intrinsic::amdgcn_flat_atomic_fadd: {
7706       EVT VT = Op.getOperand(3).getValueType();
7707       return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7708                            DAG.getVTList(VT, MVT::Other), Ops,
7709                            M->getMemOperand());
7710     }
7711     case Intrinsic::amdgcn_global_atomic_fmin:
7712     case Intrinsic::amdgcn_flat_atomic_fmin: {
7713       Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7714       break;
7715     }
7716     case Intrinsic::amdgcn_global_atomic_fmax:
7717     case Intrinsic::amdgcn_flat_atomic_fmax: {
7718       Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7719       break;
7720     }
7721     default:
7722       llvm_unreachable("unhandled atomic opcode");
7723     }
7724     return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7725                                    M->getVTList(), Ops, M->getMemoryVT(),
7726                                    M->getMemOperand());
7727   }
7728   default:
7729 
7730     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7731             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7732       return lowerImage(Op, ImageDimIntr, DAG, true);
7733 
7734     return SDValue();
7735   }
7736 }
7737 
7738 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7739 // dwordx4 if on SI.
7740 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7741                                               SDVTList VTList,
7742                                               ArrayRef<SDValue> Ops, EVT MemVT,
7743                                               MachineMemOperand *MMO,
7744                                               SelectionDAG &DAG) const {
7745   EVT VT = VTList.VTs[0];
7746   EVT WidenedVT = VT;
7747   EVT WidenedMemVT = MemVT;
7748   if (!Subtarget->hasDwordx3LoadStores() &&
7749       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7750     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7751                                  WidenedVT.getVectorElementType(), 4);
7752     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7753                                     WidenedMemVT.getVectorElementType(), 4);
7754     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7755   }
7756 
7757   assert(VTList.NumVTs == 2);
7758   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7759 
7760   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7761                                        WidenedMemVT, MMO);
7762   if (WidenedVT != VT) {
7763     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7764                                DAG.getVectorIdxConstant(0, DL));
7765     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7766   }
7767   return NewOp;
7768 }
7769 
7770 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7771                                          bool ImageStore) const {
7772   EVT StoreVT = VData.getValueType();
7773 
7774   // No change for f16 and legal vector D16 types.
7775   if (!StoreVT.isVector())
7776     return VData;
7777 
7778   SDLoc DL(VData);
7779   unsigned NumElements = StoreVT.getVectorNumElements();
7780 
7781   if (Subtarget->hasUnpackedD16VMem()) {
7782     // We need to unpack the packed data to store.
7783     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7784     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7785 
7786     EVT EquivStoreVT =
7787         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7788     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7789     return DAG.UnrollVectorOp(ZExt.getNode());
7790   }
7791 
7792   // The sq block of gfx8.1 does not estimate register use correctly for d16
7793   // image store instructions. The data operand is computed as if it were not a
7794   // d16 image instruction.
7795   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7796     // Bitcast to i16
7797     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7798     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7799 
7800     // Decompose into scalars
7801     SmallVector<SDValue, 4> Elts;
7802     DAG.ExtractVectorElements(IntVData, Elts);
7803 
7804     // Group pairs of i16 into v2i16 and bitcast to i32
7805     SmallVector<SDValue, 4> PackedElts;
7806     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7807       SDValue Pair =
7808           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7809       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7810       PackedElts.push_back(IntPair);
7811     }
7812     if ((NumElements % 2) == 1) {
7813       // Handle v3i16
7814       unsigned I = Elts.size() / 2;
7815       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7816                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7817       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7818       PackedElts.push_back(IntPair);
7819     }
7820 
7821     // Pad using UNDEF
7822     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7823 
7824     // Build final vector
7825     EVT VecVT =
7826         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7827     return DAG.getBuildVector(VecVT, DL, PackedElts);
7828   }
7829 
7830   if (NumElements == 3) {
7831     EVT IntStoreVT =
7832         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7833     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7834 
7835     EVT WidenedStoreVT = EVT::getVectorVT(
7836         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7837     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7838                                          WidenedStoreVT.getStoreSizeInBits());
7839     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7840     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7841   }
7842 
7843   assert(isTypeLegal(StoreVT));
7844   return VData;
7845 }
7846 
7847 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7848                                               SelectionDAG &DAG) const {
7849   SDLoc DL(Op);
7850   SDValue Chain = Op.getOperand(0);
7851   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7852   MachineFunction &MF = DAG.getMachineFunction();
7853 
7854   switch (IntrinsicID) {
7855   case Intrinsic::amdgcn_exp_compr: {
7856     SDValue Src0 = Op.getOperand(4);
7857     SDValue Src1 = Op.getOperand(5);
7858     // Hack around illegal type on SI by directly selecting it.
7859     if (isTypeLegal(Src0.getValueType()))
7860       return SDValue();
7861 
7862     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7863     SDValue Undef = DAG.getUNDEF(MVT::f32);
7864     const SDValue Ops[] = {
7865       Op.getOperand(2), // tgt
7866       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7867       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7868       Undef, // src2
7869       Undef, // src3
7870       Op.getOperand(7), // vm
7871       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7872       Op.getOperand(3), // en
7873       Op.getOperand(0) // Chain
7874     };
7875 
7876     unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7877     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7878   }
7879   case Intrinsic::amdgcn_s_barrier: {
7880     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7881       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7882       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7883       if (WGSize <= ST.getWavefrontSize())
7884         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7885                                           Op.getOperand(0)), 0);
7886     }
7887     return SDValue();
7888   };
7889   case Intrinsic::amdgcn_tbuffer_store: {
7890     SDValue VData = Op.getOperand(2);
7891     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7892     if (IsD16)
7893       VData = handleD16VData(VData, DAG);
7894     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7895     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7896     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7897     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7898     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7899     SDValue Ops[] = {
7900       Chain,
7901       VData,             // vdata
7902       Op.getOperand(3),  // rsrc
7903       Op.getOperand(4),  // vindex
7904       Op.getOperand(5),  // voffset
7905       Op.getOperand(6),  // soffset
7906       Op.getOperand(7),  // offset
7907       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7908       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7909       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7910     };
7911     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7912                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7913     MemSDNode *M = cast<MemSDNode>(Op);
7914     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7915                                    M->getMemoryVT(), M->getMemOperand());
7916   }
7917 
7918   case Intrinsic::amdgcn_struct_tbuffer_store: {
7919     SDValue VData = Op.getOperand(2);
7920     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7921     if (IsD16)
7922       VData = handleD16VData(VData, DAG);
7923     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7924     SDValue Ops[] = {
7925       Chain,
7926       VData,             // vdata
7927       Op.getOperand(3),  // rsrc
7928       Op.getOperand(4),  // vindex
7929       Offsets.first,     // voffset
7930       Op.getOperand(6),  // soffset
7931       Offsets.second,    // offset
7932       Op.getOperand(7),  // format
7933       Op.getOperand(8),  // cachepolicy, swizzled buffer
7934       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7935     };
7936     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7937                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7938     MemSDNode *M = cast<MemSDNode>(Op);
7939     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7940                                    M->getMemoryVT(), M->getMemOperand());
7941   }
7942 
7943   case Intrinsic::amdgcn_raw_tbuffer_store: {
7944     SDValue VData = Op.getOperand(2);
7945     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7946     if (IsD16)
7947       VData = handleD16VData(VData, DAG);
7948     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7949     SDValue Ops[] = {
7950       Chain,
7951       VData,             // vdata
7952       Op.getOperand(3),  // rsrc
7953       DAG.getConstant(0, DL, MVT::i32), // vindex
7954       Offsets.first,     // voffset
7955       Op.getOperand(5),  // soffset
7956       Offsets.second,    // offset
7957       Op.getOperand(6),  // format
7958       Op.getOperand(7),  // cachepolicy, swizzled buffer
7959       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7960     };
7961     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7962                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7963     MemSDNode *M = cast<MemSDNode>(Op);
7964     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7965                                    M->getMemoryVT(), M->getMemOperand());
7966   }
7967 
7968   case Intrinsic::amdgcn_buffer_store:
7969   case Intrinsic::amdgcn_buffer_store_format: {
7970     SDValue VData = Op.getOperand(2);
7971     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7972     if (IsD16)
7973       VData = handleD16VData(VData, DAG);
7974     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7975     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7976     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7977     SDValue Ops[] = {
7978       Chain,
7979       VData,
7980       Op.getOperand(3), // rsrc
7981       Op.getOperand(4), // vindex
7982       SDValue(), // voffset -- will be set by setBufferOffsets
7983       SDValue(), // soffset -- will be set by setBufferOffsets
7984       SDValue(), // offset -- will be set by setBufferOffsets
7985       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7986       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7987     };
7988     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7989 
7990     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7991                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7992     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7993     MemSDNode *M = cast<MemSDNode>(Op);
7994     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7995 
7996     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7997     EVT VDataType = VData.getValueType().getScalarType();
7998     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7999       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8000 
8001     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8002                                    M->getMemoryVT(), M->getMemOperand());
8003   }
8004 
8005   case Intrinsic::amdgcn_raw_buffer_store:
8006   case Intrinsic::amdgcn_raw_buffer_store_format: {
8007     const bool IsFormat =
8008         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
8009 
8010     SDValue VData = Op.getOperand(2);
8011     EVT VDataVT = VData.getValueType();
8012     EVT EltType = VDataVT.getScalarType();
8013     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8014     if (IsD16) {
8015       VData = handleD16VData(VData, DAG);
8016       VDataVT = VData.getValueType();
8017     }
8018 
8019     if (!isTypeLegal(VDataVT)) {
8020       VData =
8021           DAG.getNode(ISD::BITCAST, DL,
8022                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8023     }
8024 
8025     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
8026     SDValue Ops[] = {
8027       Chain,
8028       VData,
8029       Op.getOperand(3), // rsrc
8030       DAG.getConstant(0, DL, MVT::i32), // vindex
8031       Offsets.first,    // voffset
8032       Op.getOperand(5), // soffset
8033       Offsets.second,   // offset
8034       Op.getOperand(6), // cachepolicy, swizzled buffer
8035       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8036     };
8037     unsigned Opc =
8038         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
8039     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8040     MemSDNode *M = cast<MemSDNode>(Op);
8041     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
8042 
8043     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8044     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8045       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
8046 
8047     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8048                                    M->getMemoryVT(), M->getMemOperand());
8049   }
8050 
8051   case Intrinsic::amdgcn_struct_buffer_store:
8052   case Intrinsic::amdgcn_struct_buffer_store_format: {
8053     const bool IsFormat =
8054         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
8055 
8056     SDValue VData = Op.getOperand(2);
8057     EVT VDataVT = VData.getValueType();
8058     EVT EltType = VDataVT.getScalarType();
8059     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8060 
8061     if (IsD16) {
8062       VData = handleD16VData(VData, DAG);
8063       VDataVT = VData.getValueType();
8064     }
8065 
8066     if (!isTypeLegal(VDataVT)) {
8067       VData =
8068           DAG.getNode(ISD::BITCAST, DL,
8069                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8070     }
8071 
8072     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
8073     SDValue Ops[] = {
8074       Chain,
8075       VData,
8076       Op.getOperand(3), // rsrc
8077       Op.getOperand(4), // vindex
8078       Offsets.first,    // voffset
8079       Op.getOperand(6), // soffset
8080       Offsets.second,   // offset
8081       Op.getOperand(7), // cachepolicy, swizzled buffer
8082       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8083     };
8084     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
8085                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8086     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8087     MemSDNode *M = cast<MemSDNode>(Op);
8088     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8089 
8090     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8091     EVT VDataType = VData.getValueType().getScalarType();
8092     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8093       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8094 
8095     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8096                                    M->getMemoryVT(), M->getMemOperand());
8097   }
8098   case Intrinsic::amdgcn_end_cf:
8099     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
8100                                       Op->getOperand(2), Chain), 0);
8101 
8102   default: {
8103     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
8104             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
8105       return lowerImage(Op, ImageDimIntr, DAG, true);
8106 
8107     return Op;
8108   }
8109   }
8110 }
8111 
8112 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
8113 // offset (the offset that is included in bounds checking and swizzling, to be
8114 // split between the instruction's voffset and immoffset fields) and soffset
8115 // (the offset that is excluded from bounds checking and swizzling, to go in
8116 // the instruction's soffset field).  This function takes the first kind of
8117 // offset and figures out how to split it between voffset and immoffset.
8118 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
8119     SDValue Offset, SelectionDAG &DAG) const {
8120   SDLoc DL(Offset);
8121   const unsigned MaxImm = 4095;
8122   SDValue N0 = Offset;
8123   ConstantSDNode *C1 = nullptr;
8124 
8125   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
8126     N0 = SDValue();
8127   else if (DAG.isBaseWithConstantOffset(N0)) {
8128     C1 = cast<ConstantSDNode>(N0.getOperand(1));
8129     N0 = N0.getOperand(0);
8130   }
8131 
8132   if (C1) {
8133     unsigned ImmOffset = C1->getZExtValue();
8134     // If the immediate value is too big for the immoffset field, put the value
8135     // and -4096 into the immoffset field so that the value that is copied/added
8136     // for the voffset field is a multiple of 4096, and it stands more chance
8137     // of being CSEd with the copy/add for another similar load/store.
8138     // However, do not do that rounding down to a multiple of 4096 if that is a
8139     // negative number, as it appears to be illegal to have a negative offset
8140     // in the vgpr, even if adding the immediate offset makes it positive.
8141     unsigned Overflow = ImmOffset & ~MaxImm;
8142     ImmOffset -= Overflow;
8143     if ((int32_t)Overflow < 0) {
8144       Overflow += ImmOffset;
8145       ImmOffset = 0;
8146     }
8147     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
8148     if (Overflow) {
8149       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
8150       if (!N0)
8151         N0 = OverflowVal;
8152       else {
8153         SDValue Ops[] = { N0, OverflowVal };
8154         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
8155       }
8156     }
8157   }
8158   if (!N0)
8159     N0 = DAG.getConstant(0, DL, MVT::i32);
8160   if (!C1)
8161     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
8162   return {N0, SDValue(C1, 0)};
8163 }
8164 
8165 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
8166 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
8167 // pointed to by Offsets.
8168 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
8169                                         SelectionDAG &DAG, SDValue *Offsets,
8170                                         Align Alignment) const {
8171   SDLoc DL(CombinedOffset);
8172   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
8173     uint32_t Imm = C->getZExtValue();
8174     uint32_t SOffset, ImmOffset;
8175     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
8176                                  Alignment)) {
8177       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
8178       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8179       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8180       return;
8181     }
8182   }
8183   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
8184     SDValue N0 = CombinedOffset.getOperand(0);
8185     SDValue N1 = CombinedOffset.getOperand(1);
8186     uint32_t SOffset, ImmOffset;
8187     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
8188     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
8189                                                 Subtarget, Alignment)) {
8190       Offsets[0] = N0;
8191       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8192       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8193       return;
8194     }
8195   }
8196   Offsets[0] = CombinedOffset;
8197   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
8198   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
8199 }
8200 
8201 // Handle 8 bit and 16 bit buffer loads
8202 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
8203                                                      EVT LoadVT, SDLoc DL,
8204                                                      ArrayRef<SDValue> Ops,
8205                                                      MemSDNode *M) const {
8206   EVT IntVT = LoadVT.changeTypeToInteger();
8207   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
8208          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
8209 
8210   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
8211   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
8212                                                Ops, IntVT,
8213                                                M->getMemOperand());
8214   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
8215   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
8216 
8217   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
8218 }
8219 
8220 // Handle 8 bit and 16 bit buffer stores
8221 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
8222                                                       EVT VDataType, SDLoc DL,
8223                                                       SDValue Ops[],
8224                                                       MemSDNode *M) const {
8225   if (VDataType == MVT::f16)
8226     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
8227 
8228   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
8229   Ops[1] = BufferStoreExt;
8230   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
8231                                  AMDGPUISD::BUFFER_STORE_SHORT;
8232   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
8233   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
8234                                      M->getMemOperand());
8235 }
8236 
8237 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
8238                                  ISD::LoadExtType ExtType, SDValue Op,
8239                                  const SDLoc &SL, EVT VT) {
8240   if (VT.bitsLT(Op.getValueType()))
8241     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
8242 
8243   switch (ExtType) {
8244   case ISD::SEXTLOAD:
8245     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
8246   case ISD::ZEXTLOAD:
8247     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
8248   case ISD::EXTLOAD:
8249     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
8250   case ISD::NON_EXTLOAD:
8251     return Op;
8252   }
8253 
8254   llvm_unreachable("invalid ext type");
8255 }
8256 
8257 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
8258   SelectionDAG &DAG = DCI.DAG;
8259   if (Ld->getAlignment() < 4 || Ld->isDivergent())
8260     return SDValue();
8261 
8262   // FIXME: Constant loads should all be marked invariant.
8263   unsigned AS = Ld->getAddressSpace();
8264   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
8265       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
8266       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
8267     return SDValue();
8268 
8269   // Don't do this early, since it may interfere with adjacent load merging for
8270   // illegal types. We can avoid losing alignment information for exotic types
8271   // pre-legalize.
8272   EVT MemVT = Ld->getMemoryVT();
8273   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
8274       MemVT.getSizeInBits() >= 32)
8275     return SDValue();
8276 
8277   SDLoc SL(Ld);
8278 
8279   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
8280          "unexpected vector extload");
8281 
8282   // TODO: Drop only high part of range.
8283   SDValue Ptr = Ld->getBasePtr();
8284   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
8285                                 MVT::i32, SL, Ld->getChain(), Ptr,
8286                                 Ld->getOffset(),
8287                                 Ld->getPointerInfo(), MVT::i32,
8288                                 Ld->getAlignment(),
8289                                 Ld->getMemOperand()->getFlags(),
8290                                 Ld->getAAInfo(),
8291                                 nullptr); // Drop ranges
8292 
8293   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
8294   if (MemVT.isFloatingPoint()) {
8295     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
8296            "unexpected fp extload");
8297     TruncVT = MemVT.changeTypeToInteger();
8298   }
8299 
8300   SDValue Cvt = NewLoad;
8301   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
8302     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
8303                       DAG.getValueType(TruncVT));
8304   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
8305              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
8306     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
8307   } else {
8308     assert(Ld->getExtensionType() == ISD::EXTLOAD);
8309   }
8310 
8311   EVT VT = Ld->getValueType(0);
8312   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8313 
8314   DCI.AddToWorklist(Cvt.getNode());
8315 
8316   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
8317   // the appropriate extension from the 32-bit load.
8318   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
8319   DCI.AddToWorklist(Cvt.getNode());
8320 
8321   // Handle conversion back to floating point if necessary.
8322   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8323 
8324   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8325 }
8326 
8327 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8328   SDLoc DL(Op);
8329   LoadSDNode *Load = cast<LoadSDNode>(Op);
8330   ISD::LoadExtType ExtType = Load->getExtensionType();
8331   EVT MemVT = Load->getMemoryVT();
8332 
8333   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8334     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8335       return SDValue();
8336 
8337     // FIXME: Copied from PPC
8338     // First, load into 32 bits, then truncate to 1 bit.
8339 
8340     SDValue Chain = Load->getChain();
8341     SDValue BasePtr = Load->getBasePtr();
8342     MachineMemOperand *MMO = Load->getMemOperand();
8343 
8344     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8345 
8346     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8347                                    BasePtr, RealMemVT, MMO);
8348 
8349     if (!MemVT.isVector()) {
8350       SDValue Ops[] = {
8351         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8352         NewLD.getValue(1)
8353       };
8354 
8355       return DAG.getMergeValues(Ops, DL);
8356     }
8357 
8358     SmallVector<SDValue, 3> Elts;
8359     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8360       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8361                                 DAG.getConstant(I, DL, MVT::i32));
8362 
8363       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8364     }
8365 
8366     SDValue Ops[] = {
8367       DAG.getBuildVector(MemVT, DL, Elts),
8368       NewLD.getValue(1)
8369     };
8370 
8371     return DAG.getMergeValues(Ops, DL);
8372   }
8373 
8374   if (!MemVT.isVector())
8375     return SDValue();
8376 
8377   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8378          "Custom lowering for non-i32 vectors hasn't been implemented.");
8379 
8380   unsigned Alignment = Load->getAlignment();
8381   unsigned AS = Load->getAddressSpace();
8382   if (Subtarget->hasLDSMisalignedBug() &&
8383       AS == AMDGPUAS::FLAT_ADDRESS &&
8384       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8385     return SplitVectorLoad(Op, DAG);
8386   }
8387 
8388   MachineFunction &MF = DAG.getMachineFunction();
8389   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8390   // If there is a possibility that flat instruction access scratch memory
8391   // then we need to use the same legalization rules we use for private.
8392   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8393       !Subtarget->hasMultiDwordFlatScratchAddressing())
8394     AS = MFI->hasFlatScratchInit() ?
8395          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8396 
8397   unsigned NumElements = MemVT.getVectorNumElements();
8398 
8399   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8400       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8401     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8402       if (MemVT.isPow2VectorType())
8403         return SDValue();
8404       return WidenOrSplitVectorLoad(Op, DAG);
8405     }
8406     // Non-uniform loads will be selected to MUBUF instructions, so they
8407     // have the same legalization requirements as global and private
8408     // loads.
8409     //
8410   }
8411 
8412   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8413       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8414       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8415     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8416         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8417         Alignment >= 4 && NumElements < 32) {
8418       if (MemVT.isPow2VectorType())
8419         return SDValue();
8420       return WidenOrSplitVectorLoad(Op, DAG);
8421     }
8422     // Non-uniform loads will be selected to MUBUF instructions, so they
8423     // have the same legalization requirements as global and private
8424     // loads.
8425     //
8426   }
8427   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8428       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8429       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8430       AS == AMDGPUAS::FLAT_ADDRESS) {
8431     if (NumElements > 4)
8432       return SplitVectorLoad(Op, DAG);
8433     // v3 loads not supported on SI.
8434     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8435       return WidenOrSplitVectorLoad(Op, DAG);
8436 
8437     // v3 and v4 loads are supported for private and global memory.
8438     return SDValue();
8439   }
8440   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8441     // Depending on the setting of the private_element_size field in the
8442     // resource descriptor, we can only make private accesses up to a certain
8443     // size.
8444     switch (Subtarget->getMaxPrivateElementSize()) {
8445     case 4: {
8446       SDValue Ops[2];
8447       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8448       return DAG.getMergeValues(Ops, DL);
8449     }
8450     case 8:
8451       if (NumElements > 2)
8452         return SplitVectorLoad(Op, DAG);
8453       return SDValue();
8454     case 16:
8455       // Same as global/flat
8456       if (NumElements > 4)
8457         return SplitVectorLoad(Op, DAG);
8458       // v3 loads not supported on SI.
8459       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8460         return WidenOrSplitVectorLoad(Op, DAG);
8461 
8462       return SDValue();
8463     default:
8464       llvm_unreachable("unsupported private_element_size");
8465     }
8466   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8467     // Use ds_read_b128 or ds_read_b96 when possible.
8468     if (Subtarget->hasDS96AndDS128() &&
8469         ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) ||
8470          MemVT.getStoreSize() == 12) &&
8471         allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8472                                            Load->getAlign()))
8473       return SDValue();
8474 
8475     if (NumElements > 2)
8476       return SplitVectorLoad(Op, DAG);
8477 
8478     // SI has a hardware bug in the LDS / GDS bounds checking: if the base
8479     // address is negative, then the instruction is incorrectly treated as
8480     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8481     // loads here to avoid emitting ds_read2_b32. We may re-combine the
8482     // load later in the SILoadStoreOptimizer.
8483     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
8484         NumElements == 2 && MemVT.getStoreSize() == 8 &&
8485         Load->getAlignment() < 8) {
8486       return SplitVectorLoad(Op, DAG);
8487     }
8488   }
8489 
8490   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8491                                       MemVT, *Load->getMemOperand())) {
8492     SDValue Ops[2];
8493     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8494     return DAG.getMergeValues(Ops, DL);
8495   }
8496 
8497   return SDValue();
8498 }
8499 
8500 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8501   EVT VT = Op.getValueType();
8502   if (VT.getSizeInBits() == 128)
8503     return splitTernaryVectorOp(Op, DAG);
8504 
8505   assert(VT.getSizeInBits() == 64);
8506 
8507   SDLoc DL(Op);
8508   SDValue Cond = Op.getOperand(0);
8509 
8510   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8511   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8512 
8513   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8514   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8515 
8516   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8517   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8518 
8519   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8520 
8521   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8522   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8523 
8524   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8525 
8526   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8527   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8528 }
8529 
8530 // Catch division cases where we can use shortcuts with rcp and rsq
8531 // instructions.
8532 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8533                                               SelectionDAG &DAG) const {
8534   SDLoc SL(Op);
8535   SDValue LHS = Op.getOperand(0);
8536   SDValue RHS = Op.getOperand(1);
8537   EVT VT = Op.getValueType();
8538   const SDNodeFlags Flags = Op->getFlags();
8539 
8540   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8541 
8542   // Without !fpmath accuracy information, we can't do more because we don't
8543   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8544   if (!AllowInaccurateRcp)
8545     return SDValue();
8546 
8547   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8548     if (CLHS->isExactlyValue(1.0)) {
8549       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8550       // the CI documentation has a worst case error of 1 ulp.
8551       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8552       // use it as long as we aren't trying to use denormals.
8553       //
8554       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8555 
8556       // 1.0 / sqrt(x) -> rsq(x)
8557 
8558       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8559       // error seems really high at 2^29 ULP.
8560       if (RHS.getOpcode() == ISD::FSQRT)
8561         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8562 
8563       // 1.0 / x -> rcp(x)
8564       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8565     }
8566 
8567     // Same as for 1.0, but expand the sign out of the constant.
8568     if (CLHS->isExactlyValue(-1.0)) {
8569       // -1.0 / x -> rcp (fneg x)
8570       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8571       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8572     }
8573   }
8574 
8575   // Turn into multiply by the reciprocal.
8576   // x / y -> x * (1.0 / y)
8577   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8578   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8579 }
8580 
8581 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8582                                                 SelectionDAG &DAG) const {
8583   SDLoc SL(Op);
8584   SDValue X = Op.getOperand(0);
8585   SDValue Y = Op.getOperand(1);
8586   EVT VT = Op.getValueType();
8587   const SDNodeFlags Flags = Op->getFlags();
8588 
8589   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8590                             DAG.getTarget().Options.UnsafeFPMath;
8591   if (!AllowInaccurateDiv)
8592     return SDValue();
8593 
8594   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8595   SDValue One = DAG.getConstantFP(1.0, SL, VT);
8596 
8597   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8598   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8599 
8600   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8601   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8602   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8603   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8604   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8605   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8606 }
8607 
8608 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8609                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8610                           SDNodeFlags Flags) {
8611   if (GlueChain->getNumValues() <= 1) {
8612     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8613   }
8614 
8615   assert(GlueChain->getNumValues() == 3);
8616 
8617   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8618   switch (Opcode) {
8619   default: llvm_unreachable("no chain equivalent for opcode");
8620   case ISD::FMUL:
8621     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8622     break;
8623   }
8624 
8625   return DAG.getNode(Opcode, SL, VTList,
8626                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8627                      Flags);
8628 }
8629 
8630 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8631                            EVT VT, SDValue A, SDValue B, SDValue C,
8632                            SDValue GlueChain, SDNodeFlags Flags) {
8633   if (GlueChain->getNumValues() <= 1) {
8634     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8635   }
8636 
8637   assert(GlueChain->getNumValues() == 3);
8638 
8639   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8640   switch (Opcode) {
8641   default: llvm_unreachable("no chain equivalent for opcode");
8642   case ISD::FMA:
8643     Opcode = AMDGPUISD::FMA_W_CHAIN;
8644     break;
8645   }
8646 
8647   return DAG.getNode(Opcode, SL, VTList,
8648                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8649                      Flags);
8650 }
8651 
8652 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8653   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8654     return FastLowered;
8655 
8656   SDLoc SL(Op);
8657   SDValue Src0 = Op.getOperand(0);
8658   SDValue Src1 = Op.getOperand(1);
8659 
8660   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8661   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8662 
8663   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8664   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8665 
8666   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8667   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8668 
8669   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8670 }
8671 
8672 // Faster 2.5 ULP division that does not support denormals.
8673 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8674   SDLoc SL(Op);
8675   SDValue LHS = Op.getOperand(1);
8676   SDValue RHS = Op.getOperand(2);
8677 
8678   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8679 
8680   const APFloat K0Val(BitsToFloat(0x6f800000));
8681   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8682 
8683   const APFloat K1Val(BitsToFloat(0x2f800000));
8684   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8685 
8686   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8687 
8688   EVT SetCCVT =
8689     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8690 
8691   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8692 
8693   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8694 
8695   // TODO: Should this propagate fast-math-flags?
8696   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8697 
8698   // rcp does not support denormals.
8699   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8700 
8701   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8702 
8703   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8704 }
8705 
8706 // Returns immediate value for setting the F32 denorm mode when using the
8707 // S_DENORM_MODE instruction.
8708 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8709                                     const SDLoc &SL, const GCNSubtarget *ST) {
8710   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8711   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8712                                 ? FP_DENORM_FLUSH_NONE
8713                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8714 
8715   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8716   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8717 }
8718 
8719 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8720   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8721     return FastLowered;
8722 
8723   // The selection matcher assumes anything with a chain selecting to a
8724   // mayRaiseFPException machine instruction. Since we're introducing a chain
8725   // here, we need to explicitly report nofpexcept for the regular fdiv
8726   // lowering.
8727   SDNodeFlags Flags = Op->getFlags();
8728   Flags.setNoFPExcept(true);
8729 
8730   SDLoc SL(Op);
8731   SDValue LHS = Op.getOperand(0);
8732   SDValue RHS = Op.getOperand(1);
8733 
8734   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8735 
8736   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8737 
8738   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8739                                           {RHS, RHS, LHS}, Flags);
8740   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8741                                         {LHS, RHS, LHS}, Flags);
8742 
8743   // Denominator is scaled to not be denormal, so using rcp is ok.
8744   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8745                                   DenominatorScaled, Flags);
8746   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8747                                      DenominatorScaled, Flags);
8748 
8749   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8750                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8751                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8752   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8753 
8754   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8755 
8756   if (!HasFP32Denormals) {
8757     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8758     // lowering. The chain dependence is insufficient, and we need glue. We do
8759     // not need the glue variants in a strictfp function.
8760 
8761     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8762 
8763     SDNode *EnableDenorm;
8764     if (Subtarget->hasDenormModeInst()) {
8765       const SDValue EnableDenormValue =
8766           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8767 
8768       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8769                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8770     } else {
8771       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8772                                                         SL, MVT::i32);
8773       EnableDenorm =
8774           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8775                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8776     }
8777 
8778     SDValue Ops[3] = {
8779       NegDivScale0,
8780       SDValue(EnableDenorm, 0),
8781       SDValue(EnableDenorm, 1)
8782     };
8783 
8784     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8785   }
8786 
8787   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8788                              ApproxRcp, One, NegDivScale0, Flags);
8789 
8790   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8791                              ApproxRcp, Fma0, Flags);
8792 
8793   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8794                            Fma1, Fma1, Flags);
8795 
8796   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8797                              NumeratorScaled, Mul, Flags);
8798 
8799   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8800                              Fma2, Fma1, Mul, Fma2, Flags);
8801 
8802   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8803                              NumeratorScaled, Fma3, Flags);
8804 
8805   if (!HasFP32Denormals) {
8806     SDNode *DisableDenorm;
8807     if (Subtarget->hasDenormModeInst()) {
8808       const SDValue DisableDenormValue =
8809           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8810 
8811       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8812                                   Fma4.getValue(1), DisableDenormValue,
8813                                   Fma4.getValue(2)).getNode();
8814     } else {
8815       const SDValue DisableDenormValue =
8816           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8817 
8818       DisableDenorm = DAG.getMachineNode(
8819           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8820           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8821     }
8822 
8823     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8824                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8825     DAG.setRoot(OutputChain);
8826   }
8827 
8828   SDValue Scale = NumeratorScaled.getValue(1);
8829   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8830                              {Fma4, Fma1, Fma3, Scale}, Flags);
8831 
8832   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8833 }
8834 
8835 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8836   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
8837     return FastLowered;
8838 
8839   SDLoc SL(Op);
8840   SDValue X = Op.getOperand(0);
8841   SDValue Y = Op.getOperand(1);
8842 
8843   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8844 
8845   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8846 
8847   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8848 
8849   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8850 
8851   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8852 
8853   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8854 
8855   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8856 
8857   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8858 
8859   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8860 
8861   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8862   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8863 
8864   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8865                              NegDivScale0, Mul, DivScale1);
8866 
8867   SDValue Scale;
8868 
8869   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8870     // Workaround a hardware bug on SI where the condition output from div_scale
8871     // is not usable.
8872 
8873     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8874 
8875     // Figure out if the scale to use for div_fmas.
8876     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8877     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8878     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8879     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8880 
8881     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8882     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8883 
8884     SDValue Scale0Hi
8885       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8886     SDValue Scale1Hi
8887       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8888 
8889     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8890     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8891     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8892   } else {
8893     Scale = DivScale1.getValue(1);
8894   }
8895 
8896   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8897                              Fma4, Fma3, Mul, Scale);
8898 
8899   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8900 }
8901 
8902 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8903   EVT VT = Op.getValueType();
8904 
8905   if (VT == MVT::f32)
8906     return LowerFDIV32(Op, DAG);
8907 
8908   if (VT == MVT::f64)
8909     return LowerFDIV64(Op, DAG);
8910 
8911   if (VT == MVT::f16)
8912     return LowerFDIV16(Op, DAG);
8913 
8914   llvm_unreachable("Unexpected type for fdiv");
8915 }
8916 
8917 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8918   SDLoc DL(Op);
8919   StoreSDNode *Store = cast<StoreSDNode>(Op);
8920   EVT VT = Store->getMemoryVT();
8921 
8922   if (VT == MVT::i1) {
8923     return DAG.getTruncStore(Store->getChain(), DL,
8924        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8925        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8926   }
8927 
8928   assert(VT.isVector() &&
8929          Store->getValue().getValueType().getScalarType() == MVT::i32);
8930 
8931   unsigned AS = Store->getAddressSpace();
8932   if (Subtarget->hasLDSMisalignedBug() &&
8933       AS == AMDGPUAS::FLAT_ADDRESS &&
8934       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8935     return SplitVectorStore(Op, DAG);
8936   }
8937 
8938   MachineFunction &MF = DAG.getMachineFunction();
8939   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8940   // If there is a possibility that flat instruction access scratch memory
8941   // then we need to use the same legalization rules we use for private.
8942   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8943       !Subtarget->hasMultiDwordFlatScratchAddressing())
8944     AS = MFI->hasFlatScratchInit() ?
8945          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8946 
8947   unsigned NumElements = VT.getVectorNumElements();
8948   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8949       AS == AMDGPUAS::FLAT_ADDRESS) {
8950     if (NumElements > 4)
8951       return SplitVectorStore(Op, DAG);
8952     // v3 stores not supported on SI.
8953     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8954       return SplitVectorStore(Op, DAG);
8955 
8956     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8957                                         VT, *Store->getMemOperand()))
8958       return expandUnalignedStore(Store, DAG);
8959 
8960     return SDValue();
8961   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8962     switch (Subtarget->getMaxPrivateElementSize()) {
8963     case 4:
8964       return scalarizeVectorStore(Store, DAG);
8965     case 8:
8966       if (NumElements > 2)
8967         return SplitVectorStore(Op, DAG);
8968       return SDValue();
8969     case 16:
8970       if (NumElements > 4 ||
8971           (NumElements == 3 && !Subtarget->enableFlatScratch()))
8972         return SplitVectorStore(Op, DAG);
8973       return SDValue();
8974     default:
8975       llvm_unreachable("unsupported private_element_size");
8976     }
8977   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8978     // Use ds_write_b128 or ds_write_b96 when possible.
8979     if (Subtarget->hasDS96AndDS128() &&
8980         ((Subtarget->useDS128() && VT.getStoreSize() == 16) ||
8981          (VT.getStoreSize() == 12)) &&
8982         allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
8983                                            Store->getAlign()))
8984       return SDValue();
8985 
8986     if (NumElements > 2)
8987       return SplitVectorStore(Op, DAG);
8988 
8989     // SI has a hardware bug in the LDS / GDS bounds checking: if the base
8990     // address is negative, then the instruction is incorrectly treated as
8991     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8992     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8993     // store later in the SILoadStoreOptimizer.
8994     if (!Subtarget->hasUsableDSOffset() &&
8995         NumElements == 2 && VT.getStoreSize() == 8 &&
8996         Store->getAlignment() < 8) {
8997       return SplitVectorStore(Op, DAG);
8998     }
8999 
9000     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
9001                                         VT, *Store->getMemOperand())) {
9002       if (VT.isVector())
9003         return SplitVectorStore(Op, DAG);
9004       return expandUnalignedStore(Store, DAG);
9005     }
9006 
9007     return SDValue();
9008   } else {
9009     llvm_unreachable("unhandled address space");
9010   }
9011 }
9012 
9013 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
9014   SDLoc DL(Op);
9015   EVT VT = Op.getValueType();
9016   SDValue Arg = Op.getOperand(0);
9017   SDValue TrigVal;
9018 
9019   // Propagate fast-math flags so that the multiply we introduce can be folded
9020   // if Arg is already the result of a multiply by constant.
9021   auto Flags = Op->getFlags();
9022 
9023   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
9024 
9025   if (Subtarget->hasTrigReducedRange()) {
9026     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9027     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
9028   } else {
9029     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9030   }
9031 
9032   switch (Op.getOpcode()) {
9033   case ISD::FCOS:
9034     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
9035   case ISD::FSIN:
9036     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
9037   default:
9038     llvm_unreachable("Wrong trig opcode");
9039   }
9040 }
9041 
9042 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9043   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
9044   assert(AtomicNode->isCompareAndSwap());
9045   unsigned AS = AtomicNode->getAddressSpace();
9046 
9047   // No custom lowering required for local address space
9048   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
9049     return Op;
9050 
9051   // Non-local address space requires custom lowering for atomic compare
9052   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
9053   SDLoc DL(Op);
9054   SDValue ChainIn = Op.getOperand(0);
9055   SDValue Addr = Op.getOperand(1);
9056   SDValue Old = Op.getOperand(2);
9057   SDValue New = Op.getOperand(3);
9058   EVT VT = Op.getValueType();
9059   MVT SimpleVT = VT.getSimpleVT();
9060   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
9061 
9062   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
9063   SDValue Ops[] = { ChainIn, Addr, NewOld };
9064 
9065   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
9066                                  Ops, VT, AtomicNode->getMemOperand());
9067 }
9068 
9069 //===----------------------------------------------------------------------===//
9070 // Custom DAG optimizations
9071 //===----------------------------------------------------------------------===//
9072 
9073 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
9074                                                      DAGCombinerInfo &DCI) const {
9075   EVT VT = N->getValueType(0);
9076   EVT ScalarVT = VT.getScalarType();
9077   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
9078     return SDValue();
9079 
9080   SelectionDAG &DAG = DCI.DAG;
9081   SDLoc DL(N);
9082 
9083   SDValue Src = N->getOperand(0);
9084   EVT SrcVT = Src.getValueType();
9085 
9086   // TODO: We could try to match extracting the higher bytes, which would be
9087   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
9088   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
9089   // about in practice.
9090   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
9091     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
9092       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
9093       DCI.AddToWorklist(Cvt.getNode());
9094 
9095       // For the f16 case, fold to a cast to f32 and then cast back to f16.
9096       if (ScalarVT != MVT::f32) {
9097         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
9098                           DAG.getTargetConstant(0, DL, MVT::i32));
9099       }
9100       return Cvt;
9101     }
9102   }
9103 
9104   return SDValue();
9105 }
9106 
9107 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
9108 
9109 // This is a variant of
9110 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
9111 //
9112 // The normal DAG combiner will do this, but only if the add has one use since
9113 // that would increase the number of instructions.
9114 //
9115 // This prevents us from seeing a constant offset that can be folded into a
9116 // memory instruction's addressing mode. If we know the resulting add offset of
9117 // a pointer can be folded into an addressing offset, we can replace the pointer
9118 // operand with the add of new constant offset. This eliminates one of the uses,
9119 // and may allow the remaining use to also be simplified.
9120 //
9121 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
9122                                                unsigned AddrSpace,
9123                                                EVT MemVT,
9124                                                DAGCombinerInfo &DCI) const {
9125   SDValue N0 = N->getOperand(0);
9126   SDValue N1 = N->getOperand(1);
9127 
9128   // We only do this to handle cases where it's profitable when there are
9129   // multiple uses of the add, so defer to the standard combine.
9130   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
9131       N0->hasOneUse())
9132     return SDValue();
9133 
9134   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
9135   if (!CN1)
9136     return SDValue();
9137 
9138   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9139   if (!CAdd)
9140     return SDValue();
9141 
9142   // If the resulting offset is too large, we can't fold it into the addressing
9143   // mode offset.
9144   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
9145   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
9146 
9147   AddrMode AM;
9148   AM.HasBaseReg = true;
9149   AM.BaseOffs = Offset.getSExtValue();
9150   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
9151     return SDValue();
9152 
9153   SelectionDAG &DAG = DCI.DAG;
9154   SDLoc SL(N);
9155   EVT VT = N->getValueType(0);
9156 
9157   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
9158   SDValue COffset = DAG.getConstant(Offset, SL, VT);
9159 
9160   SDNodeFlags Flags;
9161   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
9162                           (N0.getOpcode() == ISD::OR ||
9163                            N0->getFlags().hasNoUnsignedWrap()));
9164 
9165   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
9166 }
9167 
9168 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
9169 /// by the chain and intrinsic ID. Theoretically we would also need to check the
9170 /// specific intrinsic, but they all place the pointer operand first.
9171 static unsigned getBasePtrIndex(const MemSDNode *N) {
9172   switch (N->getOpcode()) {
9173   case ISD::STORE:
9174   case ISD::INTRINSIC_W_CHAIN:
9175   case ISD::INTRINSIC_VOID:
9176     return 2;
9177   default:
9178     return 1;
9179   }
9180 }
9181 
9182 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
9183                                                   DAGCombinerInfo &DCI) const {
9184   SelectionDAG &DAG = DCI.DAG;
9185   SDLoc SL(N);
9186 
9187   unsigned PtrIdx = getBasePtrIndex(N);
9188   SDValue Ptr = N->getOperand(PtrIdx);
9189 
9190   // TODO: We could also do this for multiplies.
9191   if (Ptr.getOpcode() == ISD::SHL) {
9192     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
9193                                           N->getMemoryVT(), DCI);
9194     if (NewPtr) {
9195       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
9196 
9197       NewOps[PtrIdx] = NewPtr;
9198       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
9199     }
9200   }
9201 
9202   return SDValue();
9203 }
9204 
9205 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
9206   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
9207          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
9208          (Opc == ISD::XOR && Val == 0);
9209 }
9210 
9211 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
9212 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
9213 // integer combine opportunities since most 64-bit operations are decomposed
9214 // this way.  TODO: We won't want this for SALU especially if it is an inline
9215 // immediate.
9216 SDValue SITargetLowering::splitBinaryBitConstantOp(
9217   DAGCombinerInfo &DCI,
9218   const SDLoc &SL,
9219   unsigned Opc, SDValue LHS,
9220   const ConstantSDNode *CRHS) const {
9221   uint64_t Val = CRHS->getZExtValue();
9222   uint32_t ValLo = Lo_32(Val);
9223   uint32_t ValHi = Hi_32(Val);
9224   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9225 
9226     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
9227          bitOpWithConstantIsReducible(Opc, ValHi)) ||
9228         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
9229     // If we need to materialize a 64-bit immediate, it will be split up later
9230     // anyway. Avoid creating the harder to understand 64-bit immediate
9231     // materialization.
9232     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
9233   }
9234 
9235   return SDValue();
9236 }
9237 
9238 // Returns true if argument is a boolean value which is not serialized into
9239 // memory or argument and does not require v_cndmask_b32 to be deserialized.
9240 static bool isBoolSGPR(SDValue V) {
9241   if (V.getValueType() != MVT::i1)
9242     return false;
9243   switch (V.getOpcode()) {
9244   default:
9245     break;
9246   case ISD::SETCC:
9247   case AMDGPUISD::FP_CLASS:
9248     return true;
9249   case ISD::AND:
9250   case ISD::OR:
9251   case ISD::XOR:
9252     return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
9253   }
9254   return false;
9255 }
9256 
9257 // If a constant has all zeroes or all ones within each byte return it.
9258 // Otherwise return 0.
9259 static uint32_t getConstantPermuteMask(uint32_t C) {
9260   // 0xff for any zero byte in the mask
9261   uint32_t ZeroByteMask = 0;
9262   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
9263   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
9264   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
9265   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
9266   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
9267   if ((NonZeroByteMask & C) != NonZeroByteMask)
9268     return 0; // Partial bytes selected.
9269   return C;
9270 }
9271 
9272 // Check if a node selects whole bytes from its operand 0 starting at a byte
9273 // boundary while masking the rest. Returns select mask as in the v_perm_b32
9274 // or -1 if not succeeded.
9275 // Note byte select encoding:
9276 // value 0-3 selects corresponding source byte;
9277 // value 0xc selects zero;
9278 // value 0xff selects 0xff.
9279 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
9280   assert(V.getValueSizeInBits() == 32);
9281 
9282   if (V.getNumOperands() != 2)
9283     return ~0;
9284 
9285   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
9286   if (!N1)
9287     return ~0;
9288 
9289   uint32_t C = N1->getZExtValue();
9290 
9291   switch (V.getOpcode()) {
9292   default:
9293     break;
9294   case ISD::AND:
9295     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9296       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
9297     }
9298     break;
9299 
9300   case ISD::OR:
9301     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9302       return (0x03020100 & ~ConstMask) | ConstMask;
9303     }
9304     break;
9305 
9306   case ISD::SHL:
9307     if (C % 8)
9308       return ~0;
9309 
9310     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
9311 
9312   case ISD::SRL:
9313     if (C % 8)
9314       return ~0;
9315 
9316     return uint32_t(0x0c0c0c0c03020100ull >> C);
9317   }
9318 
9319   return ~0;
9320 }
9321 
9322 SDValue SITargetLowering::performAndCombine(SDNode *N,
9323                                             DAGCombinerInfo &DCI) const {
9324   if (DCI.isBeforeLegalize())
9325     return SDValue();
9326 
9327   SelectionDAG &DAG = DCI.DAG;
9328   EVT VT = N->getValueType(0);
9329   SDValue LHS = N->getOperand(0);
9330   SDValue RHS = N->getOperand(1);
9331 
9332 
9333   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9334   if (VT == MVT::i64 && CRHS) {
9335     if (SDValue Split
9336         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9337       return Split;
9338   }
9339 
9340   if (CRHS && VT == MVT::i32) {
9341     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9342     // nb = number of trailing zeroes in mask
9343     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9344     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9345     uint64_t Mask = CRHS->getZExtValue();
9346     unsigned Bits = countPopulation(Mask);
9347     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9348         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9349       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9350         unsigned Shift = CShift->getZExtValue();
9351         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9352         unsigned Offset = NB + Shift;
9353         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9354           SDLoc SL(N);
9355           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9356                                     LHS->getOperand(0),
9357                                     DAG.getConstant(Offset, SL, MVT::i32),
9358                                     DAG.getConstant(Bits, SL, MVT::i32));
9359           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9360           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9361                                     DAG.getValueType(NarrowVT));
9362           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9363                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9364           return Shl;
9365         }
9366       }
9367     }
9368 
9369     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9370     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9371         isa<ConstantSDNode>(LHS.getOperand(2))) {
9372       uint32_t Sel = getConstantPermuteMask(Mask);
9373       if (!Sel)
9374         return SDValue();
9375 
9376       // Select 0xc for all zero bytes
9377       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9378       SDLoc DL(N);
9379       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9380                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9381     }
9382   }
9383 
9384   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9385   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9386   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9387     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9388     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9389 
9390     SDValue X = LHS.getOperand(0);
9391     SDValue Y = RHS.getOperand(0);
9392     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9393       return SDValue();
9394 
9395     if (LCC == ISD::SETO) {
9396       if (X != LHS.getOperand(1))
9397         return SDValue();
9398 
9399       if (RCC == ISD::SETUNE) {
9400         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9401         if (!C1 || !C1->isInfinity() || C1->isNegative())
9402           return SDValue();
9403 
9404         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9405                               SIInstrFlags::N_SUBNORMAL |
9406                               SIInstrFlags::N_ZERO |
9407                               SIInstrFlags::P_ZERO |
9408                               SIInstrFlags::P_SUBNORMAL |
9409                               SIInstrFlags::P_NORMAL;
9410 
9411         static_assert(((~(SIInstrFlags::S_NAN |
9412                           SIInstrFlags::Q_NAN |
9413                           SIInstrFlags::N_INFINITY |
9414                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9415                       "mask not equal");
9416 
9417         SDLoc DL(N);
9418         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9419                            X, DAG.getConstant(Mask, DL, MVT::i32));
9420       }
9421     }
9422   }
9423 
9424   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9425     std::swap(LHS, RHS);
9426 
9427   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9428       RHS.hasOneUse()) {
9429     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9430     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9431     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9432     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9433     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9434         (RHS.getOperand(0) == LHS.getOperand(0) &&
9435          LHS.getOperand(0) == LHS.getOperand(1))) {
9436       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9437       unsigned NewMask = LCC == ISD::SETO ?
9438         Mask->getZExtValue() & ~OrdMask :
9439         Mask->getZExtValue() & OrdMask;
9440 
9441       SDLoc DL(N);
9442       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9443                          DAG.getConstant(NewMask, DL, MVT::i32));
9444     }
9445   }
9446 
9447   if (VT == MVT::i32 &&
9448       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9449     // and x, (sext cc from i1) => select cc, x, 0
9450     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9451       std::swap(LHS, RHS);
9452     if (isBoolSGPR(RHS.getOperand(0)))
9453       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9454                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9455   }
9456 
9457   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9458   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9459   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9460       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9461     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9462     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9463     if (LHSMask != ~0u && RHSMask != ~0u) {
9464       // Canonicalize the expression in an attempt to have fewer unique masks
9465       // and therefore fewer registers used to hold the masks.
9466       if (LHSMask > RHSMask) {
9467         std::swap(LHSMask, RHSMask);
9468         std::swap(LHS, RHS);
9469       }
9470 
9471       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9472       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9473       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9474       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9475 
9476       // Check of we need to combine values from two sources within a byte.
9477       if (!(LHSUsedLanes & RHSUsedLanes) &&
9478           // If we select high and lower word keep it for SDWA.
9479           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9480           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9481         // Each byte in each mask is either selector mask 0-3, or has higher
9482         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9483         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9484         // mask which is not 0xff wins. By anding both masks we have a correct
9485         // result except that 0x0c shall be corrected to give 0x0c only.
9486         uint32_t Mask = LHSMask & RHSMask;
9487         for (unsigned I = 0; I < 32; I += 8) {
9488           uint32_t ByteSel = 0xff << I;
9489           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9490             Mask &= (0x0c << I) & 0xffffffff;
9491         }
9492 
9493         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9494         // or 0x0c.
9495         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9496         SDLoc DL(N);
9497 
9498         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9499                            LHS.getOperand(0), RHS.getOperand(0),
9500                            DAG.getConstant(Sel, DL, MVT::i32));
9501       }
9502     }
9503   }
9504 
9505   return SDValue();
9506 }
9507 
9508 SDValue SITargetLowering::performOrCombine(SDNode *N,
9509                                            DAGCombinerInfo &DCI) const {
9510   SelectionDAG &DAG = DCI.DAG;
9511   SDValue LHS = N->getOperand(0);
9512   SDValue RHS = N->getOperand(1);
9513 
9514   EVT VT = N->getValueType(0);
9515   if (VT == MVT::i1) {
9516     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9517     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9518         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9519       SDValue Src = LHS.getOperand(0);
9520       if (Src != RHS.getOperand(0))
9521         return SDValue();
9522 
9523       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9524       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9525       if (!CLHS || !CRHS)
9526         return SDValue();
9527 
9528       // Only 10 bits are used.
9529       static const uint32_t MaxMask = 0x3ff;
9530 
9531       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9532       SDLoc DL(N);
9533       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9534                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9535     }
9536 
9537     return SDValue();
9538   }
9539 
9540   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9541   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9542       LHS.getOpcode() == AMDGPUISD::PERM &&
9543       isa<ConstantSDNode>(LHS.getOperand(2))) {
9544     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9545     if (!Sel)
9546       return SDValue();
9547 
9548     Sel |= LHS.getConstantOperandVal(2);
9549     SDLoc DL(N);
9550     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9551                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9552   }
9553 
9554   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9555   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9556   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9557       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9558     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9559     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9560     if (LHSMask != ~0u && RHSMask != ~0u) {
9561       // Canonicalize the expression in an attempt to have fewer unique masks
9562       // and therefore fewer registers used to hold the masks.
9563       if (LHSMask > RHSMask) {
9564         std::swap(LHSMask, RHSMask);
9565         std::swap(LHS, RHS);
9566       }
9567 
9568       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9569       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9570       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9571       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9572 
9573       // Check of we need to combine values from two sources within a byte.
9574       if (!(LHSUsedLanes & RHSUsedLanes) &&
9575           // If we select high and lower word keep it for SDWA.
9576           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9577           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9578         // Kill zero bytes selected by other mask. Zero value is 0xc.
9579         LHSMask &= ~RHSUsedLanes;
9580         RHSMask &= ~LHSUsedLanes;
9581         // Add 4 to each active LHS lane
9582         LHSMask |= LHSUsedLanes & 0x04040404;
9583         // Combine masks
9584         uint32_t Sel = LHSMask | RHSMask;
9585         SDLoc DL(N);
9586 
9587         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9588                            LHS.getOperand(0), RHS.getOperand(0),
9589                            DAG.getConstant(Sel, DL, MVT::i32));
9590       }
9591     }
9592   }
9593 
9594   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9595     return SDValue();
9596 
9597   // TODO: This could be a generic combine with a predicate for extracting the
9598   // high half of an integer being free.
9599 
9600   // (or i64:x, (zero_extend i32:y)) ->
9601   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9602   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9603       RHS.getOpcode() != ISD::ZERO_EXTEND)
9604     std::swap(LHS, RHS);
9605 
9606   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9607     SDValue ExtSrc = RHS.getOperand(0);
9608     EVT SrcVT = ExtSrc.getValueType();
9609     if (SrcVT == MVT::i32) {
9610       SDLoc SL(N);
9611       SDValue LowLHS, HiBits;
9612       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9613       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9614 
9615       DCI.AddToWorklist(LowOr.getNode());
9616       DCI.AddToWorklist(HiBits.getNode());
9617 
9618       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9619                                 LowOr, HiBits);
9620       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9621     }
9622   }
9623 
9624   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9625   if (CRHS) {
9626     if (SDValue Split
9627           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR,
9628                                      N->getOperand(0), CRHS))
9629       return Split;
9630   }
9631 
9632   return SDValue();
9633 }
9634 
9635 SDValue SITargetLowering::performXorCombine(SDNode *N,
9636                                             DAGCombinerInfo &DCI) const {
9637   if (SDValue RV = reassociateScalarOps(N, DCI.DAG))
9638     return RV;
9639 
9640   EVT VT = N->getValueType(0);
9641   if (VT != MVT::i64)
9642     return SDValue();
9643 
9644   SDValue LHS = N->getOperand(0);
9645   SDValue RHS = N->getOperand(1);
9646 
9647   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9648   if (CRHS) {
9649     if (SDValue Split
9650           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9651       return Split;
9652   }
9653 
9654   return SDValue();
9655 }
9656 
9657 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9658                                                    DAGCombinerInfo &DCI) const {
9659   if (!Subtarget->has16BitInsts() ||
9660       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9661     return SDValue();
9662 
9663   EVT VT = N->getValueType(0);
9664   if (VT != MVT::i32)
9665     return SDValue();
9666 
9667   SDValue Src = N->getOperand(0);
9668   if (Src.getValueType() != MVT::i16)
9669     return SDValue();
9670 
9671   return SDValue();
9672 }
9673 
9674 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9675                                                         DAGCombinerInfo &DCI)
9676                                                         const {
9677   SDValue Src = N->getOperand(0);
9678   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9679 
9680   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9681       VTSign->getVT() == MVT::i8) ||
9682       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9683       VTSign->getVT() == MVT::i16)) &&
9684       Src.hasOneUse()) {
9685     auto *M = cast<MemSDNode>(Src);
9686     SDValue Ops[] = {
9687       Src.getOperand(0), // Chain
9688       Src.getOperand(1), // rsrc
9689       Src.getOperand(2), // vindex
9690       Src.getOperand(3), // voffset
9691       Src.getOperand(4), // soffset
9692       Src.getOperand(5), // offset
9693       Src.getOperand(6),
9694       Src.getOperand(7)
9695     };
9696     // replace with BUFFER_LOAD_BYTE/SHORT
9697     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9698                                          Src.getOperand(0).getValueType());
9699     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9700                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9701     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9702                                                           ResList,
9703                                                           Ops, M->getMemoryVT(),
9704                                                           M->getMemOperand());
9705     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9706                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9707   }
9708   return SDValue();
9709 }
9710 
9711 SDValue SITargetLowering::performClassCombine(SDNode *N,
9712                                               DAGCombinerInfo &DCI) const {
9713   SelectionDAG &DAG = DCI.DAG;
9714   SDValue Mask = N->getOperand(1);
9715 
9716   // fp_class x, 0 -> false
9717   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9718     if (CMask->isZero())
9719       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9720   }
9721 
9722   if (N->getOperand(0).isUndef())
9723     return DAG.getUNDEF(MVT::i1);
9724 
9725   return SDValue();
9726 }
9727 
9728 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9729                                             DAGCombinerInfo &DCI) const {
9730   EVT VT = N->getValueType(0);
9731   SDValue N0 = N->getOperand(0);
9732 
9733   if (N0.isUndef())
9734     return N0;
9735 
9736   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9737                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9738     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9739                            N->getFlags());
9740   }
9741 
9742   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9743     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9744                            N0.getOperand(0), N->getFlags());
9745   }
9746 
9747   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9748 }
9749 
9750 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9751                                        unsigned MaxDepth) const {
9752   unsigned Opcode = Op.getOpcode();
9753   if (Opcode == ISD::FCANONICALIZE)
9754     return true;
9755 
9756   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9757     auto F = CFP->getValueAPF();
9758     if (F.isNaN() && F.isSignaling())
9759       return false;
9760     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9761   }
9762 
9763   // If source is a result of another standard FP operation it is already in
9764   // canonical form.
9765   if (MaxDepth == 0)
9766     return false;
9767 
9768   switch (Opcode) {
9769   // These will flush denorms if required.
9770   case ISD::FADD:
9771   case ISD::FSUB:
9772   case ISD::FMUL:
9773   case ISD::FCEIL:
9774   case ISD::FFLOOR:
9775   case ISD::FMA:
9776   case ISD::FMAD:
9777   case ISD::FSQRT:
9778   case ISD::FDIV:
9779   case ISD::FREM:
9780   case ISD::FP_ROUND:
9781   case ISD::FP_EXTEND:
9782   case AMDGPUISD::FMUL_LEGACY:
9783   case AMDGPUISD::FMAD_FTZ:
9784   case AMDGPUISD::RCP:
9785   case AMDGPUISD::RSQ:
9786   case AMDGPUISD::RSQ_CLAMP:
9787   case AMDGPUISD::RCP_LEGACY:
9788   case AMDGPUISD::RCP_IFLAG:
9789   case AMDGPUISD::DIV_SCALE:
9790   case AMDGPUISD::DIV_FMAS:
9791   case AMDGPUISD::DIV_FIXUP:
9792   case AMDGPUISD::FRACT:
9793   case AMDGPUISD::LDEXP:
9794   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9795   case AMDGPUISD::CVT_F32_UBYTE0:
9796   case AMDGPUISD::CVT_F32_UBYTE1:
9797   case AMDGPUISD::CVT_F32_UBYTE2:
9798   case AMDGPUISD::CVT_F32_UBYTE3:
9799     return true;
9800 
9801   // It can/will be lowered or combined as a bit operation.
9802   // Need to check their input recursively to handle.
9803   case ISD::FNEG:
9804   case ISD::FABS:
9805   case ISD::FCOPYSIGN:
9806     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9807 
9808   case ISD::FSIN:
9809   case ISD::FCOS:
9810   case ISD::FSINCOS:
9811     return Op.getValueType().getScalarType() != MVT::f16;
9812 
9813   case ISD::FMINNUM:
9814   case ISD::FMAXNUM:
9815   case ISD::FMINNUM_IEEE:
9816   case ISD::FMAXNUM_IEEE:
9817   case AMDGPUISD::CLAMP:
9818   case AMDGPUISD::FMED3:
9819   case AMDGPUISD::FMAX3:
9820   case AMDGPUISD::FMIN3: {
9821     // FIXME: Shouldn't treat the generic operations different based these.
9822     // However, we aren't really required to flush the result from
9823     // minnum/maxnum..
9824 
9825     // snans will be quieted, so we only need to worry about denormals.
9826     if (Subtarget->supportsMinMaxDenormModes() ||
9827         denormalsEnabledForType(DAG, Op.getValueType()))
9828       return true;
9829 
9830     // Flushing may be required.
9831     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9832     // targets need to check their input recursively.
9833 
9834     // FIXME: Does this apply with clamp? It's implemented with max.
9835     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9836       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9837         return false;
9838     }
9839 
9840     return true;
9841   }
9842   case ISD::SELECT: {
9843     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9844            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9845   }
9846   case ISD::BUILD_VECTOR: {
9847     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9848       SDValue SrcOp = Op.getOperand(i);
9849       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9850         return false;
9851     }
9852 
9853     return true;
9854   }
9855   case ISD::EXTRACT_VECTOR_ELT:
9856   case ISD::EXTRACT_SUBVECTOR: {
9857     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9858   }
9859   case ISD::INSERT_VECTOR_ELT: {
9860     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9861            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9862   }
9863   case ISD::UNDEF:
9864     // Could be anything.
9865     return false;
9866 
9867   case ISD::BITCAST:
9868     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9869   case ISD::TRUNCATE: {
9870     // Hack round the mess we make when legalizing extract_vector_elt
9871     if (Op.getValueType() == MVT::i16) {
9872       SDValue TruncSrc = Op.getOperand(0);
9873       if (TruncSrc.getValueType() == MVT::i32 &&
9874           TruncSrc.getOpcode() == ISD::BITCAST &&
9875           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9876         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9877       }
9878     }
9879     return false;
9880   }
9881   case ISD::INTRINSIC_WO_CHAIN: {
9882     unsigned IntrinsicID
9883       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9884     // TODO: Handle more intrinsics
9885     switch (IntrinsicID) {
9886     case Intrinsic::amdgcn_cvt_pkrtz:
9887     case Intrinsic::amdgcn_cubeid:
9888     case Intrinsic::amdgcn_frexp_mant:
9889     case Intrinsic::amdgcn_fdot2:
9890     case Intrinsic::amdgcn_rcp:
9891     case Intrinsic::amdgcn_rsq:
9892     case Intrinsic::amdgcn_rsq_clamp:
9893     case Intrinsic::amdgcn_rcp_legacy:
9894     case Intrinsic::amdgcn_rsq_legacy:
9895     case Intrinsic::amdgcn_trig_preop:
9896       return true;
9897     default:
9898       break;
9899     }
9900 
9901     LLVM_FALLTHROUGH;
9902   }
9903   default:
9904     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9905            DAG.isKnownNeverSNaN(Op);
9906   }
9907 
9908   llvm_unreachable("invalid operation");
9909 }
9910 
9911 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
9912                                        unsigned MaxDepth) const {
9913   MachineRegisterInfo &MRI = MF.getRegInfo();
9914   MachineInstr *MI = MRI.getVRegDef(Reg);
9915   unsigned Opcode = MI->getOpcode();
9916 
9917   if (Opcode == AMDGPU::G_FCANONICALIZE)
9918     return true;
9919 
9920   Optional<FPValueAndVReg> FCR;
9921   // Constant splat (can be padded with undef) or scalar constant.
9922   if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) {
9923     if (FCR->Value.isSignaling())
9924       return false;
9925     return !FCR->Value.isDenormal() ||
9926            denormalsEnabledForType(MRI.getType(FCR->VReg), MF);
9927   }
9928 
9929   if (MaxDepth == 0)
9930     return false;
9931 
9932   switch (Opcode) {
9933   case AMDGPU::G_FMINNUM_IEEE:
9934   case AMDGPU::G_FMAXNUM_IEEE: {
9935     if (Subtarget->supportsMinMaxDenormModes() ||
9936         denormalsEnabledForType(MRI.getType(Reg), MF))
9937       return true;
9938     for (const MachineOperand &MO : llvm::drop_begin(MI->operands()))
9939       if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1))
9940         return false;
9941     return true;
9942   }
9943   default:
9944     return denormalsEnabledForType(MRI.getType(Reg), MF) &&
9945            isKnownNeverSNaN(Reg, MRI);
9946   }
9947 
9948   llvm_unreachable("invalid operation");
9949 }
9950 
9951 // Constant fold canonicalize.
9952 SDValue SITargetLowering::getCanonicalConstantFP(
9953   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9954   // Flush denormals to 0 if not enabled.
9955   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9956     return DAG.getConstantFP(0.0, SL, VT);
9957 
9958   if (C.isNaN()) {
9959     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9960     if (C.isSignaling()) {
9961       // Quiet a signaling NaN.
9962       // FIXME: Is this supposed to preserve payload bits?
9963       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9964     }
9965 
9966     // Make sure it is the canonical NaN bitpattern.
9967     //
9968     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9969     // immediate?
9970     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9971       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9972   }
9973 
9974   // Already canonical.
9975   return DAG.getConstantFP(C, SL, VT);
9976 }
9977 
9978 static bool vectorEltWillFoldAway(SDValue Op) {
9979   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9980 }
9981 
9982 SDValue SITargetLowering::performFCanonicalizeCombine(
9983   SDNode *N,
9984   DAGCombinerInfo &DCI) const {
9985   SelectionDAG &DAG = DCI.DAG;
9986   SDValue N0 = N->getOperand(0);
9987   EVT VT = N->getValueType(0);
9988 
9989   // fcanonicalize undef -> qnan
9990   if (N0.isUndef()) {
9991     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9992     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9993   }
9994 
9995   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9996     EVT VT = N->getValueType(0);
9997     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9998   }
9999 
10000   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
10001   //                                                   (fcanonicalize k)
10002   //
10003   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
10004 
10005   // TODO: This could be better with wider vectors that will be split to v2f16,
10006   // and to consider uses since there aren't that many packed operations.
10007   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
10008       isTypeLegal(MVT::v2f16)) {
10009     SDLoc SL(N);
10010     SDValue NewElts[2];
10011     SDValue Lo = N0.getOperand(0);
10012     SDValue Hi = N0.getOperand(1);
10013     EVT EltVT = Lo.getValueType();
10014 
10015     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
10016       for (unsigned I = 0; I != 2; ++I) {
10017         SDValue Op = N0.getOperand(I);
10018         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
10019           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
10020                                               CFP->getValueAPF());
10021         } else if (Op.isUndef()) {
10022           // Handled below based on what the other operand is.
10023           NewElts[I] = Op;
10024         } else {
10025           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
10026         }
10027       }
10028 
10029       // If one half is undef, and one is constant, prefer a splat vector rather
10030       // than the normal qNaN. If it's a register, prefer 0.0 since that's
10031       // cheaper to use and may be free with a packed operation.
10032       if (NewElts[0].isUndef()) {
10033         if (isa<ConstantFPSDNode>(NewElts[1]))
10034           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
10035             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
10036       }
10037 
10038       if (NewElts[1].isUndef()) {
10039         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
10040           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
10041       }
10042 
10043       return DAG.getBuildVector(VT, SL, NewElts);
10044     }
10045   }
10046 
10047   unsigned SrcOpc = N0.getOpcode();
10048 
10049   // If it's free to do so, push canonicalizes further up the source, which may
10050   // find a canonical source.
10051   //
10052   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
10053   // sNaNs.
10054   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
10055     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10056     if (CRHS && N0.hasOneUse()) {
10057       SDLoc SL(N);
10058       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
10059                                    N0.getOperand(0));
10060       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
10061       DCI.AddToWorklist(Canon0.getNode());
10062 
10063       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
10064     }
10065   }
10066 
10067   return isCanonicalized(DAG, N0) ? N0 : SDValue();
10068 }
10069 
10070 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
10071   switch (Opc) {
10072   case ISD::FMAXNUM:
10073   case ISD::FMAXNUM_IEEE:
10074     return AMDGPUISD::FMAX3;
10075   case ISD::SMAX:
10076     return AMDGPUISD::SMAX3;
10077   case ISD::UMAX:
10078     return AMDGPUISD::UMAX3;
10079   case ISD::FMINNUM:
10080   case ISD::FMINNUM_IEEE:
10081     return AMDGPUISD::FMIN3;
10082   case ISD::SMIN:
10083     return AMDGPUISD::SMIN3;
10084   case ISD::UMIN:
10085     return AMDGPUISD::UMIN3;
10086   default:
10087     llvm_unreachable("Not a min/max opcode");
10088   }
10089 }
10090 
10091 SDValue SITargetLowering::performIntMed3ImmCombine(
10092   SelectionDAG &DAG, const SDLoc &SL,
10093   SDValue Op0, SDValue Op1, bool Signed) const {
10094   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
10095   if (!K1)
10096     return SDValue();
10097 
10098   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
10099   if (!K0)
10100     return SDValue();
10101 
10102   if (Signed) {
10103     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
10104       return SDValue();
10105   } else {
10106     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
10107       return SDValue();
10108   }
10109 
10110   EVT VT = K0->getValueType(0);
10111   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
10112   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
10113     return DAG.getNode(Med3Opc, SL, VT,
10114                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
10115   }
10116 
10117   // If there isn't a 16-bit med3 operation, convert to 32-bit.
10118   if (VT == MVT::i16) {
10119     MVT NVT = MVT::i32;
10120     unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
10121 
10122     SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
10123     SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
10124     SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
10125 
10126     SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
10127     return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
10128   }
10129 
10130   return SDValue();
10131 }
10132 
10133 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
10134   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
10135     return C;
10136 
10137   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
10138     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
10139       return C;
10140   }
10141 
10142   return nullptr;
10143 }
10144 
10145 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
10146                                                   const SDLoc &SL,
10147                                                   SDValue Op0,
10148                                                   SDValue Op1) const {
10149   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
10150   if (!K1)
10151     return SDValue();
10152 
10153   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
10154   if (!K0)
10155     return SDValue();
10156 
10157   // Ordered >= (although NaN inputs should have folded away by now).
10158   if (K0->getValueAPF() > K1->getValueAPF())
10159     return SDValue();
10160 
10161   const MachineFunction &MF = DAG.getMachineFunction();
10162   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10163 
10164   // TODO: Check IEEE bit enabled?
10165   EVT VT = Op0.getValueType();
10166   if (Info->getMode().DX10Clamp) {
10167     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
10168     // hardware fmed3 behavior converting to a min.
10169     // FIXME: Should this be allowing -0.0?
10170     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
10171       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
10172   }
10173 
10174   // med3 for f16 is only available on gfx9+, and not available for v2f16.
10175   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
10176     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
10177     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
10178     // then give the other result, which is different from med3 with a NaN
10179     // input.
10180     SDValue Var = Op0.getOperand(0);
10181     if (!DAG.isKnownNeverSNaN(Var))
10182       return SDValue();
10183 
10184     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10185 
10186     if ((!K0->hasOneUse() ||
10187          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
10188         (!K1->hasOneUse() ||
10189          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
10190       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
10191                          Var, SDValue(K0, 0), SDValue(K1, 0));
10192     }
10193   }
10194 
10195   return SDValue();
10196 }
10197 
10198 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
10199                                                DAGCombinerInfo &DCI) const {
10200   SelectionDAG &DAG = DCI.DAG;
10201 
10202   EVT VT = N->getValueType(0);
10203   unsigned Opc = N->getOpcode();
10204   SDValue Op0 = N->getOperand(0);
10205   SDValue Op1 = N->getOperand(1);
10206 
10207   // Only do this if the inner op has one use since this will just increases
10208   // register pressure for no benefit.
10209 
10210   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
10211       !VT.isVector() &&
10212       (VT == MVT::i32 || VT == MVT::f32 ||
10213        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
10214     // max(max(a, b), c) -> max3(a, b, c)
10215     // min(min(a, b), c) -> min3(a, b, c)
10216     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
10217       SDLoc DL(N);
10218       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10219                          DL,
10220                          N->getValueType(0),
10221                          Op0.getOperand(0),
10222                          Op0.getOperand(1),
10223                          Op1);
10224     }
10225 
10226     // Try commuted.
10227     // max(a, max(b, c)) -> max3(a, b, c)
10228     // min(a, min(b, c)) -> min3(a, b, c)
10229     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
10230       SDLoc DL(N);
10231       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10232                          DL,
10233                          N->getValueType(0),
10234                          Op0,
10235                          Op1.getOperand(0),
10236                          Op1.getOperand(1));
10237     }
10238   }
10239 
10240   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
10241   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
10242     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
10243       return Med3;
10244   }
10245 
10246   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
10247     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
10248       return Med3;
10249   }
10250 
10251   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
10252   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
10253        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
10254        (Opc == AMDGPUISD::FMIN_LEGACY &&
10255         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
10256       (VT == MVT::f32 || VT == MVT::f64 ||
10257        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
10258        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
10259       Op0.hasOneUse()) {
10260     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
10261       return Res;
10262   }
10263 
10264   return SDValue();
10265 }
10266 
10267 static bool isClampZeroToOne(SDValue A, SDValue B) {
10268   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
10269     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
10270       // FIXME: Should this be allowing -0.0?
10271       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
10272              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
10273     }
10274   }
10275 
10276   return false;
10277 }
10278 
10279 // FIXME: Should only worry about snans for version with chain.
10280 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
10281                                               DAGCombinerInfo &DCI) const {
10282   EVT VT = N->getValueType(0);
10283   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
10284   // NaNs. With a NaN input, the order of the operands may change the result.
10285 
10286   SelectionDAG &DAG = DCI.DAG;
10287   SDLoc SL(N);
10288 
10289   SDValue Src0 = N->getOperand(0);
10290   SDValue Src1 = N->getOperand(1);
10291   SDValue Src2 = N->getOperand(2);
10292 
10293   if (isClampZeroToOne(Src0, Src1)) {
10294     // const_a, const_b, x -> clamp is safe in all cases including signaling
10295     // nans.
10296     // FIXME: Should this be allowing -0.0?
10297     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
10298   }
10299 
10300   const MachineFunction &MF = DAG.getMachineFunction();
10301   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10302 
10303   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
10304   // handling no dx10-clamp?
10305   if (Info->getMode().DX10Clamp) {
10306     // If NaNs is clamped to 0, we are free to reorder the inputs.
10307 
10308     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10309       std::swap(Src0, Src1);
10310 
10311     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10312       std::swap(Src1, Src2);
10313 
10314     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10315       std::swap(Src0, Src1);
10316 
10317     if (isClampZeroToOne(Src1, Src2))
10318       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10319   }
10320 
10321   return SDValue();
10322 }
10323 
10324 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10325                                                  DAGCombinerInfo &DCI) const {
10326   SDValue Src0 = N->getOperand(0);
10327   SDValue Src1 = N->getOperand(1);
10328   if (Src0.isUndef() && Src1.isUndef())
10329     return DCI.DAG.getUNDEF(N->getValueType(0));
10330   return SDValue();
10331 }
10332 
10333 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10334 // expanded into a set of cmp/select instructions.
10335 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10336                                                 unsigned NumElem,
10337                                                 bool IsDivergentIdx) {
10338   if (UseDivergentRegisterIndexing)
10339     return false;
10340 
10341   unsigned VecSize = EltSize * NumElem;
10342 
10343   // Sub-dword vectors of size 2 dword or less have better implementation.
10344   if (VecSize <= 64 && EltSize < 32)
10345     return false;
10346 
10347   // Always expand the rest of sub-dword instructions, otherwise it will be
10348   // lowered via memory.
10349   if (EltSize < 32)
10350     return true;
10351 
10352   // Always do this if var-idx is divergent, otherwise it will become a loop.
10353   if (IsDivergentIdx)
10354     return true;
10355 
10356   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10357   unsigned NumInsts = NumElem /* Number of compares */ +
10358                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10359   return NumInsts <= 16;
10360 }
10361 
10362 static bool shouldExpandVectorDynExt(SDNode *N) {
10363   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10364   if (isa<ConstantSDNode>(Idx))
10365     return false;
10366 
10367   SDValue Vec = N->getOperand(0);
10368   EVT VecVT = Vec.getValueType();
10369   EVT EltVT = VecVT.getVectorElementType();
10370   unsigned EltSize = EltVT.getSizeInBits();
10371   unsigned NumElem = VecVT.getVectorNumElements();
10372 
10373   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
10374                                                     Idx->isDivergent());
10375 }
10376 
10377 SDValue SITargetLowering::performExtractVectorEltCombine(
10378   SDNode *N, DAGCombinerInfo &DCI) const {
10379   SDValue Vec = N->getOperand(0);
10380   SelectionDAG &DAG = DCI.DAG;
10381 
10382   EVT VecVT = Vec.getValueType();
10383   EVT EltVT = VecVT.getVectorElementType();
10384 
10385   if ((Vec.getOpcode() == ISD::FNEG ||
10386        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10387     SDLoc SL(N);
10388     EVT EltVT = N->getValueType(0);
10389     SDValue Idx = N->getOperand(1);
10390     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10391                               Vec.getOperand(0), Idx);
10392     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10393   }
10394 
10395   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10396   //    =>
10397   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10398   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10399   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10400   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10401     SDLoc SL(N);
10402     EVT EltVT = N->getValueType(0);
10403     SDValue Idx = N->getOperand(1);
10404     unsigned Opc = Vec.getOpcode();
10405 
10406     switch(Opc) {
10407     default:
10408       break;
10409       // TODO: Support other binary operations.
10410     case ISD::FADD:
10411     case ISD::FSUB:
10412     case ISD::FMUL:
10413     case ISD::ADD:
10414     case ISD::UMIN:
10415     case ISD::UMAX:
10416     case ISD::SMIN:
10417     case ISD::SMAX:
10418     case ISD::FMAXNUM:
10419     case ISD::FMINNUM:
10420     case ISD::FMAXNUM_IEEE:
10421     case ISD::FMINNUM_IEEE: {
10422       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10423                                  Vec.getOperand(0), Idx);
10424       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10425                                  Vec.getOperand(1), Idx);
10426 
10427       DCI.AddToWorklist(Elt0.getNode());
10428       DCI.AddToWorklist(Elt1.getNode());
10429       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10430     }
10431     }
10432   }
10433 
10434   unsigned VecSize = VecVT.getSizeInBits();
10435   unsigned EltSize = EltVT.getSizeInBits();
10436 
10437   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10438   if (::shouldExpandVectorDynExt(N)) {
10439     SDLoc SL(N);
10440     SDValue Idx = N->getOperand(1);
10441     SDValue V;
10442     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10443       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10444       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10445       if (I == 0)
10446         V = Elt;
10447       else
10448         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10449     }
10450     return V;
10451   }
10452 
10453   if (!DCI.isBeforeLegalize())
10454     return SDValue();
10455 
10456   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10457   // elements. This exposes more load reduction opportunities by replacing
10458   // multiple small extract_vector_elements with a single 32-bit extract.
10459   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10460   if (isa<MemSDNode>(Vec) &&
10461       EltSize <= 16 &&
10462       EltVT.isByteSized() &&
10463       VecSize > 32 &&
10464       VecSize % 32 == 0 &&
10465       Idx) {
10466     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10467 
10468     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10469     unsigned EltIdx = BitIndex / 32;
10470     unsigned LeftoverBitIdx = BitIndex % 32;
10471     SDLoc SL(N);
10472 
10473     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10474     DCI.AddToWorklist(Cast.getNode());
10475 
10476     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10477                               DAG.getConstant(EltIdx, SL, MVT::i32));
10478     DCI.AddToWorklist(Elt.getNode());
10479     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10480                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10481     DCI.AddToWorklist(Srl.getNode());
10482 
10483     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10484     DCI.AddToWorklist(Trunc.getNode());
10485     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10486   }
10487 
10488   return SDValue();
10489 }
10490 
10491 SDValue
10492 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10493                                                 DAGCombinerInfo &DCI) const {
10494   SDValue Vec = N->getOperand(0);
10495   SDValue Idx = N->getOperand(2);
10496   EVT VecVT = Vec.getValueType();
10497   EVT EltVT = VecVT.getVectorElementType();
10498 
10499   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10500   // => BUILD_VECTOR n x select (e, const-idx)
10501   if (!::shouldExpandVectorDynExt(N))
10502     return SDValue();
10503 
10504   SelectionDAG &DAG = DCI.DAG;
10505   SDLoc SL(N);
10506   SDValue Ins = N->getOperand(1);
10507   EVT IdxVT = Idx.getValueType();
10508 
10509   SmallVector<SDValue, 16> Ops;
10510   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10511     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10512     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10513     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10514     Ops.push_back(V);
10515   }
10516 
10517   return DAG.getBuildVector(VecVT, SL, Ops);
10518 }
10519 
10520 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10521                                           const SDNode *N0,
10522                                           const SDNode *N1) const {
10523   EVT VT = N0->getValueType(0);
10524 
10525   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10526   // support denormals ever.
10527   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10528        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10529         getSubtarget()->hasMadF16())) &&
10530        isOperationLegal(ISD::FMAD, VT))
10531     return ISD::FMAD;
10532 
10533   const TargetOptions &Options = DAG.getTarget().Options;
10534   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10535        (N0->getFlags().hasAllowContract() &&
10536         N1->getFlags().hasAllowContract())) &&
10537       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10538     return ISD::FMA;
10539   }
10540 
10541   return 0;
10542 }
10543 
10544 // For a reassociatable opcode perform:
10545 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10546 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10547                                                SelectionDAG &DAG) const {
10548   EVT VT = N->getValueType(0);
10549   if (VT != MVT::i32 && VT != MVT::i64)
10550     return SDValue();
10551 
10552   if (DAG.isBaseWithConstantOffset(SDValue(N, 0)))
10553     return SDValue();
10554 
10555   unsigned Opc = N->getOpcode();
10556   SDValue Op0 = N->getOperand(0);
10557   SDValue Op1 = N->getOperand(1);
10558 
10559   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10560     return SDValue();
10561 
10562   if (Op0->isDivergent())
10563     std::swap(Op0, Op1);
10564 
10565   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10566     return SDValue();
10567 
10568   SDValue Op2 = Op1.getOperand(1);
10569   Op1 = Op1.getOperand(0);
10570   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10571     return SDValue();
10572 
10573   if (Op1->isDivergent())
10574     std::swap(Op1, Op2);
10575 
10576   SDLoc SL(N);
10577   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10578   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10579 }
10580 
10581 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10582                            EVT VT,
10583                            SDValue N0, SDValue N1, SDValue N2,
10584                            bool Signed) {
10585   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10586   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10587   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10588   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10589 }
10590 
10591 SDValue SITargetLowering::performAddCombine(SDNode *N,
10592                                             DAGCombinerInfo &DCI) const {
10593   SelectionDAG &DAG = DCI.DAG;
10594   EVT VT = N->getValueType(0);
10595   SDLoc SL(N);
10596   SDValue LHS = N->getOperand(0);
10597   SDValue RHS = N->getOperand(1);
10598 
10599   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10600       && Subtarget->hasMad64_32() &&
10601       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10602       VT.getScalarSizeInBits() <= 64) {
10603     if (LHS.getOpcode() != ISD::MUL)
10604       std::swap(LHS, RHS);
10605 
10606     SDValue MulLHS = LHS.getOperand(0);
10607     SDValue MulRHS = LHS.getOperand(1);
10608     SDValue AddRHS = RHS;
10609 
10610     // TODO: Maybe restrict if SGPR inputs.
10611     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10612         numBitsUnsigned(MulRHS, DAG) <= 32) {
10613       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10614       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10615       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10616       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10617     }
10618 
10619     if (numBitsSigned(MulLHS, DAG) <= 32 && numBitsSigned(MulRHS, DAG) <= 32) {
10620       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10621       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10622       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10623       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10624     }
10625 
10626     return SDValue();
10627   }
10628 
10629   if (SDValue V = reassociateScalarOps(N, DAG)) {
10630     return V;
10631   }
10632 
10633   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10634     return SDValue();
10635 
10636   // add x, zext (setcc) => addcarry x, 0, setcc
10637   // add x, sext (setcc) => subcarry x, 0, setcc
10638   unsigned Opc = LHS.getOpcode();
10639   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10640       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10641     std::swap(RHS, LHS);
10642 
10643   Opc = RHS.getOpcode();
10644   switch (Opc) {
10645   default: break;
10646   case ISD::ZERO_EXTEND:
10647   case ISD::SIGN_EXTEND:
10648   case ISD::ANY_EXTEND: {
10649     auto Cond = RHS.getOperand(0);
10650     // If this won't be a real VOPC output, we would still need to insert an
10651     // extra instruction anyway.
10652     if (!isBoolSGPR(Cond))
10653       break;
10654     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10655     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10656     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10657     return DAG.getNode(Opc, SL, VTList, Args);
10658   }
10659   case ISD::ADDCARRY: {
10660     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10661     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10662     if (!C || C->getZExtValue() != 0) break;
10663     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10664     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10665   }
10666   }
10667   return SDValue();
10668 }
10669 
10670 SDValue SITargetLowering::performSubCombine(SDNode *N,
10671                                             DAGCombinerInfo &DCI) const {
10672   SelectionDAG &DAG = DCI.DAG;
10673   EVT VT = N->getValueType(0);
10674 
10675   if (VT != MVT::i32)
10676     return SDValue();
10677 
10678   SDLoc SL(N);
10679   SDValue LHS = N->getOperand(0);
10680   SDValue RHS = N->getOperand(1);
10681 
10682   // sub x, zext (setcc) => subcarry x, 0, setcc
10683   // sub x, sext (setcc) => addcarry x, 0, setcc
10684   unsigned Opc = RHS.getOpcode();
10685   switch (Opc) {
10686   default: break;
10687   case ISD::ZERO_EXTEND:
10688   case ISD::SIGN_EXTEND:
10689   case ISD::ANY_EXTEND: {
10690     auto Cond = RHS.getOperand(0);
10691     // If this won't be a real VOPC output, we would still need to insert an
10692     // extra instruction anyway.
10693     if (!isBoolSGPR(Cond))
10694       break;
10695     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10696     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10697     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10698     return DAG.getNode(Opc, SL, VTList, Args);
10699   }
10700   }
10701 
10702   if (LHS.getOpcode() == ISD::SUBCARRY) {
10703     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10704     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10705     if (!C || !C->isZero())
10706       return SDValue();
10707     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10708     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10709   }
10710   return SDValue();
10711 }
10712 
10713 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10714   DAGCombinerInfo &DCI) const {
10715 
10716   if (N->getValueType(0) != MVT::i32)
10717     return SDValue();
10718 
10719   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10720   if (!C || C->getZExtValue() != 0)
10721     return SDValue();
10722 
10723   SelectionDAG &DAG = DCI.DAG;
10724   SDValue LHS = N->getOperand(0);
10725 
10726   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10727   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10728   unsigned LHSOpc = LHS.getOpcode();
10729   unsigned Opc = N->getOpcode();
10730   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10731       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10732     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10733     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10734   }
10735   return SDValue();
10736 }
10737 
10738 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10739                                              DAGCombinerInfo &DCI) const {
10740   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10741     return SDValue();
10742 
10743   SelectionDAG &DAG = DCI.DAG;
10744   EVT VT = N->getValueType(0);
10745 
10746   SDLoc SL(N);
10747   SDValue LHS = N->getOperand(0);
10748   SDValue RHS = N->getOperand(1);
10749 
10750   // These should really be instruction patterns, but writing patterns with
10751   // source modifiers is a pain.
10752 
10753   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10754   if (LHS.getOpcode() == ISD::FADD) {
10755     SDValue A = LHS.getOperand(0);
10756     if (A == LHS.getOperand(1)) {
10757       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10758       if (FusedOp != 0) {
10759         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10760         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10761       }
10762     }
10763   }
10764 
10765   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10766   if (RHS.getOpcode() == ISD::FADD) {
10767     SDValue A = RHS.getOperand(0);
10768     if (A == RHS.getOperand(1)) {
10769       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10770       if (FusedOp != 0) {
10771         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10772         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10773       }
10774     }
10775   }
10776 
10777   return SDValue();
10778 }
10779 
10780 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10781                                              DAGCombinerInfo &DCI) const {
10782   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10783     return SDValue();
10784 
10785   SelectionDAG &DAG = DCI.DAG;
10786   SDLoc SL(N);
10787   EVT VT = N->getValueType(0);
10788   assert(!VT.isVector());
10789 
10790   // Try to get the fneg to fold into the source modifier. This undoes generic
10791   // DAG combines and folds them into the mad.
10792   //
10793   // Only do this if we are not trying to support denormals. v_mad_f32 does
10794   // not support denormals ever.
10795   SDValue LHS = N->getOperand(0);
10796   SDValue RHS = N->getOperand(1);
10797   if (LHS.getOpcode() == ISD::FADD) {
10798     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10799     SDValue A = LHS.getOperand(0);
10800     if (A == LHS.getOperand(1)) {
10801       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10802       if (FusedOp != 0){
10803         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10804         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10805 
10806         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10807       }
10808     }
10809   }
10810 
10811   if (RHS.getOpcode() == ISD::FADD) {
10812     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10813 
10814     SDValue A = RHS.getOperand(0);
10815     if (A == RHS.getOperand(1)) {
10816       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10817       if (FusedOp != 0){
10818         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10819         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10820       }
10821     }
10822   }
10823 
10824   return SDValue();
10825 }
10826 
10827 SDValue SITargetLowering::performFMACombine(SDNode *N,
10828                                             DAGCombinerInfo &DCI) const {
10829   SelectionDAG &DAG = DCI.DAG;
10830   EVT VT = N->getValueType(0);
10831   SDLoc SL(N);
10832 
10833   if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
10834     return SDValue();
10835 
10836   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10837   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10838   SDValue Op1 = N->getOperand(0);
10839   SDValue Op2 = N->getOperand(1);
10840   SDValue FMA = N->getOperand(2);
10841 
10842   if (FMA.getOpcode() != ISD::FMA ||
10843       Op1.getOpcode() != ISD::FP_EXTEND ||
10844       Op2.getOpcode() != ISD::FP_EXTEND)
10845     return SDValue();
10846 
10847   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10848   // regardless of the denorm mode setting. Therefore,
10849   // unsafe-fp-math/fp-contract is sufficient to allow generating fdot2.
10850   const TargetOptions &Options = DAG.getTarget().Options;
10851   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10852       (N->getFlags().hasAllowContract() &&
10853        FMA->getFlags().hasAllowContract())) {
10854     Op1 = Op1.getOperand(0);
10855     Op2 = Op2.getOperand(0);
10856     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10857         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10858       return SDValue();
10859 
10860     SDValue Vec1 = Op1.getOperand(0);
10861     SDValue Idx1 = Op1.getOperand(1);
10862     SDValue Vec2 = Op2.getOperand(0);
10863 
10864     SDValue FMAOp1 = FMA.getOperand(0);
10865     SDValue FMAOp2 = FMA.getOperand(1);
10866     SDValue FMAAcc = FMA.getOperand(2);
10867 
10868     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10869         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10870       return SDValue();
10871 
10872     FMAOp1 = FMAOp1.getOperand(0);
10873     FMAOp2 = FMAOp2.getOperand(0);
10874     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10875         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10876       return SDValue();
10877 
10878     SDValue Vec3 = FMAOp1.getOperand(0);
10879     SDValue Vec4 = FMAOp2.getOperand(0);
10880     SDValue Idx2 = FMAOp1.getOperand(1);
10881 
10882     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10883         // Idx1 and Idx2 cannot be the same.
10884         Idx1 == Idx2)
10885       return SDValue();
10886 
10887     if (Vec1 == Vec2 || Vec3 == Vec4)
10888       return SDValue();
10889 
10890     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10891       return SDValue();
10892 
10893     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10894         (Vec1 == Vec4 && Vec2 == Vec3)) {
10895       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10896                          DAG.getTargetConstant(0, SL, MVT::i1));
10897     }
10898   }
10899   return SDValue();
10900 }
10901 
10902 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10903                                               DAGCombinerInfo &DCI) const {
10904   SelectionDAG &DAG = DCI.DAG;
10905   SDLoc SL(N);
10906 
10907   SDValue LHS = N->getOperand(0);
10908   SDValue RHS = N->getOperand(1);
10909   EVT VT = LHS.getValueType();
10910   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10911 
10912   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10913   if (!CRHS) {
10914     CRHS = dyn_cast<ConstantSDNode>(LHS);
10915     if (CRHS) {
10916       std::swap(LHS, RHS);
10917       CC = getSetCCSwappedOperands(CC);
10918     }
10919   }
10920 
10921   if (CRHS) {
10922     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10923         isBoolSGPR(LHS.getOperand(0))) {
10924       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10925       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10926       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10927       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10928       if ((CRHS->isAllOnes() &&
10929            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10930           (CRHS->isZero() &&
10931            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10932         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10933                            DAG.getConstant(-1, SL, MVT::i1));
10934       if ((CRHS->isAllOnes() &&
10935            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10936           (CRHS->isZero() &&
10937            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10938         return LHS.getOperand(0);
10939     }
10940 
10941     const APInt &CRHSVal = CRHS->getAPIntValue();
10942     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10943         LHS.getOpcode() == ISD::SELECT &&
10944         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10945         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10946         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10947         isBoolSGPR(LHS.getOperand(0))) {
10948       // Given CT != FT:
10949       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10950       // setcc (select cc, CT, CF), CF, ne => cc
10951       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10952       // setcc (select cc, CT, CF), CT, eq => cc
10953       const APInt &CT = LHS.getConstantOperandAPInt(1);
10954       const APInt &CF = LHS.getConstantOperandAPInt(2);
10955 
10956       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10957           (CT == CRHSVal && CC == ISD::SETNE))
10958         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10959                            DAG.getConstant(-1, SL, MVT::i1));
10960       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10961           (CT == CRHSVal && CC == ISD::SETEQ))
10962         return LHS.getOperand(0);
10963     }
10964   }
10965 
10966   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10967                                            VT != MVT::f16))
10968     return SDValue();
10969 
10970   // Match isinf/isfinite pattern
10971   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10972   // (fcmp one (fabs x), inf) -> (fp_class x,
10973   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10974   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10975     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10976     if (!CRHS)
10977       return SDValue();
10978 
10979     const APFloat &APF = CRHS->getValueAPF();
10980     if (APF.isInfinity() && !APF.isNegative()) {
10981       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10982                                  SIInstrFlags::N_INFINITY;
10983       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10984                                     SIInstrFlags::P_ZERO |
10985                                     SIInstrFlags::N_NORMAL |
10986                                     SIInstrFlags::P_NORMAL |
10987                                     SIInstrFlags::N_SUBNORMAL |
10988                                     SIInstrFlags::P_SUBNORMAL;
10989       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10990       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10991                          DAG.getConstant(Mask, SL, MVT::i32));
10992     }
10993   }
10994 
10995   return SDValue();
10996 }
10997 
10998 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10999                                                      DAGCombinerInfo &DCI) const {
11000   SelectionDAG &DAG = DCI.DAG;
11001   SDLoc SL(N);
11002   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
11003 
11004   SDValue Src = N->getOperand(0);
11005   SDValue Shift = N->getOperand(0);
11006 
11007   // TODO: Extend type shouldn't matter (assuming legal types).
11008   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
11009     Shift = Shift.getOperand(0);
11010 
11011   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
11012     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
11013     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
11014     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
11015     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
11016     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
11017     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
11018       SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0),
11019                                  SDLoc(Shift.getOperand(0)), MVT::i32);
11020 
11021       unsigned ShiftOffset = 8 * Offset;
11022       if (Shift.getOpcode() == ISD::SHL)
11023         ShiftOffset -= C->getZExtValue();
11024       else
11025         ShiftOffset += C->getZExtValue();
11026 
11027       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
11028         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
11029                            MVT::f32, Shifted);
11030       }
11031     }
11032   }
11033 
11034   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11035   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
11036   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
11037     // We simplified Src. If this node is not dead, visit it again so it is
11038     // folded properly.
11039     if (N->getOpcode() != ISD::DELETED_NODE)
11040       DCI.AddToWorklist(N);
11041     return SDValue(N, 0);
11042   }
11043 
11044   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
11045   if (SDValue DemandedSrc =
11046           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
11047     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
11048 
11049   return SDValue();
11050 }
11051 
11052 SDValue SITargetLowering::performClampCombine(SDNode *N,
11053                                               DAGCombinerInfo &DCI) const {
11054   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
11055   if (!CSrc)
11056     return SDValue();
11057 
11058   const MachineFunction &MF = DCI.DAG.getMachineFunction();
11059   const APFloat &F = CSrc->getValueAPF();
11060   APFloat Zero = APFloat::getZero(F.getSemantics());
11061   if (F < Zero ||
11062       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
11063     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
11064   }
11065 
11066   APFloat One(F.getSemantics(), "1.0");
11067   if (F > One)
11068     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
11069 
11070   return SDValue(CSrc, 0);
11071 }
11072 
11073 
11074 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
11075                                             DAGCombinerInfo &DCI) const {
11076   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
11077     return SDValue();
11078   switch (N->getOpcode()) {
11079   case ISD::ADD:
11080     return performAddCombine(N, DCI);
11081   case ISD::SUB:
11082     return performSubCombine(N, DCI);
11083   case ISD::ADDCARRY:
11084   case ISD::SUBCARRY:
11085     return performAddCarrySubCarryCombine(N, DCI);
11086   case ISD::FADD:
11087     return performFAddCombine(N, DCI);
11088   case ISD::FSUB:
11089     return performFSubCombine(N, DCI);
11090   case ISD::SETCC:
11091     return performSetCCCombine(N, DCI);
11092   case ISD::FMAXNUM:
11093   case ISD::FMINNUM:
11094   case ISD::FMAXNUM_IEEE:
11095   case ISD::FMINNUM_IEEE:
11096   case ISD::SMAX:
11097   case ISD::SMIN:
11098   case ISD::UMAX:
11099   case ISD::UMIN:
11100   case AMDGPUISD::FMIN_LEGACY:
11101   case AMDGPUISD::FMAX_LEGACY:
11102     return performMinMaxCombine(N, DCI);
11103   case ISD::FMA:
11104     return performFMACombine(N, DCI);
11105   case ISD::AND:
11106     return performAndCombine(N, DCI);
11107   case ISD::OR:
11108     return performOrCombine(N, DCI);
11109   case ISD::XOR:
11110     return performXorCombine(N, DCI);
11111   case ISD::ZERO_EXTEND:
11112     return performZeroExtendCombine(N, DCI);
11113   case ISD::SIGN_EXTEND_INREG:
11114     return performSignExtendInRegCombine(N , DCI);
11115   case AMDGPUISD::FP_CLASS:
11116     return performClassCombine(N, DCI);
11117   case ISD::FCANONICALIZE:
11118     return performFCanonicalizeCombine(N, DCI);
11119   case AMDGPUISD::RCP:
11120     return performRcpCombine(N, DCI);
11121   case AMDGPUISD::FRACT:
11122   case AMDGPUISD::RSQ:
11123   case AMDGPUISD::RCP_LEGACY:
11124   case AMDGPUISD::RCP_IFLAG:
11125   case AMDGPUISD::RSQ_CLAMP:
11126   case AMDGPUISD::LDEXP: {
11127     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
11128     SDValue Src = N->getOperand(0);
11129     if (Src.isUndef())
11130       return Src;
11131     break;
11132   }
11133   case ISD::SINT_TO_FP:
11134   case ISD::UINT_TO_FP:
11135     return performUCharToFloatCombine(N, DCI);
11136   case AMDGPUISD::CVT_F32_UBYTE0:
11137   case AMDGPUISD::CVT_F32_UBYTE1:
11138   case AMDGPUISD::CVT_F32_UBYTE2:
11139   case AMDGPUISD::CVT_F32_UBYTE3:
11140     return performCvtF32UByteNCombine(N, DCI);
11141   case AMDGPUISD::FMED3:
11142     return performFMed3Combine(N, DCI);
11143   case AMDGPUISD::CVT_PKRTZ_F16_F32:
11144     return performCvtPkRTZCombine(N, DCI);
11145   case AMDGPUISD::CLAMP:
11146     return performClampCombine(N, DCI);
11147   case ISD::SCALAR_TO_VECTOR: {
11148     SelectionDAG &DAG = DCI.DAG;
11149     EVT VT = N->getValueType(0);
11150 
11151     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
11152     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
11153       SDLoc SL(N);
11154       SDValue Src = N->getOperand(0);
11155       EVT EltVT = Src.getValueType();
11156       if (EltVT == MVT::f16)
11157         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
11158 
11159       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
11160       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
11161     }
11162 
11163     break;
11164   }
11165   case ISD::EXTRACT_VECTOR_ELT:
11166     return performExtractVectorEltCombine(N, DCI);
11167   case ISD::INSERT_VECTOR_ELT:
11168     return performInsertVectorEltCombine(N, DCI);
11169   case ISD::LOAD: {
11170     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
11171       return Widended;
11172     LLVM_FALLTHROUGH;
11173   }
11174   default: {
11175     if (!DCI.isBeforeLegalize()) {
11176       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
11177         return performMemSDNodeCombine(MemNode, DCI);
11178     }
11179 
11180     break;
11181   }
11182   }
11183 
11184   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
11185 }
11186 
11187 /// Helper function for adjustWritemask
11188 static unsigned SubIdx2Lane(unsigned Idx) {
11189   switch (Idx) {
11190   default: return ~0u;
11191   case AMDGPU::sub0: return 0;
11192   case AMDGPU::sub1: return 1;
11193   case AMDGPU::sub2: return 2;
11194   case AMDGPU::sub3: return 3;
11195   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
11196   }
11197 }
11198 
11199 /// Adjust the writemask of MIMG instructions
11200 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
11201                                           SelectionDAG &DAG) const {
11202   unsigned Opcode = Node->getMachineOpcode();
11203 
11204   // Subtract 1 because the vdata output is not a MachineSDNode operand.
11205   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
11206   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
11207     return Node; // not implemented for D16
11208 
11209   SDNode *Users[5] = { nullptr };
11210   unsigned Lane = 0;
11211   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
11212   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
11213   unsigned NewDmask = 0;
11214   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
11215   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
11216   bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
11217                   Node->getConstantOperandVal(LWEIdx))
11218                      ? true
11219                      : false;
11220   unsigned TFCLane = 0;
11221   bool HasChain = Node->getNumValues() > 1;
11222 
11223   if (OldDmask == 0) {
11224     // These are folded out, but on the chance it happens don't assert.
11225     return Node;
11226   }
11227 
11228   unsigned OldBitsSet = countPopulation(OldDmask);
11229   // Work out which is the TFE/LWE lane if that is enabled.
11230   if (UsesTFC) {
11231     TFCLane = OldBitsSet;
11232   }
11233 
11234   // Try to figure out the used register components
11235   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
11236        I != E; ++I) {
11237 
11238     // Don't look at users of the chain.
11239     if (I.getUse().getResNo() != 0)
11240       continue;
11241 
11242     // Abort if we can't understand the usage
11243     if (!I->isMachineOpcode() ||
11244         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
11245       return Node;
11246 
11247     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
11248     // Note that subregs are packed, i.e. Lane==0 is the first bit set
11249     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
11250     // set, etc.
11251     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
11252     if (Lane == ~0u)
11253       return Node;
11254 
11255     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
11256     if (UsesTFC && Lane == TFCLane) {
11257       Users[Lane] = *I;
11258     } else {
11259       // Set which texture component corresponds to the lane.
11260       unsigned Comp;
11261       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
11262         Comp = countTrailingZeros(Dmask);
11263         Dmask &= ~(1 << Comp);
11264       }
11265 
11266       // Abort if we have more than one user per component.
11267       if (Users[Lane])
11268         return Node;
11269 
11270       Users[Lane] = *I;
11271       NewDmask |= 1 << Comp;
11272     }
11273   }
11274 
11275   // Don't allow 0 dmask, as hardware assumes one channel enabled.
11276   bool NoChannels = !NewDmask;
11277   if (NoChannels) {
11278     if (!UsesTFC) {
11279       // No uses of the result and not using TFC. Then do nothing.
11280       return Node;
11281     }
11282     // If the original dmask has one channel - then nothing to do
11283     if (OldBitsSet == 1)
11284       return Node;
11285     // Use an arbitrary dmask - required for the instruction to work
11286     NewDmask = 1;
11287   }
11288   // Abort if there's no change
11289   if (NewDmask == OldDmask)
11290     return Node;
11291 
11292   unsigned BitsSet = countPopulation(NewDmask);
11293 
11294   // Check for TFE or LWE - increase the number of channels by one to account
11295   // for the extra return value
11296   // This will need adjustment for D16 if this is also included in
11297   // adjustWriteMask (this function) but at present D16 are excluded.
11298   unsigned NewChannels = BitsSet + UsesTFC;
11299 
11300   int NewOpcode =
11301       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
11302   assert(NewOpcode != -1 &&
11303          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
11304          "failed to find equivalent MIMG op");
11305 
11306   // Adjust the writemask in the node
11307   SmallVector<SDValue, 12> Ops;
11308   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
11309   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
11310   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11311 
11312   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11313 
11314   MVT ResultVT = NewChannels == 1 ?
11315     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11316                            NewChannels == 5 ? 8 : NewChannels);
11317   SDVTList NewVTList = HasChain ?
11318     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11319 
11320 
11321   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11322                                               NewVTList, Ops);
11323 
11324   if (HasChain) {
11325     // Update chain.
11326     DAG.setNodeMemRefs(NewNode, Node->memoperands());
11327     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11328   }
11329 
11330   if (NewChannels == 1) {
11331     assert(Node->hasNUsesOfValue(1, 0));
11332     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11333                                       SDLoc(Node), Users[Lane]->getValueType(0),
11334                                       SDValue(NewNode, 0));
11335     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11336     return nullptr;
11337   }
11338 
11339   // Update the users of the node with the new indices
11340   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11341     SDNode *User = Users[i];
11342     if (!User) {
11343       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11344       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11345       if (i || !NoChannels)
11346         continue;
11347     } else {
11348       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11349       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11350     }
11351 
11352     switch (Idx) {
11353     default: break;
11354     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11355     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11356     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11357     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11358     }
11359   }
11360 
11361   DAG.RemoveDeadNode(Node);
11362   return nullptr;
11363 }
11364 
11365 static bool isFrameIndexOp(SDValue Op) {
11366   if (Op.getOpcode() == ISD::AssertZext)
11367     Op = Op.getOperand(0);
11368 
11369   return isa<FrameIndexSDNode>(Op);
11370 }
11371 
11372 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11373 /// with frame index operands.
11374 /// LLVM assumes that inputs are to these instructions are registers.
11375 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11376                                                         SelectionDAG &DAG) const {
11377   if (Node->getOpcode() == ISD::CopyToReg) {
11378     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11379     SDValue SrcVal = Node->getOperand(2);
11380 
11381     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11382     // to try understanding copies to physical registers.
11383     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11384       SDLoc SL(Node);
11385       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11386       SDValue VReg = DAG.getRegister(
11387         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11388 
11389       SDNode *Glued = Node->getGluedNode();
11390       SDValue ToVReg
11391         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11392                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11393       SDValue ToResultReg
11394         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11395                            VReg, ToVReg.getValue(1));
11396       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11397       DAG.RemoveDeadNode(Node);
11398       return ToResultReg.getNode();
11399     }
11400   }
11401 
11402   SmallVector<SDValue, 8> Ops;
11403   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11404     if (!isFrameIndexOp(Node->getOperand(i))) {
11405       Ops.push_back(Node->getOperand(i));
11406       continue;
11407     }
11408 
11409     SDLoc DL(Node);
11410     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11411                                      Node->getOperand(i).getValueType(),
11412                                      Node->getOperand(i)), 0));
11413   }
11414 
11415   return DAG.UpdateNodeOperands(Node, Ops);
11416 }
11417 
11418 /// Fold the instructions after selecting them.
11419 /// Returns null if users were already updated.
11420 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11421                                           SelectionDAG &DAG) const {
11422   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11423   unsigned Opcode = Node->getMachineOpcode();
11424 
11425   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11426       !TII->isGather4(Opcode) &&
11427       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11428     return adjustWritemask(Node, DAG);
11429   }
11430 
11431   if (Opcode == AMDGPU::INSERT_SUBREG ||
11432       Opcode == AMDGPU::REG_SEQUENCE) {
11433     legalizeTargetIndependentNode(Node, DAG);
11434     return Node;
11435   }
11436 
11437   switch (Opcode) {
11438   case AMDGPU::V_DIV_SCALE_F32_e64:
11439   case AMDGPU::V_DIV_SCALE_F64_e64: {
11440     // Satisfy the operand register constraint when one of the inputs is
11441     // undefined. Ordinarily each undef value will have its own implicit_def of
11442     // a vreg, so force these to use a single register.
11443     SDValue Src0 = Node->getOperand(1);
11444     SDValue Src1 = Node->getOperand(3);
11445     SDValue Src2 = Node->getOperand(5);
11446 
11447     if ((Src0.isMachineOpcode() &&
11448          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11449         (Src0 == Src1 || Src0 == Src2))
11450       break;
11451 
11452     MVT VT = Src0.getValueType().getSimpleVT();
11453     const TargetRegisterClass *RC =
11454         getRegClassFor(VT, Src0.getNode()->isDivergent());
11455 
11456     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11457     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11458 
11459     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11460                                       UndefReg, Src0, SDValue());
11461 
11462     // src0 must be the same register as src1 or src2, even if the value is
11463     // undefined, so make sure we don't violate this constraint.
11464     if (Src0.isMachineOpcode() &&
11465         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11466       if (Src1.isMachineOpcode() &&
11467           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11468         Src0 = Src1;
11469       else if (Src2.isMachineOpcode() &&
11470                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11471         Src0 = Src2;
11472       else {
11473         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11474         Src0 = UndefReg;
11475         Src1 = UndefReg;
11476       }
11477     } else
11478       break;
11479 
11480     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11481     Ops[1] = Src0;
11482     Ops[3] = Src1;
11483     Ops[5] = Src2;
11484     Ops.push_back(ImpDef.getValue(1));
11485     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11486   }
11487   default:
11488     break;
11489   }
11490 
11491   return Node;
11492 }
11493 
11494 // Any MIMG instructions that use tfe or lwe require an initialization of the
11495 // result register that will be written in the case of a memory access failure.
11496 // The required code is also added to tie this init code to the result of the
11497 // img instruction.
11498 void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
11499   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11500   const SIRegisterInfo &TRI = TII->getRegisterInfo();
11501   MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11502   MachineBasicBlock &MBB = *MI.getParent();
11503 
11504   MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
11505   MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
11506   MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
11507 
11508   if (!TFE && !LWE) // intersect_ray
11509     return;
11510 
11511   unsigned TFEVal = TFE ? TFE->getImm() : 0;
11512   unsigned LWEVal = LWE->getImm();
11513   unsigned D16Val = D16 ? D16->getImm() : 0;
11514 
11515   if (!TFEVal && !LWEVal)
11516     return;
11517 
11518   // At least one of TFE or LWE are non-zero
11519   // We have to insert a suitable initialization of the result value and
11520   // tie this to the dest of the image instruction.
11521 
11522   const DebugLoc &DL = MI.getDebugLoc();
11523 
11524   int DstIdx =
11525       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
11526 
11527   // Calculate which dword we have to initialize to 0.
11528   MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
11529 
11530   // check that dmask operand is found.
11531   assert(MO_Dmask && "Expected dmask operand in instruction");
11532 
11533   unsigned dmask = MO_Dmask->getImm();
11534   // Determine the number of active lanes taking into account the
11535   // Gather4 special case
11536   unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask);
11537 
11538   bool Packed = !Subtarget->hasUnpackedD16VMem();
11539 
11540   unsigned InitIdx =
11541       D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
11542 
11543   // Abandon attempt if the dst size isn't large enough
11544   // - this is in fact an error but this is picked up elsewhere and
11545   // reported correctly.
11546   uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
11547   if (DstSize < InitIdx)
11548     return;
11549 
11550   // Create a register for the initialization value.
11551   Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11552   unsigned NewDst = 0; // Final initialized value will be in here
11553 
11554   // If PRTStrictNull feature is enabled (the default) then initialize
11555   // all the result registers to 0, otherwise just the error indication
11556   // register (VGPRn+1)
11557   unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
11558   unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
11559 
11560   BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
11561   for (; SizeLeft; SizeLeft--, CurrIdx++) {
11562     NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11563     // Initialize dword
11564     Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
11565     BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
11566       .addImm(0);
11567     // Insert into the super-reg
11568     BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
11569       .addReg(PrevDst)
11570       .addReg(SubReg)
11571       .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
11572 
11573     PrevDst = NewDst;
11574   }
11575 
11576   // Add as an implicit operand
11577   MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
11578 
11579   // Tie the just added implicit operand to the dst
11580   MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
11581 }
11582 
11583 /// Assign the register class depending on the number of
11584 /// bits set in the writemask
11585 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11586                                                      SDNode *Node) const {
11587   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11588 
11589   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11590 
11591   if (TII->isVOP3(MI.getOpcode())) {
11592     // Make sure constant bus requirements are respected.
11593     TII->legalizeOperandsVOP3(MRI, MI);
11594 
11595     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11596     // This saves a chain-copy of registers and better balance register
11597     // use between vgpr and agpr as agpr tuples tend to be big.
11598     if (MI.getDesc().OpInfo) {
11599       unsigned Opc = MI.getOpcode();
11600       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11601       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11602                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11603         if (I == -1)
11604           break;
11605         MachineOperand &Op = MI.getOperand(I);
11606         if (!Op.isReg() || !Op.getReg().isVirtual())
11607           continue;
11608         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11609         if (!TRI->hasAGPRs(RC))
11610           continue;
11611         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11612         if (!Src || !Src->isCopy() ||
11613             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11614           continue;
11615         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11616         // All uses of agpr64 and agpr32 can also accept vgpr except for
11617         // v_accvgpr_read, but we do not produce agpr reads during selection,
11618         // so no use checks are needed.
11619         MRI.setRegClass(Op.getReg(), NewRC);
11620       }
11621     }
11622 
11623     return;
11624   }
11625 
11626   // Replace unused atomics with the no return version.
11627   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11628   if (NoRetAtomicOp != -1) {
11629     if (!Node->hasAnyUseOfValue(0)) {
11630       int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
11631                                                AMDGPU::OpName::cpol);
11632       if (CPolIdx != -1) {
11633         MachineOperand &CPol = MI.getOperand(CPolIdx);
11634         CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC);
11635       }
11636       MI.RemoveOperand(0);
11637       MI.setDesc(TII->get(NoRetAtomicOp));
11638       return;
11639     }
11640 
11641     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11642     // instruction, because the return type of these instructions is a vec2 of
11643     // the memory type, so it can be tied to the input operand.
11644     // This means these instructions always have a use, so we need to add a
11645     // special case to check if the atomic has only one extract_subreg use,
11646     // which itself has no uses.
11647     if ((Node->hasNUsesOfValue(1, 0) &&
11648          Node->use_begin()->isMachineOpcode() &&
11649          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11650          !Node->use_begin()->hasAnyUseOfValue(0))) {
11651       Register Def = MI.getOperand(0).getReg();
11652 
11653       // Change this into a noret atomic.
11654       MI.setDesc(TII->get(NoRetAtomicOp));
11655       MI.RemoveOperand(0);
11656 
11657       // If we only remove the def operand from the atomic instruction, the
11658       // extract_subreg will be left with a use of a vreg without a def.
11659       // So we need to insert an implicit_def to avoid machine verifier
11660       // errors.
11661       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11662               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11663     }
11664     return;
11665   }
11666 
11667   if (TII->isMIMG(MI) && !MI.mayStore())
11668     AddIMGInit(MI);
11669 }
11670 
11671 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11672                               uint64_t Val) {
11673   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11674   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11675 }
11676 
11677 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11678                                                 const SDLoc &DL,
11679                                                 SDValue Ptr) const {
11680   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11681 
11682   // Build the half of the subregister with the constants before building the
11683   // full 128-bit register. If we are building multiple resource descriptors,
11684   // this will allow CSEing of the 2-component register.
11685   const SDValue Ops0[] = {
11686     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11687     buildSMovImm32(DAG, DL, 0),
11688     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11689     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11690     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11691   };
11692 
11693   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11694                                                 MVT::v2i32, Ops0), 0);
11695 
11696   // Combine the constants and the pointer.
11697   const SDValue Ops1[] = {
11698     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11699     Ptr,
11700     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11701     SubRegHi,
11702     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11703   };
11704 
11705   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11706 }
11707 
11708 /// Return a resource descriptor with the 'Add TID' bit enabled
11709 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11710 ///        of the resource descriptor) to create an offset, which is added to
11711 ///        the resource pointer.
11712 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11713                                            SDValue Ptr, uint32_t RsrcDword1,
11714                                            uint64_t RsrcDword2And3) const {
11715   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11716   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11717   if (RsrcDword1) {
11718     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11719                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11720                     0);
11721   }
11722 
11723   SDValue DataLo = buildSMovImm32(DAG, DL,
11724                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11725   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11726 
11727   const SDValue Ops[] = {
11728     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11729     PtrLo,
11730     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11731     PtrHi,
11732     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11733     DataLo,
11734     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11735     DataHi,
11736     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11737   };
11738 
11739   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11740 }
11741 
11742 //===----------------------------------------------------------------------===//
11743 //                         SI Inline Assembly Support
11744 //===----------------------------------------------------------------------===//
11745 
11746 std::pair<unsigned, const TargetRegisterClass *>
11747 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
11748                                                StringRef Constraint,
11749                                                MVT VT) const {
11750   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
11751 
11752   const TargetRegisterClass *RC = nullptr;
11753   if (Constraint.size() == 1) {
11754     const unsigned BitWidth = VT.getSizeInBits();
11755     switch (Constraint[0]) {
11756     default:
11757       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11758     case 's':
11759     case 'r':
11760       switch (BitWidth) {
11761       case 16:
11762         RC = &AMDGPU::SReg_32RegClass;
11763         break;
11764       case 64:
11765         RC = &AMDGPU::SGPR_64RegClass;
11766         break;
11767       default:
11768         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11769         if (!RC)
11770           return std::make_pair(0U, nullptr);
11771         break;
11772       }
11773       break;
11774     case 'v':
11775       switch (BitWidth) {
11776       case 16:
11777         RC = &AMDGPU::VGPR_32RegClass;
11778         break;
11779       default:
11780         RC = TRI->getVGPRClassForBitWidth(BitWidth);
11781         if (!RC)
11782           return std::make_pair(0U, nullptr);
11783         break;
11784       }
11785       break;
11786     case 'a':
11787       if (!Subtarget->hasMAIInsts())
11788         break;
11789       switch (BitWidth) {
11790       case 16:
11791         RC = &AMDGPU::AGPR_32RegClass;
11792         break;
11793       default:
11794         RC = TRI->getAGPRClassForBitWidth(BitWidth);
11795         if (!RC)
11796           return std::make_pair(0U, nullptr);
11797         break;
11798       }
11799       break;
11800     }
11801     // We actually support i128, i16 and f16 as inline parameters
11802     // even if they are not reported as legal
11803     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11804                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11805       return std::make_pair(0U, RC);
11806   }
11807 
11808   if (Constraint.startswith("{") && Constraint.endswith("}")) {
11809     StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
11810     if (RegName.consume_front("v")) {
11811       RC = &AMDGPU::VGPR_32RegClass;
11812     } else if (RegName.consume_front("s")) {
11813       RC = &AMDGPU::SGPR_32RegClass;
11814     } else if (RegName.consume_front("a")) {
11815       RC = &AMDGPU::AGPR_32RegClass;
11816     }
11817 
11818     if (RC) {
11819       uint32_t Idx;
11820       if (RegName.consume_front("[")) {
11821         uint32_t End;
11822         bool Failed = RegName.consumeInteger(10, Idx);
11823         Failed |= !RegName.consume_front(":");
11824         Failed |= RegName.consumeInteger(10, End);
11825         Failed |= !RegName.consume_back("]");
11826         if (!Failed) {
11827           uint32_t Width = (End - Idx + 1) * 32;
11828           MCRegister Reg = RC->getRegister(Idx);
11829           if (SIRegisterInfo::isVGPRClass(RC))
11830             RC = TRI->getVGPRClassForBitWidth(Width);
11831           else if (SIRegisterInfo::isSGPRClass(RC))
11832             RC = TRI->getSGPRClassForBitWidth(Width);
11833           else if (SIRegisterInfo::isAGPRClass(RC))
11834             RC = TRI->getAGPRClassForBitWidth(Width);
11835           if (RC) {
11836             Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC);
11837             return std::make_pair(Reg, RC);
11838           }
11839         }
11840       } else {
11841         bool Failed = RegName.getAsInteger(10, Idx);
11842         if (!Failed && Idx < RC->getNumRegs())
11843           return std::make_pair(RC->getRegister(Idx), RC);
11844       }
11845     }
11846   }
11847 
11848   auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11849   if (Ret.first)
11850     Ret.second = TRI->getPhysRegClass(Ret.first);
11851 
11852   return Ret;
11853 }
11854 
11855 static bool isImmConstraint(StringRef Constraint) {
11856   if (Constraint.size() == 1) {
11857     switch (Constraint[0]) {
11858     default: break;
11859     case 'I':
11860     case 'J':
11861     case 'A':
11862     case 'B':
11863     case 'C':
11864       return true;
11865     }
11866   } else if (Constraint == "DA" ||
11867              Constraint == "DB") {
11868     return true;
11869   }
11870   return false;
11871 }
11872 
11873 SITargetLowering::ConstraintType
11874 SITargetLowering::getConstraintType(StringRef Constraint) const {
11875   if (Constraint.size() == 1) {
11876     switch (Constraint[0]) {
11877     default: break;
11878     case 's':
11879     case 'v':
11880     case 'a':
11881       return C_RegisterClass;
11882     }
11883   }
11884   if (isImmConstraint(Constraint)) {
11885     return C_Other;
11886   }
11887   return TargetLowering::getConstraintType(Constraint);
11888 }
11889 
11890 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11891   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11892     Val = Val & maskTrailingOnes<uint64_t>(Size);
11893   }
11894   return Val;
11895 }
11896 
11897 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11898                                                     std::string &Constraint,
11899                                                     std::vector<SDValue> &Ops,
11900                                                     SelectionDAG &DAG) const {
11901   if (isImmConstraint(Constraint)) {
11902     uint64_t Val;
11903     if (getAsmOperandConstVal(Op, Val) &&
11904         checkAsmConstraintVal(Op, Constraint, Val)) {
11905       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11906       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11907     }
11908   } else {
11909     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11910   }
11911 }
11912 
11913 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11914   unsigned Size = Op.getScalarValueSizeInBits();
11915   if (Size > 64)
11916     return false;
11917 
11918   if (Size == 16 && !Subtarget->has16BitInsts())
11919     return false;
11920 
11921   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11922     Val = C->getSExtValue();
11923     return true;
11924   }
11925   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11926     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11927     return true;
11928   }
11929   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11930     if (Size != 16 || Op.getNumOperands() != 2)
11931       return false;
11932     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11933       return false;
11934     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11935       Val = C->getSExtValue();
11936       return true;
11937     }
11938     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11939       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11940       return true;
11941     }
11942   }
11943 
11944   return false;
11945 }
11946 
11947 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11948                                              const std::string &Constraint,
11949                                              uint64_t Val) const {
11950   if (Constraint.size() == 1) {
11951     switch (Constraint[0]) {
11952     case 'I':
11953       return AMDGPU::isInlinableIntLiteral(Val);
11954     case 'J':
11955       return isInt<16>(Val);
11956     case 'A':
11957       return checkAsmConstraintValA(Op, Val);
11958     case 'B':
11959       return isInt<32>(Val);
11960     case 'C':
11961       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11962              AMDGPU::isInlinableIntLiteral(Val);
11963     default:
11964       break;
11965     }
11966   } else if (Constraint.size() == 2) {
11967     if (Constraint == "DA") {
11968       int64_t HiBits = static_cast<int32_t>(Val >> 32);
11969       int64_t LoBits = static_cast<int32_t>(Val);
11970       return checkAsmConstraintValA(Op, HiBits, 32) &&
11971              checkAsmConstraintValA(Op, LoBits, 32);
11972     }
11973     if (Constraint == "DB") {
11974       return true;
11975     }
11976   }
11977   llvm_unreachable("Invalid asm constraint");
11978 }
11979 
11980 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
11981                                               uint64_t Val,
11982                                               unsigned MaxSize) const {
11983   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
11984   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11985   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11986       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11987       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11988     return true;
11989   }
11990   return false;
11991 }
11992 
11993 static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
11994   switch (UnalignedClassID) {
11995   case AMDGPU::VReg_64RegClassID:
11996     return AMDGPU::VReg_64_Align2RegClassID;
11997   case AMDGPU::VReg_96RegClassID:
11998     return AMDGPU::VReg_96_Align2RegClassID;
11999   case AMDGPU::VReg_128RegClassID:
12000     return AMDGPU::VReg_128_Align2RegClassID;
12001   case AMDGPU::VReg_160RegClassID:
12002     return AMDGPU::VReg_160_Align2RegClassID;
12003   case AMDGPU::VReg_192RegClassID:
12004     return AMDGPU::VReg_192_Align2RegClassID;
12005   case AMDGPU::VReg_224RegClassID:
12006     return AMDGPU::VReg_224_Align2RegClassID;
12007   case AMDGPU::VReg_256RegClassID:
12008     return AMDGPU::VReg_256_Align2RegClassID;
12009   case AMDGPU::VReg_512RegClassID:
12010     return AMDGPU::VReg_512_Align2RegClassID;
12011   case AMDGPU::VReg_1024RegClassID:
12012     return AMDGPU::VReg_1024_Align2RegClassID;
12013   case AMDGPU::AReg_64RegClassID:
12014     return AMDGPU::AReg_64_Align2RegClassID;
12015   case AMDGPU::AReg_96RegClassID:
12016     return AMDGPU::AReg_96_Align2RegClassID;
12017   case AMDGPU::AReg_128RegClassID:
12018     return AMDGPU::AReg_128_Align2RegClassID;
12019   case AMDGPU::AReg_160RegClassID:
12020     return AMDGPU::AReg_160_Align2RegClassID;
12021   case AMDGPU::AReg_192RegClassID:
12022     return AMDGPU::AReg_192_Align2RegClassID;
12023   case AMDGPU::AReg_256RegClassID:
12024     return AMDGPU::AReg_256_Align2RegClassID;
12025   case AMDGPU::AReg_512RegClassID:
12026     return AMDGPU::AReg_512_Align2RegClassID;
12027   case AMDGPU::AReg_1024RegClassID:
12028     return AMDGPU::AReg_1024_Align2RegClassID;
12029   default:
12030     return -1;
12031   }
12032 }
12033 
12034 // Figure out which registers should be reserved for stack access. Only after
12035 // the function is legalized do we know all of the non-spill stack objects or if
12036 // calls are present.
12037 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
12038   MachineRegisterInfo &MRI = MF.getRegInfo();
12039   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12040   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
12041   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12042   const SIInstrInfo *TII = ST.getInstrInfo();
12043 
12044   if (Info->isEntryFunction()) {
12045     // Callable functions have fixed registers used for stack access.
12046     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
12047   }
12048 
12049   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
12050                              Info->getStackPtrOffsetReg()));
12051   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
12052     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
12053 
12054   // We need to worry about replacing the default register with itself in case
12055   // of MIR testcases missing the MFI.
12056   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
12057     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
12058 
12059   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
12060     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
12061 
12062   Info->limitOccupancy(MF);
12063 
12064   if (ST.isWave32() && !MF.empty()) {
12065     for (auto &MBB : MF) {
12066       for (auto &MI : MBB) {
12067         TII->fixImplicitOperands(MI);
12068       }
12069     }
12070   }
12071 
12072   // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
12073   // classes if required. Ideally the register class constraints would differ
12074   // per-subtarget, but there's no easy way to achieve that right now. This is
12075   // not a problem for VGPRs because the correctly aligned VGPR class is implied
12076   // from using them as the register class for legal types.
12077   if (ST.needsAlignedVGPRs()) {
12078     for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
12079       const Register Reg = Register::index2VirtReg(I);
12080       const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
12081       if (!RC)
12082         continue;
12083       int NewClassID = getAlignedAGPRClassID(RC->getID());
12084       if (NewClassID != -1)
12085         MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
12086     }
12087   }
12088 
12089   TargetLoweringBase::finalizeLowering(MF);
12090 }
12091 
12092 void SITargetLowering::computeKnownBitsForFrameIndex(
12093   const int FI, KnownBits &Known, const MachineFunction &MF) const {
12094   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
12095 
12096   // Set the high bits to zero based on the maximum allowed scratch size per
12097   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
12098   // calculation won't overflow, so assume the sign bit is never set.
12099   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
12100 }
12101 
12102 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
12103                                    KnownBits &Known, unsigned Dim) {
12104   unsigned MaxValue =
12105       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
12106   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
12107 }
12108 
12109 void SITargetLowering::computeKnownBitsForTargetInstr(
12110     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
12111     const MachineRegisterInfo &MRI, unsigned Depth) const {
12112   const MachineInstr *MI = MRI.getVRegDef(R);
12113   switch (MI->getOpcode()) {
12114   case AMDGPU::G_INTRINSIC: {
12115     switch (MI->getIntrinsicID()) {
12116     case Intrinsic::amdgcn_workitem_id_x:
12117       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
12118       break;
12119     case Intrinsic::amdgcn_workitem_id_y:
12120       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
12121       break;
12122     case Intrinsic::amdgcn_workitem_id_z:
12123       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
12124       break;
12125     case Intrinsic::amdgcn_mbcnt_lo:
12126     case Intrinsic::amdgcn_mbcnt_hi: {
12127       // These return at most the wavefront size - 1.
12128       unsigned Size = MRI.getType(R).getSizeInBits();
12129       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
12130       break;
12131     }
12132     case Intrinsic::amdgcn_groupstaticsize: {
12133       // We can report everything over the maximum size as 0. We can't report
12134       // based on the actual size because we don't know if it's accurate or not
12135       // at any given point.
12136       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
12137       break;
12138     }
12139     }
12140     break;
12141   }
12142   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
12143     Known.Zero.setHighBits(24);
12144     break;
12145   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
12146     Known.Zero.setHighBits(16);
12147     break;
12148   }
12149 }
12150 
12151 Align SITargetLowering::computeKnownAlignForTargetInstr(
12152   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
12153   unsigned Depth) const {
12154   const MachineInstr *MI = MRI.getVRegDef(R);
12155   switch (MI->getOpcode()) {
12156   case AMDGPU::G_INTRINSIC:
12157   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
12158     // FIXME: Can this move to generic code? What about the case where the call
12159     // site specifies a lower alignment?
12160     Intrinsic::ID IID = MI->getIntrinsicID();
12161     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
12162     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
12163     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
12164       return *RetAlign;
12165     return Align(1);
12166   }
12167   default:
12168     return Align(1);
12169   }
12170 }
12171 
12172 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12173   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
12174   const Align CacheLineAlign = Align(64);
12175 
12176   // Pre-GFX10 target did not benefit from loop alignment
12177   if (!ML || DisableLoopAlignment ||
12178       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
12179       getSubtarget()->hasInstFwdPrefetchBug())
12180     return PrefAlign;
12181 
12182   // On GFX10 I$ is 4 x 64 bytes cache lines.
12183   // By default prefetcher keeps one cache line behind and reads two ahead.
12184   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
12185   // behind and one ahead.
12186   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
12187   // If loop fits 64 bytes it always spans no more than two cache lines and
12188   // does not need an alignment.
12189   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
12190   // Else if loop is less or equal 192 bytes we need two lines behind.
12191 
12192   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12193   const MachineBasicBlock *Header = ML->getHeader();
12194   if (Header->getAlignment() != PrefAlign)
12195     return Header->getAlignment(); // Already processed.
12196 
12197   unsigned LoopSize = 0;
12198   for (const MachineBasicBlock *MBB : ML->blocks()) {
12199     // If inner loop block is aligned assume in average half of the alignment
12200     // size to be added as nops.
12201     if (MBB != Header)
12202       LoopSize += MBB->getAlignment().value() / 2;
12203 
12204     for (const MachineInstr &MI : *MBB) {
12205       LoopSize += TII->getInstSizeInBytes(MI);
12206       if (LoopSize > 192)
12207         return PrefAlign;
12208     }
12209   }
12210 
12211   if (LoopSize <= 64)
12212     return PrefAlign;
12213 
12214   if (LoopSize <= 128)
12215     return CacheLineAlign;
12216 
12217   // If any of parent loops is surrounded by prefetch instructions do not
12218   // insert new for inner loop, which would reset parent's settings.
12219   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
12220     if (MachineBasicBlock *Exit = P->getExitBlock()) {
12221       auto I = Exit->getFirstNonDebugInstr();
12222       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
12223         return CacheLineAlign;
12224     }
12225   }
12226 
12227   MachineBasicBlock *Pre = ML->getLoopPreheader();
12228   MachineBasicBlock *Exit = ML->getExitBlock();
12229 
12230   if (Pre && Exit) {
12231     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
12232             TII->get(AMDGPU::S_INST_PREFETCH))
12233       .addImm(1); // prefetch 2 lines behind PC
12234 
12235     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
12236             TII->get(AMDGPU::S_INST_PREFETCH))
12237       .addImm(2); // prefetch 1 line behind PC
12238   }
12239 
12240   return CacheLineAlign;
12241 }
12242 
12243 LLVM_ATTRIBUTE_UNUSED
12244 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
12245   assert(N->getOpcode() == ISD::CopyFromReg);
12246   do {
12247     // Follow the chain until we find an INLINEASM node.
12248     N = N->getOperand(0).getNode();
12249     if (N->getOpcode() == ISD::INLINEASM ||
12250         N->getOpcode() == ISD::INLINEASM_BR)
12251       return true;
12252   } while (N->getOpcode() == ISD::CopyFromReg);
12253   return false;
12254 }
12255 
12256 bool SITargetLowering::isSDNodeSourceOfDivergence(
12257     const SDNode *N, FunctionLoweringInfo *FLI,
12258     LegacyDivergenceAnalysis *KDA) const {
12259   switch (N->getOpcode()) {
12260   case ISD::CopyFromReg: {
12261     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
12262     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
12263     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12264     Register Reg = R->getReg();
12265 
12266     // FIXME: Why does this need to consider isLiveIn?
12267     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
12268       return !TRI->isSGPRReg(MRI, Reg);
12269 
12270     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
12271       return KDA->isDivergent(V);
12272 
12273     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
12274     return !TRI->isSGPRReg(MRI, Reg);
12275   }
12276   case ISD::LOAD: {
12277     const LoadSDNode *L = cast<LoadSDNode>(N);
12278     unsigned AS = L->getAddressSpace();
12279     // A flat load may access private memory.
12280     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
12281   }
12282   case ISD::CALLSEQ_END:
12283     return true;
12284   case ISD::INTRINSIC_WO_CHAIN:
12285     return AMDGPU::isIntrinsicSourceOfDivergence(
12286         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
12287   case ISD::INTRINSIC_W_CHAIN:
12288     return AMDGPU::isIntrinsicSourceOfDivergence(
12289         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
12290   case AMDGPUISD::ATOMIC_CMP_SWAP:
12291   case AMDGPUISD::ATOMIC_INC:
12292   case AMDGPUISD::ATOMIC_DEC:
12293   case AMDGPUISD::ATOMIC_LOAD_FMIN:
12294   case AMDGPUISD::ATOMIC_LOAD_FMAX:
12295   case AMDGPUISD::BUFFER_ATOMIC_SWAP:
12296   case AMDGPUISD::BUFFER_ATOMIC_ADD:
12297   case AMDGPUISD::BUFFER_ATOMIC_SUB:
12298   case AMDGPUISD::BUFFER_ATOMIC_SMIN:
12299   case AMDGPUISD::BUFFER_ATOMIC_UMIN:
12300   case AMDGPUISD::BUFFER_ATOMIC_SMAX:
12301   case AMDGPUISD::BUFFER_ATOMIC_UMAX:
12302   case AMDGPUISD::BUFFER_ATOMIC_AND:
12303   case AMDGPUISD::BUFFER_ATOMIC_OR:
12304   case AMDGPUISD::BUFFER_ATOMIC_XOR:
12305   case AMDGPUISD::BUFFER_ATOMIC_INC:
12306   case AMDGPUISD::BUFFER_ATOMIC_DEC:
12307   case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
12308   case AMDGPUISD::BUFFER_ATOMIC_CSUB:
12309   case AMDGPUISD::BUFFER_ATOMIC_FADD:
12310   case AMDGPUISD::BUFFER_ATOMIC_FMIN:
12311   case AMDGPUISD::BUFFER_ATOMIC_FMAX:
12312     // Target-specific read-modify-write atomics are sources of divergence.
12313     return true;
12314   default:
12315     if (auto *A = dyn_cast<AtomicSDNode>(N)) {
12316       // Generic read-modify-write atomics are sources of divergence.
12317       return A->readMem() && A->writeMem();
12318     }
12319     return false;
12320   }
12321 }
12322 
12323 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
12324                                                EVT VT) const {
12325   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
12326   case MVT::f32:
12327     return hasFP32Denormals(DAG.getMachineFunction());
12328   case MVT::f64:
12329   case MVT::f16:
12330     return hasFP64FP16Denormals(DAG.getMachineFunction());
12331   default:
12332     return false;
12333   }
12334 }
12335 
12336 bool SITargetLowering::denormalsEnabledForType(LLT Ty,
12337                                                MachineFunction &MF) const {
12338   switch (Ty.getScalarSizeInBits()) {
12339   case 32:
12340     return hasFP32Denormals(MF);
12341   case 64:
12342   case 16:
12343     return hasFP64FP16Denormals(MF);
12344   default:
12345     return false;
12346   }
12347 }
12348 
12349 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
12350                                                     const SelectionDAG &DAG,
12351                                                     bool SNaN,
12352                                                     unsigned Depth) const {
12353   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
12354     const MachineFunction &MF = DAG.getMachineFunction();
12355     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12356 
12357     if (Info->getMode().DX10Clamp)
12358       return true; // Clamped to 0.
12359     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
12360   }
12361 
12362   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
12363                                                             SNaN, Depth);
12364 }
12365 
12366 // Global FP atomic instructions have a hardcoded FP mode and do not support
12367 // FP32 denormals, and only support v2f16 denormals.
12368 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
12369   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
12370   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
12371   if (&Flt == &APFloat::IEEEsingle())
12372     return DenormMode == DenormalMode::getPreserveSign();
12373   return DenormMode == DenormalMode::getIEEE();
12374 }
12375 
12376 TargetLowering::AtomicExpansionKind
12377 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
12378 
12379   auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) {
12380     OptimizationRemarkEmitter ORE(RMW->getFunction());
12381     LLVMContext &Ctx = RMW->getFunction()->getContext();
12382     SmallVector<StringRef> SSNs;
12383     Ctx.getSyncScopeNames(SSNs);
12384     auto MemScope = SSNs[RMW->getSyncScopeID()].empty()
12385                         ? "system"
12386                         : SSNs[RMW->getSyncScopeID()];
12387     ORE.emit([&]() {
12388       return OptimizationRemark(DEBUG_TYPE, "Passed", RMW)
12389              << "Hardware instruction generated for atomic "
12390              << RMW->getOperationName(RMW->getOperation())
12391              << " operation at memory scope " << MemScope
12392              << " due to an unsafe request.";
12393     });
12394     return Kind;
12395   };
12396 
12397   switch (RMW->getOperation()) {
12398   case AtomicRMWInst::FAdd: {
12399     Type *Ty = RMW->getType();
12400 
12401     // We don't have a way to support 16-bit atomics now, so just leave them
12402     // as-is.
12403     if (Ty->isHalfTy())
12404       return AtomicExpansionKind::None;
12405 
12406     if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
12407       return AtomicExpansionKind::CmpXChg;
12408 
12409     unsigned AS = RMW->getPointerAddressSpace();
12410 
12411     if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) &&
12412          Subtarget->hasAtomicFaddInsts()) {
12413       if (Subtarget->hasGFX940Insts())
12414         return AtomicExpansionKind::None;
12415 
12416       // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
12417       // floating point atomic instructions. May generate more efficient code,
12418       // but may not respect rounding and denormal modes, and may give incorrect
12419       // results for certain memory destinations.
12420       if (RMW->getFunction()
12421               ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12422               .getValueAsString() != "true")
12423         return AtomicExpansionKind::CmpXChg;
12424 
12425       if (Subtarget->hasGFX90AInsts()) {
12426         if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS)
12427           return AtomicExpansionKind::CmpXChg;
12428 
12429         auto SSID = RMW->getSyncScopeID();
12430         if (SSID == SyncScope::System ||
12431             SSID == RMW->getContext().getOrInsertSyncScopeID("one-as"))
12432           return AtomicExpansionKind::CmpXChg;
12433 
12434         return ReportUnsafeHWInst(AtomicExpansionKind::None);
12435       }
12436 
12437       if (AS == AMDGPUAS::FLAT_ADDRESS)
12438         return AtomicExpansionKind::CmpXChg;
12439 
12440       return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12441                               : AtomicExpansionKind::CmpXChg;
12442     }
12443 
12444     // DS FP atomics do respect the denormal mode, but the rounding mode is
12445     // fixed to round-to-nearest-even.
12446     // The only exception is DS_ADD_F64 which never flushes regardless of mode.
12447     if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) {
12448       if (!Ty->isDoubleTy())
12449         return AtomicExpansionKind::None;
12450 
12451       if (fpModeMatchesGlobalFPAtomicMode(RMW))
12452         return AtomicExpansionKind::None;
12453 
12454       return RMW->getFunction()
12455                          ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12456                          .getValueAsString() == "true"
12457                  ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12458                  : AtomicExpansionKind::CmpXChg;
12459     }
12460 
12461     return AtomicExpansionKind::CmpXChg;
12462   }
12463   default:
12464     break;
12465   }
12466 
12467   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
12468 }
12469 
12470 const TargetRegisterClass *
12471 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
12472   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
12473   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12474   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
12475     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
12476                                                : &AMDGPU::SReg_32RegClass;
12477   if (!TRI->isSGPRClass(RC) && !isDivergent)
12478     return TRI->getEquivalentSGPRClass(RC);
12479   else if (TRI->isSGPRClass(RC) && isDivergent)
12480     return TRI->getEquivalentVGPRClass(RC);
12481 
12482   return RC;
12483 }
12484 
12485 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
12486 // uniform values (as produced by the mask results of control flow intrinsics)
12487 // used outside of divergent blocks. The phi users need to also be treated as
12488 // always uniform.
12489 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
12490                       unsigned WaveSize) {
12491   // FIXME: We assume we never cast the mask results of a control flow
12492   // intrinsic.
12493   // Early exit if the type won't be consistent as a compile time hack.
12494   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
12495   if (!IT || IT->getBitWidth() != WaveSize)
12496     return false;
12497 
12498   if (!isa<Instruction>(V))
12499     return false;
12500   if (!Visited.insert(V).second)
12501     return false;
12502   bool Result = false;
12503   for (auto U : V->users()) {
12504     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
12505       if (V == U->getOperand(1)) {
12506         switch (Intrinsic->getIntrinsicID()) {
12507         default:
12508           Result = false;
12509           break;
12510         case Intrinsic::amdgcn_if_break:
12511         case Intrinsic::amdgcn_if:
12512         case Intrinsic::amdgcn_else:
12513           Result = true;
12514           break;
12515         }
12516       }
12517       if (V == U->getOperand(0)) {
12518         switch (Intrinsic->getIntrinsicID()) {
12519         default:
12520           Result = false;
12521           break;
12522         case Intrinsic::amdgcn_end_cf:
12523         case Intrinsic::amdgcn_loop:
12524           Result = true;
12525           break;
12526         }
12527       }
12528     } else {
12529       Result = hasCFUser(U, Visited, WaveSize);
12530     }
12531     if (Result)
12532       break;
12533   }
12534   return Result;
12535 }
12536 
12537 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
12538                                                const Value *V) const {
12539   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
12540     if (CI->isInlineAsm()) {
12541       // FIXME: This cannot give a correct answer. This should only trigger in
12542       // the case where inline asm returns mixed SGPR and VGPR results, used
12543       // outside the defining block. We don't have a specific result to
12544       // consider, so this assumes if any value is SGPR, the overall register
12545       // also needs to be SGPR.
12546       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
12547       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
12548           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
12549       for (auto &TC : TargetConstraints) {
12550         if (TC.Type == InlineAsm::isOutput) {
12551           ComputeConstraintToUse(TC, SDValue());
12552           const TargetRegisterClass *RC = getRegForInlineAsmConstraint(
12553               SIRI, TC.ConstraintCode, TC.ConstraintVT).second;
12554           if (RC && SIRI->isSGPRClass(RC))
12555             return true;
12556         }
12557       }
12558     }
12559   }
12560   SmallPtrSet<const Value *, 16> Visited;
12561   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
12562 }
12563 
12564 std::pair<InstructionCost, MVT>
12565 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
12566                                           Type *Ty) const {
12567   std::pair<InstructionCost, MVT> Cost =
12568       TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
12569   auto Size = DL.getTypeSizeInBits(Ty);
12570   // Maximum load or store can handle 8 dwords for scalar and 4 for
12571   // vector ALU. Let's assume anything above 8 dwords is expensive
12572   // even if legal.
12573   if (Size <= 256)
12574     return Cost;
12575 
12576   Cost.first += (Size + 255) / 256;
12577   return Cost;
12578 }
12579 
12580 bool SITargetLowering::hasMemSDNodeUser(SDNode *N) const {
12581   SDNode::use_iterator I = N->use_begin(), E = N->use_end();
12582   for (; I != E; ++I) {
12583     if (MemSDNode *M = dyn_cast<MemSDNode>(*I)) {
12584       if (getBasePtrIndex(M) == I.getOperandNo())
12585         return true;
12586     }
12587   }
12588   return false;
12589 }
12590 
12591 bool SITargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0,
12592                                            SDValue N1) const {
12593   if (!N0.hasOneUse())
12594     return false;
12595   // Take care of the opportunity to keep N0 uniform
12596   if (N0->isDivergent() || !N1->isDivergent())
12597     return true;
12598   // Check if we have a good chance to form the memory access pattern with the
12599   // base and offset
12600   return (DAG.isBaseWithConstantOffset(N0) &&
12601           hasMemSDNodeUser(*N0->use_begin()));
12602 }
12603 
12604 MachineMemOperand::Flags
12605 SITargetLowering::getTargetMMOFlags(const Instruction &I) const {
12606   // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load.
12607   if (I.getMetadata("amdgpu.noclobber"))
12608     return MONoClobber;
12609   return MachineMemOperand::MONone;
12610 }
12611