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())
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()) {
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   // Add return address for callable functions.
2670   if (!Info->isEntryFunction()) {
2671     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2672     SDValue ReturnAddrReg = CreateLiveInRegister(
2673       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2674 
2675     SDValue ReturnAddrVirtualReg =
2676         DAG.getRegister(MF.getRegInfo().createVirtualRegister(
2677                             CallConv != CallingConv::AMDGPU_Gfx
2678                                 ? &AMDGPU::CCR_SGPR_64RegClass
2679                                 : &AMDGPU::Gfx_CCR_SGPR_64RegClass),
2680                         MVT::i64);
2681     Chain =
2682         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2683     Flag = Chain.getValue(1);
2684     RetOps.push_back(ReturnAddrVirtualReg);
2685   }
2686 
2687   // Copy the result values into the output registers.
2688   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2689        ++I, ++RealRVLocIdx) {
2690     CCValAssign &VA = RVLocs[I];
2691     assert(VA.isRegLoc() && "Can only return in registers!");
2692     // TODO: Partially return in registers if return values don't fit.
2693     SDValue Arg = OutVals[RealRVLocIdx];
2694 
2695     // Copied from other backends.
2696     switch (VA.getLocInfo()) {
2697     case CCValAssign::Full:
2698       break;
2699     case CCValAssign::BCvt:
2700       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2701       break;
2702     case CCValAssign::SExt:
2703       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2704       break;
2705     case CCValAssign::ZExt:
2706       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2707       break;
2708     case CCValAssign::AExt:
2709       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2710       break;
2711     default:
2712       llvm_unreachable("Unknown loc info!");
2713     }
2714 
2715     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2716     Flag = Chain.getValue(1);
2717     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2718   }
2719 
2720   // FIXME: Does sret work properly?
2721   if (!Info->isEntryFunction()) {
2722     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2723     const MCPhysReg *I =
2724       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2725     if (I) {
2726       for (; *I; ++I) {
2727         if (AMDGPU::SReg_64RegClass.contains(*I))
2728           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2729         else if (AMDGPU::SReg_32RegClass.contains(*I))
2730           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2731         else
2732           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2733       }
2734     }
2735   }
2736 
2737   // Update chain and glue.
2738   RetOps[0] = Chain;
2739   if (Flag.getNode())
2740     RetOps.push_back(Flag);
2741 
2742   unsigned Opc = AMDGPUISD::ENDPGM;
2743   if (!IsWaveEnd) {
2744     if (IsShader)
2745       Opc = AMDGPUISD::RETURN_TO_EPILOG;
2746     else if (CallConv == CallingConv::AMDGPU_Gfx)
2747       Opc = AMDGPUISD::RET_GFX_FLAG;
2748     else
2749       Opc = AMDGPUISD::RET_FLAG;
2750   }
2751 
2752   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2753 }
2754 
2755 SDValue SITargetLowering::LowerCallResult(
2756     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2757     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2758     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2759     SDValue ThisVal) const {
2760   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2761 
2762   // Assign locations to each value returned by this call.
2763   SmallVector<CCValAssign, 16> RVLocs;
2764   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2765                  *DAG.getContext());
2766   CCInfo.AnalyzeCallResult(Ins, RetCC);
2767 
2768   // Copy all of the result registers out of their specified physreg.
2769   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2770     CCValAssign VA = RVLocs[i];
2771     SDValue Val;
2772 
2773     if (VA.isRegLoc()) {
2774       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2775       Chain = Val.getValue(1);
2776       InFlag = Val.getValue(2);
2777     } else if (VA.isMemLoc()) {
2778       report_fatal_error("TODO: return values in memory");
2779     } else
2780       llvm_unreachable("unknown argument location type");
2781 
2782     switch (VA.getLocInfo()) {
2783     case CCValAssign::Full:
2784       break;
2785     case CCValAssign::BCvt:
2786       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2787       break;
2788     case CCValAssign::ZExt:
2789       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2790                         DAG.getValueType(VA.getValVT()));
2791       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2792       break;
2793     case CCValAssign::SExt:
2794       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2795                         DAG.getValueType(VA.getValVT()));
2796       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2797       break;
2798     case CCValAssign::AExt:
2799       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2800       break;
2801     default:
2802       llvm_unreachable("Unknown loc info!");
2803     }
2804 
2805     InVals.push_back(Val);
2806   }
2807 
2808   return Chain;
2809 }
2810 
2811 // Add code to pass special inputs required depending on used features separate
2812 // from the explicit user arguments present in the IR.
2813 void SITargetLowering::passSpecialInputs(
2814     CallLoweringInfo &CLI,
2815     CCState &CCInfo,
2816     const SIMachineFunctionInfo &Info,
2817     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2818     SmallVectorImpl<SDValue> &MemOpChains,
2819     SDValue Chain) const {
2820   // If we don't have a call site, this was a call inserted by
2821   // legalization. These can never use special inputs.
2822   if (!CLI.CB)
2823     return;
2824 
2825   SelectionDAG &DAG = CLI.DAG;
2826   const SDLoc &DL = CLI.DL;
2827   const Function &F = DAG.getMachineFunction().getFunction();
2828 
2829   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2830   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2831 
2832   const AMDGPUFunctionArgInfo *CalleeArgInfo
2833     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2834   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2835     auto &ArgUsageInfo =
2836       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2837     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2838   }
2839 
2840   // TODO: Unify with private memory register handling. This is complicated by
2841   // the fact that at least in kernels, the input argument is not necessarily
2842   // in the same location as the input.
2843   static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
2844                              StringLiteral> ImplicitAttrs[] = {
2845     {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"},
2846     {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" },
2847     {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"},
2848     {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"},
2849     {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"},
2850     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"},
2851     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"}
2852   };
2853 
2854   for (auto Attr : ImplicitAttrs) {
2855     const ArgDescriptor *OutgoingArg;
2856     const TargetRegisterClass *ArgRC;
2857     LLT ArgTy;
2858 
2859     AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first;
2860 
2861     // If the callee does not use the attribute value, skip copying the value.
2862     if (CLI.CB->hasFnAttr(Attr.second))
2863       continue;
2864 
2865     std::tie(OutgoingArg, ArgRC, ArgTy) =
2866         CalleeArgInfo->getPreloadedValue(InputID);
2867     if (!OutgoingArg)
2868       continue;
2869 
2870     const ArgDescriptor *IncomingArg;
2871     const TargetRegisterClass *IncomingArgRC;
2872     LLT Ty;
2873     std::tie(IncomingArg, IncomingArgRC, Ty) =
2874         CallerArgInfo.getPreloadedValue(InputID);
2875     assert(IncomingArgRC == ArgRC);
2876 
2877     // All special arguments are ints for now.
2878     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2879     SDValue InputReg;
2880 
2881     if (IncomingArg) {
2882       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2883     } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
2884       // The implicit arg ptr is special because it doesn't have a corresponding
2885       // input for kernels, and is computed from the kernarg segment pointer.
2886       InputReg = getImplicitArgPtr(DAG, DL);
2887     } else {
2888       // We may have proven the input wasn't needed, although the ABI is
2889       // requiring it. We just need to allocate the register appropriately.
2890       InputReg = DAG.getUNDEF(ArgVT);
2891     }
2892 
2893     if (OutgoingArg->isRegister()) {
2894       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2895       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2896         report_fatal_error("failed to allocate implicit input argument");
2897     } else {
2898       unsigned SpecialArgOffset =
2899           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2900       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2901                                               SpecialArgOffset);
2902       MemOpChains.push_back(ArgStore);
2903     }
2904   }
2905 
2906   // Pack workitem IDs into a single register or pass it as is if already
2907   // packed.
2908   const ArgDescriptor *OutgoingArg;
2909   const TargetRegisterClass *ArgRC;
2910   LLT Ty;
2911 
2912   std::tie(OutgoingArg, ArgRC, Ty) =
2913       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2914   if (!OutgoingArg)
2915     std::tie(OutgoingArg, ArgRC, Ty) =
2916         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2917   if (!OutgoingArg)
2918     std::tie(OutgoingArg, ArgRC, Ty) =
2919         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2920   if (!OutgoingArg)
2921     return;
2922 
2923   const ArgDescriptor *IncomingArgX = std::get<0>(
2924       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2925   const ArgDescriptor *IncomingArgY = std::get<0>(
2926       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2927   const ArgDescriptor *IncomingArgZ = std::get<0>(
2928       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2929 
2930   SDValue InputReg;
2931   SDLoc SL;
2932 
2933   const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
2934   const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
2935   const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
2936 
2937   // If incoming ids are not packed we need to pack them.
2938   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
2939       NeedWorkItemIDX) {
2940     if (Subtarget->getMaxWorkitemID(F, 0) != 0) {
2941       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2942     } else {
2943       InputReg = DAG.getConstant(0, DL, MVT::i32);
2944     }
2945   }
2946 
2947   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
2948       NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) {
2949     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2950     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2951                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2952     InputReg = InputReg.getNode() ?
2953                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2954   }
2955 
2956   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
2957       NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) {
2958     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2959     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2960                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2961     InputReg = InputReg.getNode() ?
2962                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2963   }
2964 
2965   if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
2966     if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) {
2967       // We're in a situation where the outgoing function requires the workitem
2968       // ID, but the calling function does not have it (e.g a graphics function
2969       // calling a C calling convention function). This is illegal, but we need
2970       // to produce something.
2971       InputReg = DAG.getUNDEF(MVT::i32);
2972     } else {
2973       // Workitem ids are already packed, any of present incoming arguments
2974       // will carry all required fields.
2975       ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2976         IncomingArgX ? *IncomingArgX :
2977         IncomingArgY ? *IncomingArgY :
2978         *IncomingArgZ, ~0u);
2979       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2980     }
2981   }
2982 
2983   if (OutgoingArg->isRegister()) {
2984     if (InputReg)
2985       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2986 
2987     CCInfo.AllocateReg(OutgoingArg->getRegister());
2988   } else {
2989     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2990     if (InputReg) {
2991       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2992                                               SpecialArgOffset);
2993       MemOpChains.push_back(ArgStore);
2994     }
2995   }
2996 }
2997 
2998 static bool canGuaranteeTCO(CallingConv::ID CC) {
2999   return CC == CallingConv::Fast;
3000 }
3001 
3002 /// Return true if we might ever do TCO for calls with this calling convention.
3003 static bool mayTailCallThisCC(CallingConv::ID CC) {
3004   switch (CC) {
3005   case CallingConv::C:
3006   case CallingConv::AMDGPU_Gfx:
3007     return true;
3008   default:
3009     return canGuaranteeTCO(CC);
3010   }
3011 }
3012 
3013 bool SITargetLowering::isEligibleForTailCallOptimization(
3014     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
3015     const SmallVectorImpl<ISD::OutputArg> &Outs,
3016     const SmallVectorImpl<SDValue> &OutVals,
3017     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3018   if (!mayTailCallThisCC(CalleeCC))
3019     return false;
3020 
3021   // For a divergent call target, we need to do a waterfall loop over the
3022   // possible callees which precludes us from using a simple jump.
3023   if (Callee->isDivergent())
3024     return false;
3025 
3026   MachineFunction &MF = DAG.getMachineFunction();
3027   const Function &CallerF = MF.getFunction();
3028   CallingConv::ID CallerCC = CallerF.getCallingConv();
3029   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3030   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3031 
3032   // Kernels aren't callable, and don't have a live in return address so it
3033   // doesn't make sense to do a tail call with entry functions.
3034   if (!CallerPreserved)
3035     return false;
3036 
3037   bool CCMatch = CallerCC == CalleeCC;
3038 
3039   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3040     if (canGuaranteeTCO(CalleeCC) && CCMatch)
3041       return true;
3042     return false;
3043   }
3044 
3045   // TODO: Can we handle var args?
3046   if (IsVarArg)
3047     return false;
3048 
3049   for (const Argument &Arg : CallerF.args()) {
3050     if (Arg.hasByValAttr())
3051       return false;
3052   }
3053 
3054   LLVMContext &Ctx = *DAG.getContext();
3055 
3056   // Check that the call results are passed in the same way.
3057   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
3058                                   CCAssignFnForCall(CalleeCC, IsVarArg),
3059                                   CCAssignFnForCall(CallerCC, IsVarArg)))
3060     return false;
3061 
3062   // The callee has to preserve all registers the caller needs to preserve.
3063   if (!CCMatch) {
3064     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3065     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3066       return false;
3067   }
3068 
3069   // Nothing more to check if the callee is taking no arguments.
3070   if (Outs.empty())
3071     return true;
3072 
3073   SmallVector<CCValAssign, 16> ArgLocs;
3074   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
3075 
3076   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
3077 
3078   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
3079   // If the stack arguments for this call do not fit into our own save area then
3080   // the call cannot be made tail.
3081   // TODO: Is this really necessary?
3082   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3083     return false;
3084 
3085   const MachineRegisterInfo &MRI = MF.getRegInfo();
3086   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
3087 }
3088 
3089 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3090   if (!CI->isTailCall())
3091     return false;
3092 
3093   const Function *ParentFn = CI->getParent()->getParent();
3094   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
3095     return false;
3096   return true;
3097 }
3098 
3099 // The wave scratch offset register is used as the global base pointer.
3100 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
3101                                     SmallVectorImpl<SDValue> &InVals) const {
3102   SelectionDAG &DAG = CLI.DAG;
3103   const SDLoc &DL = CLI.DL;
3104   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3105   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3106   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3107   SDValue Chain = CLI.Chain;
3108   SDValue Callee = CLI.Callee;
3109   bool &IsTailCall = CLI.IsTailCall;
3110   CallingConv::ID CallConv = CLI.CallConv;
3111   bool IsVarArg = CLI.IsVarArg;
3112   bool IsSibCall = false;
3113   bool IsThisReturn = false;
3114   MachineFunction &MF = DAG.getMachineFunction();
3115 
3116   if (Callee.isUndef() || isNullConstant(Callee)) {
3117     if (!CLI.IsTailCall) {
3118       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
3119         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
3120     }
3121 
3122     return Chain;
3123   }
3124 
3125   if (IsVarArg) {
3126     return lowerUnhandledCall(CLI, InVals,
3127                               "unsupported call to variadic function ");
3128   }
3129 
3130   if (!CLI.CB)
3131     report_fatal_error("unsupported libcall legalization");
3132 
3133   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
3134     return lowerUnhandledCall(CLI, InVals,
3135                               "unsupported required tail call to function ");
3136   }
3137 
3138   if (AMDGPU::isShader(CallConv)) {
3139     // Note the issue is with the CC of the called function, not of the call
3140     // itself.
3141     return lowerUnhandledCall(CLI, InVals,
3142                               "unsupported call to a shader function ");
3143   }
3144 
3145   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
3146       CallConv != CallingConv::AMDGPU_Gfx) {
3147     // Only allow calls with specific calling conventions.
3148     return lowerUnhandledCall(CLI, InVals,
3149                               "unsupported calling convention for call from "
3150                               "graphics shader of function ");
3151   }
3152 
3153   if (IsTailCall) {
3154     IsTailCall = isEligibleForTailCallOptimization(
3155       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3156     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
3157       report_fatal_error("failed to perform tail call elimination on a call "
3158                          "site marked musttail");
3159     }
3160 
3161     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3162 
3163     // A sibling call is one where we're under the usual C ABI and not planning
3164     // to change that but can still do a tail call:
3165     if (!TailCallOpt && IsTailCall)
3166       IsSibCall = true;
3167 
3168     if (IsTailCall)
3169       ++NumTailCalls;
3170   }
3171 
3172   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3173   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3174   SmallVector<SDValue, 8> MemOpChains;
3175 
3176   // Analyze operands of the call, assigning locations to each operand.
3177   SmallVector<CCValAssign, 16> ArgLocs;
3178   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3179   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3180 
3181   if (CallConv != CallingConv::AMDGPU_Gfx) {
3182     // With a fixed ABI, allocate fixed registers before user arguments.
3183     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3184   }
3185 
3186   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3187 
3188   // Get a count of how many bytes are to be pushed on the stack.
3189   unsigned NumBytes = CCInfo.getNextStackOffset();
3190 
3191   if (IsSibCall) {
3192     // Since we're not changing the ABI to make this a tail call, the memory
3193     // operands are already available in the caller's incoming argument space.
3194     NumBytes = 0;
3195   }
3196 
3197   // FPDiff is the byte offset of the call's argument area from the callee's.
3198   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3199   // by this amount for a tail call. In a sibling call it must be 0 because the
3200   // caller will deallocate the entire stack and the callee still expects its
3201   // arguments to begin at SP+0. Completely unused for non-tail calls.
3202   int32_t FPDiff = 0;
3203   MachineFrameInfo &MFI = MF.getFrameInfo();
3204 
3205   // Adjust the stack pointer for the new arguments...
3206   // These operations are automatically eliminated by the prolog/epilog pass
3207   if (!IsSibCall) {
3208     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3209 
3210     if (!Subtarget->enableFlatScratch()) {
3211       SmallVector<SDValue, 4> CopyFromChains;
3212 
3213       // In the HSA case, this should be an identity copy.
3214       SDValue ScratchRSrcReg
3215         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3216       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3217       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3218       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3219     }
3220   }
3221 
3222   MVT PtrVT = MVT::i32;
3223 
3224   // Walk the register/memloc assignments, inserting copies/loads.
3225   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3226     CCValAssign &VA = ArgLocs[i];
3227     SDValue Arg = OutVals[i];
3228 
3229     // Promote the value if needed.
3230     switch (VA.getLocInfo()) {
3231     case CCValAssign::Full:
3232       break;
3233     case CCValAssign::BCvt:
3234       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3235       break;
3236     case CCValAssign::ZExt:
3237       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3238       break;
3239     case CCValAssign::SExt:
3240       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3241       break;
3242     case CCValAssign::AExt:
3243       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3244       break;
3245     case CCValAssign::FPExt:
3246       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3247       break;
3248     default:
3249       llvm_unreachable("Unknown loc info!");
3250     }
3251 
3252     if (VA.isRegLoc()) {
3253       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3254     } else {
3255       assert(VA.isMemLoc());
3256 
3257       SDValue DstAddr;
3258       MachinePointerInfo DstInfo;
3259 
3260       unsigned LocMemOffset = VA.getLocMemOffset();
3261       int32_t Offset = LocMemOffset;
3262 
3263       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3264       MaybeAlign Alignment;
3265 
3266       if (IsTailCall) {
3267         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3268         unsigned OpSize = Flags.isByVal() ?
3269           Flags.getByValSize() : VA.getValVT().getStoreSize();
3270 
3271         // FIXME: We can have better than the minimum byval required alignment.
3272         Alignment =
3273             Flags.isByVal()
3274                 ? Flags.getNonZeroByValAlign()
3275                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3276 
3277         Offset = Offset + FPDiff;
3278         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3279 
3280         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3281         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3282 
3283         // Make sure any stack arguments overlapping with where we're storing
3284         // are loaded before this eventual operation. Otherwise they'll be
3285         // clobbered.
3286 
3287         // FIXME: Why is this really necessary? This seems to just result in a
3288         // lot of code to copy the stack and write them back to the same
3289         // locations, which are supposed to be immutable?
3290         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3291       } else {
3292         // Stores to the argument stack area are relative to the stack pointer.
3293         SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3294                                         MVT::i32);
3295         DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3296         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3297         Alignment =
3298             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3299       }
3300 
3301       if (Outs[i].Flags.isByVal()) {
3302         SDValue SizeNode =
3303             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3304         SDValue Cpy =
3305             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3306                           Outs[i].Flags.getNonZeroByValAlign(),
3307                           /*isVol = */ false, /*AlwaysInline = */ true,
3308                           /*isTailCall = */ false, DstInfo,
3309                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3310 
3311         MemOpChains.push_back(Cpy);
3312       } else {
3313         SDValue Store =
3314             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3315         MemOpChains.push_back(Store);
3316       }
3317     }
3318   }
3319 
3320   if (!MemOpChains.empty())
3321     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3322 
3323   // Build a sequence of copy-to-reg nodes chained together with token chain
3324   // and flag operands which copy the outgoing args into the appropriate regs.
3325   SDValue InFlag;
3326   for (auto &RegToPass : RegsToPass) {
3327     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3328                              RegToPass.second, InFlag);
3329     InFlag = Chain.getValue(1);
3330   }
3331 
3332 
3333   SDValue PhysReturnAddrReg;
3334   if (IsTailCall) {
3335     // Since the return is being combined with the call, we need to pass on the
3336     // return address.
3337 
3338     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3339     SDValue ReturnAddrReg = CreateLiveInRegister(
3340       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3341 
3342     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3343                                         MVT::i64);
3344     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3345     InFlag = Chain.getValue(1);
3346   }
3347 
3348   // We don't usually want to end the call-sequence here because we would tidy
3349   // the frame up *after* the call, however in the ABI-changing tail-call case
3350   // we've carefully laid out the parameters so that when sp is reset they'll be
3351   // in the correct location.
3352   if (IsTailCall && !IsSibCall) {
3353     Chain = DAG.getCALLSEQ_END(Chain,
3354                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3355                                DAG.getTargetConstant(0, DL, MVT::i32),
3356                                InFlag, DL);
3357     InFlag = Chain.getValue(1);
3358   }
3359 
3360   std::vector<SDValue> Ops;
3361   Ops.push_back(Chain);
3362   Ops.push_back(Callee);
3363   // Add a redundant copy of the callee global which will not be legalized, as
3364   // we need direct access to the callee later.
3365   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3366     const GlobalValue *GV = GSD->getGlobal();
3367     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3368   } else {
3369     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3370   }
3371 
3372   if (IsTailCall) {
3373     // Each tail call may have to adjust the stack by a different amount, so
3374     // this information must travel along with the operation for eventual
3375     // consumption by emitEpilogue.
3376     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3377 
3378     Ops.push_back(PhysReturnAddrReg);
3379   }
3380 
3381   // Add argument registers to the end of the list so that they are known live
3382   // into the call.
3383   for (auto &RegToPass : RegsToPass) {
3384     Ops.push_back(DAG.getRegister(RegToPass.first,
3385                                   RegToPass.second.getValueType()));
3386   }
3387 
3388   // Add a register mask operand representing the call-preserved registers.
3389 
3390   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3391   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3392   assert(Mask && "Missing call preserved mask for calling convention");
3393   Ops.push_back(DAG.getRegisterMask(Mask));
3394 
3395   if (InFlag.getNode())
3396     Ops.push_back(InFlag);
3397 
3398   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3399 
3400   // If we're doing a tall call, use a TC_RETURN here rather than an
3401   // actual call instruction.
3402   if (IsTailCall) {
3403     MFI.setHasTailCall();
3404     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3405   }
3406 
3407   // Returns a chain and a flag for retval copy to use.
3408   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3409   Chain = Call.getValue(0);
3410   InFlag = Call.getValue(1);
3411 
3412   uint64_t CalleePopBytes = NumBytes;
3413   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3414                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3415                              InFlag, DL);
3416   if (!Ins.empty())
3417     InFlag = Chain.getValue(1);
3418 
3419   // Handle result values, copying them out of physregs into vregs that we
3420   // return.
3421   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3422                          InVals, IsThisReturn,
3423                          IsThisReturn ? OutVals[0] : SDValue());
3424 }
3425 
3426 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3427 // except for applying the wave size scale to the increment amount.
3428 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3429     SDValue Op, SelectionDAG &DAG) const {
3430   const MachineFunction &MF = DAG.getMachineFunction();
3431   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3432 
3433   SDLoc dl(Op);
3434   EVT VT = Op.getValueType();
3435   SDValue Tmp1 = Op;
3436   SDValue Tmp2 = Op.getValue(1);
3437   SDValue Tmp3 = Op.getOperand(2);
3438   SDValue Chain = Tmp1.getOperand(0);
3439 
3440   Register SPReg = Info->getStackPtrOffsetReg();
3441 
3442   // Chain the dynamic stack allocation so that it doesn't modify the stack
3443   // pointer when other instructions are using the stack.
3444   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3445 
3446   SDValue Size  = Tmp2.getOperand(1);
3447   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3448   Chain = SP.getValue(1);
3449   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3450   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3451   const TargetFrameLowering *TFL = ST.getFrameLowering();
3452   unsigned Opc =
3453     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3454     ISD::ADD : ISD::SUB;
3455 
3456   SDValue ScaledSize = DAG.getNode(
3457       ISD::SHL, dl, VT, Size,
3458       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3459 
3460   Align StackAlign = TFL->getStackAlign();
3461   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3462   if (Alignment && *Alignment > StackAlign) {
3463     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3464                        DAG.getConstant(-(uint64_t)Alignment->value()
3465                                            << ST.getWavefrontSizeLog2(),
3466                                        dl, VT));
3467   }
3468 
3469   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3470   Tmp2 = DAG.getCALLSEQ_END(
3471       Chain, DAG.getIntPtrConstant(0, dl, true),
3472       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3473 
3474   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3475 }
3476 
3477 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3478                                                   SelectionDAG &DAG) const {
3479   // We only handle constant sizes here to allow non-entry block, static sized
3480   // allocas. A truly dynamic value is more difficult to support because we
3481   // don't know if the size value is uniform or not. If the size isn't uniform,
3482   // we would need to do a wave reduction to get the maximum size to know how
3483   // much to increment the uniform stack pointer.
3484   SDValue Size = Op.getOperand(1);
3485   if (isa<ConstantSDNode>(Size))
3486       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3487 
3488   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3489 }
3490 
3491 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3492                                              const MachineFunction &MF) const {
3493   Register Reg = StringSwitch<Register>(RegName)
3494     .Case("m0", AMDGPU::M0)
3495     .Case("exec", AMDGPU::EXEC)
3496     .Case("exec_lo", AMDGPU::EXEC_LO)
3497     .Case("exec_hi", AMDGPU::EXEC_HI)
3498     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3499     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3500     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3501     .Default(Register());
3502 
3503   if (Reg == AMDGPU::NoRegister) {
3504     report_fatal_error(Twine("invalid register name \""
3505                              + StringRef(RegName)  + "\"."));
3506 
3507   }
3508 
3509   if (!Subtarget->hasFlatScrRegister() &&
3510        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3511     report_fatal_error(Twine("invalid register \""
3512                              + StringRef(RegName)  + "\" for subtarget."));
3513   }
3514 
3515   switch (Reg) {
3516   case AMDGPU::M0:
3517   case AMDGPU::EXEC_LO:
3518   case AMDGPU::EXEC_HI:
3519   case AMDGPU::FLAT_SCR_LO:
3520   case AMDGPU::FLAT_SCR_HI:
3521     if (VT.getSizeInBits() == 32)
3522       return Reg;
3523     break;
3524   case AMDGPU::EXEC:
3525   case AMDGPU::FLAT_SCR:
3526     if (VT.getSizeInBits() == 64)
3527       return Reg;
3528     break;
3529   default:
3530     llvm_unreachable("missing register type checking");
3531   }
3532 
3533   report_fatal_error(Twine("invalid type for register \""
3534                            + StringRef(RegName) + "\"."));
3535 }
3536 
3537 // If kill is not the last instruction, split the block so kill is always a
3538 // proper terminator.
3539 MachineBasicBlock *
3540 SITargetLowering::splitKillBlock(MachineInstr &MI,
3541                                  MachineBasicBlock *BB) const {
3542   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3543   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3544   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3545   return SplitBB;
3546 }
3547 
3548 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3549 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3550 // be the first instruction in the remainder block.
3551 //
3552 /// \returns { LoopBody, Remainder }
3553 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3554 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3555   MachineFunction *MF = MBB.getParent();
3556   MachineBasicBlock::iterator I(&MI);
3557 
3558   // To insert the loop we need to split the block. Move everything after this
3559   // point to a new block, and insert a new empty block between the two.
3560   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3561   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3562   MachineFunction::iterator MBBI(MBB);
3563   ++MBBI;
3564 
3565   MF->insert(MBBI, LoopBB);
3566   MF->insert(MBBI, RemainderBB);
3567 
3568   LoopBB->addSuccessor(LoopBB);
3569   LoopBB->addSuccessor(RemainderBB);
3570 
3571   // Move the rest of the block into a new block.
3572   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3573 
3574   if (InstInLoop) {
3575     auto Next = std::next(I);
3576 
3577     // Move instruction to loop body.
3578     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3579 
3580     // Move the rest of the block.
3581     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3582   } else {
3583     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3584   }
3585 
3586   MBB.addSuccessor(LoopBB);
3587 
3588   return std::make_pair(LoopBB, RemainderBB);
3589 }
3590 
3591 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3592 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3593   MachineBasicBlock *MBB = MI.getParent();
3594   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3595   auto I = MI.getIterator();
3596   auto E = std::next(I);
3597 
3598   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3599     .addImm(0);
3600 
3601   MIBundleBuilder Bundler(*MBB, I, E);
3602   finalizeBundle(*MBB, Bundler.begin());
3603 }
3604 
3605 MachineBasicBlock *
3606 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3607                                          MachineBasicBlock *BB) const {
3608   const DebugLoc &DL = MI.getDebugLoc();
3609 
3610   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3611 
3612   MachineBasicBlock *LoopBB;
3613   MachineBasicBlock *RemainderBB;
3614   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3615 
3616   // Apparently kill flags are only valid if the def is in the same block?
3617   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3618     Src->setIsKill(false);
3619 
3620   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3621 
3622   MachineBasicBlock::iterator I = LoopBB->end();
3623 
3624   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3625     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3626 
3627   // Clear TRAP_STS.MEM_VIOL
3628   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3629     .addImm(0)
3630     .addImm(EncodedReg);
3631 
3632   bundleInstWithWaitcnt(MI);
3633 
3634   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3635 
3636   // Load and check TRAP_STS.MEM_VIOL
3637   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3638     .addImm(EncodedReg);
3639 
3640   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3641   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3642     .addReg(Reg, RegState::Kill)
3643     .addImm(0);
3644   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3645     .addMBB(LoopBB);
3646 
3647   return RemainderBB;
3648 }
3649 
3650 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3651 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3652 // will only do one iteration. In the worst case, this will loop 64 times.
3653 //
3654 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3655 static MachineBasicBlock::iterator
3656 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3657                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3658                        const DebugLoc &DL, const MachineOperand &Idx,
3659                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3660                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3661                        Register &SGPRIdxReg) {
3662 
3663   MachineFunction *MF = OrigBB.getParent();
3664   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3665   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3666   MachineBasicBlock::iterator I = LoopBB.begin();
3667 
3668   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3669   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3670   Register NewExec = MRI.createVirtualRegister(BoolRC);
3671   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3672   Register CondReg = MRI.createVirtualRegister(BoolRC);
3673 
3674   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3675     .addReg(InitReg)
3676     .addMBB(&OrigBB)
3677     .addReg(ResultReg)
3678     .addMBB(&LoopBB);
3679 
3680   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3681     .addReg(InitSaveExecReg)
3682     .addMBB(&OrigBB)
3683     .addReg(NewExec)
3684     .addMBB(&LoopBB);
3685 
3686   // Read the next variant <- also loop target.
3687   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3688       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3689 
3690   // Compare the just read M0 value to all possible Idx values.
3691   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3692       .addReg(CurrentIdxReg)
3693       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3694 
3695   // Update EXEC, save the original EXEC value to VCC.
3696   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3697                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3698           NewExec)
3699     .addReg(CondReg, RegState::Kill);
3700 
3701   MRI.setSimpleHint(NewExec, CondReg);
3702 
3703   if (UseGPRIdxMode) {
3704     if (Offset == 0) {
3705       SGPRIdxReg = CurrentIdxReg;
3706     } else {
3707       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3708       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3709           .addReg(CurrentIdxReg, RegState::Kill)
3710           .addImm(Offset);
3711     }
3712   } else {
3713     // Move index from VCC into M0
3714     if (Offset == 0) {
3715       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3716         .addReg(CurrentIdxReg, RegState::Kill);
3717     } else {
3718       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3719         .addReg(CurrentIdxReg, RegState::Kill)
3720         .addImm(Offset);
3721     }
3722   }
3723 
3724   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3725   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3726   MachineInstr *InsertPt =
3727     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3728                                                   : AMDGPU::S_XOR_B64_term), Exec)
3729       .addReg(Exec)
3730       .addReg(NewExec);
3731 
3732   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3733   // s_cbranch_scc0?
3734 
3735   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3736   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3737     .addMBB(&LoopBB);
3738 
3739   return InsertPt->getIterator();
3740 }
3741 
3742 // This has slightly sub-optimal regalloc when the source vector is killed by
3743 // the read. The register allocator does not understand that the kill is
3744 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3745 // subregister from it, using 1 more VGPR than necessary. This was saved when
3746 // this was expanded after register allocation.
3747 static MachineBasicBlock::iterator
3748 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3749                unsigned InitResultReg, unsigned PhiReg, int Offset,
3750                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3751   MachineFunction *MF = MBB.getParent();
3752   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3753   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3754   MachineRegisterInfo &MRI = MF->getRegInfo();
3755   const DebugLoc &DL = MI.getDebugLoc();
3756   MachineBasicBlock::iterator I(&MI);
3757 
3758   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3759   Register DstReg = MI.getOperand(0).getReg();
3760   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3761   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3762   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3763   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3764 
3765   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3766 
3767   // Save the EXEC mask
3768   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3769     .addReg(Exec);
3770 
3771   MachineBasicBlock *LoopBB;
3772   MachineBasicBlock *RemainderBB;
3773   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3774 
3775   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3776 
3777   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3778                                       InitResultReg, DstReg, PhiReg, TmpExec,
3779                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3780 
3781   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3782   MachineFunction::iterator MBBI(LoopBB);
3783   ++MBBI;
3784   MF->insert(MBBI, LandingPad);
3785   LoopBB->removeSuccessor(RemainderBB);
3786   LandingPad->addSuccessor(RemainderBB);
3787   LoopBB->addSuccessor(LandingPad);
3788   MachineBasicBlock::iterator First = LandingPad->begin();
3789   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3790     .addReg(SaveExec);
3791 
3792   return InsPt;
3793 }
3794 
3795 // Returns subreg index, offset
3796 static std::pair<unsigned, int>
3797 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3798                             const TargetRegisterClass *SuperRC,
3799                             unsigned VecReg,
3800                             int Offset) {
3801   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3802 
3803   // Skip out of bounds offsets, or else we would end up using an undefined
3804   // register.
3805   if (Offset >= NumElts || Offset < 0)
3806     return std::make_pair(AMDGPU::sub0, Offset);
3807 
3808   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3809 }
3810 
3811 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3812                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3813                                  int Offset) {
3814   MachineBasicBlock *MBB = MI.getParent();
3815   const DebugLoc &DL = MI.getDebugLoc();
3816   MachineBasicBlock::iterator I(&MI);
3817 
3818   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3819 
3820   assert(Idx->getReg() != AMDGPU::NoRegister);
3821 
3822   if (Offset == 0) {
3823     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3824   } else {
3825     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3826         .add(*Idx)
3827         .addImm(Offset);
3828   }
3829 }
3830 
3831 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3832                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3833                                    int Offset) {
3834   MachineBasicBlock *MBB = MI.getParent();
3835   const DebugLoc &DL = MI.getDebugLoc();
3836   MachineBasicBlock::iterator I(&MI);
3837 
3838   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3839 
3840   if (Offset == 0)
3841     return Idx->getReg();
3842 
3843   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3844   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3845       .add(*Idx)
3846       .addImm(Offset);
3847   return Tmp;
3848 }
3849 
3850 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3851                                           MachineBasicBlock &MBB,
3852                                           const GCNSubtarget &ST) {
3853   const SIInstrInfo *TII = ST.getInstrInfo();
3854   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3855   MachineFunction *MF = MBB.getParent();
3856   MachineRegisterInfo &MRI = MF->getRegInfo();
3857 
3858   Register Dst = MI.getOperand(0).getReg();
3859   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3860   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3861   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3862 
3863   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3864   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3865 
3866   unsigned SubReg;
3867   std::tie(SubReg, Offset)
3868     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3869 
3870   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3871 
3872   // Check for a SGPR index.
3873   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3874     MachineBasicBlock::iterator I(&MI);
3875     const DebugLoc &DL = MI.getDebugLoc();
3876 
3877     if (UseGPRIdxMode) {
3878       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3879       // to avoid interfering with other uses, so probably requires a new
3880       // optimization pass.
3881       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3882 
3883       const MCInstrDesc &GPRIDXDesc =
3884           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3885       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3886           .addReg(SrcReg)
3887           .addReg(Idx)
3888           .addImm(SubReg);
3889     } else {
3890       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3891 
3892       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3893         .addReg(SrcReg, 0, SubReg)
3894         .addReg(SrcReg, RegState::Implicit);
3895     }
3896 
3897     MI.eraseFromParent();
3898 
3899     return &MBB;
3900   }
3901 
3902   // Control flow needs to be inserted if indexing with a VGPR.
3903   const DebugLoc &DL = MI.getDebugLoc();
3904   MachineBasicBlock::iterator I(&MI);
3905 
3906   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3907   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3908 
3909   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3910 
3911   Register SGPRIdxReg;
3912   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3913                               UseGPRIdxMode, SGPRIdxReg);
3914 
3915   MachineBasicBlock *LoopBB = InsPt->getParent();
3916 
3917   if (UseGPRIdxMode) {
3918     const MCInstrDesc &GPRIDXDesc =
3919         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3920 
3921     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3922         .addReg(SrcReg)
3923         .addReg(SGPRIdxReg)
3924         .addImm(SubReg);
3925   } else {
3926     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3927       .addReg(SrcReg, 0, SubReg)
3928       .addReg(SrcReg, RegState::Implicit);
3929   }
3930 
3931   MI.eraseFromParent();
3932 
3933   return LoopBB;
3934 }
3935 
3936 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3937                                           MachineBasicBlock &MBB,
3938                                           const GCNSubtarget &ST) {
3939   const SIInstrInfo *TII = ST.getInstrInfo();
3940   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3941   MachineFunction *MF = MBB.getParent();
3942   MachineRegisterInfo &MRI = MF->getRegInfo();
3943 
3944   Register Dst = MI.getOperand(0).getReg();
3945   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3946   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3947   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3948   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3949   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3950   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3951 
3952   // This can be an immediate, but will be folded later.
3953   assert(Val->getReg());
3954 
3955   unsigned SubReg;
3956   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3957                                                          SrcVec->getReg(),
3958                                                          Offset);
3959   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3960 
3961   if (Idx->getReg() == AMDGPU::NoRegister) {
3962     MachineBasicBlock::iterator I(&MI);
3963     const DebugLoc &DL = MI.getDebugLoc();
3964 
3965     assert(Offset == 0);
3966 
3967     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3968         .add(*SrcVec)
3969         .add(*Val)
3970         .addImm(SubReg);
3971 
3972     MI.eraseFromParent();
3973     return &MBB;
3974   }
3975 
3976   // Check for a SGPR index.
3977   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3978     MachineBasicBlock::iterator I(&MI);
3979     const DebugLoc &DL = MI.getDebugLoc();
3980 
3981     if (UseGPRIdxMode) {
3982       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3983 
3984       const MCInstrDesc &GPRIDXDesc =
3985           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3986       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3987           .addReg(SrcVec->getReg())
3988           .add(*Val)
3989           .addReg(Idx)
3990           .addImm(SubReg);
3991     } else {
3992       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3993 
3994       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3995           TRI.getRegSizeInBits(*VecRC), 32, false);
3996       BuildMI(MBB, I, DL, MovRelDesc, Dst)
3997           .addReg(SrcVec->getReg())
3998           .add(*Val)
3999           .addImm(SubReg);
4000     }
4001     MI.eraseFromParent();
4002     return &MBB;
4003   }
4004 
4005   // Control flow needs to be inserted if indexing with a VGPR.
4006   if (Val->isReg())
4007     MRI.clearKillFlags(Val->getReg());
4008 
4009   const DebugLoc &DL = MI.getDebugLoc();
4010 
4011   Register PhiReg = MRI.createVirtualRegister(VecRC);
4012 
4013   Register SGPRIdxReg;
4014   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
4015                               UseGPRIdxMode, SGPRIdxReg);
4016   MachineBasicBlock *LoopBB = InsPt->getParent();
4017 
4018   if (UseGPRIdxMode) {
4019     const MCInstrDesc &GPRIDXDesc =
4020         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
4021 
4022     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
4023         .addReg(PhiReg)
4024         .add(*Val)
4025         .addReg(SGPRIdxReg)
4026         .addImm(AMDGPU::sub0);
4027   } else {
4028     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
4029         TRI.getRegSizeInBits(*VecRC), 32, false);
4030     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
4031         .addReg(PhiReg)
4032         .add(*Val)
4033         .addImm(AMDGPU::sub0);
4034   }
4035 
4036   MI.eraseFromParent();
4037   return LoopBB;
4038 }
4039 
4040 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
4041   MachineInstr &MI, MachineBasicBlock *BB) const {
4042 
4043   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4044   MachineFunction *MF = BB->getParent();
4045   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
4046 
4047   switch (MI.getOpcode()) {
4048   case AMDGPU::S_UADDO_PSEUDO:
4049   case AMDGPU::S_USUBO_PSEUDO: {
4050     const DebugLoc &DL = MI.getDebugLoc();
4051     MachineOperand &Dest0 = MI.getOperand(0);
4052     MachineOperand &Dest1 = MI.getOperand(1);
4053     MachineOperand &Src0 = MI.getOperand(2);
4054     MachineOperand &Src1 = MI.getOperand(3);
4055 
4056     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
4057                        ? AMDGPU::S_ADD_I32
4058                        : AMDGPU::S_SUB_I32;
4059     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
4060 
4061     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
4062         .addImm(1)
4063         .addImm(0);
4064 
4065     MI.eraseFromParent();
4066     return BB;
4067   }
4068   case AMDGPU::S_ADD_U64_PSEUDO:
4069   case AMDGPU::S_SUB_U64_PSEUDO: {
4070     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4071     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4072     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4073     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
4074     const DebugLoc &DL = MI.getDebugLoc();
4075 
4076     MachineOperand &Dest = MI.getOperand(0);
4077     MachineOperand &Src0 = MI.getOperand(1);
4078     MachineOperand &Src1 = MI.getOperand(2);
4079 
4080     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4081     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4082 
4083     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
4084         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4085     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
4086         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4087 
4088     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
4089         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4090     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
4091         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4092 
4093     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
4094 
4095     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
4096     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
4097     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
4098     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
4099     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4100         .addReg(DestSub0)
4101         .addImm(AMDGPU::sub0)
4102         .addReg(DestSub1)
4103         .addImm(AMDGPU::sub1);
4104     MI.eraseFromParent();
4105     return BB;
4106   }
4107   case AMDGPU::V_ADD_U64_PSEUDO:
4108   case AMDGPU::V_SUB_U64_PSEUDO: {
4109     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4110     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4111     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4112     const DebugLoc &DL = MI.getDebugLoc();
4113 
4114     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
4115 
4116     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4117 
4118     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4119     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4120 
4121     Register CarryReg = MRI.createVirtualRegister(CarryRC);
4122     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
4123 
4124     MachineOperand &Dest = MI.getOperand(0);
4125     MachineOperand &Src0 = MI.getOperand(1);
4126     MachineOperand &Src1 = MI.getOperand(2);
4127 
4128     const TargetRegisterClass *Src0RC = Src0.isReg()
4129                                             ? MRI.getRegClass(Src0.getReg())
4130                                             : &AMDGPU::VReg_64RegClass;
4131     const TargetRegisterClass *Src1RC = Src1.isReg()
4132                                             ? MRI.getRegClass(Src1.getReg())
4133                                             : &AMDGPU::VReg_64RegClass;
4134 
4135     const TargetRegisterClass *Src0SubRC =
4136         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
4137     const TargetRegisterClass *Src1SubRC =
4138         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
4139 
4140     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
4141         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
4142     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
4143         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
4144 
4145     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
4146         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
4147     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
4148         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
4149 
4150     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
4151     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
4152                                .addReg(CarryReg, RegState::Define)
4153                                .add(SrcReg0Sub0)
4154                                .add(SrcReg1Sub0)
4155                                .addImm(0); // clamp bit
4156 
4157     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
4158     MachineInstr *HiHalf =
4159         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4160             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4161             .add(SrcReg0Sub1)
4162             .add(SrcReg1Sub1)
4163             .addReg(CarryReg, RegState::Kill)
4164             .addImm(0); // clamp bit
4165 
4166     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4167         .addReg(DestSub0)
4168         .addImm(AMDGPU::sub0)
4169         .addReg(DestSub1)
4170         .addImm(AMDGPU::sub1);
4171     TII->legalizeOperands(*LoHalf);
4172     TII->legalizeOperands(*HiHalf);
4173     MI.eraseFromParent();
4174     return BB;
4175   }
4176   case AMDGPU::S_ADD_CO_PSEUDO:
4177   case AMDGPU::S_SUB_CO_PSEUDO: {
4178     // This pseudo has a chance to be selected
4179     // only from uniform add/subcarry node. All the VGPR operands
4180     // therefore assumed to be splat vectors.
4181     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4182     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4183     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4184     MachineBasicBlock::iterator MII = MI;
4185     const DebugLoc &DL = MI.getDebugLoc();
4186     MachineOperand &Dest = MI.getOperand(0);
4187     MachineOperand &CarryDest = MI.getOperand(1);
4188     MachineOperand &Src0 = MI.getOperand(2);
4189     MachineOperand &Src1 = MI.getOperand(3);
4190     MachineOperand &Src2 = MI.getOperand(4);
4191     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4192                        ? AMDGPU::S_ADDC_U32
4193                        : AMDGPU::S_SUBB_U32;
4194     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4195       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4196       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4197           .addReg(Src0.getReg());
4198       Src0.setReg(RegOp0);
4199     }
4200     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4201       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4202       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4203           .addReg(Src1.getReg());
4204       Src1.setReg(RegOp1);
4205     }
4206     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4207     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4208       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4209           .addReg(Src2.getReg());
4210       Src2.setReg(RegOp2);
4211     }
4212 
4213     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4214     unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC);
4215     assert(WaveSize == 64 || WaveSize == 32);
4216 
4217     if (WaveSize == 64) {
4218       if (ST.hasScalarCompareEq64()) {
4219         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4220             .addReg(Src2.getReg())
4221             .addImm(0);
4222       } else {
4223         const TargetRegisterClass *SubRC =
4224             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4225         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4226             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4227         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4228             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4229         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4230 
4231         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4232             .add(Src2Sub0)
4233             .add(Src2Sub1);
4234 
4235         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4236             .addReg(Src2_32, RegState::Kill)
4237             .addImm(0);
4238       }
4239     } else {
4240       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4241           .addReg(Src2.getReg())
4242           .addImm(0);
4243     }
4244 
4245     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4246 
4247     unsigned SelOpc =
4248         (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
4249 
4250     BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg())
4251         .addImm(-1)
4252         .addImm(0);
4253 
4254     MI.eraseFromParent();
4255     return BB;
4256   }
4257   case AMDGPU::SI_INIT_M0: {
4258     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4259             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4260         .add(MI.getOperand(0));
4261     MI.eraseFromParent();
4262     return BB;
4263   }
4264   case AMDGPU::GET_GROUPSTATICSIZE: {
4265     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4266            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4267     DebugLoc DL = MI.getDebugLoc();
4268     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4269         .add(MI.getOperand(0))
4270         .addImm(MFI->getLDSSize());
4271     MI.eraseFromParent();
4272     return BB;
4273   }
4274   case AMDGPU::SI_INDIRECT_SRC_V1:
4275   case AMDGPU::SI_INDIRECT_SRC_V2:
4276   case AMDGPU::SI_INDIRECT_SRC_V4:
4277   case AMDGPU::SI_INDIRECT_SRC_V8:
4278   case AMDGPU::SI_INDIRECT_SRC_V16:
4279   case AMDGPU::SI_INDIRECT_SRC_V32:
4280     return emitIndirectSrc(MI, *BB, *getSubtarget());
4281   case AMDGPU::SI_INDIRECT_DST_V1:
4282   case AMDGPU::SI_INDIRECT_DST_V2:
4283   case AMDGPU::SI_INDIRECT_DST_V4:
4284   case AMDGPU::SI_INDIRECT_DST_V8:
4285   case AMDGPU::SI_INDIRECT_DST_V16:
4286   case AMDGPU::SI_INDIRECT_DST_V32:
4287     return emitIndirectDst(MI, *BB, *getSubtarget());
4288   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4289   case AMDGPU::SI_KILL_I1_PSEUDO:
4290     return splitKillBlock(MI, BB);
4291   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4292     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4293     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4294     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4295 
4296     Register Dst = MI.getOperand(0).getReg();
4297     Register Src0 = MI.getOperand(1).getReg();
4298     Register Src1 = MI.getOperand(2).getReg();
4299     const DebugLoc &DL = MI.getDebugLoc();
4300     Register SrcCond = MI.getOperand(3).getReg();
4301 
4302     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4303     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4304     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4305     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4306 
4307     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4308       .addReg(SrcCond);
4309     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4310       .addImm(0)
4311       .addReg(Src0, 0, AMDGPU::sub0)
4312       .addImm(0)
4313       .addReg(Src1, 0, AMDGPU::sub0)
4314       .addReg(SrcCondCopy);
4315     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4316       .addImm(0)
4317       .addReg(Src0, 0, AMDGPU::sub1)
4318       .addImm(0)
4319       .addReg(Src1, 0, AMDGPU::sub1)
4320       .addReg(SrcCondCopy);
4321 
4322     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4323       .addReg(DstLo)
4324       .addImm(AMDGPU::sub0)
4325       .addReg(DstHi)
4326       .addImm(AMDGPU::sub1);
4327     MI.eraseFromParent();
4328     return BB;
4329   }
4330   case AMDGPU::SI_BR_UNDEF: {
4331     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4332     const DebugLoc &DL = MI.getDebugLoc();
4333     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4334                            .add(MI.getOperand(0));
4335     Br->getOperand(1).setIsUndef(true); // read undef SCC
4336     MI.eraseFromParent();
4337     return BB;
4338   }
4339   case AMDGPU::ADJCALLSTACKUP:
4340   case AMDGPU::ADJCALLSTACKDOWN: {
4341     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4342     MachineInstrBuilder MIB(*MF, &MI);
4343     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4344        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4345     return BB;
4346   }
4347   case AMDGPU::SI_CALL_ISEL: {
4348     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4349     const DebugLoc &DL = MI.getDebugLoc();
4350 
4351     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4352 
4353     MachineInstrBuilder MIB;
4354     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4355 
4356     for (const MachineOperand &MO : MI.operands())
4357       MIB.add(MO);
4358 
4359     MIB.cloneMemRefs(MI);
4360     MI.eraseFromParent();
4361     return BB;
4362   }
4363   case AMDGPU::V_ADD_CO_U32_e32:
4364   case AMDGPU::V_SUB_CO_U32_e32:
4365   case AMDGPU::V_SUBREV_CO_U32_e32: {
4366     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4367     const DebugLoc &DL = MI.getDebugLoc();
4368     unsigned Opc = MI.getOpcode();
4369 
4370     bool NeedClampOperand = false;
4371     if (TII->pseudoToMCOpcode(Opc) == -1) {
4372       Opc = AMDGPU::getVOPe64(Opc);
4373       NeedClampOperand = true;
4374     }
4375 
4376     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4377     if (TII->isVOP3(*I)) {
4378       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4379       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4380       I.addReg(TRI->getVCC(), RegState::Define);
4381     }
4382     I.add(MI.getOperand(1))
4383      .add(MI.getOperand(2));
4384     if (NeedClampOperand)
4385       I.addImm(0); // clamp bit for e64 encoding
4386 
4387     TII->legalizeOperands(*I);
4388 
4389     MI.eraseFromParent();
4390     return BB;
4391   }
4392   case AMDGPU::V_ADDC_U32_e32:
4393   case AMDGPU::V_SUBB_U32_e32:
4394   case AMDGPU::V_SUBBREV_U32_e32:
4395     // These instructions have an implicit use of vcc which counts towards the
4396     // constant bus limit.
4397     TII->legalizeOperands(MI);
4398     return BB;
4399   case AMDGPU::DS_GWS_INIT:
4400   case AMDGPU::DS_GWS_SEMA_BR:
4401   case AMDGPU::DS_GWS_BARRIER:
4402     if (Subtarget->needsAlignedVGPRs()) {
4403       // Add implicit aligned super-reg to force alignment on the data operand.
4404       const DebugLoc &DL = MI.getDebugLoc();
4405       MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4406       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
4407       MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0);
4408       Register DataReg = Op->getReg();
4409       bool IsAGPR = TRI->isAGPR(MRI, DataReg);
4410       Register Undef = MRI.createVirtualRegister(
4411           IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass);
4412       BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef);
4413       Register NewVR =
4414           MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass
4415                                            : &AMDGPU::VReg_64_Align2RegClass);
4416       BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR)
4417           .addReg(DataReg, 0, Op->getSubReg())
4418           .addImm(AMDGPU::sub0)
4419           .addReg(Undef)
4420           .addImm(AMDGPU::sub1);
4421       Op->setReg(NewVR);
4422       Op->setSubReg(AMDGPU::sub0);
4423       MI.addOperand(MachineOperand::CreateReg(NewVR, false, true));
4424     }
4425     LLVM_FALLTHROUGH;
4426   case AMDGPU::DS_GWS_SEMA_V:
4427   case AMDGPU::DS_GWS_SEMA_P:
4428   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4429     // A s_waitcnt 0 is required to be the instruction immediately following.
4430     if (getSubtarget()->hasGWSAutoReplay()) {
4431       bundleInstWithWaitcnt(MI);
4432       return BB;
4433     }
4434 
4435     return emitGWSMemViolTestLoop(MI, BB);
4436   case AMDGPU::S_SETREG_B32: {
4437     // Try to optimize cases that only set the denormal mode or rounding mode.
4438     //
4439     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4440     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4441     // instead.
4442     //
4443     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4444     // allow you to have a no side effect instruction in the output of a
4445     // sideeffecting pattern.
4446     unsigned ID, Offset, Width;
4447     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4448     if (ID != AMDGPU::Hwreg::ID_MODE)
4449       return BB;
4450 
4451     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4452     const unsigned SetMask = WidthMask << Offset;
4453 
4454     if (getSubtarget()->hasDenormModeInst()) {
4455       unsigned SetDenormOp = 0;
4456       unsigned SetRoundOp = 0;
4457 
4458       // The dedicated instructions can only set the whole denorm or round mode
4459       // at once, not a subset of bits in either.
4460       if (SetMask ==
4461           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4462         // If this fully sets both the round and denorm mode, emit the two
4463         // dedicated instructions for these.
4464         SetRoundOp = AMDGPU::S_ROUND_MODE;
4465         SetDenormOp = AMDGPU::S_DENORM_MODE;
4466       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4467         SetRoundOp = AMDGPU::S_ROUND_MODE;
4468       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4469         SetDenormOp = AMDGPU::S_DENORM_MODE;
4470       }
4471 
4472       if (SetRoundOp || SetDenormOp) {
4473         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4474         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4475         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4476           unsigned ImmVal = Def->getOperand(1).getImm();
4477           if (SetRoundOp) {
4478             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4479                 .addImm(ImmVal & 0xf);
4480 
4481             // If we also have the denorm mode, get just the denorm mode bits.
4482             ImmVal >>= 4;
4483           }
4484 
4485           if (SetDenormOp) {
4486             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4487                 .addImm(ImmVal & 0xf);
4488           }
4489 
4490           MI.eraseFromParent();
4491           return BB;
4492         }
4493       }
4494     }
4495 
4496     // If only FP bits are touched, used the no side effects pseudo.
4497     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4498                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4499       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4500 
4501     return BB;
4502   }
4503   default:
4504     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4505   }
4506 }
4507 
4508 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4509   return isTypeLegal(VT.getScalarType());
4510 }
4511 
4512 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4513   // This currently forces unfolding various combinations of fsub into fma with
4514   // free fneg'd operands. As long as we have fast FMA (controlled by
4515   // isFMAFasterThanFMulAndFAdd), we should perform these.
4516 
4517   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4518   // most of these combines appear to be cycle neutral but save on instruction
4519   // count / code size.
4520   return true;
4521 }
4522 
4523 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; }
4524 
4525 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4526                                          EVT VT) const {
4527   if (!VT.isVector()) {
4528     return MVT::i1;
4529   }
4530   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4531 }
4532 
4533 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4534   // TODO: Should i16 be used always if legal? For now it would force VALU
4535   // shifts.
4536   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4537 }
4538 
4539 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4540   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4541              ? Ty.changeElementSize(16)
4542              : Ty.changeElementSize(32);
4543 }
4544 
4545 // Answering this is somewhat tricky and depends on the specific device which
4546 // have different rates for fma or all f64 operations.
4547 //
4548 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4549 // regardless of which device (although the number of cycles differs between
4550 // devices), so it is always profitable for f64.
4551 //
4552 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4553 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4554 // which we can always do even without fused FP ops since it returns the same
4555 // result as the separate operations and since it is always full
4556 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4557 // however does not support denormals, so we do report fma as faster if we have
4558 // a fast fma device and require denormals.
4559 //
4560 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4561                                                   EVT VT) const {
4562   VT = VT.getScalarType();
4563 
4564   switch (VT.getSimpleVT().SimpleTy) {
4565   case MVT::f32: {
4566     // If mad is not available this depends only on if f32 fma is full rate.
4567     if (!Subtarget->hasMadMacF32Insts())
4568       return Subtarget->hasFastFMAF32();
4569 
4570     // Otherwise f32 mad is always full rate and returns the same result as
4571     // the separate operations so should be preferred over fma.
4572     // However does not support denormals.
4573     if (hasFP32Denormals(MF))
4574       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4575 
4576     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4577     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4578   }
4579   case MVT::f64:
4580     return true;
4581   case MVT::f16:
4582     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4583   default:
4584     break;
4585   }
4586 
4587   return false;
4588 }
4589 
4590 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4591                                                   LLT Ty) const {
4592   switch (Ty.getScalarSizeInBits()) {
4593   case 16:
4594     return isFMAFasterThanFMulAndFAdd(MF, MVT::f16);
4595   case 32:
4596     return isFMAFasterThanFMulAndFAdd(MF, MVT::f32);
4597   case 64:
4598     return isFMAFasterThanFMulAndFAdd(MF, MVT::f64);
4599   default:
4600     break;
4601   }
4602 
4603   return false;
4604 }
4605 
4606 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const {
4607   if (!Ty.isScalar())
4608     return false;
4609 
4610   if (Ty.getScalarSizeInBits() == 16)
4611     return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF());
4612   if (Ty.getScalarSizeInBits() == 32)
4613     return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF());
4614 
4615   return false;
4616 }
4617 
4618 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4619                                    const SDNode *N) const {
4620   // TODO: Check future ftz flag
4621   // v_mad_f32/v_mac_f32 do not support denormals.
4622   EVT VT = N->getValueType(0);
4623   if (VT == MVT::f32)
4624     return Subtarget->hasMadMacF32Insts() &&
4625            !hasFP32Denormals(DAG.getMachineFunction());
4626   if (VT == MVT::f16) {
4627     return Subtarget->hasMadF16() &&
4628            !hasFP64FP16Denormals(DAG.getMachineFunction());
4629   }
4630 
4631   return false;
4632 }
4633 
4634 //===----------------------------------------------------------------------===//
4635 // Custom DAG Lowering Operations
4636 //===----------------------------------------------------------------------===//
4637 
4638 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4639 // wider vector type is legal.
4640 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4641                                              SelectionDAG &DAG) const {
4642   unsigned Opc = Op.getOpcode();
4643   EVT VT = Op.getValueType();
4644   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4645 
4646   SDValue Lo, Hi;
4647   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4648 
4649   SDLoc SL(Op);
4650   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4651                              Op->getFlags());
4652   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4653                              Op->getFlags());
4654 
4655   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4656 }
4657 
4658 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4659 // wider vector type is legal.
4660 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4661                                               SelectionDAG &DAG) const {
4662   unsigned Opc = Op.getOpcode();
4663   EVT VT = Op.getValueType();
4664   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4665          VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8f32 ||
4666          VT == MVT::v16f32 || VT == MVT::v32f32);
4667 
4668   SDValue Lo0, Hi0;
4669   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4670   SDValue Lo1, Hi1;
4671   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4672 
4673   SDLoc SL(Op);
4674 
4675   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4676                              Op->getFlags());
4677   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4678                              Op->getFlags());
4679 
4680   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4681 }
4682 
4683 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4684                                               SelectionDAG &DAG) const {
4685   unsigned Opc = Op.getOpcode();
4686   EVT VT = Op.getValueType();
4687   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 ||
4688          VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v8f32 ||
4689          VT == MVT::v16f32 || VT == MVT::v32f32);
4690 
4691   SDValue Lo0, Hi0;
4692   SDValue Op0 = Op.getOperand(0);
4693   std::tie(Lo0, Hi0) = Op0.getValueType().isVector()
4694                          ? DAG.SplitVectorOperand(Op.getNode(), 0)
4695                          : std::make_pair(Op0, Op0);
4696   SDValue Lo1, Hi1;
4697   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4698   SDValue Lo2, Hi2;
4699   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4700 
4701   SDLoc SL(Op);
4702   auto ResVT = DAG.GetSplitDestVTs(VT);
4703 
4704   SDValue OpLo = DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2,
4705                              Op->getFlags());
4706   SDValue OpHi = DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2,
4707                              Op->getFlags());
4708 
4709   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4710 }
4711 
4712 
4713 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4714   switch (Op.getOpcode()) {
4715   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4716   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4717   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4718   case ISD::LOAD: {
4719     SDValue Result = LowerLOAD(Op, DAG);
4720     assert((!Result.getNode() ||
4721             Result.getNode()->getNumValues() == 2) &&
4722            "Load should return a value and a chain");
4723     return Result;
4724   }
4725 
4726   case ISD::FSIN:
4727   case ISD::FCOS:
4728     return LowerTrig(Op, DAG);
4729   case ISD::SELECT: return LowerSELECT(Op, DAG);
4730   case ISD::FDIV: return LowerFDIV(Op, DAG);
4731   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4732   case ISD::STORE: return LowerSTORE(Op, DAG);
4733   case ISD::GlobalAddress: {
4734     MachineFunction &MF = DAG.getMachineFunction();
4735     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4736     return LowerGlobalAddress(MFI, Op, DAG);
4737   }
4738   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4739   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4740   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4741   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4742   case ISD::INSERT_SUBVECTOR:
4743     return lowerINSERT_SUBVECTOR(Op, DAG);
4744   case ISD::INSERT_VECTOR_ELT:
4745     return lowerINSERT_VECTOR_ELT(Op, DAG);
4746   case ISD::EXTRACT_VECTOR_ELT:
4747     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4748   case ISD::VECTOR_SHUFFLE:
4749     return lowerVECTOR_SHUFFLE(Op, DAG);
4750   case ISD::BUILD_VECTOR:
4751     return lowerBUILD_VECTOR(Op, DAG);
4752   case ISD::FP_ROUND:
4753     return lowerFP_ROUND(Op, DAG);
4754   case ISD::FPTRUNC_ROUND: {
4755     unsigned Opc;
4756     SDLoc DL(Op);
4757 
4758     if (Op.getOperand(0)->getValueType(0) != MVT::f32)
4759       return SDValue();
4760 
4761     // Get the rounding mode from the last operand
4762     int RoundMode = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4763     if (RoundMode == (int)RoundingMode::TowardPositive)
4764       Opc = AMDGPUISD::FPTRUNC_ROUND_UPWARD;
4765     else if (RoundMode == (int)RoundingMode::TowardNegative)
4766       Opc = AMDGPUISD::FPTRUNC_ROUND_DOWNWARD;
4767     else
4768       return SDValue();
4769 
4770     return DAG.getNode(Opc, DL, Op.getNode()->getVTList(), Op->getOperand(0));
4771   }
4772   case ISD::TRAP:
4773     return lowerTRAP(Op, DAG);
4774   case ISD::DEBUGTRAP:
4775     return lowerDEBUGTRAP(Op, DAG);
4776   case ISD::FABS:
4777   case ISD::FNEG:
4778   case ISD::FCANONICALIZE:
4779   case ISD::BSWAP:
4780     return splitUnaryVectorOp(Op, DAG);
4781   case ISD::FMINNUM:
4782   case ISD::FMAXNUM:
4783     return lowerFMINNUM_FMAXNUM(Op, DAG);
4784   case ISD::FMA:
4785     return splitTernaryVectorOp(Op, DAG);
4786   case ISD::FP_TO_SINT:
4787   case ISD::FP_TO_UINT:
4788     return LowerFP_TO_INT(Op, DAG);
4789   case ISD::SHL:
4790   case ISD::SRA:
4791   case ISD::SRL:
4792   case ISD::ADD:
4793   case ISD::SUB:
4794   case ISD::MUL:
4795   case ISD::SMIN:
4796   case ISD::SMAX:
4797   case ISD::UMIN:
4798   case ISD::UMAX:
4799   case ISD::FADD:
4800   case ISD::FMUL:
4801   case ISD::FMINNUM_IEEE:
4802   case ISD::FMAXNUM_IEEE:
4803   case ISD::UADDSAT:
4804   case ISD::USUBSAT:
4805   case ISD::SADDSAT:
4806   case ISD::SSUBSAT:
4807     return splitBinaryVectorOp(Op, DAG);
4808   case ISD::SMULO:
4809   case ISD::UMULO:
4810     return lowerXMULO(Op, DAG);
4811   case ISD::SMUL_LOHI:
4812   case ISD::UMUL_LOHI:
4813     return lowerXMUL_LOHI(Op, DAG);
4814   case ISD::DYNAMIC_STACKALLOC:
4815     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4816   }
4817   return SDValue();
4818 }
4819 
4820 // Used for D16: Casts the result of an instruction into the right vector,
4821 // packs values if loads return unpacked values.
4822 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4823                                        const SDLoc &DL,
4824                                        SelectionDAG &DAG, bool Unpacked) {
4825   if (!LoadVT.isVector())
4826     return Result;
4827 
4828   // Cast back to the original packed type or to a larger type that is a
4829   // multiple of 32 bit for D16. Widening the return type is a required for
4830   // legalization.
4831   EVT FittingLoadVT = LoadVT;
4832   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4833     FittingLoadVT =
4834         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4835                          LoadVT.getVectorNumElements() + 1);
4836   }
4837 
4838   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4839     // Truncate to v2i16/v4i16.
4840     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4841 
4842     // Workaround legalizer not scalarizing truncate after vector op
4843     // legalization but not creating intermediate vector trunc.
4844     SmallVector<SDValue, 4> Elts;
4845     DAG.ExtractVectorElements(Result, Elts);
4846     for (SDValue &Elt : Elts)
4847       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4848 
4849     // Pad illegal v1i16/v3fi6 to v4i16
4850     if ((LoadVT.getVectorNumElements() % 2) == 1)
4851       Elts.push_back(DAG.getUNDEF(MVT::i16));
4852 
4853     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4854 
4855     // Bitcast to original type (v2f16/v4f16).
4856     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4857   }
4858 
4859   // Cast back to the original packed type.
4860   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4861 }
4862 
4863 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4864                                               MemSDNode *M,
4865                                               SelectionDAG &DAG,
4866                                               ArrayRef<SDValue> Ops,
4867                                               bool IsIntrinsic) const {
4868   SDLoc DL(M);
4869 
4870   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4871   EVT LoadVT = M->getValueType(0);
4872 
4873   EVT EquivLoadVT = LoadVT;
4874   if (LoadVT.isVector()) {
4875     if (Unpacked) {
4876       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4877                                      LoadVT.getVectorNumElements());
4878     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4879       // Widen v3f16 to legal type
4880       EquivLoadVT =
4881           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4882                            LoadVT.getVectorNumElements() + 1);
4883     }
4884   }
4885 
4886   // Change from v4f16/v2f16 to EquivLoadVT.
4887   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4888 
4889   SDValue Load
4890     = DAG.getMemIntrinsicNode(
4891       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4892       VTList, Ops, M->getMemoryVT(),
4893       M->getMemOperand());
4894 
4895   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4896 
4897   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4898 }
4899 
4900 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4901                                              SelectionDAG &DAG,
4902                                              ArrayRef<SDValue> Ops) const {
4903   SDLoc DL(M);
4904   EVT LoadVT = M->getValueType(0);
4905   EVT EltType = LoadVT.getScalarType();
4906   EVT IntVT = LoadVT.changeTypeToInteger();
4907 
4908   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4909 
4910   unsigned Opc =
4911       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4912 
4913   if (IsD16) {
4914     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4915   }
4916 
4917   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4918   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4919     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4920 
4921   if (isTypeLegal(LoadVT)) {
4922     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4923                                M->getMemOperand(), DAG);
4924   }
4925 
4926   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4927   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4928   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4929                                         M->getMemOperand(), DAG);
4930   return DAG.getMergeValues(
4931       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4932       DL);
4933 }
4934 
4935 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4936                                   SDNode *N, SelectionDAG &DAG) {
4937   EVT VT = N->getValueType(0);
4938   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4939   unsigned CondCode = CD->getZExtValue();
4940   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4941     return DAG.getUNDEF(VT);
4942 
4943   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4944 
4945   SDValue LHS = N->getOperand(1);
4946   SDValue RHS = N->getOperand(2);
4947 
4948   SDLoc DL(N);
4949 
4950   EVT CmpVT = LHS.getValueType();
4951   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4952     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4953       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4954     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4955     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4956   }
4957 
4958   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4959 
4960   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4961   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4962 
4963   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4964                               DAG.getCondCode(CCOpcode));
4965   if (VT.bitsEq(CCVT))
4966     return SetCC;
4967   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4968 }
4969 
4970 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4971                                   SDNode *N, SelectionDAG &DAG) {
4972   EVT VT = N->getValueType(0);
4973   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4974 
4975   unsigned CondCode = CD->getZExtValue();
4976   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4977     return DAG.getUNDEF(VT);
4978 
4979   SDValue Src0 = N->getOperand(1);
4980   SDValue Src1 = N->getOperand(2);
4981   EVT CmpVT = Src0.getValueType();
4982   SDLoc SL(N);
4983 
4984   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4985     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4986     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4987   }
4988 
4989   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4990   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4991   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4992   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4993   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4994                               Src1, DAG.getCondCode(CCOpcode));
4995   if (VT.bitsEq(CCVT))
4996     return SetCC;
4997   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4998 }
4999 
5000 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
5001                                     SelectionDAG &DAG) {
5002   EVT VT = N->getValueType(0);
5003   SDValue Src = N->getOperand(1);
5004   SDLoc SL(N);
5005 
5006   if (Src.getOpcode() == ISD::SETCC) {
5007     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
5008     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
5009                        Src.getOperand(1), Src.getOperand(2));
5010   }
5011   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
5012     // (ballot 0) -> 0
5013     if (Arg->isZero())
5014       return DAG.getConstant(0, SL, VT);
5015 
5016     // (ballot 1) -> EXEC/EXEC_LO
5017     if (Arg->isOne()) {
5018       Register Exec;
5019       if (VT.getScalarSizeInBits() == 32)
5020         Exec = AMDGPU::EXEC_LO;
5021       else if (VT.getScalarSizeInBits() == 64)
5022         Exec = AMDGPU::EXEC;
5023       else
5024         return SDValue();
5025 
5026       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
5027     }
5028   }
5029 
5030   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
5031   // ISD::SETNE)
5032   return DAG.getNode(
5033       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
5034       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
5035 }
5036 
5037 void SITargetLowering::ReplaceNodeResults(SDNode *N,
5038                                           SmallVectorImpl<SDValue> &Results,
5039                                           SelectionDAG &DAG) const {
5040   switch (N->getOpcode()) {
5041   case ISD::INSERT_VECTOR_ELT: {
5042     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
5043       Results.push_back(Res);
5044     return;
5045   }
5046   case ISD::EXTRACT_VECTOR_ELT: {
5047     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
5048       Results.push_back(Res);
5049     return;
5050   }
5051   case ISD::INTRINSIC_WO_CHAIN: {
5052     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5053     switch (IID) {
5054     case Intrinsic::amdgcn_cvt_pkrtz: {
5055       SDValue Src0 = N->getOperand(1);
5056       SDValue Src1 = N->getOperand(2);
5057       SDLoc SL(N);
5058       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
5059                                 Src0, Src1);
5060       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
5061       return;
5062     }
5063     case Intrinsic::amdgcn_cvt_pknorm_i16:
5064     case Intrinsic::amdgcn_cvt_pknorm_u16:
5065     case Intrinsic::amdgcn_cvt_pk_i16:
5066     case Intrinsic::amdgcn_cvt_pk_u16: {
5067       SDValue Src0 = N->getOperand(1);
5068       SDValue Src1 = N->getOperand(2);
5069       SDLoc SL(N);
5070       unsigned Opcode;
5071 
5072       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
5073         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
5074       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
5075         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
5076       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
5077         Opcode = AMDGPUISD::CVT_PK_I16_I32;
5078       else
5079         Opcode = AMDGPUISD::CVT_PK_U16_U32;
5080 
5081       EVT VT = N->getValueType(0);
5082       if (isTypeLegal(VT))
5083         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
5084       else {
5085         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
5086         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
5087       }
5088       return;
5089     }
5090     }
5091     break;
5092   }
5093   case ISD::INTRINSIC_W_CHAIN: {
5094     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
5095       if (Res.getOpcode() == ISD::MERGE_VALUES) {
5096         // FIXME: Hacky
5097         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
5098           Results.push_back(Res.getOperand(I));
5099         }
5100       } else {
5101         Results.push_back(Res);
5102         Results.push_back(Res.getValue(1));
5103       }
5104       return;
5105     }
5106 
5107     break;
5108   }
5109   case ISD::SELECT: {
5110     SDLoc SL(N);
5111     EVT VT = N->getValueType(0);
5112     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
5113     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
5114     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
5115 
5116     EVT SelectVT = NewVT;
5117     if (NewVT.bitsLT(MVT::i32)) {
5118       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
5119       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
5120       SelectVT = MVT::i32;
5121     }
5122 
5123     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
5124                                     N->getOperand(0), LHS, RHS);
5125 
5126     if (NewVT != SelectVT)
5127       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
5128     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
5129     return;
5130   }
5131   case ISD::FNEG: {
5132     if (N->getValueType(0) != MVT::v2f16)
5133       break;
5134 
5135     SDLoc SL(N);
5136     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5137 
5138     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
5139                              BC,
5140                              DAG.getConstant(0x80008000, SL, MVT::i32));
5141     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5142     return;
5143   }
5144   case ISD::FABS: {
5145     if (N->getValueType(0) != MVT::v2f16)
5146       break;
5147 
5148     SDLoc SL(N);
5149     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5150 
5151     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
5152                              BC,
5153                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
5154     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5155     return;
5156   }
5157   default:
5158     break;
5159   }
5160 }
5161 
5162 /// Helper function for LowerBRCOND
5163 static SDNode *findUser(SDValue Value, unsigned Opcode) {
5164 
5165   SDNode *Parent = Value.getNode();
5166   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
5167        I != E; ++I) {
5168 
5169     if (I.getUse().get() != Value)
5170       continue;
5171 
5172     if (I->getOpcode() == Opcode)
5173       return *I;
5174   }
5175   return nullptr;
5176 }
5177 
5178 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
5179   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
5180     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
5181     case Intrinsic::amdgcn_if:
5182       return AMDGPUISD::IF;
5183     case Intrinsic::amdgcn_else:
5184       return AMDGPUISD::ELSE;
5185     case Intrinsic::amdgcn_loop:
5186       return AMDGPUISD::LOOP;
5187     case Intrinsic::amdgcn_end_cf:
5188       llvm_unreachable("should not occur");
5189     default:
5190       return 0;
5191     }
5192   }
5193 
5194   // break, if_break, else_break are all only used as inputs to loop, not
5195   // directly as branch conditions.
5196   return 0;
5197 }
5198 
5199 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
5200   const Triple &TT = getTargetMachine().getTargetTriple();
5201   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5202           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5203          AMDGPU::shouldEmitConstantsToTextSection(TT);
5204 }
5205 
5206 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
5207   // FIXME: Either avoid relying on address space here or change the default
5208   // address space for functions to avoid the explicit check.
5209   return (GV->getValueType()->isFunctionTy() ||
5210           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
5211          !shouldEmitFixup(GV) &&
5212          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
5213 }
5214 
5215 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
5216   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
5217 }
5218 
5219 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
5220   if (!GV->hasExternalLinkage())
5221     return true;
5222 
5223   const auto OS = getTargetMachine().getTargetTriple().getOS();
5224   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
5225 }
5226 
5227 /// This transforms the control flow intrinsics to get the branch destination as
5228 /// last parameter, also switches branch target with BR if the need arise
5229 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
5230                                       SelectionDAG &DAG) const {
5231   SDLoc DL(BRCOND);
5232 
5233   SDNode *Intr = BRCOND.getOperand(1).getNode();
5234   SDValue Target = BRCOND.getOperand(2);
5235   SDNode *BR = nullptr;
5236   SDNode *SetCC = nullptr;
5237 
5238   if (Intr->getOpcode() == ISD::SETCC) {
5239     // As long as we negate the condition everything is fine
5240     SetCC = Intr;
5241     Intr = SetCC->getOperand(0).getNode();
5242 
5243   } else {
5244     // Get the target from BR if we don't negate the condition
5245     BR = findUser(BRCOND, ISD::BR);
5246     assert(BR && "brcond missing unconditional branch user");
5247     Target = BR->getOperand(1);
5248   }
5249 
5250   unsigned CFNode = isCFIntrinsic(Intr);
5251   if (CFNode == 0) {
5252     // This is a uniform branch so we don't need to legalize.
5253     return BRCOND;
5254   }
5255 
5256   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5257                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5258 
5259   assert(!SetCC ||
5260         (SetCC->getConstantOperandVal(1) == 1 &&
5261          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5262                                                              ISD::SETNE));
5263 
5264   // operands of the new intrinsic call
5265   SmallVector<SDValue, 4> Ops;
5266   if (HaveChain)
5267     Ops.push_back(BRCOND.getOperand(0));
5268 
5269   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5270   Ops.push_back(Target);
5271 
5272   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5273 
5274   // build the new intrinsic call
5275   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5276 
5277   if (!HaveChain) {
5278     SDValue Ops[] =  {
5279       SDValue(Result, 0),
5280       BRCOND.getOperand(0)
5281     };
5282 
5283     Result = DAG.getMergeValues(Ops, DL).getNode();
5284   }
5285 
5286   if (BR) {
5287     // Give the branch instruction our target
5288     SDValue Ops[] = {
5289       BR->getOperand(0),
5290       BRCOND.getOperand(2)
5291     };
5292     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5293     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5294   }
5295 
5296   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5297 
5298   // Copy the intrinsic results to registers
5299   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5300     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5301     if (!CopyToReg)
5302       continue;
5303 
5304     Chain = DAG.getCopyToReg(
5305       Chain, DL,
5306       CopyToReg->getOperand(1),
5307       SDValue(Result, i - 1),
5308       SDValue());
5309 
5310     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5311   }
5312 
5313   // Remove the old intrinsic from the chain
5314   DAG.ReplaceAllUsesOfValueWith(
5315     SDValue(Intr, Intr->getNumValues() - 1),
5316     Intr->getOperand(0));
5317 
5318   return Chain;
5319 }
5320 
5321 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5322                                           SelectionDAG &DAG) const {
5323   MVT VT = Op.getSimpleValueType();
5324   SDLoc DL(Op);
5325   // Checking the depth
5326   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5327     return DAG.getConstant(0, DL, VT);
5328 
5329   MachineFunction &MF = DAG.getMachineFunction();
5330   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5331   // Check for kernel and shader functions
5332   if (Info->isEntryFunction())
5333     return DAG.getConstant(0, DL, VT);
5334 
5335   MachineFrameInfo &MFI = MF.getFrameInfo();
5336   // There is a call to @llvm.returnaddress in this function
5337   MFI.setReturnAddressIsTaken(true);
5338 
5339   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5340   // Get the return address reg and mark it as an implicit live-in
5341   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5342 
5343   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5344 }
5345 
5346 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5347                                             SDValue Op,
5348                                             const SDLoc &DL,
5349                                             EVT VT) const {
5350   return Op.getValueType().bitsLE(VT) ?
5351       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5352     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5353                 DAG.getTargetConstant(0, DL, MVT::i32));
5354 }
5355 
5356 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5357   assert(Op.getValueType() == MVT::f16 &&
5358          "Do not know how to custom lower FP_ROUND for non-f16 type");
5359 
5360   SDValue Src = Op.getOperand(0);
5361   EVT SrcVT = Src.getValueType();
5362   if (SrcVT != MVT::f64)
5363     return Op;
5364 
5365   SDLoc DL(Op);
5366 
5367   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5368   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5369   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5370 }
5371 
5372 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5373                                                SelectionDAG &DAG) const {
5374   EVT VT = Op.getValueType();
5375   const MachineFunction &MF = DAG.getMachineFunction();
5376   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5377   bool IsIEEEMode = Info->getMode().IEEE;
5378 
5379   // FIXME: Assert during selection that this is only selected for
5380   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5381   // mode functions, but this happens to be OK since it's only done in cases
5382   // where there is known no sNaN.
5383   if (IsIEEEMode)
5384     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5385 
5386   if (VT == MVT::v4f16 || VT == MVT::v8f16)
5387     return splitBinaryVectorOp(Op, DAG);
5388   return Op;
5389 }
5390 
5391 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5392   EVT VT = Op.getValueType();
5393   SDLoc SL(Op);
5394   SDValue LHS = Op.getOperand(0);
5395   SDValue RHS = Op.getOperand(1);
5396   bool isSigned = Op.getOpcode() == ISD::SMULO;
5397 
5398   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5399     const APInt &C = RHSC->getAPIntValue();
5400     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5401     if (C.isPowerOf2()) {
5402       // smulo(x, signed_min) is same as umulo(x, signed_min).
5403       bool UseArithShift = isSigned && !C.isMinSignedValue();
5404       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5405       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5406       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5407           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5408                       SL, VT, Result, ShiftAmt),
5409           LHS, ISD::SETNE);
5410       return DAG.getMergeValues({ Result, Overflow }, SL);
5411     }
5412   }
5413 
5414   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5415   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5416                             SL, VT, LHS, RHS);
5417 
5418   SDValue Sign = isSigned
5419     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5420                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5421     : DAG.getConstant(0, SL, VT);
5422   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5423 
5424   return DAG.getMergeValues({ Result, Overflow }, SL);
5425 }
5426 
5427 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const {
5428   if (Op->isDivergent()) {
5429     // Select to V_MAD_[IU]64_[IU]32.
5430     return Op;
5431   }
5432   if (Subtarget->hasSMulHi()) {
5433     // Expand to S_MUL_I32 + S_MUL_HI_[IU]32.
5434     return SDValue();
5435   }
5436   // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to
5437   // calculate the high part, so we might as well do the whole thing with
5438   // V_MAD_[IU]64_[IU]32.
5439   return Op;
5440 }
5441 
5442 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5443   if (!Subtarget->isTrapHandlerEnabled() ||
5444       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5445     return lowerTrapEndpgm(Op, DAG);
5446 
5447   if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) {
5448     switch (*HsaAbiVer) {
5449     case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
5450     case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
5451       return lowerTrapHsaQueuePtr(Op, DAG);
5452     case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
5453     case ELF::ELFABIVERSION_AMDGPU_HSA_V5:
5454       return Subtarget->supportsGetDoorbellID() ?
5455           lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG);
5456     }
5457   }
5458 
5459   llvm_unreachable("Unknown trap handler");
5460 }
5461 
5462 SDValue SITargetLowering::lowerTrapEndpgm(
5463     SDValue Op, SelectionDAG &DAG) const {
5464   SDLoc SL(Op);
5465   SDValue Chain = Op.getOperand(0);
5466   return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5467 }
5468 
5469 SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5470     SDValue Op, SelectionDAG &DAG) const {
5471   SDLoc SL(Op);
5472   SDValue Chain = Op.getOperand(0);
5473 
5474   MachineFunction &MF = DAG.getMachineFunction();
5475   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5476   Register UserSGPR = Info->getQueuePtrUserSGPR();
5477 
5478   SDValue QueuePtr;
5479   if (UserSGPR == AMDGPU::NoRegister) {
5480     // We probably are in a function incorrectly marked with
5481     // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the trap,
5482     // so just use a null pointer.
5483     QueuePtr = DAG.getConstant(0, SL, MVT::i64);
5484   } else {
5485     QueuePtr = CreateLiveInRegister(
5486       DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5487   }
5488 
5489   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5490   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5491                                    QueuePtr, SDValue());
5492 
5493   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5494   SDValue Ops[] = {
5495     ToReg,
5496     DAG.getTargetConstant(TrapID, SL, MVT::i16),
5497     SGPR01,
5498     ToReg.getValue(1)
5499   };
5500   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5501 }
5502 
5503 SDValue SITargetLowering::lowerTrapHsa(
5504     SDValue Op, SelectionDAG &DAG) const {
5505   SDLoc SL(Op);
5506   SDValue Chain = Op.getOperand(0);
5507 
5508   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5509   SDValue Ops[] = {
5510     Chain,
5511     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5512   };
5513   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5514 }
5515 
5516 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5517   SDLoc SL(Op);
5518   SDValue Chain = Op.getOperand(0);
5519   MachineFunction &MF = DAG.getMachineFunction();
5520 
5521   if (!Subtarget->isTrapHandlerEnabled() ||
5522       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5523     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5524                                      "debugtrap handler not supported",
5525                                      Op.getDebugLoc(),
5526                                      DS_Warning);
5527     LLVMContext &Ctx = MF.getFunction().getContext();
5528     Ctx.diagnose(NoTrap);
5529     return Chain;
5530   }
5531 
5532   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5533   SDValue Ops[] = {
5534     Chain,
5535     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5536   };
5537   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5538 }
5539 
5540 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5541                                              SelectionDAG &DAG) const {
5542   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5543   if (Subtarget->hasApertureRegs()) {
5544     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5545         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5546         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5547     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5548         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5549         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5550     unsigned Encoding =
5551         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5552         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5553         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5554 
5555     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5556     SDValue ApertureReg = SDValue(
5557         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5558     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5559     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5560   }
5561 
5562   MachineFunction &MF = DAG.getMachineFunction();
5563   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5564   Register UserSGPR = Info->getQueuePtrUserSGPR();
5565   if (UserSGPR == AMDGPU::NoRegister) {
5566     // We probably are in a function incorrectly marked with
5567     // amdgpu-no-queue-ptr. This is undefined.
5568     return DAG.getUNDEF(MVT::i32);
5569   }
5570 
5571   SDValue QueuePtr = CreateLiveInRegister(
5572     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5573 
5574   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5575   // private_segment_aperture_base_hi.
5576   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5577 
5578   SDValue Ptr =
5579       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5580 
5581   // TODO: Use custom target PseudoSourceValue.
5582   // TODO: We should use the value from the IR intrinsic call, but it might not
5583   // be available and how do we get it?
5584   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5585   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5586                      commonAlignment(Align(64), StructOffset),
5587                      MachineMemOperand::MODereferenceable |
5588                          MachineMemOperand::MOInvariant);
5589 }
5590 
5591 /// Return true if the value is a known valid address, such that a null check is
5592 /// not necessary.
5593 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG,
5594                            const AMDGPUTargetMachine &TM, unsigned AddrSpace) {
5595   if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) ||
5596       isa<BasicBlockSDNode>(Val))
5597     return true;
5598 
5599   if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val))
5600     return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace);
5601 
5602   // TODO: Search through arithmetic, handle arguments and loads
5603   // marked nonnull.
5604   return false;
5605 }
5606 
5607 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5608                                              SelectionDAG &DAG) const {
5609   SDLoc SL(Op);
5610   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5611 
5612   SDValue Src = ASC->getOperand(0);
5613   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5614   unsigned SrcAS = ASC->getSrcAddressSpace();
5615 
5616   const AMDGPUTargetMachine &TM =
5617     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5618 
5619   // flat -> local/private
5620   if (SrcAS == AMDGPUAS::FLAT_ADDRESS) {
5621     unsigned DestAS = ASC->getDestAddressSpace();
5622 
5623     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5624         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5625       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5626 
5627       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5628         return Ptr;
5629 
5630       unsigned NullVal = TM.getNullPointerValue(DestAS);
5631       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5632       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5633 
5634       return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr,
5635                          SegmentNullPtr);
5636     }
5637   }
5638 
5639   // local/private -> flat
5640   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5641     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5642         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5643 
5644       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5645       SDValue CvtPtr =
5646           DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5647       CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr);
5648 
5649       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5650         return CvtPtr;
5651 
5652       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5653       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5654 
5655       SDValue NonNull
5656         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5657 
5658       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr,
5659                          FlatNullPtr);
5660     }
5661   }
5662 
5663   if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5664       Op.getValueType() == MVT::i64) {
5665     const SIMachineFunctionInfo *Info =
5666         DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>();
5667     SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32);
5668     SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi);
5669     return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
5670   }
5671 
5672   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5673       Src.getValueType() == MVT::i64)
5674     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5675 
5676   // global <-> flat are no-ops and never emitted.
5677 
5678   const MachineFunction &MF = DAG.getMachineFunction();
5679   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5680     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5681   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5682 
5683   return DAG.getUNDEF(ASC->getValueType(0));
5684 }
5685 
5686 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5687 // the small vector and inserting them into the big vector. That is better than
5688 // the default expansion of doing it via a stack slot. Even though the use of
5689 // the stack slot would be optimized away afterwards, the stack slot itself
5690 // remains.
5691 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5692                                                 SelectionDAG &DAG) const {
5693   SDValue Vec = Op.getOperand(0);
5694   SDValue Ins = Op.getOperand(1);
5695   SDValue Idx = Op.getOperand(2);
5696   EVT VecVT = Vec.getValueType();
5697   EVT InsVT = Ins.getValueType();
5698   EVT EltVT = VecVT.getVectorElementType();
5699   unsigned InsNumElts = InsVT.getVectorNumElements();
5700   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5701   SDLoc SL(Op);
5702 
5703   for (unsigned I = 0; I != InsNumElts; ++I) {
5704     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5705                               DAG.getConstant(I, SL, MVT::i32));
5706     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5707                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5708   }
5709   return Vec;
5710 }
5711 
5712 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5713                                                  SelectionDAG &DAG) const {
5714   SDValue Vec = Op.getOperand(0);
5715   SDValue InsVal = Op.getOperand(1);
5716   SDValue Idx = Op.getOperand(2);
5717   EVT VecVT = Vec.getValueType();
5718   EVT EltVT = VecVT.getVectorElementType();
5719   unsigned VecSize = VecVT.getSizeInBits();
5720   unsigned EltSize = EltVT.getSizeInBits();
5721 
5722 
5723   assert(VecSize <= 64);
5724 
5725   unsigned NumElts = VecVT.getVectorNumElements();
5726   SDLoc SL(Op);
5727   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5728 
5729   if (NumElts == 4 && EltSize == 16 && KIdx) {
5730     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5731 
5732     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5733                                  DAG.getConstant(0, SL, MVT::i32));
5734     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5735                                  DAG.getConstant(1, SL, MVT::i32));
5736 
5737     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5738     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5739 
5740     unsigned Idx = KIdx->getZExtValue();
5741     bool InsertLo = Idx < 2;
5742     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5743       InsertLo ? LoVec : HiVec,
5744       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5745       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5746 
5747     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5748 
5749     SDValue Concat = InsertLo ?
5750       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5751       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5752 
5753     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5754   }
5755 
5756   if (isa<ConstantSDNode>(Idx))
5757     return SDValue();
5758 
5759   MVT IntVT = MVT::getIntegerVT(VecSize);
5760 
5761   // Avoid stack access for dynamic indexing.
5762   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5763 
5764   // Create a congruent vector with the target value in each element so that
5765   // the required element can be masked and ORed into the target vector.
5766   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5767                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5768 
5769   assert(isPowerOf2_32(EltSize));
5770   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5771 
5772   // Convert vector index to bit-index.
5773   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5774 
5775   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5776   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5777                             DAG.getConstant(0xffff, SL, IntVT),
5778                             ScaledIdx);
5779 
5780   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5781   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5782                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5783 
5784   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5785   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5786 }
5787 
5788 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5789                                                   SelectionDAG &DAG) const {
5790   SDLoc SL(Op);
5791 
5792   EVT ResultVT = Op.getValueType();
5793   SDValue Vec = Op.getOperand(0);
5794   SDValue Idx = Op.getOperand(1);
5795   EVT VecVT = Vec.getValueType();
5796   unsigned VecSize = VecVT.getSizeInBits();
5797   EVT EltVT = VecVT.getVectorElementType();
5798 
5799   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5800 
5801   // Make sure we do any optimizations that will make it easier to fold
5802   // source modifiers before obscuring it with bit operations.
5803 
5804   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5805   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5806     return Combined;
5807 
5808   if (VecSize == 128) {
5809     SDValue Lo, Hi;
5810     EVT LoVT, HiVT;
5811     SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec);
5812     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5813     Lo =
5814         DAG.getBitcast(LoVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5815                                          V2, DAG.getConstant(0, SL, MVT::i32)));
5816     Hi =
5817         DAG.getBitcast(HiVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5818                                          V2, DAG.getConstant(1, SL, MVT::i32)));
5819     EVT IdxVT = Idx.getValueType();
5820     unsigned NElem = VecVT.getVectorNumElements();
5821     assert(isPowerOf2_32(NElem));
5822     SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT);
5823     SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask);
5824     SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT);
5825     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx);
5826   }
5827 
5828   assert(VecSize <= 64);
5829 
5830   unsigned EltSize = EltVT.getSizeInBits();
5831   assert(isPowerOf2_32(EltSize));
5832 
5833   MVT IntVT = MVT::getIntegerVT(VecSize);
5834   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5835 
5836   // Convert vector index to bit-index (* EltSize)
5837   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5838 
5839   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5840   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5841 
5842   if (ResultVT == MVT::f16) {
5843     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5844     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5845   }
5846 
5847   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5848 }
5849 
5850 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5851   assert(Elt % 2 == 0);
5852   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5853 }
5854 
5855 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5856                                               SelectionDAG &DAG) const {
5857   SDLoc SL(Op);
5858   EVT ResultVT = Op.getValueType();
5859   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5860 
5861   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5862   EVT EltVT = PackVT.getVectorElementType();
5863   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5864 
5865   // vector_shuffle <0,1,6,7> lhs, rhs
5866   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5867   //
5868   // vector_shuffle <6,7,2,3> lhs, rhs
5869   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5870   //
5871   // vector_shuffle <6,7,0,1> lhs, rhs
5872   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5873 
5874   // Avoid scalarizing when both halves are reading from consecutive elements.
5875   SmallVector<SDValue, 4> Pieces;
5876   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5877     if (elementPairIsContiguous(SVN->getMask(), I)) {
5878       const int Idx = SVN->getMaskElt(I);
5879       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5880       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5881       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5882                                     PackVT, SVN->getOperand(VecIdx),
5883                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5884       Pieces.push_back(SubVec);
5885     } else {
5886       const int Idx0 = SVN->getMaskElt(I);
5887       const int Idx1 = SVN->getMaskElt(I + 1);
5888       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5889       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5890       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5891       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5892 
5893       SDValue Vec0 = SVN->getOperand(VecIdx0);
5894       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5895                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5896 
5897       SDValue Vec1 = SVN->getOperand(VecIdx1);
5898       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5899                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5900       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5901     }
5902   }
5903 
5904   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5905 }
5906 
5907 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5908                                             SelectionDAG &DAG) const {
5909   SDLoc SL(Op);
5910   EVT VT = Op.getValueType();
5911 
5912   if (VT == MVT::v4i16 || VT == MVT::v4f16 ||
5913       VT == MVT::v8i16 || VT == MVT::v8f16) {
5914     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(),
5915                                   VT.getVectorNumElements() / 2);
5916     MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits());
5917 
5918     // Turn into pair of packed build_vectors.
5919     // TODO: Special case for constants that can be materialized with s_mov_b64.
5920     SmallVector<SDValue, 4> LoOps, HiOps;
5921     for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) {
5922       LoOps.push_back(Op.getOperand(I));
5923       HiOps.push_back(Op.getOperand(I + E));
5924     }
5925     SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps);
5926     SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps);
5927 
5928     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo);
5929     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi);
5930 
5931     SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL,
5932                                        { CastLo, CastHi });
5933     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5934   }
5935 
5936   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5937   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5938 
5939   SDValue Lo = Op.getOperand(0);
5940   SDValue Hi = Op.getOperand(1);
5941 
5942   // Avoid adding defined bits with the zero_extend.
5943   if (Hi.isUndef()) {
5944     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5945     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5946     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5947   }
5948 
5949   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5950   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5951 
5952   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5953                               DAG.getConstant(16, SL, MVT::i32));
5954   if (Lo.isUndef())
5955     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5956 
5957   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5958   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5959 
5960   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5961   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5962 }
5963 
5964 bool
5965 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5966   // We can fold offsets for anything that doesn't require a GOT relocation.
5967   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5968           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5969           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5970          !shouldEmitGOTReloc(GA->getGlobal());
5971 }
5972 
5973 static SDValue
5974 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5975                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5976                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5977   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5978   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5979   // lowered to the following code sequence:
5980   //
5981   // For constant address space:
5982   //   s_getpc_b64 s[0:1]
5983   //   s_add_u32 s0, s0, $symbol
5984   //   s_addc_u32 s1, s1, 0
5985   //
5986   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5987   //   a fixup or relocation is emitted to replace $symbol with a literal
5988   //   constant, which is a pc-relative offset from the encoding of the $symbol
5989   //   operand to the global variable.
5990   //
5991   // For global address space:
5992   //   s_getpc_b64 s[0:1]
5993   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5994   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5995   //
5996   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5997   //   fixups or relocations are emitted to replace $symbol@*@lo and
5998   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5999   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
6000   //   operand to the global variable.
6001   //
6002   // What we want here is an offset from the value returned by s_getpc
6003   // (which is the address of the s_add_u32 instruction) to the global
6004   // variable, but since the encoding of $symbol starts 4 bytes after the start
6005   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
6006   // small. This requires us to add 4 to the global variable offset in order to
6007   // compute the correct address. Similarly for the s_addc_u32 instruction, the
6008   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
6009   // instruction.
6010   SDValue PtrLo =
6011       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
6012   SDValue PtrHi;
6013   if (GAFlags == SIInstrInfo::MO_NONE) {
6014     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
6015   } else {
6016     PtrHi =
6017         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
6018   }
6019   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
6020 }
6021 
6022 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
6023                                              SDValue Op,
6024                                              SelectionDAG &DAG) const {
6025   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
6026   SDLoc DL(GSD);
6027   EVT PtrVT = Op.getValueType();
6028 
6029   const GlobalValue *GV = GSD->getGlobal();
6030   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
6031        shouldUseLDSConstAddress(GV)) ||
6032       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
6033       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
6034     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
6035         GV->hasExternalLinkage()) {
6036       Type *Ty = GV->getValueType();
6037       // HIP uses an unsized array `extern __shared__ T s[]` or similar
6038       // zero-sized type in other languages to declare the dynamic shared
6039       // memory which size is not known at the compile time. They will be
6040       // allocated by the runtime and placed directly after the static
6041       // allocated ones. They all share the same offset.
6042       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
6043         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
6044         // Adjust alignment for that dynamic shared memory array.
6045         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
6046         return SDValue(
6047             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
6048       }
6049     }
6050     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
6051   }
6052 
6053   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
6054     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
6055                                             SIInstrInfo::MO_ABS32_LO);
6056     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
6057   }
6058 
6059   if (shouldEmitFixup(GV))
6060     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
6061   else if (shouldEmitPCReloc(GV))
6062     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
6063                                    SIInstrInfo::MO_REL32);
6064 
6065   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
6066                                             SIInstrInfo::MO_GOTPCREL32);
6067 
6068   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
6069   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
6070   const DataLayout &DataLayout = DAG.getDataLayout();
6071   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
6072   MachinePointerInfo PtrInfo
6073     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
6074 
6075   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
6076                      MachineMemOperand::MODereferenceable |
6077                          MachineMemOperand::MOInvariant);
6078 }
6079 
6080 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
6081                                    const SDLoc &DL, SDValue V) const {
6082   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
6083   // the destination register.
6084   //
6085   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
6086   // so we will end up with redundant moves to m0.
6087   //
6088   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
6089 
6090   // A Null SDValue creates a glue result.
6091   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
6092                                   V, Chain);
6093   return SDValue(M0, 0);
6094 }
6095 
6096 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
6097                                                  SDValue Op,
6098                                                  MVT VT,
6099                                                  unsigned Offset) const {
6100   SDLoc SL(Op);
6101   SDValue Param = lowerKernargMemParameter(
6102       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
6103   // The local size values will have the hi 16-bits as zero.
6104   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
6105                      DAG.getValueType(VT));
6106 }
6107 
6108 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6109                                         EVT VT) {
6110   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6111                                       "non-hsa intrinsic with hsa target",
6112                                       DL.getDebugLoc());
6113   DAG.getContext()->diagnose(BadIntrin);
6114   return DAG.getUNDEF(VT);
6115 }
6116 
6117 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6118                                          EVT VT) {
6119   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6120                                       "intrinsic not supported on subtarget",
6121                                       DL.getDebugLoc());
6122   DAG.getContext()->diagnose(BadIntrin);
6123   return DAG.getUNDEF(VT);
6124 }
6125 
6126 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
6127                                     ArrayRef<SDValue> Elts) {
6128   assert(!Elts.empty());
6129   MVT Type;
6130   unsigned NumElts = Elts.size();
6131 
6132   if (NumElts <= 8) {
6133     Type = MVT::getVectorVT(MVT::f32, NumElts);
6134   } else {
6135     assert(Elts.size() <= 16);
6136     Type = MVT::v16f32;
6137     NumElts = 16;
6138   }
6139 
6140   SmallVector<SDValue, 16> VecElts(NumElts);
6141   for (unsigned i = 0; i < Elts.size(); ++i) {
6142     SDValue Elt = Elts[i];
6143     if (Elt.getValueType() != MVT::f32)
6144       Elt = DAG.getBitcast(MVT::f32, Elt);
6145     VecElts[i] = Elt;
6146   }
6147   for (unsigned i = Elts.size(); i < NumElts; ++i)
6148     VecElts[i] = DAG.getUNDEF(MVT::f32);
6149 
6150   if (NumElts == 1)
6151     return VecElts[0];
6152   return DAG.getBuildVector(Type, DL, VecElts);
6153 }
6154 
6155 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
6156                               SDValue Src, int ExtraElts) {
6157   EVT SrcVT = Src.getValueType();
6158 
6159   SmallVector<SDValue, 8> Elts;
6160 
6161   if (SrcVT.isVector())
6162     DAG.ExtractVectorElements(Src, Elts);
6163   else
6164     Elts.push_back(Src);
6165 
6166   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
6167   while (ExtraElts--)
6168     Elts.push_back(Undef);
6169 
6170   return DAG.getBuildVector(CastVT, DL, Elts);
6171 }
6172 
6173 // Re-construct the required return value for a image load intrinsic.
6174 // This is more complicated due to the optional use TexFailCtrl which means the required
6175 // return type is an aggregate
6176 static SDValue constructRetValue(SelectionDAG &DAG,
6177                                  MachineSDNode *Result,
6178                                  ArrayRef<EVT> ResultTypes,
6179                                  bool IsTexFail, bool Unpacked, bool IsD16,
6180                                  int DMaskPop, int NumVDataDwords,
6181                                  const SDLoc &DL) {
6182   // Determine the required return type. This is the same regardless of IsTexFail flag
6183   EVT ReqRetVT = ResultTypes[0];
6184   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
6185   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6186     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
6187 
6188   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6189     DMaskPop : (DMaskPop + 1) / 2;
6190 
6191   MVT DataDwordVT = NumDataDwords == 1 ?
6192     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
6193 
6194   MVT MaskPopVT = MaskPopDwords == 1 ?
6195     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
6196 
6197   SDValue Data(Result, 0);
6198   SDValue TexFail;
6199 
6200   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
6201     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
6202     if (MaskPopVT.isVector()) {
6203       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
6204                          SDValue(Result, 0), ZeroIdx);
6205     } else {
6206       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
6207                          SDValue(Result, 0), ZeroIdx);
6208     }
6209   }
6210 
6211   if (DataDwordVT.isVector())
6212     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
6213                           NumDataDwords - MaskPopDwords);
6214 
6215   if (IsD16)
6216     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
6217 
6218   EVT LegalReqRetVT = ReqRetVT;
6219   if (!ReqRetVT.isVector()) {
6220     if (!Data.getValueType().isInteger())
6221       Data = DAG.getNode(ISD::BITCAST, DL,
6222                          Data.getValueType().changeTypeToInteger(), Data);
6223     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
6224   } else {
6225     // We need to widen the return vector to a legal type
6226     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
6227         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
6228       LegalReqRetVT =
6229           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
6230                            ReqRetVT.getVectorNumElements() + 1);
6231     }
6232   }
6233   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
6234 
6235   if (IsTexFail) {
6236     TexFail =
6237         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
6238                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
6239 
6240     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
6241   }
6242 
6243   if (Result->getNumValues() == 1)
6244     return Data;
6245 
6246   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
6247 }
6248 
6249 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
6250                          SDValue *LWE, bool &IsTexFail) {
6251   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
6252 
6253   uint64_t Value = TexFailCtrlConst->getZExtValue();
6254   if (Value) {
6255     IsTexFail = true;
6256   }
6257 
6258   SDLoc DL(TexFailCtrlConst);
6259   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
6260   Value &= ~(uint64_t)0x1;
6261   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
6262   Value &= ~(uint64_t)0x2;
6263 
6264   return Value == 0;
6265 }
6266 
6267 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
6268                                       MVT PackVectorVT,
6269                                       SmallVectorImpl<SDValue> &PackedAddrs,
6270                                       unsigned DimIdx, unsigned EndIdx,
6271                                       unsigned NumGradients) {
6272   SDLoc DL(Op);
6273   for (unsigned I = DimIdx; I < EndIdx; I++) {
6274     SDValue Addr = Op.getOperand(I);
6275 
6276     // Gradients are packed with undef for each coordinate.
6277     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
6278     // 1D: undef,dx/dh; undef,dx/dv
6279     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
6280     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
6281     if (((I + 1) >= EndIdx) ||
6282         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
6283                                          I == DimIdx + NumGradients - 1))) {
6284       if (Addr.getValueType() != MVT::i16)
6285         Addr = DAG.getBitcast(MVT::i16, Addr);
6286       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
6287     } else {
6288       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
6289       I++;
6290     }
6291     Addr = DAG.getBitcast(MVT::f32, Addr);
6292     PackedAddrs.push_back(Addr);
6293   }
6294 }
6295 
6296 SDValue SITargetLowering::lowerImage(SDValue Op,
6297                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
6298                                      SelectionDAG &DAG, bool WithChain) const {
6299   SDLoc DL(Op);
6300   MachineFunction &MF = DAG.getMachineFunction();
6301   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
6302   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
6303       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
6304   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
6305   unsigned IntrOpcode = Intr->BaseOpcode;
6306   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6307 
6308   SmallVector<EVT, 3> ResultTypes(Op->values());
6309   SmallVector<EVT, 3> OrigResultTypes(Op->values());
6310   bool IsD16 = false;
6311   bool IsG16 = false;
6312   bool IsA16 = false;
6313   SDValue VData;
6314   int NumVDataDwords;
6315   bool AdjustRetType = false;
6316 
6317   // Offset of intrinsic arguments
6318   const unsigned ArgOffset = WithChain ? 2 : 1;
6319 
6320   unsigned DMask;
6321   unsigned DMaskLanes = 0;
6322 
6323   if (BaseOpcode->Atomic) {
6324     VData = Op.getOperand(2);
6325 
6326     bool Is64Bit = VData.getValueType() == MVT::i64;
6327     if (BaseOpcode->AtomicX2) {
6328       SDValue VData2 = Op.getOperand(3);
6329       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6330                                  {VData, VData2});
6331       if (Is64Bit)
6332         VData = DAG.getBitcast(MVT::v4i32, VData);
6333 
6334       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6335       DMask = Is64Bit ? 0xf : 0x3;
6336       NumVDataDwords = Is64Bit ? 4 : 2;
6337     } else {
6338       DMask = Is64Bit ? 0x3 : 0x1;
6339       NumVDataDwords = Is64Bit ? 2 : 1;
6340     }
6341   } else {
6342     auto *DMaskConst =
6343         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6344     DMask = DMaskConst->getZExtValue();
6345     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6346 
6347     if (BaseOpcode->Store) {
6348       VData = Op.getOperand(2);
6349 
6350       MVT StoreVT = VData.getSimpleValueType();
6351       if (StoreVT.getScalarType() == MVT::f16) {
6352         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6353           return Op; // D16 is unsupported for this instruction
6354 
6355         IsD16 = true;
6356         VData = handleD16VData(VData, DAG, true);
6357       }
6358 
6359       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6360     } else {
6361       // Work out the num dwords based on the dmask popcount and underlying type
6362       // and whether packing is supported.
6363       MVT LoadVT = ResultTypes[0].getSimpleVT();
6364       if (LoadVT.getScalarType() == MVT::f16) {
6365         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6366           return Op; // D16 is unsupported for this instruction
6367 
6368         IsD16 = true;
6369       }
6370 
6371       // Confirm that the return type is large enough for the dmask specified
6372       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6373           (!LoadVT.isVector() && DMaskLanes > 1))
6374           return Op;
6375 
6376       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6377       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6378       // instructions.
6379       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6380           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6381         NumVDataDwords = (DMaskLanes + 1) / 2;
6382       else
6383         NumVDataDwords = DMaskLanes;
6384 
6385       AdjustRetType = true;
6386     }
6387   }
6388 
6389   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6390   SmallVector<SDValue, 4> VAddrs;
6391 
6392   // Check for 16 bit addresses or derivatives and pack if true.
6393   MVT VAddrVT =
6394       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6395   MVT VAddrScalarVT = VAddrVT.getScalarType();
6396   MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6397   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6398 
6399   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6400   VAddrScalarVT = VAddrVT.getScalarType();
6401   MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6402   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6403 
6404   // Push back extra arguments.
6405   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) {
6406     if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) {
6407       assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument");
6408       // Special handling of bias when A16 is on. Bias is of type half but
6409       // occupies full 32-bit.
6410       SDValue Bias = DAG.getBuildVector(
6411           MVT::v2f16, DL,
6412           {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)});
6413       VAddrs.push_back(Bias);
6414     } else {
6415       assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) &&
6416              "Bias needs to be converted to 16 bit in A16 mode");
6417       VAddrs.push_back(Op.getOperand(ArgOffset + I));
6418     }
6419   }
6420 
6421   if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
6422     // 16 bit gradients are supported, but are tied to the A16 control
6423     // so both gradients and addresses must be 16 bit
6424     LLVM_DEBUG(
6425         dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6426                   "require 16 bit args for both gradients and addresses");
6427     return Op;
6428   }
6429 
6430   if (IsA16) {
6431     if (!ST->hasA16()) {
6432       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6433                            "support 16 bit addresses\n");
6434       return Op;
6435     }
6436   }
6437 
6438   // We've dealt with incorrect input so we know that if IsA16, IsG16
6439   // are set then we have to compress/pack operands (either address,
6440   // gradient or both)
6441   // In the case where a16 and gradients are tied (no G16 support) then we
6442   // have already verified that both IsA16 and IsG16 are true
6443   if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
6444     // Activate g16
6445     const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6446         AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6447     IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6448   }
6449 
6450   // Add gradients (packed or unpacked)
6451   if (IsG16) {
6452     // Pack the gradients
6453     // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6454     packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
6455                               ArgOffset + Intr->GradientStart,
6456                               ArgOffset + Intr->CoordStart, Intr->NumGradients);
6457   } else {
6458     for (unsigned I = ArgOffset + Intr->GradientStart;
6459          I < ArgOffset + Intr->CoordStart; I++)
6460       VAddrs.push_back(Op.getOperand(I));
6461   }
6462 
6463   // Add addresses (packed or unpacked)
6464   if (IsA16) {
6465     packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
6466                               ArgOffset + Intr->CoordStart, VAddrEnd,
6467                               0 /* No gradients */);
6468   } else {
6469     // Add uncompressed address
6470     for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6471       VAddrs.push_back(Op.getOperand(I));
6472   }
6473 
6474   // If the register allocator cannot place the address registers contiguously
6475   // without introducing moves, then using the non-sequential address encoding
6476   // is always preferable, since it saves VALU instructions and is usually a
6477   // wash in terms of code size or even better.
6478   //
6479   // However, we currently have no way of hinting to the register allocator that
6480   // MIMG addresses should be placed contiguously when it is possible to do so,
6481   // so force non-NSA for the common 2-address case as a heuristic.
6482   //
6483   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6484   // allocation when possible.
6485   bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) &&
6486                 VAddrs.size() >= 3 &&
6487                 VAddrs.size() <= (unsigned)ST->getNSAMaxSize();
6488   SDValue VAddr;
6489   if (!UseNSA)
6490     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6491 
6492   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6493   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6494   SDValue Unorm;
6495   if (!BaseOpcode->Sampler) {
6496     Unorm = True;
6497   } else {
6498     auto UnormConst =
6499         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6500 
6501     Unorm = UnormConst->getZExtValue() ? True : False;
6502   }
6503 
6504   SDValue TFE;
6505   SDValue LWE;
6506   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6507   bool IsTexFail = false;
6508   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6509     return Op;
6510 
6511   if (IsTexFail) {
6512     if (!DMaskLanes) {
6513       // Expecting to get an error flag since TFC is on - and dmask is 0
6514       // Force dmask to be at least 1 otherwise the instruction will fail
6515       DMask = 0x1;
6516       DMaskLanes = 1;
6517       NumVDataDwords = 1;
6518     }
6519     NumVDataDwords += 1;
6520     AdjustRetType = true;
6521   }
6522 
6523   // Has something earlier tagged that the return type needs adjusting
6524   // This happens if the instruction is a load or has set TexFailCtrl flags
6525   if (AdjustRetType) {
6526     // NumVDataDwords reflects the true number of dwords required in the return type
6527     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6528       // This is a no-op load. This can be eliminated
6529       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6530       if (isa<MemSDNode>(Op))
6531         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6532       return Undef;
6533     }
6534 
6535     EVT NewVT = NumVDataDwords > 1 ?
6536                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6537                 : MVT::i32;
6538 
6539     ResultTypes[0] = NewVT;
6540     if (ResultTypes.size() == 3) {
6541       // Original result was aggregate type used for TexFailCtrl results
6542       // The actual instruction returns as a vector type which has now been
6543       // created. Remove the aggregate result.
6544       ResultTypes.erase(&ResultTypes[1]);
6545     }
6546   }
6547 
6548   unsigned CPol = cast<ConstantSDNode>(
6549       Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6550   if (BaseOpcode->Atomic)
6551     CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6552   if (CPol & ~AMDGPU::CPol::ALL)
6553     return Op;
6554 
6555   SmallVector<SDValue, 26> Ops;
6556   if (BaseOpcode->Store || BaseOpcode->Atomic)
6557     Ops.push_back(VData); // vdata
6558   if (UseNSA)
6559     append_range(Ops, VAddrs);
6560   else
6561     Ops.push_back(VAddr);
6562   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6563   if (BaseOpcode->Sampler)
6564     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6565   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6566   if (IsGFX10Plus)
6567     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6568   Ops.push_back(Unorm);
6569   Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6570   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6571                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6572   if (IsGFX10Plus)
6573     Ops.push_back(IsA16 ? True : False);
6574   if (!Subtarget->hasGFX90AInsts()) {
6575     Ops.push_back(TFE); //tfe
6576   } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6577     report_fatal_error("TFE is not supported on this GPU");
6578   }
6579   Ops.push_back(LWE); // lwe
6580   if (!IsGFX10Plus)
6581     Ops.push_back(DimInfo->DA ? True : False);
6582   if (BaseOpcode->HasD16)
6583     Ops.push_back(IsD16 ? True : False);
6584   if (isa<MemSDNode>(Op))
6585     Ops.push_back(Op.getOperand(0)); // chain
6586 
6587   int NumVAddrDwords =
6588       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6589   int Opcode = -1;
6590 
6591   if (IsGFX10Plus) {
6592     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6593                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6594                                           : AMDGPU::MIMGEncGfx10Default,
6595                                    NumVDataDwords, NumVAddrDwords);
6596   } else {
6597     if (Subtarget->hasGFX90AInsts()) {
6598       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6599                                      NumVDataDwords, NumVAddrDwords);
6600       if (Opcode == -1)
6601         report_fatal_error(
6602             "requested image instruction is not supported on this GPU");
6603     }
6604     if (Opcode == -1 &&
6605         Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6606       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6607                                      NumVDataDwords, NumVAddrDwords);
6608     if (Opcode == -1)
6609       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6610                                      NumVDataDwords, NumVAddrDwords);
6611   }
6612   assert(Opcode != -1);
6613 
6614   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6615   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6616     MachineMemOperand *MemRef = MemOp->getMemOperand();
6617     DAG.setNodeMemRefs(NewNode, {MemRef});
6618   }
6619 
6620   if (BaseOpcode->AtomicX2) {
6621     SmallVector<SDValue, 1> Elt;
6622     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6623     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6624   }
6625   if (BaseOpcode->Store)
6626     return SDValue(NewNode, 0);
6627   return constructRetValue(DAG, NewNode,
6628                            OrigResultTypes, IsTexFail,
6629                            Subtarget->hasUnpackedD16VMem(), IsD16,
6630                            DMaskLanes, NumVDataDwords, DL);
6631 }
6632 
6633 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6634                                        SDValue Offset, SDValue CachePolicy,
6635                                        SelectionDAG &DAG) const {
6636   MachineFunction &MF = DAG.getMachineFunction();
6637 
6638   const DataLayout &DataLayout = DAG.getDataLayout();
6639   Align Alignment =
6640       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6641 
6642   MachineMemOperand *MMO = MF.getMachineMemOperand(
6643       MachinePointerInfo(),
6644       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6645           MachineMemOperand::MOInvariant,
6646       VT.getStoreSize(), Alignment);
6647 
6648   if (!Offset->isDivergent()) {
6649     SDValue Ops[] = {
6650         Rsrc,
6651         Offset, // Offset
6652         CachePolicy
6653     };
6654 
6655     // Widen vec3 load to vec4.
6656     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6657       EVT WidenedVT =
6658           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6659       auto WidenedOp = DAG.getMemIntrinsicNode(
6660           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6661           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6662       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6663                                    DAG.getVectorIdxConstant(0, DL));
6664       return Subvector;
6665     }
6666 
6667     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6668                                    DAG.getVTList(VT), Ops, VT, MMO);
6669   }
6670 
6671   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6672   // assume that the buffer is unswizzled.
6673   SmallVector<SDValue, 4> Loads;
6674   unsigned NumLoads = 1;
6675   MVT LoadVT = VT.getSimpleVT();
6676   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6677   assert((LoadVT.getScalarType() == MVT::i32 ||
6678           LoadVT.getScalarType() == MVT::f32));
6679 
6680   if (NumElts == 8 || NumElts == 16) {
6681     NumLoads = NumElts / 4;
6682     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6683   }
6684 
6685   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6686   SDValue Ops[] = {
6687       DAG.getEntryNode(),                               // Chain
6688       Rsrc,                                             // rsrc
6689       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6690       {},                                               // voffset
6691       {},                                               // soffset
6692       {},                                               // offset
6693       CachePolicy,                                      // cachepolicy
6694       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6695   };
6696 
6697   // Use the alignment to ensure that the required offsets will fit into the
6698   // immediate offsets.
6699   setBufferOffsets(Offset, DAG, &Ops[3],
6700                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6701 
6702   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6703   for (unsigned i = 0; i < NumLoads; ++i) {
6704     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6705     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6706                                         LoadVT, MMO, DAG));
6707   }
6708 
6709   if (NumElts == 8 || NumElts == 16)
6710     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6711 
6712   return Loads[0];
6713 }
6714 
6715 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6716                                                   SelectionDAG &DAG) const {
6717   MachineFunction &MF = DAG.getMachineFunction();
6718   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6719 
6720   EVT VT = Op.getValueType();
6721   SDLoc DL(Op);
6722   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6723 
6724   // TODO: Should this propagate fast-math-flags?
6725 
6726   switch (IntrinsicID) {
6727   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6728     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6729       return emitNonHSAIntrinsicError(DAG, DL, VT);
6730     return getPreloadedValue(DAG, *MFI, VT,
6731                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6732   }
6733   case Intrinsic::amdgcn_dispatch_ptr:
6734   case Intrinsic::amdgcn_queue_ptr: {
6735     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6736       DiagnosticInfoUnsupported BadIntrin(
6737           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6738           DL.getDebugLoc());
6739       DAG.getContext()->diagnose(BadIntrin);
6740       return DAG.getUNDEF(VT);
6741     }
6742 
6743     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6744       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6745     return getPreloadedValue(DAG, *MFI, VT, RegID);
6746   }
6747   case Intrinsic::amdgcn_implicitarg_ptr: {
6748     if (MFI->isEntryFunction())
6749       return getImplicitArgPtr(DAG, DL);
6750     return getPreloadedValue(DAG, *MFI, VT,
6751                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6752   }
6753   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6754     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6755       // This only makes sense to call in a kernel, so just lower to null.
6756       return DAG.getConstant(0, DL, VT);
6757     }
6758 
6759     return getPreloadedValue(DAG, *MFI, VT,
6760                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6761   }
6762   case Intrinsic::amdgcn_dispatch_id: {
6763     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6764   }
6765   case Intrinsic::amdgcn_rcp:
6766     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6767   case Intrinsic::amdgcn_rsq:
6768     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6769   case Intrinsic::amdgcn_rsq_legacy:
6770     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6771       return emitRemovedIntrinsicError(DAG, DL, VT);
6772     return SDValue();
6773   case Intrinsic::amdgcn_rcp_legacy:
6774     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6775       return emitRemovedIntrinsicError(DAG, DL, VT);
6776     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6777   case Intrinsic::amdgcn_rsq_clamp: {
6778     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6779       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6780 
6781     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6782     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6783     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6784 
6785     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6786     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6787                               DAG.getConstantFP(Max, DL, VT));
6788     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6789                        DAG.getConstantFP(Min, DL, VT));
6790   }
6791   case Intrinsic::r600_read_ngroups_x:
6792     if (Subtarget->isAmdHsaOS())
6793       return emitNonHSAIntrinsicError(DAG, DL, VT);
6794 
6795     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6796                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6797                                     false);
6798   case Intrinsic::r600_read_ngroups_y:
6799     if (Subtarget->isAmdHsaOS())
6800       return emitNonHSAIntrinsicError(DAG, DL, VT);
6801 
6802     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6803                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6804                                     false);
6805   case Intrinsic::r600_read_ngroups_z:
6806     if (Subtarget->isAmdHsaOS())
6807       return emitNonHSAIntrinsicError(DAG, DL, VT);
6808 
6809     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6810                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6811                                     false);
6812   case Intrinsic::r600_read_global_size_x:
6813     if (Subtarget->isAmdHsaOS())
6814       return emitNonHSAIntrinsicError(DAG, DL, VT);
6815 
6816     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6817                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6818                                     Align(4), false);
6819   case Intrinsic::r600_read_global_size_y:
6820     if (Subtarget->isAmdHsaOS())
6821       return emitNonHSAIntrinsicError(DAG, DL, VT);
6822 
6823     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6824                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6825                                     Align(4), false);
6826   case Intrinsic::r600_read_global_size_z:
6827     if (Subtarget->isAmdHsaOS())
6828       return emitNonHSAIntrinsicError(DAG, DL, VT);
6829 
6830     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6831                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6832                                     Align(4), false);
6833   case Intrinsic::r600_read_local_size_x:
6834     if (Subtarget->isAmdHsaOS())
6835       return emitNonHSAIntrinsicError(DAG, DL, VT);
6836 
6837     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6838                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6839   case Intrinsic::r600_read_local_size_y:
6840     if (Subtarget->isAmdHsaOS())
6841       return emitNonHSAIntrinsicError(DAG, DL, VT);
6842 
6843     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6844                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6845   case Intrinsic::r600_read_local_size_z:
6846     if (Subtarget->isAmdHsaOS())
6847       return emitNonHSAIntrinsicError(DAG, DL, VT);
6848 
6849     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6850                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6851   case Intrinsic::amdgcn_workgroup_id_x:
6852     return getPreloadedValue(DAG, *MFI, VT,
6853                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6854   case Intrinsic::amdgcn_workgroup_id_y:
6855     return getPreloadedValue(DAG, *MFI, VT,
6856                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6857   case Intrinsic::amdgcn_workgroup_id_z:
6858     return getPreloadedValue(DAG, *MFI, VT,
6859                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6860   case Intrinsic::amdgcn_workitem_id_x:
6861     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 0) == 0)
6862       return DAG.getConstant(0, DL, MVT::i32);
6863 
6864     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6865                           SDLoc(DAG.getEntryNode()),
6866                           MFI->getArgInfo().WorkItemIDX);
6867   case Intrinsic::amdgcn_workitem_id_y:
6868     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 1) == 0)
6869       return DAG.getConstant(0, DL, MVT::i32);
6870 
6871     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6872                           SDLoc(DAG.getEntryNode()),
6873                           MFI->getArgInfo().WorkItemIDY);
6874   case Intrinsic::amdgcn_workitem_id_z:
6875     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 2) == 0)
6876       return DAG.getConstant(0, DL, MVT::i32);
6877 
6878     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6879                           SDLoc(DAG.getEntryNode()),
6880                           MFI->getArgInfo().WorkItemIDZ);
6881   case Intrinsic::amdgcn_wavefrontsize:
6882     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6883                            SDLoc(Op), MVT::i32);
6884   case Intrinsic::amdgcn_s_buffer_load: {
6885     unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6886     if (CPol & ~AMDGPU::CPol::ALL)
6887       return Op;
6888     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6889                         DAG);
6890   }
6891   case Intrinsic::amdgcn_fdiv_fast:
6892     return lowerFDIV_FAST(Op, DAG);
6893   case Intrinsic::amdgcn_sin:
6894     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6895 
6896   case Intrinsic::amdgcn_cos:
6897     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6898 
6899   case Intrinsic::amdgcn_mul_u24:
6900     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6901   case Intrinsic::amdgcn_mul_i24:
6902     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6903 
6904   case Intrinsic::amdgcn_log_clamp: {
6905     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6906       return SDValue();
6907 
6908     return emitRemovedIntrinsicError(DAG, DL, VT);
6909   }
6910   case Intrinsic::amdgcn_ldexp:
6911     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6912                        Op.getOperand(1), Op.getOperand(2));
6913 
6914   case Intrinsic::amdgcn_fract:
6915     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6916 
6917   case Intrinsic::amdgcn_class:
6918     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6919                        Op.getOperand(1), Op.getOperand(2));
6920   case Intrinsic::amdgcn_div_fmas:
6921     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6922                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6923                        Op.getOperand(4));
6924 
6925   case Intrinsic::amdgcn_div_fixup:
6926     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6927                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6928 
6929   case Intrinsic::amdgcn_div_scale: {
6930     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6931 
6932     // Translate to the operands expected by the machine instruction. The
6933     // first parameter must be the same as the first instruction.
6934     SDValue Numerator = Op.getOperand(1);
6935     SDValue Denominator = Op.getOperand(2);
6936 
6937     // Note this order is opposite of the machine instruction's operations,
6938     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6939     // intrinsic has the numerator as the first operand to match a normal
6940     // division operation.
6941 
6942     SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator;
6943 
6944     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6945                        Denominator, Numerator);
6946   }
6947   case Intrinsic::amdgcn_icmp: {
6948     // There is a Pat that handles this variant, so return it as-is.
6949     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6950         Op.getConstantOperandVal(2) == 0 &&
6951         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6952       return Op;
6953     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6954   }
6955   case Intrinsic::amdgcn_fcmp: {
6956     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6957   }
6958   case Intrinsic::amdgcn_ballot:
6959     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6960   case Intrinsic::amdgcn_fmed3:
6961     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6962                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6963   case Intrinsic::amdgcn_fdot2:
6964     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6965                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6966                        Op.getOperand(4));
6967   case Intrinsic::amdgcn_fmul_legacy:
6968     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6969                        Op.getOperand(1), Op.getOperand(2));
6970   case Intrinsic::amdgcn_sffbh:
6971     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6972   case Intrinsic::amdgcn_sbfe:
6973     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6974                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6975   case Intrinsic::amdgcn_ubfe:
6976     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6977                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6978   case Intrinsic::amdgcn_cvt_pkrtz:
6979   case Intrinsic::amdgcn_cvt_pknorm_i16:
6980   case Intrinsic::amdgcn_cvt_pknorm_u16:
6981   case Intrinsic::amdgcn_cvt_pk_i16:
6982   case Intrinsic::amdgcn_cvt_pk_u16: {
6983     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6984     EVT VT = Op.getValueType();
6985     unsigned Opcode;
6986 
6987     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6988       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6989     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6990       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6991     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6992       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6993     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6994       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6995     else
6996       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6997 
6998     if (isTypeLegal(VT))
6999       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
7000 
7001     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
7002                                Op.getOperand(1), Op.getOperand(2));
7003     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
7004   }
7005   case Intrinsic::amdgcn_fmad_ftz:
7006     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
7007                        Op.getOperand(2), Op.getOperand(3));
7008 
7009   case Intrinsic::amdgcn_if_break:
7010     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
7011                                       Op->getOperand(1), Op->getOperand(2)), 0);
7012 
7013   case Intrinsic::amdgcn_groupstaticsize: {
7014     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
7015     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
7016       return Op;
7017 
7018     const Module *M = MF.getFunction().getParent();
7019     const GlobalValue *GV =
7020         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
7021     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
7022                                             SIInstrInfo::MO_ABS32_LO);
7023     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
7024   }
7025   case Intrinsic::amdgcn_is_shared:
7026   case Intrinsic::amdgcn_is_private: {
7027     SDLoc SL(Op);
7028     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
7029       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
7030     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
7031     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
7032                                  Op.getOperand(1));
7033 
7034     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
7035                                 DAG.getConstant(1, SL, MVT::i32));
7036     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
7037   }
7038   case Intrinsic::amdgcn_perm:
7039     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
7040                        Op.getOperand(2), Op.getOperand(3));
7041   case Intrinsic::amdgcn_reloc_constant: {
7042     Module *M = const_cast<Module *>(MF.getFunction().getParent());
7043     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
7044     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
7045     auto RelocSymbol = cast<GlobalVariable>(
7046         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
7047     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
7048                                             SIInstrInfo::MO_ABS32_LO);
7049     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
7050   }
7051   default:
7052     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7053             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7054       return lowerImage(Op, ImageDimIntr, DAG, false);
7055 
7056     return Op;
7057   }
7058 }
7059 
7060 /// Update \p MMO based on the offset inputs to an intrinsic.
7061 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset,
7062                             SDValue SOffset, SDValue Offset,
7063                             SDValue VIndex = SDValue()) {
7064   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
7065       !isa<ConstantSDNode>(Offset)) {
7066     // The combined offset is not known to be constant, so we cannot represent
7067     // it in the MMO. Give up.
7068     MMO->setValue((Value *)nullptr);
7069     return;
7070   }
7071 
7072   if (VIndex && (!isa<ConstantSDNode>(VIndex) ||
7073                  !cast<ConstantSDNode>(VIndex)->isZero())) {
7074     // The strided index component of the address is not known to be zero, so we
7075     // cannot represent it in the MMO. Give up.
7076     MMO->setValue((Value *)nullptr);
7077     return;
7078   }
7079 
7080   MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() +
7081                  cast<ConstantSDNode>(SOffset)->getSExtValue() +
7082                  cast<ConstantSDNode>(Offset)->getSExtValue());
7083 }
7084 
7085 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
7086                                                      SelectionDAG &DAG,
7087                                                      unsigned NewOpcode) const {
7088   SDLoc DL(Op);
7089 
7090   SDValue VData = Op.getOperand(2);
7091   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7092   SDValue Ops[] = {
7093     Op.getOperand(0), // Chain
7094     VData,            // vdata
7095     Op.getOperand(3), // rsrc
7096     DAG.getConstant(0, DL, MVT::i32), // vindex
7097     Offsets.first,    // voffset
7098     Op.getOperand(5), // soffset
7099     Offsets.second,   // offset
7100     Op.getOperand(6), // cachepolicy
7101     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7102   };
7103 
7104   auto *M = cast<MemSDNode>(Op);
7105   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
7106 
7107   EVT MemVT = VData.getValueType();
7108   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7109                                  M->getMemOperand());
7110 }
7111 
7112 // Return a value to use for the idxen operand by examining the vindex operand.
7113 static unsigned getIdxEn(SDValue VIndex) {
7114   if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex))
7115     // No need to set idxen if vindex is known to be zero.
7116     return VIndexC->getZExtValue() != 0;
7117   return 1;
7118 }
7119 
7120 SDValue
7121 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
7122                                                 unsigned NewOpcode) const {
7123   SDLoc DL(Op);
7124 
7125   SDValue VData = Op.getOperand(2);
7126   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7127   SDValue Ops[] = {
7128     Op.getOperand(0), // Chain
7129     VData,            // vdata
7130     Op.getOperand(3), // rsrc
7131     Op.getOperand(4), // vindex
7132     Offsets.first,    // voffset
7133     Op.getOperand(6), // soffset
7134     Offsets.second,   // offset
7135     Op.getOperand(7), // cachepolicy
7136     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7137   };
7138 
7139   auto *M = cast<MemSDNode>(Op);
7140   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7141 
7142   EVT MemVT = VData.getValueType();
7143   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7144                                  M->getMemOperand());
7145 }
7146 
7147 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
7148                                                  SelectionDAG &DAG) const {
7149   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7150   SDLoc DL(Op);
7151 
7152   switch (IntrID) {
7153   case Intrinsic::amdgcn_ds_ordered_add:
7154   case Intrinsic::amdgcn_ds_ordered_swap: {
7155     MemSDNode *M = cast<MemSDNode>(Op);
7156     SDValue Chain = M->getOperand(0);
7157     SDValue M0 = M->getOperand(2);
7158     SDValue Value = M->getOperand(3);
7159     unsigned IndexOperand = M->getConstantOperandVal(7);
7160     unsigned WaveRelease = M->getConstantOperandVal(8);
7161     unsigned WaveDone = M->getConstantOperandVal(9);
7162 
7163     unsigned OrderedCountIndex = IndexOperand & 0x3f;
7164     IndexOperand &= ~0x3f;
7165     unsigned CountDw = 0;
7166 
7167     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
7168       CountDw = (IndexOperand >> 24) & 0xf;
7169       IndexOperand &= ~(0xf << 24);
7170 
7171       if (CountDw < 1 || CountDw > 4) {
7172         report_fatal_error(
7173             "ds_ordered_count: dword count must be between 1 and 4");
7174       }
7175     }
7176 
7177     if (IndexOperand)
7178       report_fatal_error("ds_ordered_count: bad index operand");
7179 
7180     if (WaveDone && !WaveRelease)
7181       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
7182 
7183     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
7184     unsigned ShaderType =
7185         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
7186     unsigned Offset0 = OrderedCountIndex << 2;
7187     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
7188                        (Instruction << 4);
7189 
7190     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
7191       Offset1 |= (CountDw - 1) << 6;
7192 
7193     unsigned Offset = Offset0 | (Offset1 << 8);
7194 
7195     SDValue Ops[] = {
7196       Chain,
7197       Value,
7198       DAG.getTargetConstant(Offset, DL, MVT::i16),
7199       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
7200     };
7201     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
7202                                    M->getVTList(), Ops, M->getMemoryVT(),
7203                                    M->getMemOperand());
7204   }
7205   case Intrinsic::amdgcn_ds_fadd: {
7206     MemSDNode *M = cast<MemSDNode>(Op);
7207     unsigned Opc;
7208     switch (IntrID) {
7209     case Intrinsic::amdgcn_ds_fadd:
7210       Opc = ISD::ATOMIC_LOAD_FADD;
7211       break;
7212     }
7213 
7214     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
7215                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
7216                          M->getMemOperand());
7217   }
7218   case Intrinsic::amdgcn_atomic_inc:
7219   case Intrinsic::amdgcn_atomic_dec:
7220   case Intrinsic::amdgcn_ds_fmin:
7221   case Intrinsic::amdgcn_ds_fmax: {
7222     MemSDNode *M = cast<MemSDNode>(Op);
7223     unsigned Opc;
7224     switch (IntrID) {
7225     case Intrinsic::amdgcn_atomic_inc:
7226       Opc = AMDGPUISD::ATOMIC_INC;
7227       break;
7228     case Intrinsic::amdgcn_atomic_dec:
7229       Opc = AMDGPUISD::ATOMIC_DEC;
7230       break;
7231     case Intrinsic::amdgcn_ds_fmin:
7232       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
7233       break;
7234     case Intrinsic::amdgcn_ds_fmax:
7235       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
7236       break;
7237     default:
7238       llvm_unreachable("Unknown intrinsic!");
7239     }
7240     SDValue Ops[] = {
7241       M->getOperand(0), // Chain
7242       M->getOperand(2), // Ptr
7243       M->getOperand(3)  // Value
7244     };
7245 
7246     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
7247                                    M->getMemoryVT(), M->getMemOperand());
7248   }
7249   case Intrinsic::amdgcn_buffer_load:
7250   case Intrinsic::amdgcn_buffer_load_format: {
7251     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
7252     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7253     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7254     SDValue Ops[] = {
7255       Op.getOperand(0), // Chain
7256       Op.getOperand(2), // rsrc
7257       Op.getOperand(3), // vindex
7258       SDValue(),        // voffset -- will be set by setBufferOffsets
7259       SDValue(),        // soffset -- will be set by setBufferOffsets
7260       SDValue(),        // offset -- will be set by setBufferOffsets
7261       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7262       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7263     };
7264     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
7265 
7266     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
7267         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
7268 
7269     EVT VT = Op.getValueType();
7270     EVT IntVT = VT.changeTypeToInteger();
7271     auto *M = cast<MemSDNode>(Op);
7272     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7273     EVT LoadVT = Op.getValueType();
7274 
7275     if (LoadVT.getScalarType() == MVT::f16)
7276       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
7277                                  M, DAG, Ops);
7278 
7279     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
7280     if (LoadVT.getScalarType() == MVT::i8 ||
7281         LoadVT.getScalarType() == MVT::i16)
7282       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
7283 
7284     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
7285                                M->getMemOperand(), DAG);
7286   }
7287   case Intrinsic::amdgcn_raw_buffer_load:
7288   case Intrinsic::amdgcn_raw_buffer_load_format: {
7289     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
7290 
7291     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7292     SDValue Ops[] = {
7293       Op.getOperand(0), // Chain
7294       Op.getOperand(2), // rsrc
7295       DAG.getConstant(0, DL, MVT::i32), // vindex
7296       Offsets.first,    // voffset
7297       Op.getOperand(4), // soffset
7298       Offsets.second,   // offset
7299       Op.getOperand(5), // cachepolicy, swizzled buffer
7300       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7301     };
7302 
7303     auto *M = cast<MemSDNode>(Op);
7304     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]);
7305     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
7306   }
7307   case Intrinsic::amdgcn_struct_buffer_load:
7308   case Intrinsic::amdgcn_struct_buffer_load_format: {
7309     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
7310 
7311     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7312     SDValue Ops[] = {
7313       Op.getOperand(0), // Chain
7314       Op.getOperand(2), // rsrc
7315       Op.getOperand(3), // vindex
7316       Offsets.first,    // voffset
7317       Op.getOperand(5), // soffset
7318       Offsets.second,   // offset
7319       Op.getOperand(6), // cachepolicy, swizzled buffer
7320       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7321     };
7322 
7323     auto *M = cast<MemSDNode>(Op);
7324     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7325     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7326   }
7327   case Intrinsic::amdgcn_tbuffer_load: {
7328     MemSDNode *M = cast<MemSDNode>(Op);
7329     EVT LoadVT = Op.getValueType();
7330 
7331     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7332     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7333     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7334     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7335     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7336     SDValue Ops[] = {
7337       Op.getOperand(0),  // Chain
7338       Op.getOperand(2),  // rsrc
7339       Op.getOperand(3),  // vindex
7340       Op.getOperand(4),  // voffset
7341       Op.getOperand(5),  // soffset
7342       Op.getOperand(6),  // offset
7343       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7344       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7345       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7346     };
7347 
7348     if (LoadVT.getScalarType() == MVT::f16)
7349       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7350                                  M, DAG, Ops);
7351     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7352                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7353                                DAG);
7354   }
7355   case Intrinsic::amdgcn_raw_tbuffer_load: {
7356     MemSDNode *M = cast<MemSDNode>(Op);
7357     EVT LoadVT = Op.getValueType();
7358     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7359 
7360     SDValue Ops[] = {
7361       Op.getOperand(0),  // Chain
7362       Op.getOperand(2),  // rsrc
7363       DAG.getConstant(0, DL, MVT::i32), // vindex
7364       Offsets.first,     // voffset
7365       Op.getOperand(4),  // soffset
7366       Offsets.second,    // offset
7367       Op.getOperand(5),  // format
7368       Op.getOperand(6),  // cachepolicy, swizzled buffer
7369       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7370     };
7371 
7372     if (LoadVT.getScalarType() == MVT::f16)
7373       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7374                                  M, DAG, Ops);
7375     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7376                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7377                                DAG);
7378   }
7379   case Intrinsic::amdgcn_struct_tbuffer_load: {
7380     MemSDNode *M = cast<MemSDNode>(Op);
7381     EVT LoadVT = Op.getValueType();
7382     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7383 
7384     SDValue Ops[] = {
7385       Op.getOperand(0),  // Chain
7386       Op.getOperand(2),  // rsrc
7387       Op.getOperand(3),  // vindex
7388       Offsets.first,     // voffset
7389       Op.getOperand(5),  // soffset
7390       Offsets.second,    // offset
7391       Op.getOperand(6),  // format
7392       Op.getOperand(7),  // cachepolicy, swizzled buffer
7393       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7394     };
7395 
7396     if (LoadVT.getScalarType() == MVT::f16)
7397       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7398                                  M, DAG, Ops);
7399     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7400                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7401                                DAG);
7402   }
7403   case Intrinsic::amdgcn_buffer_atomic_swap:
7404   case Intrinsic::amdgcn_buffer_atomic_add:
7405   case Intrinsic::amdgcn_buffer_atomic_sub:
7406   case Intrinsic::amdgcn_buffer_atomic_csub:
7407   case Intrinsic::amdgcn_buffer_atomic_smin:
7408   case Intrinsic::amdgcn_buffer_atomic_umin:
7409   case Intrinsic::amdgcn_buffer_atomic_smax:
7410   case Intrinsic::amdgcn_buffer_atomic_umax:
7411   case Intrinsic::amdgcn_buffer_atomic_and:
7412   case Intrinsic::amdgcn_buffer_atomic_or:
7413   case Intrinsic::amdgcn_buffer_atomic_xor:
7414   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7415     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7416     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7417     SDValue Ops[] = {
7418       Op.getOperand(0), // Chain
7419       Op.getOperand(2), // vdata
7420       Op.getOperand(3), // rsrc
7421       Op.getOperand(4), // vindex
7422       SDValue(),        // voffset -- will be set by setBufferOffsets
7423       SDValue(),        // soffset -- will be set by setBufferOffsets
7424       SDValue(),        // offset -- will be set by setBufferOffsets
7425       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7426       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7427     };
7428     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7429 
7430     EVT VT = Op.getValueType();
7431 
7432     auto *M = cast<MemSDNode>(Op);
7433     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7434     unsigned Opcode = 0;
7435 
7436     switch (IntrID) {
7437     case Intrinsic::amdgcn_buffer_atomic_swap:
7438       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7439       break;
7440     case Intrinsic::amdgcn_buffer_atomic_add:
7441       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7442       break;
7443     case Intrinsic::amdgcn_buffer_atomic_sub:
7444       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7445       break;
7446     case Intrinsic::amdgcn_buffer_atomic_csub:
7447       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7448       break;
7449     case Intrinsic::amdgcn_buffer_atomic_smin:
7450       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7451       break;
7452     case Intrinsic::amdgcn_buffer_atomic_umin:
7453       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7454       break;
7455     case Intrinsic::amdgcn_buffer_atomic_smax:
7456       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7457       break;
7458     case Intrinsic::amdgcn_buffer_atomic_umax:
7459       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7460       break;
7461     case Intrinsic::amdgcn_buffer_atomic_and:
7462       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7463       break;
7464     case Intrinsic::amdgcn_buffer_atomic_or:
7465       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7466       break;
7467     case Intrinsic::amdgcn_buffer_atomic_xor:
7468       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7469       break;
7470     case Intrinsic::amdgcn_buffer_atomic_fadd:
7471       if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7472         DiagnosticInfoUnsupported
7473           NoFpRet(DAG.getMachineFunction().getFunction(),
7474                   "return versions of fp atomics not supported",
7475                   DL.getDebugLoc(), DS_Error);
7476         DAG.getContext()->diagnose(NoFpRet);
7477         return SDValue();
7478       }
7479       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7480       break;
7481     default:
7482       llvm_unreachable("unhandled atomic opcode");
7483     }
7484 
7485     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7486                                    M->getMemOperand());
7487   }
7488   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7489     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7490   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7491     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7492   case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7493     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7494   case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7495     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7496   case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7497     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7498   case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7499     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7500   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7501     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7502   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7503     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7504   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7505     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7506   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7507     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7508   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7509     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7510   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7511     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7512   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7513     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7514   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7515     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7516   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7517     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7518   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7519     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7520   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7521     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7522   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7523     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7524   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7525     return lowerStructBufferAtomicIntrin(Op, DAG,
7526                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7527   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7528     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7529   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7530     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7531   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7532     return lowerStructBufferAtomicIntrin(Op, DAG,
7533                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7534   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7535     return lowerStructBufferAtomicIntrin(Op, DAG,
7536                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7537   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7538     return lowerStructBufferAtomicIntrin(Op, DAG,
7539                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7540   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7541     return lowerStructBufferAtomicIntrin(Op, DAG,
7542                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7543   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7544     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7545   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7546     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7547   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7548     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7549   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7550     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7551   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7552     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7553 
7554   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7555     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7556     unsigned IdxEn = getIdxEn(Op.getOperand(5));
7557     SDValue Ops[] = {
7558       Op.getOperand(0), // Chain
7559       Op.getOperand(2), // src
7560       Op.getOperand(3), // cmp
7561       Op.getOperand(4), // rsrc
7562       Op.getOperand(5), // vindex
7563       SDValue(),        // voffset -- will be set by setBufferOffsets
7564       SDValue(),        // soffset -- will be set by setBufferOffsets
7565       SDValue(),        // offset -- will be set by setBufferOffsets
7566       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7567       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7568     };
7569     setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
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_raw_buffer_atomic_cmpswap: {
7579     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7580     SDValue Ops[] = {
7581       Op.getOperand(0), // Chain
7582       Op.getOperand(2), // src
7583       Op.getOperand(3), // cmp
7584       Op.getOperand(4), // rsrc
7585       DAG.getConstant(0, DL, MVT::i32), // vindex
7586       Offsets.first,    // voffset
7587       Op.getOperand(6), // soffset
7588       Offsets.second,   // offset
7589       Op.getOperand(7), // cachepolicy
7590       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7591     };
7592     EVT VT = Op.getValueType();
7593     auto *M = cast<MemSDNode>(Op);
7594     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]);
7595 
7596     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7597                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7598   }
7599   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7600     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7601     SDValue Ops[] = {
7602       Op.getOperand(0), // Chain
7603       Op.getOperand(2), // src
7604       Op.getOperand(3), // cmp
7605       Op.getOperand(4), // rsrc
7606       Op.getOperand(5), // vindex
7607       Offsets.first,    // voffset
7608       Op.getOperand(7), // soffset
7609       Offsets.second,   // offset
7610       Op.getOperand(8), // cachepolicy
7611       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7612     };
7613     EVT VT = Op.getValueType();
7614     auto *M = cast<MemSDNode>(Op);
7615     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7616 
7617     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7618                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7619   }
7620   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7621     MemSDNode *M = cast<MemSDNode>(Op);
7622     SDValue NodePtr = M->getOperand(2);
7623     SDValue RayExtent = M->getOperand(3);
7624     SDValue RayOrigin = M->getOperand(4);
7625     SDValue RayDir = M->getOperand(5);
7626     SDValue RayInvDir = M->getOperand(6);
7627     SDValue TDescr = M->getOperand(7);
7628 
7629     assert(NodePtr.getValueType() == MVT::i32 ||
7630            NodePtr.getValueType() == MVT::i64);
7631     assert(RayDir.getValueType() == MVT::v3f16 ||
7632            RayDir.getValueType() == MVT::v3f32);
7633 
7634     if (!Subtarget->hasGFX10_AEncoding()) {
7635       emitRemovedIntrinsicError(DAG, DL, Op.getValueType());
7636       return SDValue();
7637     }
7638 
7639     const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7640     const bool Is64 = NodePtr.getValueType() == MVT::i64;
7641     const unsigned NumVDataDwords = 4;
7642     const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
7643     const bool UseNSA = Subtarget->hasNSAEncoding() &&
7644                         NumVAddrDwords <= Subtarget->getNSAMaxSize();
7645     const unsigned BaseOpcodes[2][2] = {
7646         {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
7647         {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
7648          AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
7649     int Opcode;
7650     if (UseNSA) {
7651       Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7652                                      AMDGPU::MIMGEncGfx10NSA, NumVDataDwords,
7653                                      NumVAddrDwords);
7654     } else {
7655       Opcode = AMDGPU::getMIMGOpcode(
7656           BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords,
7657           PowerOf2Ceil(NumVAddrDwords));
7658     }
7659     assert(Opcode != -1);
7660 
7661     SmallVector<SDValue, 16> Ops;
7662 
7663     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7664       SmallVector<SDValue, 3> Lanes;
7665       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7666       if (Lanes[0].getValueSizeInBits() == 32) {
7667         for (unsigned I = 0; I < 3; ++I)
7668           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7669       } else {
7670         if (IsAligned) {
7671           Ops.push_back(
7672             DAG.getBitcast(MVT::i32,
7673                            DAG.getBuildVector(MVT::v2f16, DL,
7674                                               { Lanes[0], Lanes[1] })));
7675           Ops.push_back(Lanes[2]);
7676         } else {
7677           SDValue Elt0 = Ops.pop_back_val();
7678           Ops.push_back(
7679             DAG.getBitcast(MVT::i32,
7680                            DAG.getBuildVector(MVT::v2f16, DL,
7681                                               { Elt0, Lanes[0] })));
7682           Ops.push_back(
7683             DAG.getBitcast(MVT::i32,
7684                            DAG.getBuildVector(MVT::v2f16, DL,
7685                                               { Lanes[1], Lanes[2] })));
7686         }
7687       }
7688     };
7689 
7690     if (Is64)
7691       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7692     else
7693       Ops.push_back(NodePtr);
7694 
7695     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7696     packLanes(RayOrigin, true);
7697     packLanes(RayDir, true);
7698     packLanes(RayInvDir, false);
7699 
7700     if (!UseNSA) {
7701       // Build a single vector containing all the operands so far prepared.
7702       if (NumVAddrDwords > 8) {
7703         SDValue Undef = DAG.getUNDEF(MVT::i32);
7704         Ops.append(16 - Ops.size(), Undef);
7705       }
7706       assert(Ops.size() == 8 || Ops.size() == 16);
7707       SDValue MergedOps = DAG.getBuildVector(
7708           Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops);
7709       Ops.clear();
7710       Ops.push_back(MergedOps);
7711     }
7712 
7713     Ops.push_back(TDescr);
7714     if (IsA16)
7715       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7716     Ops.push_back(M->getChain());
7717 
7718     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7719     MachineMemOperand *MemRef = M->getMemOperand();
7720     DAG.setNodeMemRefs(NewNode, {MemRef});
7721     return SDValue(NewNode, 0);
7722   }
7723   case Intrinsic::amdgcn_global_atomic_fadd:
7724     if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7725       DiagnosticInfoUnsupported
7726         NoFpRet(DAG.getMachineFunction().getFunction(),
7727                 "return versions of fp atomics not supported",
7728                 DL.getDebugLoc(), DS_Error);
7729       DAG.getContext()->diagnose(NoFpRet);
7730       return SDValue();
7731     }
7732     LLVM_FALLTHROUGH;
7733   case Intrinsic::amdgcn_global_atomic_fmin:
7734   case Intrinsic::amdgcn_global_atomic_fmax:
7735   case Intrinsic::amdgcn_flat_atomic_fadd:
7736   case Intrinsic::amdgcn_flat_atomic_fmin:
7737   case Intrinsic::amdgcn_flat_atomic_fmax: {
7738     MemSDNode *M = cast<MemSDNode>(Op);
7739     SDValue Ops[] = {
7740       M->getOperand(0), // Chain
7741       M->getOperand(2), // Ptr
7742       M->getOperand(3)  // Value
7743     };
7744     unsigned Opcode = 0;
7745     switch (IntrID) {
7746     case Intrinsic::amdgcn_global_atomic_fadd:
7747     case Intrinsic::amdgcn_flat_atomic_fadd: {
7748       EVT VT = Op.getOperand(3).getValueType();
7749       return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7750                            DAG.getVTList(VT, MVT::Other), Ops,
7751                            M->getMemOperand());
7752     }
7753     case Intrinsic::amdgcn_global_atomic_fmin:
7754     case Intrinsic::amdgcn_flat_atomic_fmin: {
7755       Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7756       break;
7757     }
7758     case Intrinsic::amdgcn_global_atomic_fmax:
7759     case Intrinsic::amdgcn_flat_atomic_fmax: {
7760       Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7761       break;
7762     }
7763     default:
7764       llvm_unreachable("unhandled atomic opcode");
7765     }
7766     return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7767                                    M->getVTList(), Ops, M->getMemoryVT(),
7768                                    M->getMemOperand());
7769   }
7770   default:
7771 
7772     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7773             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7774       return lowerImage(Op, ImageDimIntr, DAG, true);
7775 
7776     return SDValue();
7777   }
7778 }
7779 
7780 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7781 // dwordx4 if on SI.
7782 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7783                                               SDVTList VTList,
7784                                               ArrayRef<SDValue> Ops, EVT MemVT,
7785                                               MachineMemOperand *MMO,
7786                                               SelectionDAG &DAG) const {
7787   EVT VT = VTList.VTs[0];
7788   EVT WidenedVT = VT;
7789   EVT WidenedMemVT = MemVT;
7790   if (!Subtarget->hasDwordx3LoadStores() &&
7791       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7792     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7793                                  WidenedVT.getVectorElementType(), 4);
7794     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7795                                     WidenedMemVT.getVectorElementType(), 4);
7796     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7797   }
7798 
7799   assert(VTList.NumVTs == 2);
7800   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7801 
7802   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7803                                        WidenedMemVT, MMO);
7804   if (WidenedVT != VT) {
7805     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7806                                DAG.getVectorIdxConstant(0, DL));
7807     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7808   }
7809   return NewOp;
7810 }
7811 
7812 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7813                                          bool ImageStore) const {
7814   EVT StoreVT = VData.getValueType();
7815 
7816   // No change for f16 and legal vector D16 types.
7817   if (!StoreVT.isVector())
7818     return VData;
7819 
7820   SDLoc DL(VData);
7821   unsigned NumElements = StoreVT.getVectorNumElements();
7822 
7823   if (Subtarget->hasUnpackedD16VMem()) {
7824     // We need to unpack the packed data to store.
7825     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7826     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7827 
7828     EVT EquivStoreVT =
7829         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7830     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7831     return DAG.UnrollVectorOp(ZExt.getNode());
7832   }
7833 
7834   // The sq block of gfx8.1 does not estimate register use correctly for d16
7835   // image store instructions. The data operand is computed as if it were not a
7836   // d16 image instruction.
7837   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7838     // Bitcast to i16
7839     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7840     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7841 
7842     // Decompose into scalars
7843     SmallVector<SDValue, 4> Elts;
7844     DAG.ExtractVectorElements(IntVData, Elts);
7845 
7846     // Group pairs of i16 into v2i16 and bitcast to i32
7847     SmallVector<SDValue, 4> PackedElts;
7848     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7849       SDValue Pair =
7850           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7851       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7852       PackedElts.push_back(IntPair);
7853     }
7854     if ((NumElements % 2) == 1) {
7855       // Handle v3i16
7856       unsigned I = Elts.size() / 2;
7857       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7858                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7859       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7860       PackedElts.push_back(IntPair);
7861     }
7862 
7863     // Pad using UNDEF
7864     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7865 
7866     // Build final vector
7867     EVT VecVT =
7868         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7869     return DAG.getBuildVector(VecVT, DL, PackedElts);
7870   }
7871 
7872   if (NumElements == 3) {
7873     EVT IntStoreVT =
7874         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7875     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7876 
7877     EVT WidenedStoreVT = EVT::getVectorVT(
7878         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7879     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7880                                          WidenedStoreVT.getStoreSizeInBits());
7881     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7882     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7883   }
7884 
7885   assert(isTypeLegal(StoreVT));
7886   return VData;
7887 }
7888 
7889 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7890                                               SelectionDAG &DAG) const {
7891   SDLoc DL(Op);
7892   SDValue Chain = Op.getOperand(0);
7893   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7894   MachineFunction &MF = DAG.getMachineFunction();
7895 
7896   switch (IntrinsicID) {
7897   case Intrinsic::amdgcn_exp_compr: {
7898     SDValue Src0 = Op.getOperand(4);
7899     SDValue Src1 = Op.getOperand(5);
7900     // Hack around illegal type on SI by directly selecting it.
7901     if (isTypeLegal(Src0.getValueType()))
7902       return SDValue();
7903 
7904     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7905     SDValue Undef = DAG.getUNDEF(MVT::f32);
7906     const SDValue Ops[] = {
7907       Op.getOperand(2), // tgt
7908       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7909       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7910       Undef, // src2
7911       Undef, // src3
7912       Op.getOperand(7), // vm
7913       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7914       Op.getOperand(3), // en
7915       Op.getOperand(0) // Chain
7916     };
7917 
7918     unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7919     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7920   }
7921   case Intrinsic::amdgcn_s_barrier: {
7922     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7923       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7924       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7925       if (WGSize <= ST.getWavefrontSize())
7926         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7927                                           Op.getOperand(0)), 0);
7928     }
7929     return SDValue();
7930   };
7931   case Intrinsic::amdgcn_tbuffer_store: {
7932     SDValue VData = Op.getOperand(2);
7933     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7934     if (IsD16)
7935       VData = handleD16VData(VData, DAG);
7936     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7937     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7938     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7939     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7940     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7941     SDValue Ops[] = {
7942       Chain,
7943       VData,             // vdata
7944       Op.getOperand(3),  // rsrc
7945       Op.getOperand(4),  // vindex
7946       Op.getOperand(5),  // voffset
7947       Op.getOperand(6),  // soffset
7948       Op.getOperand(7),  // offset
7949       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7950       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7951       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7952     };
7953     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7954                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7955     MemSDNode *M = cast<MemSDNode>(Op);
7956     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7957                                    M->getMemoryVT(), M->getMemOperand());
7958   }
7959 
7960   case Intrinsic::amdgcn_struct_tbuffer_store: {
7961     SDValue VData = Op.getOperand(2);
7962     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7963     if (IsD16)
7964       VData = handleD16VData(VData, DAG);
7965     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7966     SDValue Ops[] = {
7967       Chain,
7968       VData,             // vdata
7969       Op.getOperand(3),  // rsrc
7970       Op.getOperand(4),  // vindex
7971       Offsets.first,     // voffset
7972       Op.getOperand(6),  // soffset
7973       Offsets.second,    // offset
7974       Op.getOperand(7),  // format
7975       Op.getOperand(8),  // cachepolicy, swizzled buffer
7976       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7977     };
7978     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7979                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7980     MemSDNode *M = cast<MemSDNode>(Op);
7981     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7982                                    M->getMemoryVT(), M->getMemOperand());
7983   }
7984 
7985   case Intrinsic::amdgcn_raw_tbuffer_store: {
7986     SDValue VData = Op.getOperand(2);
7987     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7988     if (IsD16)
7989       VData = handleD16VData(VData, DAG);
7990     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7991     SDValue Ops[] = {
7992       Chain,
7993       VData,             // vdata
7994       Op.getOperand(3),  // rsrc
7995       DAG.getConstant(0, DL, MVT::i32), // vindex
7996       Offsets.first,     // voffset
7997       Op.getOperand(5),  // soffset
7998       Offsets.second,    // offset
7999       Op.getOperand(6),  // format
8000       Op.getOperand(7),  // cachepolicy, swizzled buffer
8001       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8002     };
8003     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
8004                            AMDGPUISD::TBUFFER_STORE_FORMAT;
8005     MemSDNode *M = cast<MemSDNode>(Op);
8006     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8007                                    M->getMemoryVT(), M->getMemOperand());
8008   }
8009 
8010   case Intrinsic::amdgcn_buffer_store:
8011   case Intrinsic::amdgcn_buffer_store_format: {
8012     SDValue VData = Op.getOperand(2);
8013     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8014     if (IsD16)
8015       VData = handleD16VData(VData, DAG);
8016     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
8017     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
8018     unsigned IdxEn = getIdxEn(Op.getOperand(4));
8019     SDValue Ops[] = {
8020       Chain,
8021       VData,
8022       Op.getOperand(3), // rsrc
8023       Op.getOperand(4), // vindex
8024       SDValue(), // voffset -- will be set by setBufferOffsets
8025       SDValue(), // soffset -- will be set by setBufferOffsets
8026       SDValue(), // offset -- will be set by setBufferOffsets
8027       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
8028       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
8029     };
8030     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
8031 
8032     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
8033                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8034     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8035     MemSDNode *M = cast<MemSDNode>(Op);
8036     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8037 
8038     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8039     EVT VDataType = VData.getValueType().getScalarType();
8040     if (VDataType == MVT::i8 || VDataType == MVT::i16)
8041       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8042 
8043     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8044                                    M->getMemoryVT(), M->getMemOperand());
8045   }
8046 
8047   case Intrinsic::amdgcn_raw_buffer_store:
8048   case Intrinsic::amdgcn_raw_buffer_store_format: {
8049     const bool IsFormat =
8050         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
8051 
8052     SDValue VData = Op.getOperand(2);
8053     EVT VDataVT = VData.getValueType();
8054     EVT EltType = VDataVT.getScalarType();
8055     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8056     if (IsD16) {
8057       VData = handleD16VData(VData, DAG);
8058       VDataVT = VData.getValueType();
8059     }
8060 
8061     if (!isTypeLegal(VDataVT)) {
8062       VData =
8063           DAG.getNode(ISD::BITCAST, DL,
8064                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8065     }
8066 
8067     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
8068     SDValue Ops[] = {
8069       Chain,
8070       VData,
8071       Op.getOperand(3), // rsrc
8072       DAG.getConstant(0, DL, MVT::i32), // vindex
8073       Offsets.first,    // voffset
8074       Op.getOperand(5), // soffset
8075       Offsets.second,   // offset
8076       Op.getOperand(6), // cachepolicy, swizzled buffer
8077       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8078     };
8079     unsigned Opc =
8080         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
8081     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8082     MemSDNode *M = cast<MemSDNode>(Op);
8083     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
8084 
8085     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8086     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8087       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
8088 
8089     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8090                                    M->getMemoryVT(), M->getMemOperand());
8091   }
8092 
8093   case Intrinsic::amdgcn_struct_buffer_store:
8094   case Intrinsic::amdgcn_struct_buffer_store_format: {
8095     const bool IsFormat =
8096         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
8097 
8098     SDValue VData = Op.getOperand(2);
8099     EVT VDataVT = VData.getValueType();
8100     EVT EltType = VDataVT.getScalarType();
8101     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8102 
8103     if (IsD16) {
8104       VData = handleD16VData(VData, DAG);
8105       VDataVT = VData.getValueType();
8106     }
8107 
8108     if (!isTypeLegal(VDataVT)) {
8109       VData =
8110           DAG.getNode(ISD::BITCAST, DL,
8111                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8112     }
8113 
8114     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
8115     SDValue Ops[] = {
8116       Chain,
8117       VData,
8118       Op.getOperand(3), // rsrc
8119       Op.getOperand(4), // vindex
8120       Offsets.first,    // voffset
8121       Op.getOperand(6), // soffset
8122       Offsets.second,   // offset
8123       Op.getOperand(7), // cachepolicy, swizzled buffer
8124       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8125     };
8126     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
8127                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8128     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8129     MemSDNode *M = cast<MemSDNode>(Op);
8130     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8131 
8132     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8133     EVT VDataType = VData.getValueType().getScalarType();
8134     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8135       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8136 
8137     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8138                                    M->getMemoryVT(), M->getMemOperand());
8139   }
8140   case Intrinsic::amdgcn_end_cf:
8141     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
8142                                       Op->getOperand(2), Chain), 0);
8143 
8144   default: {
8145     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
8146             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
8147       return lowerImage(Op, ImageDimIntr, DAG, true);
8148 
8149     return Op;
8150   }
8151   }
8152 }
8153 
8154 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
8155 // offset (the offset that is included in bounds checking and swizzling, to be
8156 // split between the instruction's voffset and immoffset fields) and soffset
8157 // (the offset that is excluded from bounds checking and swizzling, to go in
8158 // the instruction's soffset field).  This function takes the first kind of
8159 // offset and figures out how to split it between voffset and immoffset.
8160 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
8161     SDValue Offset, SelectionDAG &DAG) const {
8162   SDLoc DL(Offset);
8163   const unsigned MaxImm = 4095;
8164   SDValue N0 = Offset;
8165   ConstantSDNode *C1 = nullptr;
8166 
8167   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
8168     N0 = SDValue();
8169   else if (DAG.isBaseWithConstantOffset(N0)) {
8170     C1 = cast<ConstantSDNode>(N0.getOperand(1));
8171     N0 = N0.getOperand(0);
8172   }
8173 
8174   if (C1) {
8175     unsigned ImmOffset = C1->getZExtValue();
8176     // If the immediate value is too big for the immoffset field, put the value
8177     // and -4096 into the immoffset field so that the value that is copied/added
8178     // for the voffset field is a multiple of 4096, and it stands more chance
8179     // of being CSEd with the copy/add for another similar load/store.
8180     // However, do not do that rounding down to a multiple of 4096 if that is a
8181     // negative number, as it appears to be illegal to have a negative offset
8182     // in the vgpr, even if adding the immediate offset makes it positive.
8183     unsigned Overflow = ImmOffset & ~MaxImm;
8184     ImmOffset -= Overflow;
8185     if ((int32_t)Overflow < 0) {
8186       Overflow += ImmOffset;
8187       ImmOffset = 0;
8188     }
8189     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
8190     if (Overflow) {
8191       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
8192       if (!N0)
8193         N0 = OverflowVal;
8194       else {
8195         SDValue Ops[] = { N0, OverflowVal };
8196         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
8197       }
8198     }
8199   }
8200   if (!N0)
8201     N0 = DAG.getConstant(0, DL, MVT::i32);
8202   if (!C1)
8203     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
8204   return {N0, SDValue(C1, 0)};
8205 }
8206 
8207 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
8208 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
8209 // pointed to by Offsets.
8210 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
8211                                         SelectionDAG &DAG, SDValue *Offsets,
8212                                         Align Alignment) const {
8213   SDLoc DL(CombinedOffset);
8214   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
8215     uint32_t Imm = C->getZExtValue();
8216     uint32_t SOffset, ImmOffset;
8217     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
8218                                  Alignment)) {
8219       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
8220       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8221       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8222       return;
8223     }
8224   }
8225   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
8226     SDValue N0 = CombinedOffset.getOperand(0);
8227     SDValue N1 = CombinedOffset.getOperand(1);
8228     uint32_t SOffset, ImmOffset;
8229     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
8230     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
8231                                                 Subtarget, Alignment)) {
8232       Offsets[0] = N0;
8233       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8234       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8235       return;
8236     }
8237   }
8238   Offsets[0] = CombinedOffset;
8239   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
8240   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
8241 }
8242 
8243 // Handle 8 bit and 16 bit buffer loads
8244 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
8245                                                      EVT LoadVT, SDLoc DL,
8246                                                      ArrayRef<SDValue> Ops,
8247                                                      MemSDNode *M) const {
8248   EVT IntVT = LoadVT.changeTypeToInteger();
8249   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
8250          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
8251 
8252   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
8253   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
8254                                                Ops, IntVT,
8255                                                M->getMemOperand());
8256   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
8257   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
8258 
8259   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
8260 }
8261 
8262 // Handle 8 bit and 16 bit buffer stores
8263 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
8264                                                       EVT VDataType, SDLoc DL,
8265                                                       SDValue Ops[],
8266                                                       MemSDNode *M) const {
8267   if (VDataType == MVT::f16)
8268     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
8269 
8270   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
8271   Ops[1] = BufferStoreExt;
8272   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
8273                                  AMDGPUISD::BUFFER_STORE_SHORT;
8274   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
8275   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
8276                                      M->getMemOperand());
8277 }
8278 
8279 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
8280                                  ISD::LoadExtType ExtType, SDValue Op,
8281                                  const SDLoc &SL, EVT VT) {
8282   if (VT.bitsLT(Op.getValueType()))
8283     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
8284 
8285   switch (ExtType) {
8286   case ISD::SEXTLOAD:
8287     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
8288   case ISD::ZEXTLOAD:
8289     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
8290   case ISD::EXTLOAD:
8291     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
8292   case ISD::NON_EXTLOAD:
8293     return Op;
8294   }
8295 
8296   llvm_unreachable("invalid ext type");
8297 }
8298 
8299 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
8300   SelectionDAG &DAG = DCI.DAG;
8301   if (Ld->getAlignment() < 4 || Ld->isDivergent())
8302     return SDValue();
8303 
8304   // FIXME: Constant loads should all be marked invariant.
8305   unsigned AS = Ld->getAddressSpace();
8306   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
8307       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
8308       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
8309     return SDValue();
8310 
8311   // Don't do this early, since it may interfere with adjacent load merging for
8312   // illegal types. We can avoid losing alignment information for exotic types
8313   // pre-legalize.
8314   EVT MemVT = Ld->getMemoryVT();
8315   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
8316       MemVT.getSizeInBits() >= 32)
8317     return SDValue();
8318 
8319   SDLoc SL(Ld);
8320 
8321   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
8322          "unexpected vector extload");
8323 
8324   // TODO: Drop only high part of range.
8325   SDValue Ptr = Ld->getBasePtr();
8326   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
8327                                 MVT::i32, SL, Ld->getChain(), Ptr,
8328                                 Ld->getOffset(),
8329                                 Ld->getPointerInfo(), MVT::i32,
8330                                 Ld->getAlignment(),
8331                                 Ld->getMemOperand()->getFlags(),
8332                                 Ld->getAAInfo(),
8333                                 nullptr); // Drop ranges
8334 
8335   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
8336   if (MemVT.isFloatingPoint()) {
8337     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
8338            "unexpected fp extload");
8339     TruncVT = MemVT.changeTypeToInteger();
8340   }
8341 
8342   SDValue Cvt = NewLoad;
8343   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
8344     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
8345                       DAG.getValueType(TruncVT));
8346   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
8347              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
8348     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
8349   } else {
8350     assert(Ld->getExtensionType() == ISD::EXTLOAD);
8351   }
8352 
8353   EVT VT = Ld->getValueType(0);
8354   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8355 
8356   DCI.AddToWorklist(Cvt.getNode());
8357 
8358   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
8359   // the appropriate extension from the 32-bit load.
8360   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
8361   DCI.AddToWorklist(Cvt.getNode());
8362 
8363   // Handle conversion back to floating point if necessary.
8364   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8365 
8366   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8367 }
8368 
8369 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8370   SDLoc DL(Op);
8371   LoadSDNode *Load = cast<LoadSDNode>(Op);
8372   ISD::LoadExtType ExtType = Load->getExtensionType();
8373   EVT MemVT = Load->getMemoryVT();
8374 
8375   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8376     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8377       return SDValue();
8378 
8379     // FIXME: Copied from PPC
8380     // First, load into 32 bits, then truncate to 1 bit.
8381 
8382     SDValue Chain = Load->getChain();
8383     SDValue BasePtr = Load->getBasePtr();
8384     MachineMemOperand *MMO = Load->getMemOperand();
8385 
8386     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8387 
8388     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8389                                    BasePtr, RealMemVT, MMO);
8390 
8391     if (!MemVT.isVector()) {
8392       SDValue Ops[] = {
8393         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8394         NewLD.getValue(1)
8395       };
8396 
8397       return DAG.getMergeValues(Ops, DL);
8398     }
8399 
8400     SmallVector<SDValue, 3> Elts;
8401     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8402       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8403                                 DAG.getConstant(I, DL, MVT::i32));
8404 
8405       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8406     }
8407 
8408     SDValue Ops[] = {
8409       DAG.getBuildVector(MemVT, DL, Elts),
8410       NewLD.getValue(1)
8411     };
8412 
8413     return DAG.getMergeValues(Ops, DL);
8414   }
8415 
8416   if (!MemVT.isVector())
8417     return SDValue();
8418 
8419   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8420          "Custom lowering for non-i32 vectors hasn't been implemented.");
8421 
8422   unsigned Alignment = Load->getAlignment();
8423   unsigned AS = Load->getAddressSpace();
8424   if (Subtarget->hasLDSMisalignedBug() &&
8425       AS == AMDGPUAS::FLAT_ADDRESS &&
8426       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8427     return SplitVectorLoad(Op, DAG);
8428   }
8429 
8430   MachineFunction &MF = DAG.getMachineFunction();
8431   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8432   // If there is a possibility that flat instruction access scratch memory
8433   // then we need to use the same legalization rules we use for private.
8434   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8435       !Subtarget->hasMultiDwordFlatScratchAddressing())
8436     AS = MFI->hasFlatScratchInit() ?
8437          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8438 
8439   unsigned NumElements = MemVT.getVectorNumElements();
8440 
8441   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8442       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8443     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8444       if (MemVT.isPow2VectorType())
8445         return SDValue();
8446       return WidenOrSplitVectorLoad(Op, DAG);
8447     }
8448     // Non-uniform loads will be selected to MUBUF instructions, so they
8449     // have the same legalization requirements as global and private
8450     // loads.
8451     //
8452   }
8453 
8454   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8455       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8456       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8457     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8458         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8459         Alignment >= 4 && NumElements < 32) {
8460       if (MemVT.isPow2VectorType())
8461         return SDValue();
8462       return WidenOrSplitVectorLoad(Op, DAG);
8463     }
8464     // Non-uniform loads will be selected to MUBUF instructions, so they
8465     // have the same legalization requirements as global and private
8466     // loads.
8467     //
8468   }
8469   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8470       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8471       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8472       AS == AMDGPUAS::FLAT_ADDRESS) {
8473     if (NumElements > 4)
8474       return SplitVectorLoad(Op, DAG);
8475     // v3 loads not supported on SI.
8476     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8477       return WidenOrSplitVectorLoad(Op, DAG);
8478 
8479     // v3 and v4 loads are supported for private and global memory.
8480     return SDValue();
8481   }
8482   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8483     // Depending on the setting of the private_element_size field in the
8484     // resource descriptor, we can only make private accesses up to a certain
8485     // size.
8486     switch (Subtarget->getMaxPrivateElementSize()) {
8487     case 4: {
8488       SDValue Ops[2];
8489       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8490       return DAG.getMergeValues(Ops, DL);
8491     }
8492     case 8:
8493       if (NumElements > 2)
8494         return SplitVectorLoad(Op, DAG);
8495       return SDValue();
8496     case 16:
8497       // Same as global/flat
8498       if (NumElements > 4)
8499         return SplitVectorLoad(Op, DAG);
8500       // v3 loads not supported on SI.
8501       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8502         return WidenOrSplitVectorLoad(Op, DAG);
8503 
8504       return SDValue();
8505     default:
8506       llvm_unreachable("unsupported private_element_size");
8507     }
8508   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8509     // Use ds_read_b128 or ds_read_b96 when possible.
8510     if (Subtarget->hasDS96AndDS128() &&
8511         ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) ||
8512          MemVT.getStoreSize() == 12) &&
8513         allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8514                                            Load->getAlign()))
8515       return SDValue();
8516 
8517     if (NumElements > 2)
8518       return SplitVectorLoad(Op, DAG);
8519 
8520     // SI has a hardware bug in the LDS / GDS bounds checking: if the base
8521     // address is negative, then the instruction is incorrectly treated as
8522     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8523     // loads here to avoid emitting ds_read2_b32. We may re-combine the
8524     // load later in the SILoadStoreOptimizer.
8525     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
8526         NumElements == 2 && MemVT.getStoreSize() == 8 &&
8527         Load->getAlignment() < 8) {
8528       return SplitVectorLoad(Op, DAG);
8529     }
8530   }
8531 
8532   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8533                                       MemVT, *Load->getMemOperand())) {
8534     SDValue Ops[2];
8535     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8536     return DAG.getMergeValues(Ops, DL);
8537   }
8538 
8539   return SDValue();
8540 }
8541 
8542 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8543   EVT VT = Op.getValueType();
8544   if (VT.getSizeInBits() == 128)
8545     return splitTernaryVectorOp(Op, DAG);
8546 
8547   assert(VT.getSizeInBits() == 64);
8548 
8549   SDLoc DL(Op);
8550   SDValue Cond = Op.getOperand(0);
8551 
8552   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8553   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8554 
8555   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8556   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8557 
8558   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8559   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8560 
8561   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8562 
8563   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8564   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8565 
8566   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8567 
8568   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8569   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8570 }
8571 
8572 // Catch division cases where we can use shortcuts with rcp and rsq
8573 // instructions.
8574 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8575                                               SelectionDAG &DAG) const {
8576   SDLoc SL(Op);
8577   SDValue LHS = Op.getOperand(0);
8578   SDValue RHS = Op.getOperand(1);
8579   EVT VT = Op.getValueType();
8580   const SDNodeFlags Flags = Op->getFlags();
8581 
8582   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8583 
8584   // Without !fpmath accuracy information, we can't do more because we don't
8585   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8586   if (!AllowInaccurateRcp)
8587     return SDValue();
8588 
8589   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8590     if (CLHS->isExactlyValue(1.0)) {
8591       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8592       // the CI documentation has a worst case error of 1 ulp.
8593       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8594       // use it as long as we aren't trying to use denormals.
8595       //
8596       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8597 
8598       // 1.0 / sqrt(x) -> rsq(x)
8599 
8600       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8601       // error seems really high at 2^29 ULP.
8602       if (RHS.getOpcode() == ISD::FSQRT)
8603         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8604 
8605       // 1.0 / x -> rcp(x)
8606       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8607     }
8608 
8609     // Same as for 1.0, but expand the sign out of the constant.
8610     if (CLHS->isExactlyValue(-1.0)) {
8611       // -1.0 / x -> rcp (fneg x)
8612       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8613       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8614     }
8615   }
8616 
8617   // Turn into multiply by the reciprocal.
8618   // x / y -> x * (1.0 / y)
8619   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8620   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8621 }
8622 
8623 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8624                                                 SelectionDAG &DAG) const {
8625   SDLoc SL(Op);
8626   SDValue X = Op.getOperand(0);
8627   SDValue Y = Op.getOperand(1);
8628   EVT VT = Op.getValueType();
8629   const SDNodeFlags Flags = Op->getFlags();
8630 
8631   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8632                             DAG.getTarget().Options.UnsafeFPMath;
8633   if (!AllowInaccurateDiv)
8634     return SDValue();
8635 
8636   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8637   SDValue One = DAG.getConstantFP(1.0, SL, VT);
8638 
8639   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8640   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8641 
8642   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8643   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8644   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8645   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8646   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8647   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8648 }
8649 
8650 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8651                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8652                           SDNodeFlags Flags) {
8653   if (GlueChain->getNumValues() <= 1) {
8654     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8655   }
8656 
8657   assert(GlueChain->getNumValues() == 3);
8658 
8659   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8660   switch (Opcode) {
8661   default: llvm_unreachable("no chain equivalent for opcode");
8662   case ISD::FMUL:
8663     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8664     break;
8665   }
8666 
8667   return DAG.getNode(Opcode, SL, VTList,
8668                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8669                      Flags);
8670 }
8671 
8672 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8673                            EVT VT, SDValue A, SDValue B, SDValue C,
8674                            SDValue GlueChain, SDNodeFlags Flags) {
8675   if (GlueChain->getNumValues() <= 1) {
8676     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8677   }
8678 
8679   assert(GlueChain->getNumValues() == 3);
8680 
8681   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8682   switch (Opcode) {
8683   default: llvm_unreachable("no chain equivalent for opcode");
8684   case ISD::FMA:
8685     Opcode = AMDGPUISD::FMA_W_CHAIN;
8686     break;
8687   }
8688 
8689   return DAG.getNode(Opcode, SL, VTList,
8690                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8691                      Flags);
8692 }
8693 
8694 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8695   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8696     return FastLowered;
8697 
8698   SDLoc SL(Op);
8699   SDValue Src0 = Op.getOperand(0);
8700   SDValue Src1 = Op.getOperand(1);
8701 
8702   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8703   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8704 
8705   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8706   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8707 
8708   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8709   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8710 
8711   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8712 }
8713 
8714 // Faster 2.5 ULP division that does not support denormals.
8715 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8716   SDLoc SL(Op);
8717   SDValue LHS = Op.getOperand(1);
8718   SDValue RHS = Op.getOperand(2);
8719 
8720   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8721 
8722   const APFloat K0Val(BitsToFloat(0x6f800000));
8723   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8724 
8725   const APFloat K1Val(BitsToFloat(0x2f800000));
8726   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8727 
8728   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8729 
8730   EVT SetCCVT =
8731     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8732 
8733   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8734 
8735   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8736 
8737   // TODO: Should this propagate fast-math-flags?
8738   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8739 
8740   // rcp does not support denormals.
8741   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8742 
8743   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8744 
8745   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8746 }
8747 
8748 // Returns immediate value for setting the F32 denorm mode when using the
8749 // S_DENORM_MODE instruction.
8750 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8751                                     const SDLoc &SL, const GCNSubtarget *ST) {
8752   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8753   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8754                                 ? FP_DENORM_FLUSH_NONE
8755                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8756 
8757   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8758   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8759 }
8760 
8761 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8762   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8763     return FastLowered;
8764 
8765   // The selection matcher assumes anything with a chain selecting to a
8766   // mayRaiseFPException machine instruction. Since we're introducing a chain
8767   // here, we need to explicitly report nofpexcept for the regular fdiv
8768   // lowering.
8769   SDNodeFlags Flags = Op->getFlags();
8770   Flags.setNoFPExcept(true);
8771 
8772   SDLoc SL(Op);
8773   SDValue LHS = Op.getOperand(0);
8774   SDValue RHS = Op.getOperand(1);
8775 
8776   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8777 
8778   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8779 
8780   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8781                                           {RHS, RHS, LHS}, Flags);
8782   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8783                                         {LHS, RHS, LHS}, Flags);
8784 
8785   // Denominator is scaled to not be denormal, so using rcp is ok.
8786   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8787                                   DenominatorScaled, Flags);
8788   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8789                                      DenominatorScaled, Flags);
8790 
8791   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8792                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8793                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8794   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8795 
8796   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8797 
8798   if (!HasFP32Denormals) {
8799     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8800     // lowering. The chain dependence is insufficient, and we need glue. We do
8801     // not need the glue variants in a strictfp function.
8802 
8803     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8804 
8805     SDNode *EnableDenorm;
8806     if (Subtarget->hasDenormModeInst()) {
8807       const SDValue EnableDenormValue =
8808           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8809 
8810       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8811                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8812     } else {
8813       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8814                                                         SL, MVT::i32);
8815       EnableDenorm =
8816           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8817                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8818     }
8819 
8820     SDValue Ops[3] = {
8821       NegDivScale0,
8822       SDValue(EnableDenorm, 0),
8823       SDValue(EnableDenorm, 1)
8824     };
8825 
8826     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8827   }
8828 
8829   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8830                              ApproxRcp, One, NegDivScale0, Flags);
8831 
8832   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8833                              ApproxRcp, Fma0, Flags);
8834 
8835   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8836                            Fma1, Fma1, Flags);
8837 
8838   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8839                              NumeratorScaled, Mul, Flags);
8840 
8841   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8842                              Fma2, Fma1, Mul, Fma2, Flags);
8843 
8844   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8845                              NumeratorScaled, Fma3, Flags);
8846 
8847   if (!HasFP32Denormals) {
8848     SDNode *DisableDenorm;
8849     if (Subtarget->hasDenormModeInst()) {
8850       const SDValue DisableDenormValue =
8851           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8852 
8853       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8854                                   Fma4.getValue(1), DisableDenormValue,
8855                                   Fma4.getValue(2)).getNode();
8856     } else {
8857       const SDValue DisableDenormValue =
8858           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8859 
8860       DisableDenorm = DAG.getMachineNode(
8861           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8862           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8863     }
8864 
8865     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8866                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8867     DAG.setRoot(OutputChain);
8868   }
8869 
8870   SDValue Scale = NumeratorScaled.getValue(1);
8871   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8872                              {Fma4, Fma1, Fma3, Scale}, Flags);
8873 
8874   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8875 }
8876 
8877 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8878   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
8879     return FastLowered;
8880 
8881   SDLoc SL(Op);
8882   SDValue X = Op.getOperand(0);
8883   SDValue Y = Op.getOperand(1);
8884 
8885   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8886 
8887   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8888 
8889   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8890 
8891   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8892 
8893   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8894 
8895   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8896 
8897   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8898 
8899   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8900 
8901   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8902 
8903   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8904   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8905 
8906   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8907                              NegDivScale0, Mul, DivScale1);
8908 
8909   SDValue Scale;
8910 
8911   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8912     // Workaround a hardware bug on SI where the condition output from div_scale
8913     // is not usable.
8914 
8915     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8916 
8917     // Figure out if the scale to use for div_fmas.
8918     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8919     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8920     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8921     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8922 
8923     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8924     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8925 
8926     SDValue Scale0Hi
8927       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8928     SDValue Scale1Hi
8929       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8930 
8931     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8932     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8933     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8934   } else {
8935     Scale = DivScale1.getValue(1);
8936   }
8937 
8938   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8939                              Fma4, Fma3, Mul, Scale);
8940 
8941   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8942 }
8943 
8944 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8945   EVT VT = Op.getValueType();
8946 
8947   if (VT == MVT::f32)
8948     return LowerFDIV32(Op, DAG);
8949 
8950   if (VT == MVT::f64)
8951     return LowerFDIV64(Op, DAG);
8952 
8953   if (VT == MVT::f16)
8954     return LowerFDIV16(Op, DAG);
8955 
8956   llvm_unreachable("Unexpected type for fdiv");
8957 }
8958 
8959 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8960   SDLoc DL(Op);
8961   StoreSDNode *Store = cast<StoreSDNode>(Op);
8962   EVT VT = Store->getMemoryVT();
8963 
8964   if (VT == MVT::i1) {
8965     return DAG.getTruncStore(Store->getChain(), DL,
8966        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8967        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8968   }
8969 
8970   assert(VT.isVector() &&
8971          Store->getValue().getValueType().getScalarType() == MVT::i32);
8972 
8973   unsigned AS = Store->getAddressSpace();
8974   if (Subtarget->hasLDSMisalignedBug() &&
8975       AS == AMDGPUAS::FLAT_ADDRESS &&
8976       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8977     return SplitVectorStore(Op, DAG);
8978   }
8979 
8980   MachineFunction &MF = DAG.getMachineFunction();
8981   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8982   // If there is a possibility that flat instruction access scratch memory
8983   // then we need to use the same legalization rules we use for private.
8984   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8985       !Subtarget->hasMultiDwordFlatScratchAddressing())
8986     AS = MFI->hasFlatScratchInit() ?
8987          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8988 
8989   unsigned NumElements = VT.getVectorNumElements();
8990   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8991       AS == AMDGPUAS::FLAT_ADDRESS) {
8992     if (NumElements > 4)
8993       return SplitVectorStore(Op, DAG);
8994     // v3 stores not supported on SI.
8995     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8996       return SplitVectorStore(Op, DAG);
8997 
8998     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8999                                         VT, *Store->getMemOperand()))
9000       return expandUnalignedStore(Store, DAG);
9001 
9002     return SDValue();
9003   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
9004     switch (Subtarget->getMaxPrivateElementSize()) {
9005     case 4:
9006       return scalarizeVectorStore(Store, DAG);
9007     case 8:
9008       if (NumElements > 2)
9009         return SplitVectorStore(Op, DAG);
9010       return SDValue();
9011     case 16:
9012       if (NumElements > 4 ||
9013           (NumElements == 3 && !Subtarget->enableFlatScratch()))
9014         return SplitVectorStore(Op, DAG);
9015       return SDValue();
9016     default:
9017       llvm_unreachable("unsupported private_element_size");
9018     }
9019   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
9020     // Use ds_write_b128 or ds_write_b96 when possible.
9021     if (Subtarget->hasDS96AndDS128() &&
9022         ((Subtarget->useDS128() && VT.getStoreSize() == 16) ||
9023          (VT.getStoreSize() == 12)) &&
9024         allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
9025                                            Store->getAlign()))
9026       return SDValue();
9027 
9028     if (NumElements > 2)
9029       return SplitVectorStore(Op, DAG);
9030 
9031     // SI has a hardware bug in the LDS / GDS bounds checking: if the base
9032     // address is negative, then the instruction is incorrectly treated as
9033     // out-of-bounds even if base + offsets is in bounds. Split vectorized
9034     // stores here to avoid emitting ds_write2_b32. We may re-combine the
9035     // store later in the SILoadStoreOptimizer.
9036     if (!Subtarget->hasUsableDSOffset() &&
9037         NumElements == 2 && VT.getStoreSize() == 8 &&
9038         Store->getAlignment() < 8) {
9039       return SplitVectorStore(Op, DAG);
9040     }
9041 
9042     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
9043                                         VT, *Store->getMemOperand())) {
9044       if (VT.isVector())
9045         return SplitVectorStore(Op, DAG);
9046       return expandUnalignedStore(Store, DAG);
9047     }
9048 
9049     return SDValue();
9050   } else {
9051     llvm_unreachable("unhandled address space");
9052   }
9053 }
9054 
9055 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
9056   SDLoc DL(Op);
9057   EVT VT = Op.getValueType();
9058   SDValue Arg = Op.getOperand(0);
9059   SDValue TrigVal;
9060 
9061   // Propagate fast-math flags so that the multiply we introduce can be folded
9062   // if Arg is already the result of a multiply by constant.
9063   auto Flags = Op->getFlags();
9064 
9065   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
9066 
9067   if (Subtarget->hasTrigReducedRange()) {
9068     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9069     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
9070   } else {
9071     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9072   }
9073 
9074   switch (Op.getOpcode()) {
9075   case ISD::FCOS:
9076     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
9077   case ISD::FSIN:
9078     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
9079   default:
9080     llvm_unreachable("Wrong trig opcode");
9081   }
9082 }
9083 
9084 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9085   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
9086   assert(AtomicNode->isCompareAndSwap());
9087   unsigned AS = AtomicNode->getAddressSpace();
9088 
9089   // No custom lowering required for local address space
9090   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
9091     return Op;
9092 
9093   // Non-local address space requires custom lowering for atomic compare
9094   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
9095   SDLoc DL(Op);
9096   SDValue ChainIn = Op.getOperand(0);
9097   SDValue Addr = Op.getOperand(1);
9098   SDValue Old = Op.getOperand(2);
9099   SDValue New = Op.getOperand(3);
9100   EVT VT = Op.getValueType();
9101   MVT SimpleVT = VT.getSimpleVT();
9102   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
9103 
9104   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
9105   SDValue Ops[] = { ChainIn, Addr, NewOld };
9106 
9107   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
9108                                  Ops, VT, AtomicNode->getMemOperand());
9109 }
9110 
9111 //===----------------------------------------------------------------------===//
9112 // Custom DAG optimizations
9113 //===----------------------------------------------------------------------===//
9114 
9115 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
9116                                                      DAGCombinerInfo &DCI) const {
9117   EVT VT = N->getValueType(0);
9118   EVT ScalarVT = VT.getScalarType();
9119   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
9120     return SDValue();
9121 
9122   SelectionDAG &DAG = DCI.DAG;
9123   SDLoc DL(N);
9124 
9125   SDValue Src = N->getOperand(0);
9126   EVT SrcVT = Src.getValueType();
9127 
9128   // TODO: We could try to match extracting the higher bytes, which would be
9129   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
9130   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
9131   // about in practice.
9132   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
9133     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
9134       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
9135       DCI.AddToWorklist(Cvt.getNode());
9136 
9137       // For the f16 case, fold to a cast to f32 and then cast back to f16.
9138       if (ScalarVT != MVT::f32) {
9139         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
9140                           DAG.getTargetConstant(0, DL, MVT::i32));
9141       }
9142       return Cvt;
9143     }
9144   }
9145 
9146   return SDValue();
9147 }
9148 
9149 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
9150 
9151 // This is a variant of
9152 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
9153 //
9154 // The normal DAG combiner will do this, but only if the add has one use since
9155 // that would increase the number of instructions.
9156 //
9157 // This prevents us from seeing a constant offset that can be folded into a
9158 // memory instruction's addressing mode. If we know the resulting add offset of
9159 // a pointer can be folded into an addressing offset, we can replace the pointer
9160 // operand with the add of new constant offset. This eliminates one of the uses,
9161 // and may allow the remaining use to also be simplified.
9162 //
9163 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
9164                                                unsigned AddrSpace,
9165                                                EVT MemVT,
9166                                                DAGCombinerInfo &DCI) const {
9167   SDValue N0 = N->getOperand(0);
9168   SDValue N1 = N->getOperand(1);
9169 
9170   // We only do this to handle cases where it's profitable when there are
9171   // multiple uses of the add, so defer to the standard combine.
9172   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
9173       N0->hasOneUse())
9174     return SDValue();
9175 
9176   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
9177   if (!CN1)
9178     return SDValue();
9179 
9180   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9181   if (!CAdd)
9182     return SDValue();
9183 
9184   // If the resulting offset is too large, we can't fold it into the addressing
9185   // mode offset.
9186   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
9187   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
9188 
9189   AddrMode AM;
9190   AM.HasBaseReg = true;
9191   AM.BaseOffs = Offset.getSExtValue();
9192   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
9193     return SDValue();
9194 
9195   SelectionDAG &DAG = DCI.DAG;
9196   SDLoc SL(N);
9197   EVT VT = N->getValueType(0);
9198 
9199   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
9200   SDValue COffset = DAG.getConstant(Offset, SL, VT);
9201 
9202   SDNodeFlags Flags;
9203   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
9204                           (N0.getOpcode() == ISD::OR ||
9205                            N0->getFlags().hasNoUnsignedWrap()));
9206 
9207   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
9208 }
9209 
9210 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
9211 /// by the chain and intrinsic ID. Theoretically we would also need to check the
9212 /// specific intrinsic, but they all place the pointer operand first.
9213 static unsigned getBasePtrIndex(const MemSDNode *N) {
9214   switch (N->getOpcode()) {
9215   case ISD::STORE:
9216   case ISD::INTRINSIC_W_CHAIN:
9217   case ISD::INTRINSIC_VOID:
9218     return 2;
9219   default:
9220     return 1;
9221   }
9222 }
9223 
9224 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
9225                                                   DAGCombinerInfo &DCI) const {
9226   SelectionDAG &DAG = DCI.DAG;
9227   SDLoc SL(N);
9228 
9229   unsigned PtrIdx = getBasePtrIndex(N);
9230   SDValue Ptr = N->getOperand(PtrIdx);
9231 
9232   // TODO: We could also do this for multiplies.
9233   if (Ptr.getOpcode() == ISD::SHL) {
9234     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
9235                                           N->getMemoryVT(), DCI);
9236     if (NewPtr) {
9237       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
9238 
9239       NewOps[PtrIdx] = NewPtr;
9240       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
9241     }
9242   }
9243 
9244   return SDValue();
9245 }
9246 
9247 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
9248   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
9249          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
9250          (Opc == ISD::XOR && Val == 0);
9251 }
9252 
9253 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
9254 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
9255 // integer combine opportunities since most 64-bit operations are decomposed
9256 // this way.  TODO: We won't want this for SALU especially if it is an inline
9257 // immediate.
9258 SDValue SITargetLowering::splitBinaryBitConstantOp(
9259   DAGCombinerInfo &DCI,
9260   const SDLoc &SL,
9261   unsigned Opc, SDValue LHS,
9262   const ConstantSDNode *CRHS) const {
9263   uint64_t Val = CRHS->getZExtValue();
9264   uint32_t ValLo = Lo_32(Val);
9265   uint32_t ValHi = Hi_32(Val);
9266   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9267 
9268     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
9269          bitOpWithConstantIsReducible(Opc, ValHi)) ||
9270         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
9271     // If we need to materialize a 64-bit immediate, it will be split up later
9272     // anyway. Avoid creating the harder to understand 64-bit immediate
9273     // materialization.
9274     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
9275   }
9276 
9277   return SDValue();
9278 }
9279 
9280 // Returns true if argument is a boolean value which is not serialized into
9281 // memory or argument and does not require v_cndmask_b32 to be deserialized.
9282 static bool isBoolSGPR(SDValue V) {
9283   if (V.getValueType() != MVT::i1)
9284     return false;
9285   switch (V.getOpcode()) {
9286   default:
9287     break;
9288   case ISD::SETCC:
9289   case AMDGPUISD::FP_CLASS:
9290     return true;
9291   case ISD::AND:
9292   case ISD::OR:
9293   case ISD::XOR:
9294     return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
9295   }
9296   return false;
9297 }
9298 
9299 // If a constant has all zeroes or all ones within each byte return it.
9300 // Otherwise return 0.
9301 static uint32_t getConstantPermuteMask(uint32_t C) {
9302   // 0xff for any zero byte in the mask
9303   uint32_t ZeroByteMask = 0;
9304   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
9305   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
9306   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
9307   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
9308   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
9309   if ((NonZeroByteMask & C) != NonZeroByteMask)
9310     return 0; // Partial bytes selected.
9311   return C;
9312 }
9313 
9314 // Check if a node selects whole bytes from its operand 0 starting at a byte
9315 // boundary while masking the rest. Returns select mask as in the v_perm_b32
9316 // or -1 if not succeeded.
9317 // Note byte select encoding:
9318 // value 0-3 selects corresponding source byte;
9319 // value 0xc selects zero;
9320 // value 0xff selects 0xff.
9321 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
9322   assert(V.getValueSizeInBits() == 32);
9323 
9324   if (V.getNumOperands() != 2)
9325     return ~0;
9326 
9327   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
9328   if (!N1)
9329     return ~0;
9330 
9331   uint32_t C = N1->getZExtValue();
9332 
9333   switch (V.getOpcode()) {
9334   default:
9335     break;
9336   case ISD::AND:
9337     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9338       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
9339     }
9340     break;
9341 
9342   case ISD::OR:
9343     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9344       return (0x03020100 & ~ConstMask) | ConstMask;
9345     }
9346     break;
9347 
9348   case ISD::SHL:
9349     if (C % 8)
9350       return ~0;
9351 
9352     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
9353 
9354   case ISD::SRL:
9355     if (C % 8)
9356       return ~0;
9357 
9358     return uint32_t(0x0c0c0c0c03020100ull >> C);
9359   }
9360 
9361   return ~0;
9362 }
9363 
9364 SDValue SITargetLowering::performAndCombine(SDNode *N,
9365                                             DAGCombinerInfo &DCI) const {
9366   if (DCI.isBeforeLegalize())
9367     return SDValue();
9368 
9369   SelectionDAG &DAG = DCI.DAG;
9370   EVT VT = N->getValueType(0);
9371   SDValue LHS = N->getOperand(0);
9372   SDValue RHS = N->getOperand(1);
9373 
9374 
9375   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9376   if (VT == MVT::i64 && CRHS) {
9377     if (SDValue Split
9378         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9379       return Split;
9380   }
9381 
9382   if (CRHS && VT == MVT::i32) {
9383     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9384     // nb = number of trailing zeroes in mask
9385     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9386     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9387     uint64_t Mask = CRHS->getZExtValue();
9388     unsigned Bits = countPopulation(Mask);
9389     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9390         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9391       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9392         unsigned Shift = CShift->getZExtValue();
9393         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9394         unsigned Offset = NB + Shift;
9395         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9396           SDLoc SL(N);
9397           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9398                                     LHS->getOperand(0),
9399                                     DAG.getConstant(Offset, SL, MVT::i32),
9400                                     DAG.getConstant(Bits, SL, MVT::i32));
9401           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9402           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9403                                     DAG.getValueType(NarrowVT));
9404           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9405                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9406           return Shl;
9407         }
9408       }
9409     }
9410 
9411     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9412     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9413         isa<ConstantSDNode>(LHS.getOperand(2))) {
9414       uint32_t Sel = getConstantPermuteMask(Mask);
9415       if (!Sel)
9416         return SDValue();
9417 
9418       // Select 0xc for all zero bytes
9419       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9420       SDLoc DL(N);
9421       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9422                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9423     }
9424   }
9425 
9426   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9427   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9428   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9429     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9430     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9431 
9432     SDValue X = LHS.getOperand(0);
9433     SDValue Y = RHS.getOperand(0);
9434     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9435       return SDValue();
9436 
9437     if (LCC == ISD::SETO) {
9438       if (X != LHS.getOperand(1))
9439         return SDValue();
9440 
9441       if (RCC == ISD::SETUNE) {
9442         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9443         if (!C1 || !C1->isInfinity() || C1->isNegative())
9444           return SDValue();
9445 
9446         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9447                               SIInstrFlags::N_SUBNORMAL |
9448                               SIInstrFlags::N_ZERO |
9449                               SIInstrFlags::P_ZERO |
9450                               SIInstrFlags::P_SUBNORMAL |
9451                               SIInstrFlags::P_NORMAL;
9452 
9453         static_assert(((~(SIInstrFlags::S_NAN |
9454                           SIInstrFlags::Q_NAN |
9455                           SIInstrFlags::N_INFINITY |
9456                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9457                       "mask not equal");
9458 
9459         SDLoc DL(N);
9460         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9461                            X, DAG.getConstant(Mask, DL, MVT::i32));
9462       }
9463     }
9464   }
9465 
9466   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9467     std::swap(LHS, RHS);
9468 
9469   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9470       RHS.hasOneUse()) {
9471     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9472     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9473     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9474     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9475     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9476         (RHS.getOperand(0) == LHS.getOperand(0) &&
9477          LHS.getOperand(0) == LHS.getOperand(1))) {
9478       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9479       unsigned NewMask = LCC == ISD::SETO ?
9480         Mask->getZExtValue() & ~OrdMask :
9481         Mask->getZExtValue() & OrdMask;
9482 
9483       SDLoc DL(N);
9484       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9485                          DAG.getConstant(NewMask, DL, MVT::i32));
9486     }
9487   }
9488 
9489   if (VT == MVT::i32 &&
9490       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9491     // and x, (sext cc from i1) => select cc, x, 0
9492     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9493       std::swap(LHS, RHS);
9494     if (isBoolSGPR(RHS.getOperand(0)))
9495       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9496                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9497   }
9498 
9499   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9500   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9501   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9502       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9503     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9504     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9505     if (LHSMask != ~0u && RHSMask != ~0u) {
9506       // Canonicalize the expression in an attempt to have fewer unique masks
9507       // and therefore fewer registers used to hold the masks.
9508       if (LHSMask > RHSMask) {
9509         std::swap(LHSMask, RHSMask);
9510         std::swap(LHS, RHS);
9511       }
9512 
9513       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9514       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9515       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9516       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9517 
9518       // Check of we need to combine values from two sources within a byte.
9519       if (!(LHSUsedLanes & RHSUsedLanes) &&
9520           // If we select high and lower word keep it for SDWA.
9521           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9522           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9523         // Each byte in each mask is either selector mask 0-3, or has higher
9524         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9525         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9526         // mask which is not 0xff wins. By anding both masks we have a correct
9527         // result except that 0x0c shall be corrected to give 0x0c only.
9528         uint32_t Mask = LHSMask & RHSMask;
9529         for (unsigned I = 0; I < 32; I += 8) {
9530           uint32_t ByteSel = 0xff << I;
9531           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9532             Mask &= (0x0c << I) & 0xffffffff;
9533         }
9534 
9535         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9536         // or 0x0c.
9537         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9538         SDLoc DL(N);
9539 
9540         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9541                            LHS.getOperand(0), RHS.getOperand(0),
9542                            DAG.getConstant(Sel, DL, MVT::i32));
9543       }
9544     }
9545   }
9546 
9547   return SDValue();
9548 }
9549 
9550 SDValue SITargetLowering::performOrCombine(SDNode *N,
9551                                            DAGCombinerInfo &DCI) const {
9552   SelectionDAG &DAG = DCI.DAG;
9553   SDValue LHS = N->getOperand(0);
9554   SDValue RHS = N->getOperand(1);
9555 
9556   EVT VT = N->getValueType(0);
9557   if (VT == MVT::i1) {
9558     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9559     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9560         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9561       SDValue Src = LHS.getOperand(0);
9562       if (Src != RHS.getOperand(0))
9563         return SDValue();
9564 
9565       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9566       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9567       if (!CLHS || !CRHS)
9568         return SDValue();
9569 
9570       // Only 10 bits are used.
9571       static const uint32_t MaxMask = 0x3ff;
9572 
9573       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9574       SDLoc DL(N);
9575       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9576                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9577     }
9578 
9579     return SDValue();
9580   }
9581 
9582   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9583   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9584       LHS.getOpcode() == AMDGPUISD::PERM &&
9585       isa<ConstantSDNode>(LHS.getOperand(2))) {
9586     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9587     if (!Sel)
9588       return SDValue();
9589 
9590     Sel |= LHS.getConstantOperandVal(2);
9591     SDLoc DL(N);
9592     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9593                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9594   }
9595 
9596   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9597   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9598   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9599       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9600     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9601     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9602     if (LHSMask != ~0u && RHSMask != ~0u) {
9603       // Canonicalize the expression in an attempt to have fewer unique masks
9604       // and therefore fewer registers used to hold the masks.
9605       if (LHSMask > RHSMask) {
9606         std::swap(LHSMask, RHSMask);
9607         std::swap(LHS, RHS);
9608       }
9609 
9610       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9611       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9612       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9613       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9614 
9615       // Check of we need to combine values from two sources within a byte.
9616       if (!(LHSUsedLanes & RHSUsedLanes) &&
9617           // If we select high and lower word keep it for SDWA.
9618           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9619           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9620         // Kill zero bytes selected by other mask. Zero value is 0xc.
9621         LHSMask &= ~RHSUsedLanes;
9622         RHSMask &= ~LHSUsedLanes;
9623         // Add 4 to each active LHS lane
9624         LHSMask |= LHSUsedLanes & 0x04040404;
9625         // Combine masks
9626         uint32_t Sel = LHSMask | RHSMask;
9627         SDLoc DL(N);
9628 
9629         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9630                            LHS.getOperand(0), RHS.getOperand(0),
9631                            DAG.getConstant(Sel, DL, MVT::i32));
9632       }
9633     }
9634   }
9635 
9636   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9637     return SDValue();
9638 
9639   // TODO: This could be a generic combine with a predicate for extracting the
9640   // high half of an integer being free.
9641 
9642   // (or i64:x, (zero_extend i32:y)) ->
9643   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9644   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9645       RHS.getOpcode() != ISD::ZERO_EXTEND)
9646     std::swap(LHS, RHS);
9647 
9648   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9649     SDValue ExtSrc = RHS.getOperand(0);
9650     EVT SrcVT = ExtSrc.getValueType();
9651     if (SrcVT == MVT::i32) {
9652       SDLoc SL(N);
9653       SDValue LowLHS, HiBits;
9654       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9655       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9656 
9657       DCI.AddToWorklist(LowOr.getNode());
9658       DCI.AddToWorklist(HiBits.getNode());
9659 
9660       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9661                                 LowOr, HiBits);
9662       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9663     }
9664   }
9665 
9666   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9667   if (CRHS) {
9668     if (SDValue Split
9669           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR,
9670                                      N->getOperand(0), CRHS))
9671       return Split;
9672   }
9673 
9674   return SDValue();
9675 }
9676 
9677 SDValue SITargetLowering::performXorCombine(SDNode *N,
9678                                             DAGCombinerInfo &DCI) const {
9679   if (SDValue RV = reassociateScalarOps(N, DCI.DAG))
9680     return RV;
9681 
9682   EVT VT = N->getValueType(0);
9683   if (VT != MVT::i64)
9684     return SDValue();
9685 
9686   SDValue LHS = N->getOperand(0);
9687   SDValue RHS = N->getOperand(1);
9688 
9689   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9690   if (CRHS) {
9691     if (SDValue Split
9692           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9693       return Split;
9694   }
9695 
9696   return SDValue();
9697 }
9698 
9699 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9700                                                    DAGCombinerInfo &DCI) const {
9701   if (!Subtarget->has16BitInsts() ||
9702       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9703     return SDValue();
9704 
9705   EVT VT = N->getValueType(0);
9706   if (VT != MVT::i32)
9707     return SDValue();
9708 
9709   SDValue Src = N->getOperand(0);
9710   if (Src.getValueType() != MVT::i16)
9711     return SDValue();
9712 
9713   return SDValue();
9714 }
9715 
9716 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9717                                                         DAGCombinerInfo &DCI)
9718                                                         const {
9719   SDValue Src = N->getOperand(0);
9720   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9721 
9722   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9723       VTSign->getVT() == MVT::i8) ||
9724       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9725       VTSign->getVT() == MVT::i16)) &&
9726       Src.hasOneUse()) {
9727     auto *M = cast<MemSDNode>(Src);
9728     SDValue Ops[] = {
9729       Src.getOperand(0), // Chain
9730       Src.getOperand(1), // rsrc
9731       Src.getOperand(2), // vindex
9732       Src.getOperand(3), // voffset
9733       Src.getOperand(4), // soffset
9734       Src.getOperand(5), // offset
9735       Src.getOperand(6),
9736       Src.getOperand(7)
9737     };
9738     // replace with BUFFER_LOAD_BYTE/SHORT
9739     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9740                                          Src.getOperand(0).getValueType());
9741     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9742                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9743     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9744                                                           ResList,
9745                                                           Ops, M->getMemoryVT(),
9746                                                           M->getMemOperand());
9747     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9748                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9749   }
9750   return SDValue();
9751 }
9752 
9753 SDValue SITargetLowering::performClassCombine(SDNode *N,
9754                                               DAGCombinerInfo &DCI) const {
9755   SelectionDAG &DAG = DCI.DAG;
9756   SDValue Mask = N->getOperand(1);
9757 
9758   // fp_class x, 0 -> false
9759   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9760     if (CMask->isZero())
9761       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9762   }
9763 
9764   if (N->getOperand(0).isUndef())
9765     return DAG.getUNDEF(MVT::i1);
9766 
9767   return SDValue();
9768 }
9769 
9770 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9771                                             DAGCombinerInfo &DCI) const {
9772   EVT VT = N->getValueType(0);
9773   SDValue N0 = N->getOperand(0);
9774 
9775   if (N0.isUndef())
9776     return N0;
9777 
9778   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9779                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9780     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9781                            N->getFlags());
9782   }
9783 
9784   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9785     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9786                            N0.getOperand(0), N->getFlags());
9787   }
9788 
9789   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9790 }
9791 
9792 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9793                                        unsigned MaxDepth) const {
9794   unsigned Opcode = Op.getOpcode();
9795   if (Opcode == ISD::FCANONICALIZE)
9796     return true;
9797 
9798   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9799     auto F = CFP->getValueAPF();
9800     if (F.isNaN() && F.isSignaling())
9801       return false;
9802     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9803   }
9804 
9805   // If source is a result of another standard FP operation it is already in
9806   // canonical form.
9807   if (MaxDepth == 0)
9808     return false;
9809 
9810   switch (Opcode) {
9811   // These will flush denorms if required.
9812   case ISD::FADD:
9813   case ISD::FSUB:
9814   case ISD::FMUL:
9815   case ISD::FCEIL:
9816   case ISD::FFLOOR:
9817   case ISD::FMA:
9818   case ISD::FMAD:
9819   case ISD::FSQRT:
9820   case ISD::FDIV:
9821   case ISD::FREM:
9822   case ISD::FP_ROUND:
9823   case ISD::FP_EXTEND:
9824   case AMDGPUISD::FMUL_LEGACY:
9825   case AMDGPUISD::FMAD_FTZ:
9826   case AMDGPUISD::RCP:
9827   case AMDGPUISD::RSQ:
9828   case AMDGPUISD::RSQ_CLAMP:
9829   case AMDGPUISD::RCP_LEGACY:
9830   case AMDGPUISD::RCP_IFLAG:
9831   case AMDGPUISD::DIV_SCALE:
9832   case AMDGPUISD::DIV_FMAS:
9833   case AMDGPUISD::DIV_FIXUP:
9834   case AMDGPUISD::FRACT:
9835   case AMDGPUISD::LDEXP:
9836   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9837   case AMDGPUISD::CVT_F32_UBYTE0:
9838   case AMDGPUISD::CVT_F32_UBYTE1:
9839   case AMDGPUISD::CVT_F32_UBYTE2:
9840   case AMDGPUISD::CVT_F32_UBYTE3:
9841     return true;
9842 
9843   // It can/will be lowered or combined as a bit operation.
9844   // Need to check their input recursively to handle.
9845   case ISD::FNEG:
9846   case ISD::FABS:
9847   case ISD::FCOPYSIGN:
9848     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9849 
9850   case ISD::FSIN:
9851   case ISD::FCOS:
9852   case ISD::FSINCOS:
9853     return Op.getValueType().getScalarType() != MVT::f16;
9854 
9855   case ISD::FMINNUM:
9856   case ISD::FMAXNUM:
9857   case ISD::FMINNUM_IEEE:
9858   case ISD::FMAXNUM_IEEE:
9859   case AMDGPUISD::CLAMP:
9860   case AMDGPUISD::FMED3:
9861   case AMDGPUISD::FMAX3:
9862   case AMDGPUISD::FMIN3: {
9863     // FIXME: Shouldn't treat the generic operations different based these.
9864     // However, we aren't really required to flush the result from
9865     // minnum/maxnum..
9866 
9867     // snans will be quieted, so we only need to worry about denormals.
9868     if (Subtarget->supportsMinMaxDenormModes() ||
9869         denormalsEnabledForType(DAG, Op.getValueType()))
9870       return true;
9871 
9872     // Flushing may be required.
9873     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9874     // targets need to check their input recursively.
9875 
9876     // FIXME: Does this apply with clamp? It's implemented with max.
9877     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9878       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9879         return false;
9880     }
9881 
9882     return true;
9883   }
9884   case ISD::SELECT: {
9885     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9886            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9887   }
9888   case ISD::BUILD_VECTOR: {
9889     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9890       SDValue SrcOp = Op.getOperand(i);
9891       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9892         return false;
9893     }
9894 
9895     return true;
9896   }
9897   case ISD::EXTRACT_VECTOR_ELT:
9898   case ISD::EXTRACT_SUBVECTOR: {
9899     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9900   }
9901   case ISD::INSERT_VECTOR_ELT: {
9902     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9903            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9904   }
9905   case ISD::UNDEF:
9906     // Could be anything.
9907     return false;
9908 
9909   case ISD::BITCAST:
9910     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9911   case ISD::TRUNCATE: {
9912     // Hack round the mess we make when legalizing extract_vector_elt
9913     if (Op.getValueType() == MVT::i16) {
9914       SDValue TruncSrc = Op.getOperand(0);
9915       if (TruncSrc.getValueType() == MVT::i32 &&
9916           TruncSrc.getOpcode() == ISD::BITCAST &&
9917           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9918         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9919       }
9920     }
9921     return false;
9922   }
9923   case ISD::INTRINSIC_WO_CHAIN: {
9924     unsigned IntrinsicID
9925       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9926     // TODO: Handle more intrinsics
9927     switch (IntrinsicID) {
9928     case Intrinsic::amdgcn_cvt_pkrtz:
9929     case Intrinsic::amdgcn_cubeid:
9930     case Intrinsic::amdgcn_frexp_mant:
9931     case Intrinsic::amdgcn_fdot2:
9932     case Intrinsic::amdgcn_rcp:
9933     case Intrinsic::amdgcn_rsq:
9934     case Intrinsic::amdgcn_rsq_clamp:
9935     case Intrinsic::amdgcn_rcp_legacy:
9936     case Intrinsic::amdgcn_rsq_legacy:
9937     case Intrinsic::amdgcn_trig_preop:
9938       return true;
9939     default:
9940       break;
9941     }
9942 
9943     LLVM_FALLTHROUGH;
9944   }
9945   default:
9946     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9947            DAG.isKnownNeverSNaN(Op);
9948   }
9949 
9950   llvm_unreachable("invalid operation");
9951 }
9952 
9953 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
9954                                        unsigned MaxDepth) const {
9955   MachineRegisterInfo &MRI = MF.getRegInfo();
9956   MachineInstr *MI = MRI.getVRegDef(Reg);
9957   unsigned Opcode = MI->getOpcode();
9958 
9959   if (Opcode == AMDGPU::G_FCANONICALIZE)
9960     return true;
9961 
9962   Optional<FPValueAndVReg> FCR;
9963   // Constant splat (can be padded with undef) or scalar constant.
9964   if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) {
9965     if (FCR->Value.isSignaling())
9966       return false;
9967     return !FCR->Value.isDenormal() ||
9968            denormalsEnabledForType(MRI.getType(FCR->VReg), MF);
9969   }
9970 
9971   if (MaxDepth == 0)
9972     return false;
9973 
9974   switch (Opcode) {
9975   case AMDGPU::G_FMINNUM_IEEE:
9976   case AMDGPU::G_FMAXNUM_IEEE: {
9977     if (Subtarget->supportsMinMaxDenormModes() ||
9978         denormalsEnabledForType(MRI.getType(Reg), MF))
9979       return true;
9980     for (const MachineOperand &MO : llvm::drop_begin(MI->operands()))
9981       if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1))
9982         return false;
9983     return true;
9984   }
9985   default:
9986     return denormalsEnabledForType(MRI.getType(Reg), MF) &&
9987            isKnownNeverSNaN(Reg, MRI);
9988   }
9989 
9990   llvm_unreachable("invalid operation");
9991 }
9992 
9993 // Constant fold canonicalize.
9994 SDValue SITargetLowering::getCanonicalConstantFP(
9995   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9996   // Flush denormals to 0 if not enabled.
9997   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9998     return DAG.getConstantFP(0.0, SL, VT);
9999 
10000   if (C.isNaN()) {
10001     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
10002     if (C.isSignaling()) {
10003       // Quiet a signaling NaN.
10004       // FIXME: Is this supposed to preserve payload bits?
10005       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
10006     }
10007 
10008     // Make sure it is the canonical NaN bitpattern.
10009     //
10010     // TODO: Can we use -1 as the canonical NaN value since it's an inline
10011     // immediate?
10012     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
10013       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
10014   }
10015 
10016   // Already canonical.
10017   return DAG.getConstantFP(C, SL, VT);
10018 }
10019 
10020 static bool vectorEltWillFoldAway(SDValue Op) {
10021   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
10022 }
10023 
10024 SDValue SITargetLowering::performFCanonicalizeCombine(
10025   SDNode *N,
10026   DAGCombinerInfo &DCI) const {
10027   SelectionDAG &DAG = DCI.DAG;
10028   SDValue N0 = N->getOperand(0);
10029   EVT VT = N->getValueType(0);
10030 
10031   // fcanonicalize undef -> qnan
10032   if (N0.isUndef()) {
10033     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
10034     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
10035   }
10036 
10037   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
10038     EVT VT = N->getValueType(0);
10039     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
10040   }
10041 
10042   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
10043   //                                                   (fcanonicalize k)
10044   //
10045   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
10046 
10047   // TODO: This could be better with wider vectors that will be split to v2f16,
10048   // and to consider uses since there aren't that many packed operations.
10049   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
10050       isTypeLegal(MVT::v2f16)) {
10051     SDLoc SL(N);
10052     SDValue NewElts[2];
10053     SDValue Lo = N0.getOperand(0);
10054     SDValue Hi = N0.getOperand(1);
10055     EVT EltVT = Lo.getValueType();
10056 
10057     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
10058       for (unsigned I = 0; I != 2; ++I) {
10059         SDValue Op = N0.getOperand(I);
10060         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
10061           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
10062                                               CFP->getValueAPF());
10063         } else if (Op.isUndef()) {
10064           // Handled below based on what the other operand is.
10065           NewElts[I] = Op;
10066         } else {
10067           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
10068         }
10069       }
10070 
10071       // If one half is undef, and one is constant, prefer a splat vector rather
10072       // than the normal qNaN. If it's a register, prefer 0.0 since that's
10073       // cheaper to use and may be free with a packed operation.
10074       if (NewElts[0].isUndef()) {
10075         if (isa<ConstantFPSDNode>(NewElts[1]))
10076           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
10077             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
10078       }
10079 
10080       if (NewElts[1].isUndef()) {
10081         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
10082           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
10083       }
10084 
10085       return DAG.getBuildVector(VT, SL, NewElts);
10086     }
10087   }
10088 
10089   unsigned SrcOpc = N0.getOpcode();
10090 
10091   // If it's free to do so, push canonicalizes further up the source, which may
10092   // find a canonical source.
10093   //
10094   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
10095   // sNaNs.
10096   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
10097     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10098     if (CRHS && N0.hasOneUse()) {
10099       SDLoc SL(N);
10100       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
10101                                    N0.getOperand(0));
10102       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
10103       DCI.AddToWorklist(Canon0.getNode());
10104 
10105       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
10106     }
10107   }
10108 
10109   return isCanonicalized(DAG, N0) ? N0 : SDValue();
10110 }
10111 
10112 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
10113   switch (Opc) {
10114   case ISD::FMAXNUM:
10115   case ISD::FMAXNUM_IEEE:
10116     return AMDGPUISD::FMAX3;
10117   case ISD::SMAX:
10118     return AMDGPUISD::SMAX3;
10119   case ISD::UMAX:
10120     return AMDGPUISD::UMAX3;
10121   case ISD::FMINNUM:
10122   case ISD::FMINNUM_IEEE:
10123     return AMDGPUISD::FMIN3;
10124   case ISD::SMIN:
10125     return AMDGPUISD::SMIN3;
10126   case ISD::UMIN:
10127     return AMDGPUISD::UMIN3;
10128   default:
10129     llvm_unreachable("Not a min/max opcode");
10130   }
10131 }
10132 
10133 SDValue SITargetLowering::performIntMed3ImmCombine(
10134   SelectionDAG &DAG, const SDLoc &SL,
10135   SDValue Op0, SDValue Op1, bool Signed) const {
10136   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
10137   if (!K1)
10138     return SDValue();
10139 
10140   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
10141   if (!K0)
10142     return SDValue();
10143 
10144   if (Signed) {
10145     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
10146       return SDValue();
10147   } else {
10148     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
10149       return SDValue();
10150   }
10151 
10152   EVT VT = K0->getValueType(0);
10153   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
10154   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
10155     return DAG.getNode(Med3Opc, SL, VT,
10156                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
10157   }
10158 
10159   // If there isn't a 16-bit med3 operation, convert to 32-bit.
10160   if (VT == MVT::i16) {
10161     MVT NVT = MVT::i32;
10162     unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
10163 
10164     SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
10165     SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
10166     SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
10167 
10168     SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
10169     return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
10170   }
10171 
10172   return SDValue();
10173 }
10174 
10175 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
10176   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
10177     return C;
10178 
10179   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
10180     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
10181       return C;
10182   }
10183 
10184   return nullptr;
10185 }
10186 
10187 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
10188                                                   const SDLoc &SL,
10189                                                   SDValue Op0,
10190                                                   SDValue Op1) const {
10191   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
10192   if (!K1)
10193     return SDValue();
10194 
10195   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
10196   if (!K0)
10197     return SDValue();
10198 
10199   // Ordered >= (although NaN inputs should have folded away by now).
10200   if (K0->getValueAPF() > K1->getValueAPF())
10201     return SDValue();
10202 
10203   const MachineFunction &MF = DAG.getMachineFunction();
10204   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10205 
10206   // TODO: Check IEEE bit enabled?
10207   EVT VT = Op0.getValueType();
10208   if (Info->getMode().DX10Clamp) {
10209     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
10210     // hardware fmed3 behavior converting to a min.
10211     // FIXME: Should this be allowing -0.0?
10212     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
10213       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
10214   }
10215 
10216   // med3 for f16 is only available on gfx9+, and not available for v2f16.
10217   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
10218     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
10219     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
10220     // then give the other result, which is different from med3 with a NaN
10221     // input.
10222     SDValue Var = Op0.getOperand(0);
10223     if (!DAG.isKnownNeverSNaN(Var))
10224       return SDValue();
10225 
10226     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10227 
10228     if ((!K0->hasOneUse() ||
10229          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
10230         (!K1->hasOneUse() ||
10231          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
10232       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
10233                          Var, SDValue(K0, 0), SDValue(K1, 0));
10234     }
10235   }
10236 
10237   return SDValue();
10238 }
10239 
10240 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
10241                                                DAGCombinerInfo &DCI) const {
10242   SelectionDAG &DAG = DCI.DAG;
10243 
10244   EVT VT = N->getValueType(0);
10245   unsigned Opc = N->getOpcode();
10246   SDValue Op0 = N->getOperand(0);
10247   SDValue Op1 = N->getOperand(1);
10248 
10249   // Only do this if the inner op has one use since this will just increases
10250   // register pressure for no benefit.
10251 
10252   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
10253       !VT.isVector() &&
10254       (VT == MVT::i32 || VT == MVT::f32 ||
10255        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
10256     // max(max(a, b), c) -> max3(a, b, c)
10257     // min(min(a, b), c) -> min3(a, b, c)
10258     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
10259       SDLoc DL(N);
10260       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10261                          DL,
10262                          N->getValueType(0),
10263                          Op0.getOperand(0),
10264                          Op0.getOperand(1),
10265                          Op1);
10266     }
10267 
10268     // Try commuted.
10269     // max(a, max(b, c)) -> max3(a, b, c)
10270     // min(a, min(b, c)) -> min3(a, b, c)
10271     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
10272       SDLoc DL(N);
10273       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10274                          DL,
10275                          N->getValueType(0),
10276                          Op0,
10277                          Op1.getOperand(0),
10278                          Op1.getOperand(1));
10279     }
10280   }
10281 
10282   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
10283   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
10284     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
10285       return Med3;
10286   }
10287 
10288   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
10289     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
10290       return Med3;
10291   }
10292 
10293   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
10294   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
10295        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
10296        (Opc == AMDGPUISD::FMIN_LEGACY &&
10297         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
10298       (VT == MVT::f32 || VT == MVT::f64 ||
10299        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
10300        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
10301       Op0.hasOneUse()) {
10302     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
10303       return Res;
10304   }
10305 
10306   return SDValue();
10307 }
10308 
10309 static bool isClampZeroToOne(SDValue A, SDValue B) {
10310   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
10311     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
10312       // FIXME: Should this be allowing -0.0?
10313       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
10314              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
10315     }
10316   }
10317 
10318   return false;
10319 }
10320 
10321 // FIXME: Should only worry about snans for version with chain.
10322 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
10323                                               DAGCombinerInfo &DCI) const {
10324   EVT VT = N->getValueType(0);
10325   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
10326   // NaNs. With a NaN input, the order of the operands may change the result.
10327 
10328   SelectionDAG &DAG = DCI.DAG;
10329   SDLoc SL(N);
10330 
10331   SDValue Src0 = N->getOperand(0);
10332   SDValue Src1 = N->getOperand(1);
10333   SDValue Src2 = N->getOperand(2);
10334 
10335   if (isClampZeroToOne(Src0, Src1)) {
10336     // const_a, const_b, x -> clamp is safe in all cases including signaling
10337     // nans.
10338     // FIXME: Should this be allowing -0.0?
10339     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
10340   }
10341 
10342   const MachineFunction &MF = DAG.getMachineFunction();
10343   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10344 
10345   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
10346   // handling no dx10-clamp?
10347   if (Info->getMode().DX10Clamp) {
10348     // If NaNs is clamped to 0, we are free to reorder the inputs.
10349 
10350     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10351       std::swap(Src0, Src1);
10352 
10353     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10354       std::swap(Src1, Src2);
10355 
10356     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10357       std::swap(Src0, Src1);
10358 
10359     if (isClampZeroToOne(Src1, Src2))
10360       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10361   }
10362 
10363   return SDValue();
10364 }
10365 
10366 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10367                                                  DAGCombinerInfo &DCI) const {
10368   SDValue Src0 = N->getOperand(0);
10369   SDValue Src1 = N->getOperand(1);
10370   if (Src0.isUndef() && Src1.isUndef())
10371     return DCI.DAG.getUNDEF(N->getValueType(0));
10372   return SDValue();
10373 }
10374 
10375 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10376 // expanded into a set of cmp/select instructions.
10377 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10378                                                 unsigned NumElem,
10379                                                 bool IsDivergentIdx) {
10380   if (UseDivergentRegisterIndexing)
10381     return false;
10382 
10383   unsigned VecSize = EltSize * NumElem;
10384 
10385   // Sub-dword vectors of size 2 dword or less have better implementation.
10386   if (VecSize <= 64 && EltSize < 32)
10387     return false;
10388 
10389   // Always expand the rest of sub-dword instructions, otherwise it will be
10390   // lowered via memory.
10391   if (EltSize < 32)
10392     return true;
10393 
10394   // Always do this if var-idx is divergent, otherwise it will become a loop.
10395   if (IsDivergentIdx)
10396     return true;
10397 
10398   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10399   unsigned NumInsts = NumElem /* Number of compares */ +
10400                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10401   return NumInsts <= 16;
10402 }
10403 
10404 static bool shouldExpandVectorDynExt(SDNode *N) {
10405   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10406   if (isa<ConstantSDNode>(Idx))
10407     return false;
10408 
10409   SDValue Vec = N->getOperand(0);
10410   EVT VecVT = Vec.getValueType();
10411   EVT EltVT = VecVT.getVectorElementType();
10412   unsigned EltSize = EltVT.getSizeInBits();
10413   unsigned NumElem = VecVT.getVectorNumElements();
10414 
10415   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
10416                                                     Idx->isDivergent());
10417 }
10418 
10419 SDValue SITargetLowering::performExtractVectorEltCombine(
10420   SDNode *N, DAGCombinerInfo &DCI) const {
10421   SDValue Vec = N->getOperand(0);
10422   SelectionDAG &DAG = DCI.DAG;
10423 
10424   EVT VecVT = Vec.getValueType();
10425   EVT EltVT = VecVT.getVectorElementType();
10426 
10427   if ((Vec.getOpcode() == ISD::FNEG ||
10428        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10429     SDLoc SL(N);
10430     EVT EltVT = N->getValueType(0);
10431     SDValue Idx = N->getOperand(1);
10432     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10433                               Vec.getOperand(0), Idx);
10434     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10435   }
10436 
10437   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10438   //    =>
10439   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10440   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10441   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10442   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10443     SDLoc SL(N);
10444     EVT EltVT = N->getValueType(0);
10445     SDValue Idx = N->getOperand(1);
10446     unsigned Opc = Vec.getOpcode();
10447 
10448     switch(Opc) {
10449     default:
10450       break;
10451       // TODO: Support other binary operations.
10452     case ISD::FADD:
10453     case ISD::FSUB:
10454     case ISD::FMUL:
10455     case ISD::ADD:
10456     case ISD::UMIN:
10457     case ISD::UMAX:
10458     case ISD::SMIN:
10459     case ISD::SMAX:
10460     case ISD::FMAXNUM:
10461     case ISD::FMINNUM:
10462     case ISD::FMAXNUM_IEEE:
10463     case ISD::FMINNUM_IEEE: {
10464       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10465                                  Vec.getOperand(0), Idx);
10466       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10467                                  Vec.getOperand(1), Idx);
10468 
10469       DCI.AddToWorklist(Elt0.getNode());
10470       DCI.AddToWorklist(Elt1.getNode());
10471       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10472     }
10473     }
10474   }
10475 
10476   unsigned VecSize = VecVT.getSizeInBits();
10477   unsigned EltSize = EltVT.getSizeInBits();
10478 
10479   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10480   if (::shouldExpandVectorDynExt(N)) {
10481     SDLoc SL(N);
10482     SDValue Idx = N->getOperand(1);
10483     SDValue V;
10484     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10485       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10486       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10487       if (I == 0)
10488         V = Elt;
10489       else
10490         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10491     }
10492     return V;
10493   }
10494 
10495   if (!DCI.isBeforeLegalize())
10496     return SDValue();
10497 
10498   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10499   // elements. This exposes more load reduction opportunities by replacing
10500   // multiple small extract_vector_elements with a single 32-bit extract.
10501   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10502   if (isa<MemSDNode>(Vec) &&
10503       EltSize <= 16 &&
10504       EltVT.isByteSized() &&
10505       VecSize > 32 &&
10506       VecSize % 32 == 0 &&
10507       Idx) {
10508     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10509 
10510     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10511     unsigned EltIdx = BitIndex / 32;
10512     unsigned LeftoverBitIdx = BitIndex % 32;
10513     SDLoc SL(N);
10514 
10515     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10516     DCI.AddToWorklist(Cast.getNode());
10517 
10518     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10519                               DAG.getConstant(EltIdx, SL, MVT::i32));
10520     DCI.AddToWorklist(Elt.getNode());
10521     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10522                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10523     DCI.AddToWorklist(Srl.getNode());
10524 
10525     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10526     DCI.AddToWorklist(Trunc.getNode());
10527     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10528   }
10529 
10530   return SDValue();
10531 }
10532 
10533 SDValue
10534 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10535                                                 DAGCombinerInfo &DCI) const {
10536   SDValue Vec = N->getOperand(0);
10537   SDValue Idx = N->getOperand(2);
10538   EVT VecVT = Vec.getValueType();
10539   EVT EltVT = VecVT.getVectorElementType();
10540 
10541   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10542   // => BUILD_VECTOR n x select (e, const-idx)
10543   if (!::shouldExpandVectorDynExt(N))
10544     return SDValue();
10545 
10546   SelectionDAG &DAG = DCI.DAG;
10547   SDLoc SL(N);
10548   SDValue Ins = N->getOperand(1);
10549   EVT IdxVT = Idx.getValueType();
10550 
10551   SmallVector<SDValue, 16> Ops;
10552   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10553     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10554     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10555     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10556     Ops.push_back(V);
10557   }
10558 
10559   return DAG.getBuildVector(VecVT, SL, Ops);
10560 }
10561 
10562 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10563                                           const SDNode *N0,
10564                                           const SDNode *N1) const {
10565   EVT VT = N0->getValueType(0);
10566 
10567   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10568   // support denormals ever.
10569   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10570        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10571         getSubtarget()->hasMadF16())) &&
10572        isOperationLegal(ISD::FMAD, VT))
10573     return ISD::FMAD;
10574 
10575   const TargetOptions &Options = DAG.getTarget().Options;
10576   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10577        (N0->getFlags().hasAllowContract() &&
10578         N1->getFlags().hasAllowContract())) &&
10579       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10580     return ISD::FMA;
10581   }
10582 
10583   return 0;
10584 }
10585 
10586 // For a reassociatable opcode perform:
10587 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10588 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10589                                                SelectionDAG &DAG) const {
10590   EVT VT = N->getValueType(0);
10591   if (VT != MVT::i32 && VT != MVT::i64)
10592     return SDValue();
10593 
10594   if (DAG.isBaseWithConstantOffset(SDValue(N, 0)))
10595     return SDValue();
10596 
10597   unsigned Opc = N->getOpcode();
10598   SDValue Op0 = N->getOperand(0);
10599   SDValue Op1 = N->getOperand(1);
10600 
10601   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10602     return SDValue();
10603 
10604   if (Op0->isDivergent())
10605     std::swap(Op0, Op1);
10606 
10607   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10608     return SDValue();
10609 
10610   SDValue Op2 = Op1.getOperand(1);
10611   Op1 = Op1.getOperand(0);
10612   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10613     return SDValue();
10614 
10615   if (Op1->isDivergent())
10616     std::swap(Op1, Op2);
10617 
10618   SDLoc SL(N);
10619   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10620   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10621 }
10622 
10623 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10624                            EVT VT,
10625                            SDValue N0, SDValue N1, SDValue N2,
10626                            bool Signed) {
10627   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10628   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10629   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10630   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10631 }
10632 
10633 SDValue SITargetLowering::performAddCombine(SDNode *N,
10634                                             DAGCombinerInfo &DCI) const {
10635   SelectionDAG &DAG = DCI.DAG;
10636   EVT VT = N->getValueType(0);
10637   SDLoc SL(N);
10638   SDValue LHS = N->getOperand(0);
10639   SDValue RHS = N->getOperand(1);
10640 
10641   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10642       && Subtarget->hasMad64_32() &&
10643       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10644       VT.getScalarSizeInBits() <= 64) {
10645     if (LHS.getOpcode() != ISD::MUL)
10646       std::swap(LHS, RHS);
10647 
10648     SDValue MulLHS = LHS.getOperand(0);
10649     SDValue MulRHS = LHS.getOperand(1);
10650     SDValue AddRHS = RHS;
10651 
10652     // TODO: Maybe restrict if SGPR inputs.
10653     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10654         numBitsUnsigned(MulRHS, DAG) <= 32) {
10655       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10656       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10657       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10658       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10659     }
10660 
10661     if (numBitsSigned(MulLHS, DAG) <= 32 && numBitsSigned(MulRHS, DAG) <= 32) {
10662       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10663       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10664       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10665       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10666     }
10667 
10668     return SDValue();
10669   }
10670 
10671   if (SDValue V = reassociateScalarOps(N, DAG)) {
10672     return V;
10673   }
10674 
10675   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10676     return SDValue();
10677 
10678   // add x, zext (setcc) => addcarry x, 0, setcc
10679   // add x, sext (setcc) => subcarry x, 0, setcc
10680   unsigned Opc = LHS.getOpcode();
10681   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10682       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10683     std::swap(RHS, LHS);
10684 
10685   Opc = RHS.getOpcode();
10686   switch (Opc) {
10687   default: break;
10688   case ISD::ZERO_EXTEND:
10689   case ISD::SIGN_EXTEND:
10690   case ISD::ANY_EXTEND: {
10691     auto Cond = RHS.getOperand(0);
10692     // If this won't be a real VOPC output, we would still need to insert an
10693     // extra instruction anyway.
10694     if (!isBoolSGPR(Cond))
10695       break;
10696     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10697     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10698     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10699     return DAG.getNode(Opc, SL, VTList, Args);
10700   }
10701   case ISD::ADDCARRY: {
10702     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10703     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10704     if (!C || C->getZExtValue() != 0) break;
10705     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10706     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10707   }
10708   }
10709   return SDValue();
10710 }
10711 
10712 SDValue SITargetLowering::performSubCombine(SDNode *N,
10713                                             DAGCombinerInfo &DCI) const {
10714   SelectionDAG &DAG = DCI.DAG;
10715   EVT VT = N->getValueType(0);
10716 
10717   if (VT != MVT::i32)
10718     return SDValue();
10719 
10720   SDLoc SL(N);
10721   SDValue LHS = N->getOperand(0);
10722   SDValue RHS = N->getOperand(1);
10723 
10724   // sub x, zext (setcc) => subcarry x, 0, setcc
10725   // sub x, sext (setcc) => addcarry x, 0, setcc
10726   unsigned Opc = RHS.getOpcode();
10727   switch (Opc) {
10728   default: break;
10729   case ISD::ZERO_EXTEND:
10730   case ISD::SIGN_EXTEND:
10731   case ISD::ANY_EXTEND: {
10732     auto Cond = RHS.getOperand(0);
10733     // If this won't be a real VOPC output, we would still need to insert an
10734     // extra instruction anyway.
10735     if (!isBoolSGPR(Cond))
10736       break;
10737     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10738     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10739     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10740     return DAG.getNode(Opc, SL, VTList, Args);
10741   }
10742   }
10743 
10744   if (LHS.getOpcode() == ISD::SUBCARRY) {
10745     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10746     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10747     if (!C || !C->isZero())
10748       return SDValue();
10749     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10750     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10751   }
10752   return SDValue();
10753 }
10754 
10755 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10756   DAGCombinerInfo &DCI) const {
10757 
10758   if (N->getValueType(0) != MVT::i32)
10759     return SDValue();
10760 
10761   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10762   if (!C || C->getZExtValue() != 0)
10763     return SDValue();
10764 
10765   SelectionDAG &DAG = DCI.DAG;
10766   SDValue LHS = N->getOperand(0);
10767 
10768   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10769   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10770   unsigned LHSOpc = LHS.getOpcode();
10771   unsigned Opc = N->getOpcode();
10772   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10773       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10774     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10775     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10776   }
10777   return SDValue();
10778 }
10779 
10780 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10781                                              DAGCombinerInfo &DCI) const {
10782   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10783     return SDValue();
10784 
10785   SelectionDAG &DAG = DCI.DAG;
10786   EVT VT = N->getValueType(0);
10787 
10788   SDLoc SL(N);
10789   SDValue LHS = N->getOperand(0);
10790   SDValue RHS = N->getOperand(1);
10791 
10792   // These should really be instruction patterns, but writing patterns with
10793   // source modifiers is a pain.
10794 
10795   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10796   if (LHS.getOpcode() == ISD::FADD) {
10797     SDValue A = LHS.getOperand(0);
10798     if (A == LHS.getOperand(1)) {
10799       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10800       if (FusedOp != 0) {
10801         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10802         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10803       }
10804     }
10805   }
10806 
10807   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10808   if (RHS.getOpcode() == ISD::FADD) {
10809     SDValue A = RHS.getOperand(0);
10810     if (A == RHS.getOperand(1)) {
10811       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10812       if (FusedOp != 0) {
10813         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10814         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10815       }
10816     }
10817   }
10818 
10819   return SDValue();
10820 }
10821 
10822 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10823                                              DAGCombinerInfo &DCI) const {
10824   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10825     return SDValue();
10826 
10827   SelectionDAG &DAG = DCI.DAG;
10828   SDLoc SL(N);
10829   EVT VT = N->getValueType(0);
10830   assert(!VT.isVector());
10831 
10832   // Try to get the fneg to fold into the source modifier. This undoes generic
10833   // DAG combines and folds them into the mad.
10834   //
10835   // Only do this if we are not trying to support denormals. v_mad_f32 does
10836   // not support denormals ever.
10837   SDValue LHS = N->getOperand(0);
10838   SDValue RHS = N->getOperand(1);
10839   if (LHS.getOpcode() == ISD::FADD) {
10840     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10841     SDValue A = LHS.getOperand(0);
10842     if (A == LHS.getOperand(1)) {
10843       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10844       if (FusedOp != 0){
10845         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10846         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10847 
10848         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10849       }
10850     }
10851   }
10852 
10853   if (RHS.getOpcode() == ISD::FADD) {
10854     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10855 
10856     SDValue A = RHS.getOperand(0);
10857     if (A == RHS.getOperand(1)) {
10858       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10859       if (FusedOp != 0){
10860         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10861         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10862       }
10863     }
10864   }
10865 
10866   return SDValue();
10867 }
10868 
10869 SDValue SITargetLowering::performFMACombine(SDNode *N,
10870                                             DAGCombinerInfo &DCI) const {
10871   SelectionDAG &DAG = DCI.DAG;
10872   EVT VT = N->getValueType(0);
10873   SDLoc SL(N);
10874 
10875   if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
10876     return SDValue();
10877 
10878   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10879   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10880   SDValue Op1 = N->getOperand(0);
10881   SDValue Op2 = N->getOperand(1);
10882   SDValue FMA = N->getOperand(2);
10883 
10884   if (FMA.getOpcode() != ISD::FMA ||
10885       Op1.getOpcode() != ISD::FP_EXTEND ||
10886       Op2.getOpcode() != ISD::FP_EXTEND)
10887     return SDValue();
10888 
10889   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10890   // regardless of the denorm mode setting. Therefore,
10891   // unsafe-fp-math/fp-contract is sufficient to allow generating fdot2.
10892   const TargetOptions &Options = DAG.getTarget().Options;
10893   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10894       (N->getFlags().hasAllowContract() &&
10895        FMA->getFlags().hasAllowContract())) {
10896     Op1 = Op1.getOperand(0);
10897     Op2 = Op2.getOperand(0);
10898     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10899         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10900       return SDValue();
10901 
10902     SDValue Vec1 = Op1.getOperand(0);
10903     SDValue Idx1 = Op1.getOperand(1);
10904     SDValue Vec2 = Op2.getOperand(0);
10905 
10906     SDValue FMAOp1 = FMA.getOperand(0);
10907     SDValue FMAOp2 = FMA.getOperand(1);
10908     SDValue FMAAcc = FMA.getOperand(2);
10909 
10910     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10911         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10912       return SDValue();
10913 
10914     FMAOp1 = FMAOp1.getOperand(0);
10915     FMAOp2 = FMAOp2.getOperand(0);
10916     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10917         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10918       return SDValue();
10919 
10920     SDValue Vec3 = FMAOp1.getOperand(0);
10921     SDValue Vec4 = FMAOp2.getOperand(0);
10922     SDValue Idx2 = FMAOp1.getOperand(1);
10923 
10924     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10925         // Idx1 and Idx2 cannot be the same.
10926         Idx1 == Idx2)
10927       return SDValue();
10928 
10929     if (Vec1 == Vec2 || Vec3 == Vec4)
10930       return SDValue();
10931 
10932     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10933       return SDValue();
10934 
10935     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10936         (Vec1 == Vec4 && Vec2 == Vec3)) {
10937       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10938                          DAG.getTargetConstant(0, SL, MVT::i1));
10939     }
10940   }
10941   return SDValue();
10942 }
10943 
10944 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10945                                               DAGCombinerInfo &DCI) const {
10946   SelectionDAG &DAG = DCI.DAG;
10947   SDLoc SL(N);
10948 
10949   SDValue LHS = N->getOperand(0);
10950   SDValue RHS = N->getOperand(1);
10951   EVT VT = LHS.getValueType();
10952   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10953 
10954   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10955   if (!CRHS) {
10956     CRHS = dyn_cast<ConstantSDNode>(LHS);
10957     if (CRHS) {
10958       std::swap(LHS, RHS);
10959       CC = getSetCCSwappedOperands(CC);
10960     }
10961   }
10962 
10963   if (CRHS) {
10964     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10965         isBoolSGPR(LHS.getOperand(0))) {
10966       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10967       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10968       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10969       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10970       if ((CRHS->isAllOnes() &&
10971            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10972           (CRHS->isZero() &&
10973            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10974         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10975                            DAG.getConstant(-1, SL, MVT::i1));
10976       if ((CRHS->isAllOnes() &&
10977            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10978           (CRHS->isZero() &&
10979            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10980         return LHS.getOperand(0);
10981     }
10982 
10983     const APInt &CRHSVal = CRHS->getAPIntValue();
10984     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10985         LHS.getOpcode() == ISD::SELECT &&
10986         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10987         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10988         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10989         isBoolSGPR(LHS.getOperand(0))) {
10990       // Given CT != FT:
10991       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10992       // setcc (select cc, CT, CF), CF, ne => cc
10993       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10994       // setcc (select cc, CT, CF), CT, eq => cc
10995       const APInt &CT = LHS.getConstantOperandAPInt(1);
10996       const APInt &CF = LHS.getConstantOperandAPInt(2);
10997 
10998       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10999           (CT == CRHSVal && CC == ISD::SETNE))
11000         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
11001                            DAG.getConstant(-1, SL, MVT::i1));
11002       if ((CF == CRHSVal && CC == ISD::SETNE) ||
11003           (CT == CRHSVal && CC == ISD::SETEQ))
11004         return LHS.getOperand(0);
11005     }
11006   }
11007 
11008   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
11009                                            VT != MVT::f16))
11010     return SDValue();
11011 
11012   // Match isinf/isfinite pattern
11013   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
11014   // (fcmp one (fabs x), inf) -> (fp_class x,
11015   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
11016   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
11017     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
11018     if (!CRHS)
11019       return SDValue();
11020 
11021     const APFloat &APF = CRHS->getValueAPF();
11022     if (APF.isInfinity() && !APF.isNegative()) {
11023       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
11024                                  SIInstrFlags::N_INFINITY;
11025       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
11026                                     SIInstrFlags::P_ZERO |
11027                                     SIInstrFlags::N_NORMAL |
11028                                     SIInstrFlags::P_NORMAL |
11029                                     SIInstrFlags::N_SUBNORMAL |
11030                                     SIInstrFlags::P_SUBNORMAL;
11031       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
11032       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
11033                          DAG.getConstant(Mask, SL, MVT::i32));
11034     }
11035   }
11036 
11037   return SDValue();
11038 }
11039 
11040 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
11041                                                      DAGCombinerInfo &DCI) const {
11042   SelectionDAG &DAG = DCI.DAG;
11043   SDLoc SL(N);
11044   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
11045 
11046   SDValue Src = N->getOperand(0);
11047   SDValue Shift = N->getOperand(0);
11048 
11049   // TODO: Extend type shouldn't matter (assuming legal types).
11050   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
11051     Shift = Shift.getOperand(0);
11052 
11053   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
11054     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
11055     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
11056     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
11057     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
11058     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
11059     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
11060       SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0),
11061                                  SDLoc(Shift.getOperand(0)), MVT::i32);
11062 
11063       unsigned ShiftOffset = 8 * Offset;
11064       if (Shift.getOpcode() == ISD::SHL)
11065         ShiftOffset -= C->getZExtValue();
11066       else
11067         ShiftOffset += C->getZExtValue();
11068 
11069       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
11070         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
11071                            MVT::f32, Shifted);
11072       }
11073     }
11074   }
11075 
11076   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11077   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
11078   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
11079     // We simplified Src. If this node is not dead, visit it again so it is
11080     // folded properly.
11081     if (N->getOpcode() != ISD::DELETED_NODE)
11082       DCI.AddToWorklist(N);
11083     return SDValue(N, 0);
11084   }
11085 
11086   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
11087   if (SDValue DemandedSrc =
11088           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
11089     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
11090 
11091   return SDValue();
11092 }
11093 
11094 SDValue SITargetLowering::performClampCombine(SDNode *N,
11095                                               DAGCombinerInfo &DCI) const {
11096   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
11097   if (!CSrc)
11098     return SDValue();
11099 
11100   const MachineFunction &MF = DCI.DAG.getMachineFunction();
11101   const APFloat &F = CSrc->getValueAPF();
11102   APFloat Zero = APFloat::getZero(F.getSemantics());
11103   if (F < Zero ||
11104       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
11105     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
11106   }
11107 
11108   APFloat One(F.getSemantics(), "1.0");
11109   if (F > One)
11110     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
11111 
11112   return SDValue(CSrc, 0);
11113 }
11114 
11115 
11116 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
11117                                             DAGCombinerInfo &DCI) const {
11118   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
11119     return SDValue();
11120   switch (N->getOpcode()) {
11121   case ISD::ADD:
11122     return performAddCombine(N, DCI);
11123   case ISD::SUB:
11124     return performSubCombine(N, DCI);
11125   case ISD::ADDCARRY:
11126   case ISD::SUBCARRY:
11127     return performAddCarrySubCarryCombine(N, DCI);
11128   case ISD::FADD:
11129     return performFAddCombine(N, DCI);
11130   case ISD::FSUB:
11131     return performFSubCombine(N, DCI);
11132   case ISD::SETCC:
11133     return performSetCCCombine(N, DCI);
11134   case ISD::FMAXNUM:
11135   case ISD::FMINNUM:
11136   case ISD::FMAXNUM_IEEE:
11137   case ISD::FMINNUM_IEEE:
11138   case ISD::SMAX:
11139   case ISD::SMIN:
11140   case ISD::UMAX:
11141   case ISD::UMIN:
11142   case AMDGPUISD::FMIN_LEGACY:
11143   case AMDGPUISD::FMAX_LEGACY:
11144     return performMinMaxCombine(N, DCI);
11145   case ISD::FMA:
11146     return performFMACombine(N, DCI);
11147   case ISD::AND:
11148     return performAndCombine(N, DCI);
11149   case ISD::OR:
11150     return performOrCombine(N, DCI);
11151   case ISD::XOR:
11152     return performXorCombine(N, DCI);
11153   case ISD::ZERO_EXTEND:
11154     return performZeroExtendCombine(N, DCI);
11155   case ISD::SIGN_EXTEND_INREG:
11156     return performSignExtendInRegCombine(N , DCI);
11157   case AMDGPUISD::FP_CLASS:
11158     return performClassCombine(N, DCI);
11159   case ISD::FCANONICALIZE:
11160     return performFCanonicalizeCombine(N, DCI);
11161   case AMDGPUISD::RCP:
11162     return performRcpCombine(N, DCI);
11163   case AMDGPUISD::FRACT:
11164   case AMDGPUISD::RSQ:
11165   case AMDGPUISD::RCP_LEGACY:
11166   case AMDGPUISD::RCP_IFLAG:
11167   case AMDGPUISD::RSQ_CLAMP:
11168   case AMDGPUISD::LDEXP: {
11169     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
11170     SDValue Src = N->getOperand(0);
11171     if (Src.isUndef())
11172       return Src;
11173     break;
11174   }
11175   case ISD::SINT_TO_FP:
11176   case ISD::UINT_TO_FP:
11177     return performUCharToFloatCombine(N, DCI);
11178   case AMDGPUISD::CVT_F32_UBYTE0:
11179   case AMDGPUISD::CVT_F32_UBYTE1:
11180   case AMDGPUISD::CVT_F32_UBYTE2:
11181   case AMDGPUISD::CVT_F32_UBYTE3:
11182     return performCvtF32UByteNCombine(N, DCI);
11183   case AMDGPUISD::FMED3:
11184     return performFMed3Combine(N, DCI);
11185   case AMDGPUISD::CVT_PKRTZ_F16_F32:
11186     return performCvtPkRTZCombine(N, DCI);
11187   case AMDGPUISD::CLAMP:
11188     return performClampCombine(N, DCI);
11189   case ISD::SCALAR_TO_VECTOR: {
11190     SelectionDAG &DAG = DCI.DAG;
11191     EVT VT = N->getValueType(0);
11192 
11193     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
11194     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
11195       SDLoc SL(N);
11196       SDValue Src = N->getOperand(0);
11197       EVT EltVT = Src.getValueType();
11198       if (EltVT == MVT::f16)
11199         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
11200 
11201       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
11202       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
11203     }
11204 
11205     break;
11206   }
11207   case ISD::EXTRACT_VECTOR_ELT:
11208     return performExtractVectorEltCombine(N, DCI);
11209   case ISD::INSERT_VECTOR_ELT:
11210     return performInsertVectorEltCombine(N, DCI);
11211   case ISD::LOAD: {
11212     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
11213       return Widended;
11214     LLVM_FALLTHROUGH;
11215   }
11216   default: {
11217     if (!DCI.isBeforeLegalize()) {
11218       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
11219         return performMemSDNodeCombine(MemNode, DCI);
11220     }
11221 
11222     break;
11223   }
11224   }
11225 
11226   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
11227 }
11228 
11229 /// Helper function for adjustWritemask
11230 static unsigned SubIdx2Lane(unsigned Idx) {
11231   switch (Idx) {
11232   default: return ~0u;
11233   case AMDGPU::sub0: return 0;
11234   case AMDGPU::sub1: return 1;
11235   case AMDGPU::sub2: return 2;
11236   case AMDGPU::sub3: return 3;
11237   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
11238   }
11239 }
11240 
11241 /// Adjust the writemask of MIMG instructions
11242 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
11243                                           SelectionDAG &DAG) const {
11244   unsigned Opcode = Node->getMachineOpcode();
11245 
11246   // Subtract 1 because the vdata output is not a MachineSDNode operand.
11247   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
11248   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
11249     return Node; // not implemented for D16
11250 
11251   SDNode *Users[5] = { nullptr };
11252   unsigned Lane = 0;
11253   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
11254   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
11255   unsigned NewDmask = 0;
11256   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
11257   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
11258   bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
11259                   Node->getConstantOperandVal(LWEIdx))
11260                      ? true
11261                      : false;
11262   unsigned TFCLane = 0;
11263   bool HasChain = Node->getNumValues() > 1;
11264 
11265   if (OldDmask == 0) {
11266     // These are folded out, but on the chance it happens don't assert.
11267     return Node;
11268   }
11269 
11270   unsigned OldBitsSet = countPopulation(OldDmask);
11271   // Work out which is the TFE/LWE lane if that is enabled.
11272   if (UsesTFC) {
11273     TFCLane = OldBitsSet;
11274   }
11275 
11276   // Try to figure out the used register components
11277   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
11278        I != E; ++I) {
11279 
11280     // Don't look at users of the chain.
11281     if (I.getUse().getResNo() != 0)
11282       continue;
11283 
11284     // Abort if we can't understand the usage
11285     if (!I->isMachineOpcode() ||
11286         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
11287       return Node;
11288 
11289     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
11290     // Note that subregs are packed, i.e. Lane==0 is the first bit set
11291     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
11292     // set, etc.
11293     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
11294     if (Lane == ~0u)
11295       return Node;
11296 
11297     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
11298     if (UsesTFC && Lane == TFCLane) {
11299       Users[Lane] = *I;
11300     } else {
11301       // Set which texture component corresponds to the lane.
11302       unsigned Comp;
11303       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
11304         Comp = countTrailingZeros(Dmask);
11305         Dmask &= ~(1 << Comp);
11306       }
11307 
11308       // Abort if we have more than one user per component.
11309       if (Users[Lane])
11310         return Node;
11311 
11312       Users[Lane] = *I;
11313       NewDmask |= 1 << Comp;
11314     }
11315   }
11316 
11317   // Don't allow 0 dmask, as hardware assumes one channel enabled.
11318   bool NoChannels = !NewDmask;
11319   if (NoChannels) {
11320     if (!UsesTFC) {
11321       // No uses of the result and not using TFC. Then do nothing.
11322       return Node;
11323     }
11324     // If the original dmask has one channel - then nothing to do
11325     if (OldBitsSet == 1)
11326       return Node;
11327     // Use an arbitrary dmask - required for the instruction to work
11328     NewDmask = 1;
11329   }
11330   // Abort if there's no change
11331   if (NewDmask == OldDmask)
11332     return Node;
11333 
11334   unsigned BitsSet = countPopulation(NewDmask);
11335 
11336   // Check for TFE or LWE - increase the number of channels by one to account
11337   // for the extra return value
11338   // This will need adjustment for D16 if this is also included in
11339   // adjustWriteMask (this function) but at present D16 are excluded.
11340   unsigned NewChannels = BitsSet + UsesTFC;
11341 
11342   int NewOpcode =
11343       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
11344   assert(NewOpcode != -1 &&
11345          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
11346          "failed to find equivalent MIMG op");
11347 
11348   // Adjust the writemask in the node
11349   SmallVector<SDValue, 12> Ops;
11350   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
11351   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
11352   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11353 
11354   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11355 
11356   MVT ResultVT = NewChannels == 1 ?
11357     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11358                            NewChannels == 5 ? 8 : NewChannels);
11359   SDVTList NewVTList = HasChain ?
11360     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11361 
11362 
11363   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11364                                               NewVTList, Ops);
11365 
11366   if (HasChain) {
11367     // Update chain.
11368     DAG.setNodeMemRefs(NewNode, Node->memoperands());
11369     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11370   }
11371 
11372   if (NewChannels == 1) {
11373     assert(Node->hasNUsesOfValue(1, 0));
11374     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11375                                       SDLoc(Node), Users[Lane]->getValueType(0),
11376                                       SDValue(NewNode, 0));
11377     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11378     return nullptr;
11379   }
11380 
11381   // Update the users of the node with the new indices
11382   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11383     SDNode *User = Users[i];
11384     if (!User) {
11385       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11386       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11387       if (i || !NoChannels)
11388         continue;
11389     } else {
11390       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11391       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11392     }
11393 
11394     switch (Idx) {
11395     default: break;
11396     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11397     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11398     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11399     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11400     }
11401   }
11402 
11403   DAG.RemoveDeadNode(Node);
11404   return nullptr;
11405 }
11406 
11407 static bool isFrameIndexOp(SDValue Op) {
11408   if (Op.getOpcode() == ISD::AssertZext)
11409     Op = Op.getOperand(0);
11410 
11411   return isa<FrameIndexSDNode>(Op);
11412 }
11413 
11414 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11415 /// with frame index operands.
11416 /// LLVM assumes that inputs are to these instructions are registers.
11417 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11418                                                         SelectionDAG &DAG) const {
11419   if (Node->getOpcode() == ISD::CopyToReg) {
11420     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11421     SDValue SrcVal = Node->getOperand(2);
11422 
11423     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11424     // to try understanding copies to physical registers.
11425     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11426       SDLoc SL(Node);
11427       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11428       SDValue VReg = DAG.getRegister(
11429         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11430 
11431       SDNode *Glued = Node->getGluedNode();
11432       SDValue ToVReg
11433         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11434                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11435       SDValue ToResultReg
11436         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11437                            VReg, ToVReg.getValue(1));
11438       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11439       DAG.RemoveDeadNode(Node);
11440       return ToResultReg.getNode();
11441     }
11442   }
11443 
11444   SmallVector<SDValue, 8> Ops;
11445   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11446     if (!isFrameIndexOp(Node->getOperand(i))) {
11447       Ops.push_back(Node->getOperand(i));
11448       continue;
11449     }
11450 
11451     SDLoc DL(Node);
11452     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11453                                      Node->getOperand(i).getValueType(),
11454                                      Node->getOperand(i)), 0));
11455   }
11456 
11457   return DAG.UpdateNodeOperands(Node, Ops);
11458 }
11459 
11460 /// Fold the instructions after selecting them.
11461 /// Returns null if users were already updated.
11462 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11463                                           SelectionDAG &DAG) const {
11464   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11465   unsigned Opcode = Node->getMachineOpcode();
11466 
11467   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11468       !TII->isGather4(Opcode) &&
11469       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11470     return adjustWritemask(Node, DAG);
11471   }
11472 
11473   if (Opcode == AMDGPU::INSERT_SUBREG ||
11474       Opcode == AMDGPU::REG_SEQUENCE) {
11475     legalizeTargetIndependentNode(Node, DAG);
11476     return Node;
11477   }
11478 
11479   switch (Opcode) {
11480   case AMDGPU::V_DIV_SCALE_F32_e64:
11481   case AMDGPU::V_DIV_SCALE_F64_e64: {
11482     // Satisfy the operand register constraint when one of the inputs is
11483     // undefined. Ordinarily each undef value will have its own implicit_def of
11484     // a vreg, so force these to use a single register.
11485     SDValue Src0 = Node->getOperand(1);
11486     SDValue Src1 = Node->getOperand(3);
11487     SDValue Src2 = Node->getOperand(5);
11488 
11489     if ((Src0.isMachineOpcode() &&
11490          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11491         (Src0 == Src1 || Src0 == Src2))
11492       break;
11493 
11494     MVT VT = Src0.getValueType().getSimpleVT();
11495     const TargetRegisterClass *RC =
11496         getRegClassFor(VT, Src0.getNode()->isDivergent());
11497 
11498     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11499     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11500 
11501     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11502                                       UndefReg, Src0, SDValue());
11503 
11504     // src0 must be the same register as src1 or src2, even if the value is
11505     // undefined, so make sure we don't violate this constraint.
11506     if (Src0.isMachineOpcode() &&
11507         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11508       if (Src1.isMachineOpcode() &&
11509           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11510         Src0 = Src1;
11511       else if (Src2.isMachineOpcode() &&
11512                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11513         Src0 = Src2;
11514       else {
11515         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11516         Src0 = UndefReg;
11517         Src1 = UndefReg;
11518       }
11519     } else
11520       break;
11521 
11522     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11523     Ops[1] = Src0;
11524     Ops[3] = Src1;
11525     Ops[5] = Src2;
11526     Ops.push_back(ImpDef.getValue(1));
11527     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11528   }
11529   default:
11530     break;
11531   }
11532 
11533   return Node;
11534 }
11535 
11536 // Any MIMG instructions that use tfe or lwe require an initialization of the
11537 // result register that will be written in the case of a memory access failure.
11538 // The required code is also added to tie this init code to the result of the
11539 // img instruction.
11540 void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
11541   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11542   const SIRegisterInfo &TRI = TII->getRegisterInfo();
11543   MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11544   MachineBasicBlock &MBB = *MI.getParent();
11545 
11546   MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
11547   MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
11548   MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
11549 
11550   if (!TFE && !LWE) // intersect_ray
11551     return;
11552 
11553   unsigned TFEVal = TFE ? TFE->getImm() : 0;
11554   unsigned LWEVal = LWE->getImm();
11555   unsigned D16Val = D16 ? D16->getImm() : 0;
11556 
11557   if (!TFEVal && !LWEVal)
11558     return;
11559 
11560   // At least one of TFE or LWE are non-zero
11561   // We have to insert a suitable initialization of the result value and
11562   // tie this to the dest of the image instruction.
11563 
11564   const DebugLoc &DL = MI.getDebugLoc();
11565 
11566   int DstIdx =
11567       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
11568 
11569   // Calculate which dword we have to initialize to 0.
11570   MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
11571 
11572   // check that dmask operand is found.
11573   assert(MO_Dmask && "Expected dmask operand in instruction");
11574 
11575   unsigned dmask = MO_Dmask->getImm();
11576   // Determine the number of active lanes taking into account the
11577   // Gather4 special case
11578   unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask);
11579 
11580   bool Packed = !Subtarget->hasUnpackedD16VMem();
11581 
11582   unsigned InitIdx =
11583       D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
11584 
11585   // Abandon attempt if the dst size isn't large enough
11586   // - this is in fact an error but this is picked up elsewhere and
11587   // reported correctly.
11588   uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
11589   if (DstSize < InitIdx)
11590     return;
11591 
11592   // Create a register for the initialization value.
11593   Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11594   unsigned NewDst = 0; // Final initialized value will be in here
11595 
11596   // If PRTStrictNull feature is enabled (the default) then initialize
11597   // all the result registers to 0, otherwise just the error indication
11598   // register (VGPRn+1)
11599   unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
11600   unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
11601 
11602   BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
11603   for (; SizeLeft; SizeLeft--, CurrIdx++) {
11604     NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11605     // Initialize dword
11606     Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
11607     BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
11608       .addImm(0);
11609     // Insert into the super-reg
11610     BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
11611       .addReg(PrevDst)
11612       .addReg(SubReg)
11613       .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
11614 
11615     PrevDst = NewDst;
11616   }
11617 
11618   // Add as an implicit operand
11619   MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
11620 
11621   // Tie the just added implicit operand to the dst
11622   MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
11623 }
11624 
11625 /// Assign the register class depending on the number of
11626 /// bits set in the writemask
11627 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11628                                                      SDNode *Node) const {
11629   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11630 
11631   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11632 
11633   if (TII->isVOP3(MI.getOpcode())) {
11634     // Make sure constant bus requirements are respected.
11635     TII->legalizeOperandsVOP3(MRI, MI);
11636 
11637     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11638     // This saves a chain-copy of registers and better balance register
11639     // use between vgpr and agpr as agpr tuples tend to be big.
11640     if (MI.getDesc().OpInfo) {
11641       unsigned Opc = MI.getOpcode();
11642       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11643       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11644                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11645         if (I == -1)
11646           break;
11647         MachineOperand &Op = MI.getOperand(I);
11648         if (!Op.isReg() || !Op.getReg().isVirtual())
11649           continue;
11650         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11651         if (!TRI->hasAGPRs(RC))
11652           continue;
11653         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11654         if (!Src || !Src->isCopy() ||
11655             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11656           continue;
11657         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11658         // All uses of agpr64 and agpr32 can also accept vgpr except for
11659         // v_accvgpr_read, but we do not produce agpr reads during selection,
11660         // so no use checks are needed.
11661         MRI.setRegClass(Op.getReg(), NewRC);
11662       }
11663     }
11664 
11665     return;
11666   }
11667 
11668   // Replace unused atomics with the no return version.
11669   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11670   if (NoRetAtomicOp != -1) {
11671     if (!Node->hasAnyUseOfValue(0)) {
11672       int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
11673                                                AMDGPU::OpName::cpol);
11674       if (CPolIdx != -1) {
11675         MachineOperand &CPol = MI.getOperand(CPolIdx);
11676         CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC);
11677       }
11678       MI.RemoveOperand(0);
11679       MI.setDesc(TII->get(NoRetAtomicOp));
11680       return;
11681     }
11682 
11683     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11684     // instruction, because the return type of these instructions is a vec2 of
11685     // the memory type, so it can be tied to the input operand.
11686     // This means these instructions always have a use, so we need to add a
11687     // special case to check if the atomic has only one extract_subreg use,
11688     // which itself has no uses.
11689     if ((Node->hasNUsesOfValue(1, 0) &&
11690          Node->use_begin()->isMachineOpcode() &&
11691          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11692          !Node->use_begin()->hasAnyUseOfValue(0))) {
11693       Register Def = MI.getOperand(0).getReg();
11694 
11695       // Change this into a noret atomic.
11696       MI.setDesc(TII->get(NoRetAtomicOp));
11697       MI.RemoveOperand(0);
11698 
11699       // If we only remove the def operand from the atomic instruction, the
11700       // extract_subreg will be left with a use of a vreg without a def.
11701       // So we need to insert an implicit_def to avoid machine verifier
11702       // errors.
11703       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11704               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11705     }
11706     return;
11707   }
11708 
11709   if (TII->isMIMG(MI) && !MI.mayStore())
11710     AddIMGInit(MI);
11711 }
11712 
11713 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11714                               uint64_t Val) {
11715   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11716   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11717 }
11718 
11719 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11720                                                 const SDLoc &DL,
11721                                                 SDValue Ptr) const {
11722   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11723 
11724   // Build the half of the subregister with the constants before building the
11725   // full 128-bit register. If we are building multiple resource descriptors,
11726   // this will allow CSEing of the 2-component register.
11727   const SDValue Ops0[] = {
11728     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11729     buildSMovImm32(DAG, DL, 0),
11730     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11731     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11732     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11733   };
11734 
11735   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11736                                                 MVT::v2i32, Ops0), 0);
11737 
11738   // Combine the constants and the pointer.
11739   const SDValue Ops1[] = {
11740     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11741     Ptr,
11742     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11743     SubRegHi,
11744     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11745   };
11746 
11747   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11748 }
11749 
11750 /// Return a resource descriptor with the 'Add TID' bit enabled
11751 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11752 ///        of the resource descriptor) to create an offset, which is added to
11753 ///        the resource pointer.
11754 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11755                                            SDValue Ptr, uint32_t RsrcDword1,
11756                                            uint64_t RsrcDword2And3) const {
11757   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11758   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11759   if (RsrcDword1) {
11760     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11761                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11762                     0);
11763   }
11764 
11765   SDValue DataLo = buildSMovImm32(DAG, DL,
11766                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11767   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11768 
11769   const SDValue Ops[] = {
11770     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11771     PtrLo,
11772     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11773     PtrHi,
11774     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11775     DataLo,
11776     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11777     DataHi,
11778     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11779   };
11780 
11781   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11782 }
11783 
11784 //===----------------------------------------------------------------------===//
11785 //                         SI Inline Assembly Support
11786 //===----------------------------------------------------------------------===//
11787 
11788 std::pair<unsigned, const TargetRegisterClass *>
11789 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
11790                                                StringRef Constraint,
11791                                                MVT VT) const {
11792   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
11793 
11794   const TargetRegisterClass *RC = nullptr;
11795   if (Constraint.size() == 1) {
11796     const unsigned BitWidth = VT.getSizeInBits();
11797     switch (Constraint[0]) {
11798     default:
11799       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11800     case 's':
11801     case 'r':
11802       switch (BitWidth) {
11803       case 16:
11804         RC = &AMDGPU::SReg_32RegClass;
11805         break;
11806       case 64:
11807         RC = &AMDGPU::SGPR_64RegClass;
11808         break;
11809       default:
11810         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11811         if (!RC)
11812           return std::make_pair(0U, nullptr);
11813         break;
11814       }
11815       break;
11816     case 'v':
11817       switch (BitWidth) {
11818       case 16:
11819         RC = &AMDGPU::VGPR_32RegClass;
11820         break;
11821       default:
11822         RC = TRI->getVGPRClassForBitWidth(BitWidth);
11823         if (!RC)
11824           return std::make_pair(0U, nullptr);
11825         break;
11826       }
11827       break;
11828     case 'a':
11829       if (!Subtarget->hasMAIInsts())
11830         break;
11831       switch (BitWidth) {
11832       case 16:
11833         RC = &AMDGPU::AGPR_32RegClass;
11834         break;
11835       default:
11836         RC = TRI->getAGPRClassForBitWidth(BitWidth);
11837         if (!RC)
11838           return std::make_pair(0U, nullptr);
11839         break;
11840       }
11841       break;
11842     }
11843     // We actually support i128, i16 and f16 as inline parameters
11844     // even if they are not reported as legal
11845     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11846                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11847       return std::make_pair(0U, RC);
11848   }
11849 
11850   if (Constraint.startswith("{") && Constraint.endswith("}")) {
11851     StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
11852     if (RegName.consume_front("v")) {
11853       RC = &AMDGPU::VGPR_32RegClass;
11854     } else if (RegName.consume_front("s")) {
11855       RC = &AMDGPU::SGPR_32RegClass;
11856     } else if (RegName.consume_front("a")) {
11857       RC = &AMDGPU::AGPR_32RegClass;
11858     }
11859 
11860     if (RC) {
11861       uint32_t Idx;
11862       if (RegName.consume_front("[")) {
11863         uint32_t End;
11864         bool Failed = RegName.consumeInteger(10, Idx);
11865         Failed |= !RegName.consume_front(":");
11866         Failed |= RegName.consumeInteger(10, End);
11867         Failed |= !RegName.consume_back("]");
11868         if (!Failed) {
11869           uint32_t Width = (End - Idx + 1) * 32;
11870           MCRegister Reg = RC->getRegister(Idx);
11871           if (SIRegisterInfo::isVGPRClass(RC))
11872             RC = TRI->getVGPRClassForBitWidth(Width);
11873           else if (SIRegisterInfo::isSGPRClass(RC))
11874             RC = TRI->getSGPRClassForBitWidth(Width);
11875           else if (SIRegisterInfo::isAGPRClass(RC))
11876             RC = TRI->getAGPRClassForBitWidth(Width);
11877           if (RC) {
11878             Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC);
11879             return std::make_pair(Reg, RC);
11880           }
11881         }
11882       } else {
11883         bool Failed = RegName.getAsInteger(10, Idx);
11884         if (!Failed && Idx < RC->getNumRegs())
11885           return std::make_pair(RC->getRegister(Idx), RC);
11886       }
11887     }
11888   }
11889 
11890   auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11891   if (Ret.first)
11892     Ret.second = TRI->getPhysRegClass(Ret.first);
11893 
11894   return Ret;
11895 }
11896 
11897 static bool isImmConstraint(StringRef Constraint) {
11898   if (Constraint.size() == 1) {
11899     switch (Constraint[0]) {
11900     default: break;
11901     case 'I':
11902     case 'J':
11903     case 'A':
11904     case 'B':
11905     case 'C':
11906       return true;
11907     }
11908   } else if (Constraint == "DA" ||
11909              Constraint == "DB") {
11910     return true;
11911   }
11912   return false;
11913 }
11914 
11915 SITargetLowering::ConstraintType
11916 SITargetLowering::getConstraintType(StringRef Constraint) const {
11917   if (Constraint.size() == 1) {
11918     switch (Constraint[0]) {
11919     default: break;
11920     case 's':
11921     case 'v':
11922     case 'a':
11923       return C_RegisterClass;
11924     }
11925   }
11926   if (isImmConstraint(Constraint)) {
11927     return C_Other;
11928   }
11929   return TargetLowering::getConstraintType(Constraint);
11930 }
11931 
11932 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11933   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11934     Val = Val & maskTrailingOnes<uint64_t>(Size);
11935   }
11936   return Val;
11937 }
11938 
11939 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11940                                                     std::string &Constraint,
11941                                                     std::vector<SDValue> &Ops,
11942                                                     SelectionDAG &DAG) const {
11943   if (isImmConstraint(Constraint)) {
11944     uint64_t Val;
11945     if (getAsmOperandConstVal(Op, Val) &&
11946         checkAsmConstraintVal(Op, Constraint, Val)) {
11947       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11948       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11949     }
11950   } else {
11951     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11952   }
11953 }
11954 
11955 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11956   unsigned Size = Op.getScalarValueSizeInBits();
11957   if (Size > 64)
11958     return false;
11959 
11960   if (Size == 16 && !Subtarget->has16BitInsts())
11961     return false;
11962 
11963   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11964     Val = C->getSExtValue();
11965     return true;
11966   }
11967   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11968     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11969     return true;
11970   }
11971   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11972     if (Size != 16 || Op.getNumOperands() != 2)
11973       return false;
11974     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11975       return false;
11976     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11977       Val = C->getSExtValue();
11978       return true;
11979     }
11980     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11981       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11982       return true;
11983     }
11984   }
11985 
11986   return false;
11987 }
11988 
11989 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11990                                              const std::string &Constraint,
11991                                              uint64_t Val) const {
11992   if (Constraint.size() == 1) {
11993     switch (Constraint[0]) {
11994     case 'I':
11995       return AMDGPU::isInlinableIntLiteral(Val);
11996     case 'J':
11997       return isInt<16>(Val);
11998     case 'A':
11999       return checkAsmConstraintValA(Op, Val);
12000     case 'B':
12001       return isInt<32>(Val);
12002     case 'C':
12003       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
12004              AMDGPU::isInlinableIntLiteral(Val);
12005     default:
12006       break;
12007     }
12008   } else if (Constraint.size() == 2) {
12009     if (Constraint == "DA") {
12010       int64_t HiBits = static_cast<int32_t>(Val >> 32);
12011       int64_t LoBits = static_cast<int32_t>(Val);
12012       return checkAsmConstraintValA(Op, HiBits, 32) &&
12013              checkAsmConstraintValA(Op, LoBits, 32);
12014     }
12015     if (Constraint == "DB") {
12016       return true;
12017     }
12018   }
12019   llvm_unreachable("Invalid asm constraint");
12020 }
12021 
12022 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
12023                                               uint64_t Val,
12024                                               unsigned MaxSize) const {
12025   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
12026   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
12027   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
12028       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
12029       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
12030     return true;
12031   }
12032   return false;
12033 }
12034 
12035 static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
12036   switch (UnalignedClassID) {
12037   case AMDGPU::VReg_64RegClassID:
12038     return AMDGPU::VReg_64_Align2RegClassID;
12039   case AMDGPU::VReg_96RegClassID:
12040     return AMDGPU::VReg_96_Align2RegClassID;
12041   case AMDGPU::VReg_128RegClassID:
12042     return AMDGPU::VReg_128_Align2RegClassID;
12043   case AMDGPU::VReg_160RegClassID:
12044     return AMDGPU::VReg_160_Align2RegClassID;
12045   case AMDGPU::VReg_192RegClassID:
12046     return AMDGPU::VReg_192_Align2RegClassID;
12047   case AMDGPU::VReg_224RegClassID:
12048     return AMDGPU::VReg_224_Align2RegClassID;
12049   case AMDGPU::VReg_256RegClassID:
12050     return AMDGPU::VReg_256_Align2RegClassID;
12051   case AMDGPU::VReg_512RegClassID:
12052     return AMDGPU::VReg_512_Align2RegClassID;
12053   case AMDGPU::VReg_1024RegClassID:
12054     return AMDGPU::VReg_1024_Align2RegClassID;
12055   case AMDGPU::AReg_64RegClassID:
12056     return AMDGPU::AReg_64_Align2RegClassID;
12057   case AMDGPU::AReg_96RegClassID:
12058     return AMDGPU::AReg_96_Align2RegClassID;
12059   case AMDGPU::AReg_128RegClassID:
12060     return AMDGPU::AReg_128_Align2RegClassID;
12061   case AMDGPU::AReg_160RegClassID:
12062     return AMDGPU::AReg_160_Align2RegClassID;
12063   case AMDGPU::AReg_192RegClassID:
12064     return AMDGPU::AReg_192_Align2RegClassID;
12065   case AMDGPU::AReg_256RegClassID:
12066     return AMDGPU::AReg_256_Align2RegClassID;
12067   case AMDGPU::AReg_512RegClassID:
12068     return AMDGPU::AReg_512_Align2RegClassID;
12069   case AMDGPU::AReg_1024RegClassID:
12070     return AMDGPU::AReg_1024_Align2RegClassID;
12071   default:
12072     return -1;
12073   }
12074 }
12075 
12076 // Figure out which registers should be reserved for stack access. Only after
12077 // the function is legalized do we know all of the non-spill stack objects or if
12078 // calls are present.
12079 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
12080   MachineRegisterInfo &MRI = MF.getRegInfo();
12081   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12082   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
12083   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12084   const SIInstrInfo *TII = ST.getInstrInfo();
12085 
12086   if (Info->isEntryFunction()) {
12087     // Callable functions have fixed registers used for stack access.
12088     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
12089   }
12090 
12091   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
12092                              Info->getStackPtrOffsetReg()));
12093   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
12094     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
12095 
12096   // We need to worry about replacing the default register with itself in case
12097   // of MIR testcases missing the MFI.
12098   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
12099     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
12100 
12101   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
12102     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
12103 
12104   Info->limitOccupancy(MF);
12105 
12106   if (ST.isWave32() && !MF.empty()) {
12107     for (auto &MBB : MF) {
12108       for (auto &MI : MBB) {
12109         TII->fixImplicitOperands(MI);
12110       }
12111     }
12112   }
12113 
12114   // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
12115   // classes if required. Ideally the register class constraints would differ
12116   // per-subtarget, but there's no easy way to achieve that right now. This is
12117   // not a problem for VGPRs because the correctly aligned VGPR class is implied
12118   // from using them as the register class for legal types.
12119   if (ST.needsAlignedVGPRs()) {
12120     for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
12121       const Register Reg = Register::index2VirtReg(I);
12122       const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
12123       if (!RC)
12124         continue;
12125       int NewClassID = getAlignedAGPRClassID(RC->getID());
12126       if (NewClassID != -1)
12127         MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
12128     }
12129   }
12130 
12131   TargetLoweringBase::finalizeLowering(MF);
12132 }
12133 
12134 void SITargetLowering::computeKnownBitsForFrameIndex(
12135   const int FI, KnownBits &Known, const MachineFunction &MF) const {
12136   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
12137 
12138   // Set the high bits to zero based on the maximum allowed scratch size per
12139   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
12140   // calculation won't overflow, so assume the sign bit is never set.
12141   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
12142 }
12143 
12144 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
12145                                    KnownBits &Known, unsigned Dim) {
12146   unsigned MaxValue =
12147       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
12148   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
12149 }
12150 
12151 void SITargetLowering::computeKnownBitsForTargetInstr(
12152     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
12153     const MachineRegisterInfo &MRI, unsigned Depth) const {
12154   const MachineInstr *MI = MRI.getVRegDef(R);
12155   switch (MI->getOpcode()) {
12156   case AMDGPU::G_INTRINSIC: {
12157     switch (MI->getIntrinsicID()) {
12158     case Intrinsic::amdgcn_workitem_id_x:
12159       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
12160       break;
12161     case Intrinsic::amdgcn_workitem_id_y:
12162       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
12163       break;
12164     case Intrinsic::amdgcn_workitem_id_z:
12165       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
12166       break;
12167     case Intrinsic::amdgcn_mbcnt_lo:
12168     case Intrinsic::amdgcn_mbcnt_hi: {
12169       // These return at most the wavefront size - 1.
12170       unsigned Size = MRI.getType(R).getSizeInBits();
12171       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
12172       break;
12173     }
12174     case Intrinsic::amdgcn_groupstaticsize: {
12175       // We can report everything over the maximum size as 0. We can't report
12176       // based on the actual size because we don't know if it's accurate or not
12177       // at any given point.
12178       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
12179       break;
12180     }
12181     }
12182     break;
12183   }
12184   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
12185     Known.Zero.setHighBits(24);
12186     break;
12187   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
12188     Known.Zero.setHighBits(16);
12189     break;
12190   }
12191 }
12192 
12193 Align SITargetLowering::computeKnownAlignForTargetInstr(
12194   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
12195   unsigned Depth) const {
12196   const MachineInstr *MI = MRI.getVRegDef(R);
12197   switch (MI->getOpcode()) {
12198   case AMDGPU::G_INTRINSIC:
12199   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
12200     // FIXME: Can this move to generic code? What about the case where the call
12201     // site specifies a lower alignment?
12202     Intrinsic::ID IID = MI->getIntrinsicID();
12203     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
12204     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
12205     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
12206       return *RetAlign;
12207     return Align(1);
12208   }
12209   default:
12210     return Align(1);
12211   }
12212 }
12213 
12214 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12215   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
12216   const Align CacheLineAlign = Align(64);
12217 
12218   // Pre-GFX10 target did not benefit from loop alignment
12219   if (!ML || DisableLoopAlignment ||
12220       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
12221       getSubtarget()->hasInstFwdPrefetchBug())
12222     return PrefAlign;
12223 
12224   // On GFX10 I$ is 4 x 64 bytes cache lines.
12225   // By default prefetcher keeps one cache line behind and reads two ahead.
12226   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
12227   // behind and one ahead.
12228   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
12229   // If loop fits 64 bytes it always spans no more than two cache lines and
12230   // does not need an alignment.
12231   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
12232   // Else if loop is less or equal 192 bytes we need two lines behind.
12233 
12234   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12235   const MachineBasicBlock *Header = ML->getHeader();
12236   if (Header->getAlignment() != PrefAlign)
12237     return Header->getAlignment(); // Already processed.
12238 
12239   unsigned LoopSize = 0;
12240   for (const MachineBasicBlock *MBB : ML->blocks()) {
12241     // If inner loop block is aligned assume in average half of the alignment
12242     // size to be added as nops.
12243     if (MBB != Header)
12244       LoopSize += MBB->getAlignment().value() / 2;
12245 
12246     for (const MachineInstr &MI : *MBB) {
12247       LoopSize += TII->getInstSizeInBytes(MI);
12248       if (LoopSize > 192)
12249         return PrefAlign;
12250     }
12251   }
12252 
12253   if (LoopSize <= 64)
12254     return PrefAlign;
12255 
12256   if (LoopSize <= 128)
12257     return CacheLineAlign;
12258 
12259   // If any of parent loops is surrounded by prefetch instructions do not
12260   // insert new for inner loop, which would reset parent's settings.
12261   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
12262     if (MachineBasicBlock *Exit = P->getExitBlock()) {
12263       auto I = Exit->getFirstNonDebugInstr();
12264       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
12265         return CacheLineAlign;
12266     }
12267   }
12268 
12269   MachineBasicBlock *Pre = ML->getLoopPreheader();
12270   MachineBasicBlock *Exit = ML->getExitBlock();
12271 
12272   if (Pre && Exit) {
12273     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
12274             TII->get(AMDGPU::S_INST_PREFETCH))
12275       .addImm(1); // prefetch 2 lines behind PC
12276 
12277     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
12278             TII->get(AMDGPU::S_INST_PREFETCH))
12279       .addImm(2); // prefetch 1 line behind PC
12280   }
12281 
12282   return CacheLineAlign;
12283 }
12284 
12285 LLVM_ATTRIBUTE_UNUSED
12286 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
12287   assert(N->getOpcode() == ISD::CopyFromReg);
12288   do {
12289     // Follow the chain until we find an INLINEASM node.
12290     N = N->getOperand(0).getNode();
12291     if (N->getOpcode() == ISD::INLINEASM ||
12292         N->getOpcode() == ISD::INLINEASM_BR)
12293       return true;
12294   } while (N->getOpcode() == ISD::CopyFromReg);
12295   return false;
12296 }
12297 
12298 bool SITargetLowering::isSDNodeSourceOfDivergence(
12299     const SDNode *N, FunctionLoweringInfo *FLI,
12300     LegacyDivergenceAnalysis *KDA) const {
12301   switch (N->getOpcode()) {
12302   case ISD::CopyFromReg: {
12303     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
12304     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
12305     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12306     Register Reg = R->getReg();
12307 
12308     // FIXME: Why does this need to consider isLiveIn?
12309     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
12310       return !TRI->isSGPRReg(MRI, Reg);
12311 
12312     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
12313       return KDA->isDivergent(V);
12314 
12315     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
12316     return !TRI->isSGPRReg(MRI, Reg);
12317   }
12318   case ISD::LOAD: {
12319     const LoadSDNode *L = cast<LoadSDNode>(N);
12320     unsigned AS = L->getAddressSpace();
12321     // A flat load may access private memory.
12322     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
12323   }
12324   case ISD::CALLSEQ_END:
12325     return true;
12326   case ISD::INTRINSIC_WO_CHAIN:
12327     return AMDGPU::isIntrinsicSourceOfDivergence(
12328         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
12329   case ISD::INTRINSIC_W_CHAIN:
12330     return AMDGPU::isIntrinsicSourceOfDivergence(
12331         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
12332   case AMDGPUISD::ATOMIC_CMP_SWAP:
12333   case AMDGPUISD::ATOMIC_INC:
12334   case AMDGPUISD::ATOMIC_DEC:
12335   case AMDGPUISD::ATOMIC_LOAD_FMIN:
12336   case AMDGPUISD::ATOMIC_LOAD_FMAX:
12337   case AMDGPUISD::BUFFER_ATOMIC_SWAP:
12338   case AMDGPUISD::BUFFER_ATOMIC_ADD:
12339   case AMDGPUISD::BUFFER_ATOMIC_SUB:
12340   case AMDGPUISD::BUFFER_ATOMIC_SMIN:
12341   case AMDGPUISD::BUFFER_ATOMIC_UMIN:
12342   case AMDGPUISD::BUFFER_ATOMIC_SMAX:
12343   case AMDGPUISD::BUFFER_ATOMIC_UMAX:
12344   case AMDGPUISD::BUFFER_ATOMIC_AND:
12345   case AMDGPUISD::BUFFER_ATOMIC_OR:
12346   case AMDGPUISD::BUFFER_ATOMIC_XOR:
12347   case AMDGPUISD::BUFFER_ATOMIC_INC:
12348   case AMDGPUISD::BUFFER_ATOMIC_DEC:
12349   case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
12350   case AMDGPUISD::BUFFER_ATOMIC_CSUB:
12351   case AMDGPUISD::BUFFER_ATOMIC_FADD:
12352   case AMDGPUISD::BUFFER_ATOMIC_FMIN:
12353   case AMDGPUISD::BUFFER_ATOMIC_FMAX:
12354     // Target-specific read-modify-write atomics are sources of divergence.
12355     return true;
12356   default:
12357     if (auto *A = dyn_cast<AtomicSDNode>(N)) {
12358       // Generic read-modify-write atomics are sources of divergence.
12359       return A->readMem() && A->writeMem();
12360     }
12361     return false;
12362   }
12363 }
12364 
12365 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
12366                                                EVT VT) const {
12367   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
12368   case MVT::f32:
12369     return hasFP32Denormals(DAG.getMachineFunction());
12370   case MVT::f64:
12371   case MVT::f16:
12372     return hasFP64FP16Denormals(DAG.getMachineFunction());
12373   default:
12374     return false;
12375   }
12376 }
12377 
12378 bool SITargetLowering::denormalsEnabledForType(LLT Ty,
12379                                                MachineFunction &MF) const {
12380   switch (Ty.getScalarSizeInBits()) {
12381   case 32:
12382     return hasFP32Denormals(MF);
12383   case 64:
12384   case 16:
12385     return hasFP64FP16Denormals(MF);
12386   default:
12387     return false;
12388   }
12389 }
12390 
12391 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
12392                                                     const SelectionDAG &DAG,
12393                                                     bool SNaN,
12394                                                     unsigned Depth) const {
12395   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
12396     const MachineFunction &MF = DAG.getMachineFunction();
12397     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12398 
12399     if (Info->getMode().DX10Clamp)
12400       return true; // Clamped to 0.
12401     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
12402   }
12403 
12404   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
12405                                                             SNaN, Depth);
12406 }
12407 
12408 // Global FP atomic instructions have a hardcoded FP mode and do not support
12409 // FP32 denormals, and only support v2f16 denormals.
12410 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
12411   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
12412   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
12413   if (&Flt == &APFloat::IEEEsingle())
12414     return DenormMode == DenormalMode::getPreserveSign();
12415   return DenormMode == DenormalMode::getIEEE();
12416 }
12417 
12418 TargetLowering::AtomicExpansionKind
12419 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
12420 
12421   auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) {
12422     OptimizationRemarkEmitter ORE(RMW->getFunction());
12423     LLVMContext &Ctx = RMW->getFunction()->getContext();
12424     SmallVector<StringRef> SSNs;
12425     Ctx.getSyncScopeNames(SSNs);
12426     auto MemScope = SSNs[RMW->getSyncScopeID()].empty()
12427                         ? "system"
12428                         : SSNs[RMW->getSyncScopeID()];
12429     ORE.emit([&]() {
12430       return OptimizationRemark(DEBUG_TYPE, "Passed", RMW)
12431              << "Hardware instruction generated for atomic "
12432              << RMW->getOperationName(RMW->getOperation())
12433              << " operation at memory scope " << MemScope
12434              << " due to an unsafe request.";
12435     });
12436     return Kind;
12437   };
12438 
12439   switch (RMW->getOperation()) {
12440   case AtomicRMWInst::FAdd: {
12441     Type *Ty = RMW->getType();
12442 
12443     // We don't have a way to support 16-bit atomics now, so just leave them
12444     // as-is.
12445     if (Ty->isHalfTy())
12446       return AtomicExpansionKind::None;
12447 
12448     if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
12449       return AtomicExpansionKind::CmpXChg;
12450 
12451     unsigned AS = RMW->getPointerAddressSpace();
12452 
12453     if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) &&
12454          Subtarget->hasAtomicFaddInsts()) {
12455       if (Subtarget->hasGFX940Insts())
12456         return AtomicExpansionKind::None;
12457 
12458       // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
12459       // floating point atomic instructions. May generate more efficient code,
12460       // but may not respect rounding and denormal modes, and may give incorrect
12461       // results for certain memory destinations.
12462       if (RMW->getFunction()
12463               ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12464               .getValueAsString() != "true")
12465         return AtomicExpansionKind::CmpXChg;
12466 
12467       if (Subtarget->hasGFX90AInsts()) {
12468         if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS)
12469           return AtomicExpansionKind::CmpXChg;
12470 
12471         auto SSID = RMW->getSyncScopeID();
12472         if (SSID == SyncScope::System ||
12473             SSID == RMW->getContext().getOrInsertSyncScopeID("one-as"))
12474           return AtomicExpansionKind::CmpXChg;
12475 
12476         return ReportUnsafeHWInst(AtomicExpansionKind::None);
12477       }
12478 
12479       if (AS == AMDGPUAS::FLAT_ADDRESS)
12480         return AtomicExpansionKind::CmpXChg;
12481 
12482       return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12483                               : AtomicExpansionKind::CmpXChg;
12484     }
12485 
12486     // DS FP atomics do respect the denormal mode, but the rounding mode is
12487     // fixed to round-to-nearest-even.
12488     // The only exception is DS_ADD_F64 which never flushes regardless of mode.
12489     if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) {
12490       if (!Ty->isDoubleTy())
12491         return AtomicExpansionKind::None;
12492 
12493       if (fpModeMatchesGlobalFPAtomicMode(RMW))
12494         return AtomicExpansionKind::None;
12495 
12496       return RMW->getFunction()
12497                          ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12498                          .getValueAsString() == "true"
12499                  ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12500                  : AtomicExpansionKind::CmpXChg;
12501     }
12502 
12503     return AtomicExpansionKind::CmpXChg;
12504   }
12505   default:
12506     break;
12507   }
12508 
12509   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
12510 }
12511 
12512 const TargetRegisterClass *
12513 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
12514   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
12515   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12516   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
12517     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
12518                                                : &AMDGPU::SReg_32RegClass;
12519   if (!TRI->isSGPRClass(RC) && !isDivergent)
12520     return TRI->getEquivalentSGPRClass(RC);
12521   else if (TRI->isSGPRClass(RC) && isDivergent)
12522     return TRI->getEquivalentVGPRClass(RC);
12523 
12524   return RC;
12525 }
12526 
12527 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
12528 // uniform values (as produced by the mask results of control flow intrinsics)
12529 // used outside of divergent blocks. The phi users need to also be treated as
12530 // always uniform.
12531 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
12532                       unsigned WaveSize) {
12533   // FIXME: We assume we never cast the mask results of a control flow
12534   // intrinsic.
12535   // Early exit if the type won't be consistent as a compile time hack.
12536   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
12537   if (!IT || IT->getBitWidth() != WaveSize)
12538     return false;
12539 
12540   if (!isa<Instruction>(V))
12541     return false;
12542   if (!Visited.insert(V).second)
12543     return false;
12544   bool Result = false;
12545   for (auto U : V->users()) {
12546     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
12547       if (V == U->getOperand(1)) {
12548         switch (Intrinsic->getIntrinsicID()) {
12549         default:
12550           Result = false;
12551           break;
12552         case Intrinsic::amdgcn_if_break:
12553         case Intrinsic::amdgcn_if:
12554         case Intrinsic::amdgcn_else:
12555           Result = true;
12556           break;
12557         }
12558       }
12559       if (V == U->getOperand(0)) {
12560         switch (Intrinsic->getIntrinsicID()) {
12561         default:
12562           Result = false;
12563           break;
12564         case Intrinsic::amdgcn_end_cf:
12565         case Intrinsic::amdgcn_loop:
12566           Result = true;
12567           break;
12568         }
12569       }
12570     } else {
12571       Result = hasCFUser(U, Visited, WaveSize);
12572     }
12573     if (Result)
12574       break;
12575   }
12576   return Result;
12577 }
12578 
12579 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
12580                                                const Value *V) const {
12581   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
12582     if (CI->isInlineAsm()) {
12583       // FIXME: This cannot give a correct answer. This should only trigger in
12584       // the case where inline asm returns mixed SGPR and VGPR results, used
12585       // outside the defining block. We don't have a specific result to
12586       // consider, so this assumes if any value is SGPR, the overall register
12587       // also needs to be SGPR.
12588       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
12589       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
12590           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
12591       for (auto &TC : TargetConstraints) {
12592         if (TC.Type == InlineAsm::isOutput) {
12593           ComputeConstraintToUse(TC, SDValue());
12594           const TargetRegisterClass *RC = getRegForInlineAsmConstraint(
12595               SIRI, TC.ConstraintCode, TC.ConstraintVT).second;
12596           if (RC && SIRI->isSGPRClass(RC))
12597             return true;
12598         }
12599       }
12600     }
12601   }
12602   SmallPtrSet<const Value *, 16> Visited;
12603   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
12604 }
12605 
12606 std::pair<InstructionCost, MVT>
12607 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
12608                                           Type *Ty) const {
12609   std::pair<InstructionCost, MVT> Cost =
12610       TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
12611   auto Size = DL.getTypeSizeInBits(Ty);
12612   // Maximum load or store can handle 8 dwords for scalar and 4 for
12613   // vector ALU. Let's assume anything above 8 dwords is expensive
12614   // even if legal.
12615   if (Size <= 256)
12616     return Cost;
12617 
12618   Cost.first += (Size + 255) / 256;
12619   return Cost;
12620 }
12621 
12622 bool SITargetLowering::hasMemSDNodeUser(SDNode *N) const {
12623   SDNode::use_iterator I = N->use_begin(), E = N->use_end();
12624   for (; I != E; ++I) {
12625     if (MemSDNode *M = dyn_cast<MemSDNode>(*I)) {
12626       if (getBasePtrIndex(M) == I.getOperandNo())
12627         return true;
12628     }
12629   }
12630   return false;
12631 }
12632 
12633 bool SITargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0,
12634                                            SDValue N1) const {
12635   if (!N0.hasOneUse())
12636     return false;
12637   // Take care of the opportunity to keep N0 uniform
12638   if (N0->isDivergent() || !N1->isDivergent())
12639     return true;
12640   // Check if we have a good chance to form the memory access pattern with the
12641   // base and offset
12642   return (DAG.isBaseWithConstantOffset(N0) &&
12643           hasMemSDNodeUser(*N0->use_begin()));
12644 }
12645 
12646 MachineMemOperand::Flags
12647 SITargetLowering::getTargetMMOFlags(const Instruction &I) const {
12648   // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load.
12649   if (I.getMetadata("amdgpu.noclobber"))
12650     return MONoClobber;
12651   return MachineMemOperand::MONone;
12652 }
12653