1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// Custom DAG lowering for SI
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "SIISelLowering.h"
15 #include "AMDGPU.h"
16 #include "AMDGPUInstrInfo.h"
17 #include "AMDGPUTargetMachine.h"
18 #include "SIMachineFunctionInfo.h"
19 #include "SIRegisterInfo.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
22 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
23 #include "llvm/BinaryFormat/ELF.h"
24 #include "llvm/CodeGen/Analysis.h"
25 #include "llvm/CodeGen/FunctionLoweringInfo.h"
26 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
27 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineLoopInfo.h"
30 #include "llvm/IR/DiagnosticInfo.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/IntrinsicsAMDGPU.h"
33 #include "llvm/IR/IntrinsicsR600.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/KnownBits.h"
36 
37 using namespace llvm;
38 
39 #define DEBUG_TYPE "si-lower"
40 
41 STATISTIC(NumTailCalls, "Number of tail calls");
42 
43 static cl::opt<bool> DisableLoopAlignment(
44   "amdgpu-disable-loop-alignment",
45   cl::desc("Do not align and prefetch loops"),
46   cl::init(false));
47 
48 static cl::opt<bool> UseDivergentRegisterIndexing(
49   "amdgpu-use-divergent-register-indexing",
50   cl::Hidden,
51   cl::desc("Use indirect register addressing for divergent indexes"),
52   cl::init(false));
53 
54 static bool hasFP32Denormals(const MachineFunction &MF) {
55   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
56   return Info->getMode().allFP32Denormals();
57 }
58 
59 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
60   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
61   return Info->getMode().allFP64FP16Denormals();
62 }
63 
64 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
65   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
66   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
67     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
68       return AMDGPU::SGPR0 + Reg;
69     }
70   }
71   llvm_unreachable("Cannot allocate sgpr");
72 }
73 
74 SITargetLowering::SITargetLowering(const TargetMachine &TM,
75                                    const GCNSubtarget &STI)
76     : AMDGPUTargetLowering(TM, STI),
77       Subtarget(&STI) {
78   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
79   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
80 
81   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
82   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
83 
84   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
85 
86   const SIRegisterInfo *TRI = STI.getRegisterInfo();
87   const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class();
88 
89   addRegisterClass(MVT::f64, V64RegClass);
90   addRegisterClass(MVT::v2f32, V64RegClass);
91 
92   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
93   addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96));
94 
95   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
96   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
97 
98   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
99   addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128));
100 
101   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
102   addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160));
103 
104   addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass);
105   addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192));
106 
107   addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass);
108   addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192));
109 
110   addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass);
111   addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224));
112 
113   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
114   addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256));
115 
116   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
117   addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256));
118 
119   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
120   addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512));
121 
122   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
123   addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512));
124 
125   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
126   addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024));
127 
128   if (Subtarget->has16BitInsts()) {
129     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
130     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
131 
132     // Unless there are also VOP3P operations, not operations are really legal.
133     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
134     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
135     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
136     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
137     addRegisterClass(MVT::v8i16, &AMDGPU::SGPR_128RegClass);
138     addRegisterClass(MVT::v8f16, &AMDGPU::SGPR_128RegClass);
139   }
140 
141   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
142   addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024));
143 
144   computeRegisterProperties(Subtarget->getRegisterInfo());
145 
146   // The boolean content concept here is too inflexible. Compares only ever
147   // really produce a 1-bit result. Any copy/extend from these will turn into a
148   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
149   // it's what most targets use.
150   setBooleanContents(ZeroOrOneBooleanContent);
151   setBooleanVectorContents(ZeroOrOneBooleanContent);
152 
153   // We need to custom lower vector stores from local memory
154   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
155   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
156   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
157   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
158   setOperationAction(ISD::LOAD, MVT::v6i32, Custom);
159   setOperationAction(ISD::LOAD, MVT::v7i32, Custom);
160   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
161   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
162   setOperationAction(ISD::LOAD, MVT::i1, Custom);
163   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
164 
165   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
166   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
167   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
168   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
169   setOperationAction(ISD::STORE, MVT::v6i32, Custom);
170   setOperationAction(ISD::STORE, MVT::v7i32, Custom);
171   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
172   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
173   setOperationAction(ISD::STORE, MVT::i1, Custom);
174   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
175 
176   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
177   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
178   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
179   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
180   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
181   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
182   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
183   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
184   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
185   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
186   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
187   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
188   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
189   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
190   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
191   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
192 
193   setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand);
194   setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand);
195   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
196   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
197   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
198   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
199   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
200 
201   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
202   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
203 
204   setOperationAction(ISD::SELECT, MVT::i1, Promote);
205   setOperationAction(ISD::SELECT, MVT::i64, Custom);
206   setOperationAction(ISD::SELECT, MVT::f64, Promote);
207   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
208 
209   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
210   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
211   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
212   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
213   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
214 
215   setOperationAction(ISD::SETCC, MVT::i1, Promote);
216   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
217   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
218   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
219 
220   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
221   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
222   setOperationAction(ISD::TRUNCATE, MVT::v3i32, Expand);
223   setOperationAction(ISD::FP_ROUND, MVT::v3f32, Expand);
224   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
225   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
226   setOperationAction(ISD::TRUNCATE, MVT::v5i32, Expand);
227   setOperationAction(ISD::FP_ROUND, MVT::v5f32, Expand);
228   setOperationAction(ISD::TRUNCATE, MVT::v6i32, Expand);
229   setOperationAction(ISD::FP_ROUND, MVT::v6f32, Expand);
230   setOperationAction(ISD::TRUNCATE, MVT::v7i32, Expand);
231   setOperationAction(ISD::FP_ROUND, MVT::v7f32, Expand);
232   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
233   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
234   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
235   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
236 
237   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
238   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
239   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
240   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
241   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
242   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
243   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
244   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
245 
246   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
247   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
248   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
249   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
250   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
251   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
252 
253   setOperationAction(ISD::UADDO, MVT::i32, Legal);
254   setOperationAction(ISD::USUBO, MVT::i32, Legal);
255 
256   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
257   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
258 
259   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
260   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
261   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
262 
263 #if 0
264   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
265   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
266 #endif
267 
268   // We only support LOAD/STORE and vector manipulation ops for vectors
269   // with > 4 elements.
270   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
271                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
272                   MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32,
273                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
274                   MVT::v8i16, MVT::v8f16, MVT::v16i64, MVT::v16f64,
275                   MVT::v32i32, MVT::v32f32 }) {
276     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
277       switch (Op) {
278       case ISD::LOAD:
279       case ISD::STORE:
280       case ISD::BUILD_VECTOR:
281       case ISD::BITCAST:
282       case ISD::EXTRACT_VECTOR_ELT:
283       case ISD::INSERT_VECTOR_ELT:
284       case ISD::EXTRACT_SUBVECTOR:
285       case ISD::SCALAR_TO_VECTOR:
286         break;
287       case ISD::INSERT_SUBVECTOR:
288       case ISD::CONCAT_VECTORS:
289         setOperationAction(Op, VT, Custom);
290         break;
291       default:
292         setOperationAction(Op, VT, Expand);
293         break;
294       }
295     }
296   }
297 
298   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
299 
300   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
301   // is expanded to avoid having two separate loops in case the index is a VGPR.
302 
303   // Most operations are naturally 32-bit vector operations. We only support
304   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
305   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
306     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
307     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
308 
309     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
310     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
311 
312     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
313     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
314 
315     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
316     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
317   }
318 
319   for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) {
320     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
321     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32);
322 
323     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
324     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32);
325 
326     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
327     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32);
328 
329     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
330     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32);
331   }
332 
333   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
334     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
335     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
336 
337     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
338     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
339 
340     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
341     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
342 
343     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
344     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
345   }
346 
347   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
348     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
349     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
350 
351     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
352     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
353 
354     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
355     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
356 
357     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
358     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
359   }
360 
361   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
362     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
363     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
364 
365     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
366     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
367 
368     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
369     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
370 
371     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
372     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
373   }
374 
375   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
376   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
377   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
378   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
379 
380   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
381   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
382 
383   // Avoid stack access for these.
384   // TODO: Generalize to more vector types.
385   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
386   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
387   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
388   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
389 
390   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
391   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
392   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
393   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
394   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
395   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
396 
397   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
398   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
399   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
400   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
401 
402   // Deal with vec3 vector operations when widened to vec4.
403   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
404   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
405   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
406   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
407 
408   // Deal with vec5/6/7 vector operations when widened to vec8.
409   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
410   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
411   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6i32, Custom);
412   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6f32, Custom);
413   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7i32, Custom);
414   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7f32, Custom);
415   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
416   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
417 
418   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
419   // and output demarshalling
420   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
421   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
422 
423   // We can't return success/failure, only the old value,
424   // let LLVM add the comparison
425   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
426   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
427 
428   if (Subtarget->hasFlatAddressSpace()) {
429     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
430     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
431   }
432 
433   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
434   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
435 
436   // FIXME: This should be narrowed to i32, but that only happens if i64 is
437   // illegal.
438   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
439   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
440   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
441 
442   // On SI this is s_memtime and s_memrealtime on VI.
443   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
444   setOperationAction(ISD::TRAP, MVT::Other, Custom);
445   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
446 
447   if (Subtarget->has16BitInsts()) {
448     setOperationAction(ISD::FPOW, MVT::f16, Promote);
449     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
450     setOperationAction(ISD::FLOG, MVT::f16, Custom);
451     setOperationAction(ISD::FEXP, MVT::f16, Custom);
452     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
453   }
454 
455   if (Subtarget->hasMadMacF32Insts())
456     setOperationAction(ISD::FMAD, MVT::f32, Legal);
457 
458   if (!Subtarget->hasBFI()) {
459     // fcopysign can be done in a single instruction with BFI.
460     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
461     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
462   }
463 
464   if (!Subtarget->hasBCNT(32))
465     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
466 
467   if (!Subtarget->hasBCNT(64))
468     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
469 
470   if (Subtarget->hasFFBH()) {
471     setOperationAction(ISD::CTLZ, MVT::i32, Custom);
472     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
473   }
474 
475   if (Subtarget->hasFFBL()) {
476     setOperationAction(ISD::CTTZ, MVT::i32, Custom);
477     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
478   }
479 
480   // We only really have 32-bit BFE instructions (and 16-bit on VI).
481   //
482   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
483   // effort to match them now. We want this to be false for i64 cases when the
484   // extraction isn't restricted to the upper or lower half. Ideally we would
485   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
486   // span the midpoint are probably relatively rare, so don't worry about them
487   // for now.
488   if (Subtarget->hasBFE())
489     setHasExtractBitsInsn(true);
490 
491   // Clamp modifier on add/sub
492   if (Subtarget->hasIntClamp()) {
493     setOperationAction(ISD::UADDSAT, MVT::i32, Legal);
494     setOperationAction(ISD::USUBSAT, MVT::i32, Legal);
495   }
496 
497   if (Subtarget->hasAddNoCarry()) {
498     setOperationAction(ISD::SADDSAT, MVT::i16, Legal);
499     setOperationAction(ISD::SSUBSAT, MVT::i16, Legal);
500     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
501     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
502   }
503 
504   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
505   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
506   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
507   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
508 
509 
510   // These are really only legal for ieee_mode functions. We should be avoiding
511   // them for functions that don't have ieee_mode enabled, so just say they are
512   // legal.
513   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
514   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
515   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
516   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
517 
518 
519   if (Subtarget->haveRoundOpsF64()) {
520     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
521     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
522     setOperationAction(ISD::FRINT, MVT::f64, Legal);
523   } else {
524     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
525     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
526     setOperationAction(ISD::FRINT, MVT::f64, Custom);
527     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
528   }
529 
530   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
531 
532   setOperationAction(ISD::FSIN, MVT::f32, Custom);
533   setOperationAction(ISD::FCOS, MVT::f32, Custom);
534   setOperationAction(ISD::FDIV, MVT::f32, Custom);
535   setOperationAction(ISD::FDIV, MVT::f64, Custom);
536 
537   if (Subtarget->has16BitInsts()) {
538     setOperationAction(ISD::Constant, MVT::i16, Legal);
539 
540     setOperationAction(ISD::SMIN, MVT::i16, Legal);
541     setOperationAction(ISD::SMAX, MVT::i16, Legal);
542 
543     setOperationAction(ISD::UMIN, MVT::i16, Legal);
544     setOperationAction(ISD::UMAX, MVT::i16, Legal);
545 
546     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
547     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
548 
549     setOperationAction(ISD::ROTR, MVT::i16, Expand);
550     setOperationAction(ISD::ROTL, MVT::i16, Expand);
551 
552     setOperationAction(ISD::SDIV, MVT::i16, Promote);
553     setOperationAction(ISD::UDIV, MVT::i16, Promote);
554     setOperationAction(ISD::SREM, MVT::i16, Promote);
555     setOperationAction(ISD::UREM, MVT::i16, Promote);
556     setOperationAction(ISD::UADDSAT, MVT::i16, Legal);
557     setOperationAction(ISD::USUBSAT, MVT::i16, Legal);
558 
559     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
560 
561     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
562     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
563     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
564     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
565     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
566 
567     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
568 
569     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
570 
571     setOperationAction(ISD::LOAD, MVT::i16, Custom);
572 
573     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
574 
575     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
576     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
577     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
578     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
579 
580     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Custom);
581     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Custom);
582 
583     // F16 - Constant Actions.
584     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
585 
586     // F16 - Load/Store Actions.
587     setOperationAction(ISD::LOAD, MVT::f16, Promote);
588     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
589     setOperationAction(ISD::STORE, MVT::f16, Promote);
590     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
591 
592     // F16 - VOP1 Actions.
593     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
594     setOperationAction(ISD::FCOS, MVT::f16, Custom);
595     setOperationAction(ISD::FSIN, MVT::f16, Custom);
596 
597     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
598     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
599 
600     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
601     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
602     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
603     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
604     setOperationAction(ISD::FROUND, MVT::f16, Custom);
605 
606     // F16 - VOP2 Actions.
607     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
608     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
609 
610     setOperationAction(ISD::FDIV, MVT::f16, Custom);
611 
612     // F16 - VOP3 Actions.
613     setOperationAction(ISD::FMA, MVT::f16, Legal);
614     if (STI.hasMadF16())
615       setOperationAction(ISD::FMAD, MVT::f16, Legal);
616 
617     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16, MVT::v8i16,
618                    MVT::v8f16}) {
619       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
620         switch (Op) {
621         case ISD::LOAD:
622         case ISD::STORE:
623         case ISD::BUILD_VECTOR:
624         case ISD::BITCAST:
625         case ISD::EXTRACT_VECTOR_ELT:
626         case ISD::INSERT_VECTOR_ELT:
627         case ISD::INSERT_SUBVECTOR:
628         case ISD::EXTRACT_SUBVECTOR:
629         case ISD::SCALAR_TO_VECTOR:
630           break;
631         case ISD::CONCAT_VECTORS:
632           setOperationAction(Op, VT, Custom);
633           break;
634         default:
635           setOperationAction(Op, VT, Expand);
636           break;
637         }
638       }
639     }
640 
641     // v_perm_b32 can handle either of these.
642     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
643     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
644     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
645 
646     // XXX - Do these do anything? Vector constants turn into build_vector.
647     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
648     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
649 
650     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
651     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
652 
653     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
654     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
655     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
656     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
657 
658     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
659     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
660     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
661     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
662 
663     setOperationAction(ISD::AND, MVT::v2i16, Promote);
664     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
665     setOperationAction(ISD::OR, MVT::v2i16, Promote);
666     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
667     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
668     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
669 
670     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
671     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
672     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
673     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
674 
675     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
676     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
677     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
678     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
679 
680     setOperationAction(ISD::LOAD, MVT::v8i16, Promote);
681     AddPromotedToType(ISD::LOAD, MVT::v8i16, MVT::v4i32);
682     setOperationAction(ISD::LOAD, MVT::v8f16, Promote);
683     AddPromotedToType(ISD::LOAD, MVT::v8f16, MVT::v4i32);
684 
685     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
686     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
687     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
688     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
689 
690     setOperationAction(ISD::STORE, MVT::v8i16, Promote);
691     AddPromotedToType(ISD::STORE, MVT::v8i16, MVT::v4i32);
692     setOperationAction(ISD::STORE, MVT::v8f16, Promote);
693     AddPromotedToType(ISD::STORE, MVT::v8f16, MVT::v4i32);
694 
695     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
696     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
697     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
698     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
699 
700     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
701     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
702     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
703 
704     setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Expand);
705     setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Expand);
706     setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Expand);
707 
708     if (!Subtarget->hasVOP3PInsts()) {
709       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
710       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
711     }
712 
713     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
714     // This isn't really legal, but this avoids the legalizer unrolling it (and
715     // allows matching fneg (fabs x) patterns)
716     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
717 
718     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
719     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
720     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
721     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
722 
723     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
724     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
725     setOperationAction(ISD::FMINNUM_IEEE, MVT::v8f16, Custom);
726     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v8f16, Custom);
727 
728     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
729     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
730     setOperationAction(ISD::FMINNUM, MVT::v8f16, Expand);
731     setOperationAction(ISD::FMAXNUM, MVT::v8f16, Expand);
732 
733     for (MVT Vec16 : { MVT::v8i16, MVT::v8f16 }) {
734       setOperationAction(ISD::BUILD_VECTOR, Vec16, Custom);
735       setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec16, Custom);
736       setOperationAction(ISD::INSERT_VECTOR_ELT, Vec16, Expand);
737       setOperationAction(ISD::SCALAR_TO_VECTOR, Vec16, Expand);
738     }
739   }
740 
741   if (Subtarget->hasVOP3PInsts()) {
742     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
743     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
744     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
745     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
746     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
747     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
748     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
749     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
750     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
751     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
752 
753     setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal);
754     setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal);
755     setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal);
756     setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal);
757 
758     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
759     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
760     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
761 
762     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
763     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
764 
765     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
766 
767     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
768     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
769 
770     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
771     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
772     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f16, Custom);
773     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i16, Custom);
774 
775     for (MVT VT : { MVT::v4i16, MVT::v8i16 }) {
776       // Split vector operations.
777       setOperationAction(ISD::SHL, VT, Custom);
778       setOperationAction(ISD::SRA, VT, Custom);
779       setOperationAction(ISD::SRL, VT, Custom);
780       setOperationAction(ISD::ADD, VT, Custom);
781       setOperationAction(ISD::SUB, VT, Custom);
782       setOperationAction(ISD::MUL, VT, Custom);
783 
784       setOperationAction(ISD::SMIN, VT, Custom);
785       setOperationAction(ISD::SMAX, VT, Custom);
786       setOperationAction(ISD::UMIN, VT, Custom);
787       setOperationAction(ISD::UMAX, VT, Custom);
788 
789       setOperationAction(ISD::UADDSAT, VT, Custom);
790       setOperationAction(ISD::SADDSAT, VT, Custom);
791       setOperationAction(ISD::USUBSAT, VT, Custom);
792       setOperationAction(ISD::SSUBSAT, VT, Custom);
793     }
794 
795     for (MVT VT : { MVT::v4f16, MVT::v8f16 }) {
796       // Split vector operations.
797       setOperationAction(ISD::FADD, VT, Custom);
798       setOperationAction(ISD::FMUL, VT, Custom);
799       setOperationAction(ISD::FMA, VT, Custom);
800       setOperationAction(ISD::FCANONICALIZE, VT, Custom);
801     }
802 
803     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
804     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
805 
806     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
807     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
808 
809     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
810     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
811     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
812 
813     if (Subtarget->hasPackedFP32Ops()) {
814       setOperationAction(ISD::FADD, MVT::v2f32, Legal);
815       setOperationAction(ISD::FMUL, MVT::v2f32, Legal);
816       setOperationAction(ISD::FMA,  MVT::v2f32, Legal);
817       setOperationAction(ISD::FNEG, MVT::v2f32, Legal);
818 
819       for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) {
820         setOperationAction(ISD::FADD, VT, Custom);
821         setOperationAction(ISD::FMUL, VT, Custom);
822         setOperationAction(ISD::FMA, VT, Custom);
823       }
824     }
825   }
826 
827   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
828   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
829 
830   if (Subtarget->has16BitInsts()) {
831     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
832     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
833     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
834     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
835   } else {
836     // Legalization hack.
837     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
838     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
839 
840     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
841     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
842   }
843 
844   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8,
845                   MVT::v8i16, MVT::v8f16 }) {
846     setOperationAction(ISD::SELECT, VT, Custom);
847   }
848 
849   setOperationAction(ISD::SMULO, MVT::i64, Custom);
850   setOperationAction(ISD::UMULO, MVT::i64, Custom);
851 
852   if (Subtarget->hasMad64_32()) {
853     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
854     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
855   }
856 
857   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
858   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
859   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
860   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
861   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
862   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
863   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
864 
865   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
866   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
867   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom);
868   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom);
869   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
870   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
871   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
872   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
873   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
874   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
875   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
876 
877   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
878   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
879   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
880   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom);
881   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom);
882   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
883   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
884   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
885   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
886   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
887 
888   setTargetDAGCombine(ISD::ADD);
889   setTargetDAGCombine(ISD::ADDCARRY);
890   setTargetDAGCombine(ISD::SUB);
891   setTargetDAGCombine(ISD::SUBCARRY);
892   setTargetDAGCombine(ISD::FADD);
893   setTargetDAGCombine(ISD::FSUB);
894   setTargetDAGCombine(ISD::FMINNUM);
895   setTargetDAGCombine(ISD::FMAXNUM);
896   setTargetDAGCombine(ISD::FMINNUM_IEEE);
897   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
898   setTargetDAGCombine(ISD::FMA);
899   setTargetDAGCombine(ISD::SMIN);
900   setTargetDAGCombine(ISD::SMAX);
901   setTargetDAGCombine(ISD::UMIN);
902   setTargetDAGCombine(ISD::UMAX);
903   setTargetDAGCombine(ISD::SETCC);
904   setTargetDAGCombine(ISD::AND);
905   setTargetDAGCombine(ISD::OR);
906   setTargetDAGCombine(ISD::XOR);
907   setTargetDAGCombine(ISD::SINT_TO_FP);
908   setTargetDAGCombine(ISD::UINT_TO_FP);
909   setTargetDAGCombine(ISD::FCANONICALIZE);
910   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
911   setTargetDAGCombine(ISD::ZERO_EXTEND);
912   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
913   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
914   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
915 
916   // All memory operations. Some folding on the pointer operand is done to help
917   // matching the constant offsets in the addressing modes.
918   setTargetDAGCombine(ISD::LOAD);
919   setTargetDAGCombine(ISD::STORE);
920   setTargetDAGCombine(ISD::ATOMIC_LOAD);
921   setTargetDAGCombine(ISD::ATOMIC_STORE);
922   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
923   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
924   setTargetDAGCombine(ISD::ATOMIC_SWAP);
925   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
926   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
927   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
928   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
929   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
930   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
931   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
932   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
933   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
934   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
935   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
936   setTargetDAGCombine(ISD::INTRINSIC_VOID);
937   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
938 
939   // FIXME: In other contexts we pretend this is a per-function property.
940   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
941 
942   setSchedulingPreference(Sched::RegPressure);
943 }
944 
945 const GCNSubtarget *SITargetLowering::getSubtarget() const {
946   return Subtarget;
947 }
948 
949 //===----------------------------------------------------------------------===//
950 // TargetLowering queries
951 //===----------------------------------------------------------------------===//
952 
953 // v_mad_mix* support a conversion from f16 to f32.
954 //
955 // There is only one special case when denormals are enabled we don't currently,
956 // where this is OK to use.
957 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
958                                        EVT DestVT, EVT SrcVT) const {
959   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
960           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
961     DestVT.getScalarType() == MVT::f32 &&
962     SrcVT.getScalarType() == MVT::f16 &&
963     // TODO: This probably only requires no input flushing?
964     !hasFP32Denormals(DAG.getMachineFunction());
965 }
966 
967 bool SITargetLowering::isFPExtFoldable(const MachineInstr &MI, unsigned Opcode,
968                                        LLT DestTy, LLT SrcTy) const {
969   return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) ||
970           (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) &&
971          DestTy.getScalarSizeInBits() == 32 &&
972          SrcTy.getScalarSizeInBits() == 16 &&
973          // TODO: This probably only requires no input flushing?
974          !hasFP32Denormals(*MI.getMF());
975 }
976 
977 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
978   // SI has some legal vector types, but no legal vector operations. Say no
979   // shuffles are legal in order to prefer scalarizing some vector operations.
980   return false;
981 }
982 
983 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
984                                                     CallingConv::ID CC,
985                                                     EVT VT) const {
986   if (CC == CallingConv::AMDGPU_KERNEL)
987     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
988 
989   if (VT.isVector()) {
990     EVT ScalarVT = VT.getScalarType();
991     unsigned Size = ScalarVT.getSizeInBits();
992     if (Size == 16) {
993       if (Subtarget->has16BitInsts())
994         return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
995       return VT.isInteger() ? MVT::i32 : MVT::f32;
996     }
997 
998     if (Size < 16)
999       return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
1000     return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
1001   }
1002 
1003   if (VT.getSizeInBits() > 32)
1004     return MVT::i32;
1005 
1006   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1007 }
1008 
1009 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1010                                                          CallingConv::ID CC,
1011                                                          EVT VT) const {
1012   if (CC == CallingConv::AMDGPU_KERNEL)
1013     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1014 
1015   if (VT.isVector()) {
1016     unsigned NumElts = VT.getVectorNumElements();
1017     EVT ScalarVT = VT.getScalarType();
1018     unsigned Size = ScalarVT.getSizeInBits();
1019 
1020     // FIXME: Should probably promote 8-bit vectors to i16.
1021     if (Size == 16 && Subtarget->has16BitInsts())
1022       return (NumElts + 1) / 2;
1023 
1024     if (Size <= 32)
1025       return NumElts;
1026 
1027     if (Size > 32)
1028       return NumElts * ((Size + 31) / 32);
1029   } else if (VT.getSizeInBits() > 32)
1030     return (VT.getSizeInBits() + 31) / 32;
1031 
1032   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1033 }
1034 
1035 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
1036   LLVMContext &Context, CallingConv::ID CC,
1037   EVT VT, EVT &IntermediateVT,
1038   unsigned &NumIntermediates, MVT &RegisterVT) const {
1039   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
1040     unsigned NumElts = VT.getVectorNumElements();
1041     EVT ScalarVT = VT.getScalarType();
1042     unsigned Size = ScalarVT.getSizeInBits();
1043     // FIXME: We should fix the ABI to be the same on targets without 16-bit
1044     // support, but unless we can properly handle 3-vectors, it will be still be
1045     // inconsistent.
1046     if (Size == 16 && Subtarget->has16BitInsts()) {
1047       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
1048       IntermediateVT = RegisterVT;
1049       NumIntermediates = (NumElts + 1) / 2;
1050       return NumIntermediates;
1051     }
1052 
1053     if (Size == 32) {
1054       RegisterVT = ScalarVT.getSimpleVT();
1055       IntermediateVT = RegisterVT;
1056       NumIntermediates = NumElts;
1057       return NumIntermediates;
1058     }
1059 
1060     if (Size < 16 && Subtarget->has16BitInsts()) {
1061       // FIXME: Should probably form v2i16 pieces
1062       RegisterVT = MVT::i16;
1063       IntermediateVT = ScalarVT;
1064       NumIntermediates = NumElts;
1065       return NumIntermediates;
1066     }
1067 
1068 
1069     if (Size != 16 && Size <= 32) {
1070       RegisterVT = MVT::i32;
1071       IntermediateVT = ScalarVT;
1072       NumIntermediates = NumElts;
1073       return NumIntermediates;
1074     }
1075 
1076     if (Size > 32) {
1077       RegisterVT = MVT::i32;
1078       IntermediateVT = RegisterVT;
1079       NumIntermediates = NumElts * ((Size + 31) / 32);
1080       return NumIntermediates;
1081     }
1082   }
1083 
1084   return TargetLowering::getVectorTypeBreakdownForCallingConv(
1085     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
1086 }
1087 
1088 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
1089   assert(DMaskLanes != 0);
1090 
1091   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1092     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
1093     return EVT::getVectorVT(Ty->getContext(),
1094                             EVT::getEVT(VT->getElementType()),
1095                             NumElts);
1096   }
1097 
1098   return EVT::getEVT(Ty);
1099 }
1100 
1101 // Peek through TFE struct returns to only use the data size.
1102 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
1103   auto *ST = dyn_cast<StructType>(Ty);
1104   if (!ST)
1105     return memVTFromImageData(Ty, DMaskLanes);
1106 
1107   // Some intrinsics return an aggregate type - special case to work out the
1108   // correct memVT.
1109   //
1110   // Only limited forms of aggregate type currently expected.
1111   if (ST->getNumContainedTypes() != 2 ||
1112       !ST->getContainedType(1)->isIntegerTy(32))
1113     return EVT();
1114   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
1115 }
1116 
1117 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1118                                           const CallInst &CI,
1119                                           MachineFunction &MF,
1120                                           unsigned IntrID) const {
1121   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1122           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1123     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1124                                                   (Intrinsic::ID)IntrID);
1125     if (Attr.hasFnAttr(Attribute::ReadNone))
1126       return false;
1127 
1128     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1129 
1130     if (RsrcIntr->IsImage) {
1131       Info.ptrVal =
1132           MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1133       Info.align.reset();
1134     } else {
1135       Info.ptrVal =
1136           MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1137     }
1138 
1139     Info.flags = MachineMemOperand::MODereferenceable;
1140     if (Attr.hasFnAttr(Attribute::ReadOnly)) {
1141       unsigned DMaskLanes = 4;
1142 
1143       if (RsrcIntr->IsImage) {
1144         const AMDGPU::ImageDimIntrinsicInfo *Intr
1145           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1146         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1147           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1148 
1149         if (!BaseOpcode->Gather4) {
1150           // If this isn't a gather, we may have excess loaded elements in the
1151           // IR type. Check the dmask for the real number of elements loaded.
1152           unsigned DMask
1153             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1154           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1155         }
1156 
1157         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1158       } else
1159         Info.memVT = EVT::getEVT(CI.getType());
1160 
1161       // FIXME: What does alignment mean for an image?
1162       Info.opc = ISD::INTRINSIC_W_CHAIN;
1163       Info.flags |= MachineMemOperand::MOLoad;
1164     } else if (Attr.hasFnAttr(Attribute::WriteOnly)) {
1165       Info.opc = ISD::INTRINSIC_VOID;
1166 
1167       Type *DataTy = CI.getArgOperand(0)->getType();
1168       if (RsrcIntr->IsImage) {
1169         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1170         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1171         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1172       } else
1173         Info.memVT = EVT::getEVT(DataTy);
1174 
1175       Info.flags |= MachineMemOperand::MOStore;
1176     } else {
1177       // Atomic
1178       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1179                                             ISD::INTRINSIC_W_CHAIN;
1180       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1181       Info.flags = MachineMemOperand::MOLoad |
1182                    MachineMemOperand::MOStore |
1183                    MachineMemOperand::MODereferenceable;
1184 
1185       // XXX - Should this be volatile without known ordering?
1186       Info.flags |= MachineMemOperand::MOVolatile;
1187     }
1188     return true;
1189   }
1190 
1191   switch (IntrID) {
1192   case Intrinsic::amdgcn_atomic_inc:
1193   case Intrinsic::amdgcn_atomic_dec:
1194   case Intrinsic::amdgcn_ds_ordered_add:
1195   case Intrinsic::amdgcn_ds_ordered_swap:
1196   case Intrinsic::amdgcn_ds_fadd:
1197   case Intrinsic::amdgcn_ds_fmin:
1198   case Intrinsic::amdgcn_ds_fmax: {
1199     Info.opc = ISD::INTRINSIC_W_CHAIN;
1200     Info.memVT = MVT::getVT(CI.getType());
1201     Info.ptrVal = CI.getOperand(0);
1202     Info.align.reset();
1203     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1204 
1205     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1206     if (!Vol->isZero())
1207       Info.flags |= MachineMemOperand::MOVolatile;
1208 
1209     return true;
1210   }
1211   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1212     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1213 
1214     Info.opc = ISD::INTRINSIC_W_CHAIN;
1215     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1216     Info.ptrVal =
1217         MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1218     Info.align.reset();
1219     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1220 
1221     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1222     if (!Vol || !Vol->isZero())
1223       Info.flags |= MachineMemOperand::MOVolatile;
1224 
1225     return true;
1226   }
1227   case Intrinsic::amdgcn_ds_append:
1228   case Intrinsic::amdgcn_ds_consume: {
1229     Info.opc = ISD::INTRINSIC_W_CHAIN;
1230     Info.memVT = MVT::getVT(CI.getType());
1231     Info.ptrVal = CI.getOperand(0);
1232     Info.align.reset();
1233     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1234 
1235     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1236     if (!Vol->isZero())
1237       Info.flags |= MachineMemOperand::MOVolatile;
1238 
1239     return true;
1240   }
1241   case Intrinsic::amdgcn_global_atomic_csub: {
1242     Info.opc = ISD::INTRINSIC_W_CHAIN;
1243     Info.memVT = MVT::getVT(CI.getType());
1244     Info.ptrVal = CI.getOperand(0);
1245     Info.align.reset();
1246     Info.flags = MachineMemOperand::MOLoad |
1247                  MachineMemOperand::MOStore |
1248                  MachineMemOperand::MOVolatile;
1249     return true;
1250   }
1251   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1252     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1253     Info.opc = ISD::INTRINSIC_W_CHAIN;
1254     Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1255     Info.ptrVal =
1256         MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1257     Info.align.reset();
1258     Info.flags = MachineMemOperand::MOLoad |
1259                  MachineMemOperand::MODereferenceable;
1260     return true;
1261   }
1262   case Intrinsic::amdgcn_global_atomic_fadd:
1263   case Intrinsic::amdgcn_global_atomic_fmin:
1264   case Intrinsic::amdgcn_global_atomic_fmax:
1265   case Intrinsic::amdgcn_flat_atomic_fadd:
1266   case Intrinsic::amdgcn_flat_atomic_fmin:
1267   case Intrinsic::amdgcn_flat_atomic_fmax: {
1268     Info.opc = ISD::INTRINSIC_W_CHAIN;
1269     Info.memVT = MVT::getVT(CI.getType());
1270     Info.ptrVal = CI.getOperand(0);
1271     Info.align.reset();
1272     Info.flags = MachineMemOperand::MOLoad |
1273                  MachineMemOperand::MOStore |
1274                  MachineMemOperand::MODereferenceable |
1275                  MachineMemOperand::MOVolatile;
1276     return true;
1277   }
1278   case Intrinsic::amdgcn_ds_gws_init:
1279   case Intrinsic::amdgcn_ds_gws_barrier:
1280   case Intrinsic::amdgcn_ds_gws_sema_v:
1281   case Intrinsic::amdgcn_ds_gws_sema_br:
1282   case Intrinsic::amdgcn_ds_gws_sema_p:
1283   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1284     Info.opc = ISD::INTRINSIC_VOID;
1285 
1286     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1287     Info.ptrVal =
1288         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1289 
1290     // This is an abstract access, but we need to specify a type and size.
1291     Info.memVT = MVT::i32;
1292     Info.size = 4;
1293     Info.align = Align(4);
1294 
1295     Info.flags = MachineMemOperand::MOStore;
1296     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1297       Info.flags = MachineMemOperand::MOLoad;
1298     return true;
1299   }
1300   default:
1301     return false;
1302   }
1303 }
1304 
1305 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1306                                             SmallVectorImpl<Value*> &Ops,
1307                                             Type *&AccessTy) const {
1308   switch (II->getIntrinsicID()) {
1309   case Intrinsic::amdgcn_atomic_inc:
1310   case Intrinsic::amdgcn_atomic_dec:
1311   case Intrinsic::amdgcn_ds_ordered_add:
1312   case Intrinsic::amdgcn_ds_ordered_swap:
1313   case Intrinsic::amdgcn_ds_append:
1314   case Intrinsic::amdgcn_ds_consume:
1315   case Intrinsic::amdgcn_ds_fadd:
1316   case Intrinsic::amdgcn_ds_fmin:
1317   case Intrinsic::amdgcn_ds_fmax:
1318   case Intrinsic::amdgcn_global_atomic_fadd:
1319   case Intrinsic::amdgcn_flat_atomic_fadd:
1320   case Intrinsic::amdgcn_flat_atomic_fmin:
1321   case Intrinsic::amdgcn_flat_atomic_fmax:
1322   case Intrinsic::amdgcn_global_atomic_csub: {
1323     Value *Ptr = II->getArgOperand(0);
1324     AccessTy = II->getType();
1325     Ops.push_back(Ptr);
1326     return true;
1327   }
1328   default:
1329     return false;
1330   }
1331 }
1332 
1333 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1334   if (!Subtarget->hasFlatInstOffsets()) {
1335     // Flat instructions do not have offsets, and only have the register
1336     // address.
1337     return AM.BaseOffs == 0 && AM.Scale == 0;
1338   }
1339 
1340   return AM.Scale == 0 &&
1341          (AM.BaseOffs == 0 ||
1342           Subtarget->getInstrInfo()->isLegalFLATOffset(
1343               AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT));
1344 }
1345 
1346 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1347   if (Subtarget->hasFlatGlobalInsts())
1348     return AM.Scale == 0 &&
1349            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1350                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1351                                     SIInstrFlags::FlatGlobal));
1352 
1353   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1354       // Assume the we will use FLAT for all global memory accesses
1355       // on VI.
1356       // FIXME: This assumption is currently wrong.  On VI we still use
1357       // MUBUF instructions for the r + i addressing mode.  As currently
1358       // implemented, the MUBUF instructions only work on buffer < 4GB.
1359       // It may be possible to support > 4GB buffers with MUBUF instructions,
1360       // by setting the stride value in the resource descriptor which would
1361       // increase the size limit to (stride * 4GB).  However, this is risky,
1362       // because it has never been validated.
1363     return isLegalFlatAddressingMode(AM);
1364   }
1365 
1366   return isLegalMUBUFAddressingMode(AM);
1367 }
1368 
1369 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1370   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1371   // additionally can do r + r + i with addr64. 32-bit has more addressing
1372   // mode options. Depending on the resource constant, it can also do
1373   // (i64 r0) + (i32 r1) * (i14 i).
1374   //
1375   // Private arrays end up using a scratch buffer most of the time, so also
1376   // assume those use MUBUF instructions. Scratch loads / stores are currently
1377   // implemented as mubuf instructions with offen bit set, so slightly
1378   // different than the normal addr64.
1379   if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1380     return false;
1381 
1382   // FIXME: Since we can split immediate into soffset and immediate offset,
1383   // would it make sense to allow any immediate?
1384 
1385   switch (AM.Scale) {
1386   case 0: // r + i or just i, depending on HasBaseReg.
1387     return true;
1388   case 1:
1389     return true; // We have r + r or r + i.
1390   case 2:
1391     if (AM.HasBaseReg) {
1392       // Reject 2 * r + r.
1393       return false;
1394     }
1395 
1396     // Allow 2 * r as r + r
1397     // Or  2 * r + i is allowed as r + r + i.
1398     return true;
1399   default: // Don't allow n * r
1400     return false;
1401   }
1402 }
1403 
1404 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1405                                              const AddrMode &AM, Type *Ty,
1406                                              unsigned AS, Instruction *I) const {
1407   // No global is ever allowed as a base.
1408   if (AM.BaseGV)
1409     return false;
1410 
1411   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1412     return isLegalGlobalAddressingMode(AM);
1413 
1414   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1415       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1416       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1417     // If the offset isn't a multiple of 4, it probably isn't going to be
1418     // correctly aligned.
1419     // FIXME: Can we get the real alignment here?
1420     if (AM.BaseOffs % 4 != 0)
1421       return isLegalMUBUFAddressingMode(AM);
1422 
1423     // There are no SMRD extloads, so if we have to do a small type access we
1424     // will use a MUBUF load.
1425     // FIXME?: We also need to do this if unaligned, but we don't know the
1426     // alignment here.
1427     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1428       return isLegalGlobalAddressingMode(AM);
1429 
1430     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1431       // SMRD instructions have an 8-bit, dword offset on SI.
1432       if (!isUInt<8>(AM.BaseOffs / 4))
1433         return false;
1434     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1435       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1436       // in 8-bits, it can use a smaller encoding.
1437       if (!isUInt<32>(AM.BaseOffs / 4))
1438         return false;
1439     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1440       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1441       if (!isUInt<20>(AM.BaseOffs))
1442         return false;
1443     } else
1444       llvm_unreachable("unhandled generation");
1445 
1446     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1447       return true;
1448 
1449     if (AM.Scale == 1 && AM.HasBaseReg)
1450       return true;
1451 
1452     return false;
1453 
1454   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1455     return isLegalMUBUFAddressingMode(AM);
1456   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1457              AS == AMDGPUAS::REGION_ADDRESS) {
1458     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1459     // field.
1460     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1461     // an 8-bit dword offset but we don't know the alignment here.
1462     if (!isUInt<16>(AM.BaseOffs))
1463       return false;
1464 
1465     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1466       return true;
1467 
1468     if (AM.Scale == 1 && AM.HasBaseReg)
1469       return true;
1470 
1471     return false;
1472   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1473              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1474     // For an unknown address space, this usually means that this is for some
1475     // reason being used for pure arithmetic, and not based on some addressing
1476     // computation. We don't have instructions that compute pointers with any
1477     // addressing modes, so treat them as having no offset like flat
1478     // instructions.
1479     return isLegalFlatAddressingMode(AM);
1480   }
1481 
1482   // Assume a user alias of global for unknown address spaces.
1483   return isLegalGlobalAddressingMode(AM);
1484 }
1485 
1486 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1487                                         const MachineFunction &MF) const {
1488   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1489     return (MemVT.getSizeInBits() <= 4 * 32);
1490   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1491     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1492     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1493   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1494     return (MemVT.getSizeInBits() <= 2 * 32);
1495   }
1496   return true;
1497 }
1498 
1499 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1500     unsigned Size, unsigned AddrSpace, Align Alignment,
1501     MachineMemOperand::Flags Flags, bool *IsFast) const {
1502   if (IsFast)
1503     *IsFast = false;
1504 
1505   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1506       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1507     // Check if alignment requirements for ds_read/write instructions are
1508     // disabled.
1509     if (Subtarget->hasUnalignedDSAccessEnabled() &&
1510         !Subtarget->hasLDSMisalignedBug()) {
1511       if (IsFast)
1512         *IsFast = Alignment != Align(2);
1513       return true;
1514     }
1515 
1516     // Either, the alignment requirements are "enabled", or there is an
1517     // unaligned LDS access related hardware bug though alignment requirements
1518     // are "disabled". In either case, we need to check for proper alignment
1519     // requirements.
1520     //
1521     if (Size == 64) {
1522       // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
1523       // can do a 4 byte aligned, 8 byte access in a single operation using
1524       // ds_read2/write2_b32 with adjacent offsets.
1525       bool AlignedBy4 = Alignment >= Align(4);
1526       if (IsFast)
1527         *IsFast = AlignedBy4;
1528 
1529       return AlignedBy4;
1530     }
1531     if (Size == 96) {
1532       // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
1533       // gfx8 and older.
1534       bool AlignedBy16 = Alignment >= Align(16);
1535       if (IsFast)
1536         *IsFast = AlignedBy16;
1537 
1538       return AlignedBy16;
1539     }
1540     if (Size == 128) {
1541       // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
1542       // gfx8 and older, but  we can do a 8 byte aligned, 16 byte access in a
1543       // single operation using ds_read2/write2_b64.
1544       bool AlignedBy8 = Alignment >= Align(8);
1545       if (IsFast)
1546         *IsFast = AlignedBy8;
1547 
1548       return AlignedBy8;
1549     }
1550   }
1551 
1552   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1553     bool AlignedBy4 = Alignment >= Align(4);
1554     if (IsFast)
1555       *IsFast = AlignedBy4;
1556 
1557     return AlignedBy4 ||
1558            Subtarget->enableFlatScratch() ||
1559            Subtarget->hasUnalignedScratchAccess();
1560   }
1561 
1562   // FIXME: We have to be conservative here and assume that flat operations
1563   // will access scratch.  If we had access to the IR function, then we
1564   // could determine if any private memory was used in the function.
1565   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1566       !Subtarget->hasUnalignedScratchAccess()) {
1567     bool AlignedBy4 = Alignment >= Align(4);
1568     if (IsFast)
1569       *IsFast = AlignedBy4;
1570 
1571     return AlignedBy4;
1572   }
1573 
1574   if (Subtarget->hasUnalignedBufferAccessEnabled() &&
1575       !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1576         AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1577     // If we have an uniform constant load, it still requires using a slow
1578     // buffer instruction if unaligned.
1579     if (IsFast) {
1580       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1581       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1582       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1583                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1584         Alignment >= Align(4) : Alignment != Align(2);
1585     }
1586 
1587     return true;
1588   }
1589 
1590   // Smaller than dword value must be aligned.
1591   if (Size < 32)
1592     return false;
1593 
1594   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1595   // byte-address are ignored, thus forcing Dword alignment.
1596   // This applies to private, global, and constant memory.
1597   if (IsFast)
1598     *IsFast = true;
1599 
1600   return Size >= 32 && Alignment >= Align(4);
1601 }
1602 
1603 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1604     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1605     bool *IsFast) const {
1606   if (IsFast)
1607     *IsFast = false;
1608 
1609   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1610   // which isn't a simple VT.
1611   // Until MVT is extended to handle this, simply check for the size and
1612   // rely on the condition below: allow accesses if the size is a multiple of 4.
1613   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1614                            VT.getStoreSize() > 16)) {
1615     return false;
1616   }
1617 
1618   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1619                                             Alignment, Flags, IsFast);
1620 }
1621 
1622 EVT SITargetLowering::getOptimalMemOpType(
1623     const MemOp &Op, const AttributeList &FuncAttributes) const {
1624   // FIXME: Should account for address space here.
1625 
1626   // The default fallback uses the private pointer size as a guess for a type to
1627   // use. Make sure we switch these to 64-bit accesses.
1628 
1629   if (Op.size() >= 16 &&
1630       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1631     return MVT::v4i32;
1632 
1633   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1634     return MVT::v2i32;
1635 
1636   // Use the default.
1637   return MVT::Other;
1638 }
1639 
1640 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1641   const MemSDNode *MemNode = cast<MemSDNode>(N);
1642   const Value *Ptr = MemNode->getMemOperand()->getValue();
1643   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1644   return I && I->getMetadata("amdgpu.noclobber");
1645 }
1646 
1647 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1648   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1649          AS == AMDGPUAS::PRIVATE_ADDRESS;
1650 }
1651 
1652 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1653                                            unsigned DestAS) const {
1654   // Flat -> private/local is a simple truncate.
1655   // Flat -> global is no-op
1656   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1657     return true;
1658 
1659   const GCNTargetMachine &TM =
1660       static_cast<const GCNTargetMachine &>(getTargetMachine());
1661   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1662 }
1663 
1664 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1665   const MemSDNode *MemNode = cast<MemSDNode>(N);
1666 
1667   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1668 }
1669 
1670 TargetLoweringBase::LegalizeTypeAction
1671 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1672   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1673       VT.getScalarType().bitsLE(MVT::i16))
1674     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1675   return TargetLoweringBase::getPreferredVectorAction(VT);
1676 }
1677 
1678 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1679                                                          Type *Ty) const {
1680   // FIXME: Could be smarter if called for vector constants.
1681   return true;
1682 }
1683 
1684 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1685   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1686     switch (Op) {
1687     case ISD::LOAD:
1688     case ISD::STORE:
1689 
1690     // These operations are done with 32-bit instructions anyway.
1691     case ISD::AND:
1692     case ISD::OR:
1693     case ISD::XOR:
1694     case ISD::SELECT:
1695       // TODO: Extensions?
1696       return true;
1697     default:
1698       return false;
1699     }
1700   }
1701 
1702   // SimplifySetCC uses this function to determine whether or not it should
1703   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1704   if (VT == MVT::i1 && Op == ISD::SETCC)
1705     return false;
1706 
1707   return TargetLowering::isTypeDesirableForOp(Op, VT);
1708 }
1709 
1710 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1711                                                    const SDLoc &SL,
1712                                                    SDValue Chain,
1713                                                    uint64_t Offset) const {
1714   const DataLayout &DL = DAG.getDataLayout();
1715   MachineFunction &MF = DAG.getMachineFunction();
1716   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1717 
1718   const ArgDescriptor *InputPtrReg;
1719   const TargetRegisterClass *RC;
1720   LLT ArgTy;
1721   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1722 
1723   std::tie(InputPtrReg, RC, ArgTy) =
1724       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1725 
1726   // We may not have the kernarg segment argument if we have no kernel
1727   // arguments.
1728   if (!InputPtrReg)
1729     return DAG.getConstant(0, SL, PtrVT);
1730 
1731   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1732   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1733     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1734 
1735   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1736 }
1737 
1738 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1739                                             const SDLoc &SL) const {
1740   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1741                                                FIRST_IMPLICIT);
1742   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1743 }
1744 
1745 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1746                                          const SDLoc &SL, SDValue Val,
1747                                          bool Signed,
1748                                          const ISD::InputArg *Arg) const {
1749   // First, if it is a widened vector, narrow it.
1750   if (VT.isVector() &&
1751       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1752     EVT NarrowedVT =
1753         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1754                          VT.getVectorNumElements());
1755     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1756                       DAG.getConstant(0, SL, MVT::i32));
1757   }
1758 
1759   // Then convert the vector elements or scalar value.
1760   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1761       VT.bitsLT(MemVT)) {
1762     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1763     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1764   }
1765 
1766   if (MemVT.isFloatingPoint())
1767     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1768   else if (Signed)
1769     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1770   else
1771     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1772 
1773   return Val;
1774 }
1775 
1776 SDValue SITargetLowering::lowerKernargMemParameter(
1777     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1778     uint64_t Offset, Align Alignment, bool Signed,
1779     const ISD::InputArg *Arg) const {
1780   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1781 
1782   // Try to avoid using an extload by loading earlier than the argument address,
1783   // and extracting the relevant bits. The load should hopefully be merged with
1784   // the previous argument.
1785   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1786     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1787     int64_t AlignDownOffset = alignDown(Offset, 4);
1788     int64_t OffsetDiff = Offset - AlignDownOffset;
1789 
1790     EVT IntVT = MemVT.changeTypeToInteger();
1791 
1792     // TODO: If we passed in the base kernel offset we could have a better
1793     // alignment than 4, but we don't really need it.
1794     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1795     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1796                                MachineMemOperand::MODereferenceable |
1797                                    MachineMemOperand::MOInvariant);
1798 
1799     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1800     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1801 
1802     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1803     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1804     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1805 
1806 
1807     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1808   }
1809 
1810   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1811   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1812                              MachineMemOperand::MODereferenceable |
1813                                  MachineMemOperand::MOInvariant);
1814 
1815   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1816   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1817 }
1818 
1819 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1820                                               const SDLoc &SL, SDValue Chain,
1821                                               const ISD::InputArg &Arg) const {
1822   MachineFunction &MF = DAG.getMachineFunction();
1823   MachineFrameInfo &MFI = MF.getFrameInfo();
1824 
1825   if (Arg.Flags.isByVal()) {
1826     unsigned Size = Arg.Flags.getByValSize();
1827     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1828     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1829   }
1830 
1831   unsigned ArgOffset = VA.getLocMemOffset();
1832   unsigned ArgSize = VA.getValVT().getStoreSize();
1833 
1834   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1835 
1836   // Create load nodes to retrieve arguments from the stack.
1837   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1838   SDValue ArgValue;
1839 
1840   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1841   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1842   MVT MemVT = VA.getValVT();
1843 
1844   switch (VA.getLocInfo()) {
1845   default:
1846     break;
1847   case CCValAssign::BCvt:
1848     MemVT = VA.getLocVT();
1849     break;
1850   case CCValAssign::SExt:
1851     ExtType = ISD::SEXTLOAD;
1852     break;
1853   case CCValAssign::ZExt:
1854     ExtType = ISD::ZEXTLOAD;
1855     break;
1856   case CCValAssign::AExt:
1857     ExtType = ISD::EXTLOAD;
1858     break;
1859   }
1860 
1861   ArgValue = DAG.getExtLoad(
1862     ExtType, SL, VA.getLocVT(), Chain, FIN,
1863     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1864     MemVT);
1865   return ArgValue;
1866 }
1867 
1868 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1869   const SIMachineFunctionInfo &MFI,
1870   EVT VT,
1871   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1872   const ArgDescriptor *Reg;
1873   const TargetRegisterClass *RC;
1874   LLT Ty;
1875 
1876   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1877   if (!Reg) {
1878     if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) {
1879       // It's possible for a kernarg intrinsic call to appear in a kernel with
1880       // no allocated segment, in which case we do not add the user sgpr
1881       // argument, so just return null.
1882       return DAG.getConstant(0, SDLoc(), VT);
1883     }
1884 
1885     // It's undefined behavior if a function marked with the amdgpu-no-*
1886     // attributes uses the corresponding intrinsic.
1887     return DAG.getUNDEF(VT);
1888   }
1889 
1890   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1891 }
1892 
1893 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1894                                CallingConv::ID CallConv,
1895                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1896                                FunctionType *FType,
1897                                SIMachineFunctionInfo *Info) {
1898   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1899     const ISD::InputArg *Arg = &Ins[I];
1900 
1901     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1902            "vector type argument should have been split");
1903 
1904     // First check if it's a PS input addr.
1905     if (CallConv == CallingConv::AMDGPU_PS &&
1906         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1907       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1908 
1909       // Inconveniently only the first part of the split is marked as isSplit,
1910       // so skip to the end. We only want to increment PSInputNum once for the
1911       // entire split argument.
1912       if (Arg->Flags.isSplit()) {
1913         while (!Arg->Flags.isSplitEnd()) {
1914           assert((!Arg->VT.isVector() ||
1915                   Arg->VT.getScalarSizeInBits() == 16) &&
1916                  "unexpected vector split in ps argument type");
1917           if (!SkipArg)
1918             Splits.push_back(*Arg);
1919           Arg = &Ins[++I];
1920         }
1921       }
1922 
1923       if (SkipArg) {
1924         // We can safely skip PS inputs.
1925         Skipped.set(Arg->getOrigArgIndex());
1926         ++PSInputNum;
1927         continue;
1928       }
1929 
1930       Info->markPSInputAllocated(PSInputNum);
1931       if (Arg->Used)
1932         Info->markPSInputEnabled(PSInputNum);
1933 
1934       ++PSInputNum;
1935     }
1936 
1937     Splits.push_back(*Arg);
1938   }
1939 }
1940 
1941 // Allocate special inputs passed in VGPRs.
1942 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1943                                                       MachineFunction &MF,
1944                                                       const SIRegisterInfo &TRI,
1945                                                       SIMachineFunctionInfo &Info) const {
1946   const LLT S32 = LLT::scalar(32);
1947   MachineRegisterInfo &MRI = MF.getRegInfo();
1948 
1949   if (Info.hasWorkItemIDX()) {
1950     Register Reg = AMDGPU::VGPR0;
1951     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1952 
1953     CCInfo.AllocateReg(Reg);
1954     unsigned Mask = (Subtarget->hasPackedTID() &&
1955                      Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
1956     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1957   }
1958 
1959   if (Info.hasWorkItemIDY()) {
1960     assert(Info.hasWorkItemIDX());
1961     if (Subtarget->hasPackedTID()) {
1962       Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1963                                                         0x3ff << 10));
1964     } else {
1965       unsigned Reg = AMDGPU::VGPR1;
1966       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1967 
1968       CCInfo.AllocateReg(Reg);
1969       Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1970     }
1971   }
1972 
1973   if (Info.hasWorkItemIDZ()) {
1974     assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
1975     if (Subtarget->hasPackedTID()) {
1976       Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1977                                                         0x3ff << 20));
1978     } else {
1979       unsigned Reg = AMDGPU::VGPR2;
1980       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1981 
1982       CCInfo.AllocateReg(Reg);
1983       Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1984     }
1985   }
1986 }
1987 
1988 // Try to allocate a VGPR at the end of the argument list, or if no argument
1989 // VGPRs are left allocating a stack slot.
1990 // If \p Mask is is given it indicates bitfield position in the register.
1991 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1992 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1993                                          ArgDescriptor Arg = ArgDescriptor()) {
1994   if (Arg.isSet())
1995     return ArgDescriptor::createArg(Arg, Mask);
1996 
1997   ArrayRef<MCPhysReg> ArgVGPRs
1998     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1999   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
2000   if (RegIdx == ArgVGPRs.size()) {
2001     // Spill to stack required.
2002     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
2003 
2004     return ArgDescriptor::createStack(Offset, Mask);
2005   }
2006 
2007   unsigned Reg = ArgVGPRs[RegIdx];
2008   Reg = CCInfo.AllocateReg(Reg);
2009   assert(Reg != AMDGPU::NoRegister);
2010 
2011   MachineFunction &MF = CCInfo.getMachineFunction();
2012   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
2013   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
2014   return ArgDescriptor::createRegister(Reg, Mask);
2015 }
2016 
2017 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
2018                                              const TargetRegisterClass *RC,
2019                                              unsigned NumArgRegs) {
2020   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
2021   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
2022   if (RegIdx == ArgSGPRs.size())
2023     report_fatal_error("ran out of SGPRs for arguments");
2024 
2025   unsigned Reg = ArgSGPRs[RegIdx];
2026   Reg = CCInfo.AllocateReg(Reg);
2027   assert(Reg != AMDGPU::NoRegister);
2028 
2029   MachineFunction &MF = CCInfo.getMachineFunction();
2030   MF.addLiveIn(Reg, RC);
2031   return ArgDescriptor::createRegister(Reg);
2032 }
2033 
2034 // If this has a fixed position, we still should allocate the register in the
2035 // CCInfo state. Technically we could get away with this for values passed
2036 // outside of the normal argument range.
2037 static void allocateFixedSGPRInputImpl(CCState &CCInfo,
2038                                        const TargetRegisterClass *RC,
2039                                        MCRegister Reg) {
2040   Reg = CCInfo.AllocateReg(Reg);
2041   assert(Reg != AMDGPU::NoRegister);
2042   MachineFunction &MF = CCInfo.getMachineFunction();
2043   MF.addLiveIn(Reg, RC);
2044 }
2045 
2046 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
2047   if (Arg) {
2048     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
2049                                Arg.getRegister());
2050   } else
2051     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
2052 }
2053 
2054 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
2055   if (Arg) {
2056     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
2057                                Arg.getRegister());
2058   } else
2059     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
2060 }
2061 
2062 /// Allocate implicit function VGPR arguments at the end of allocated user
2063 /// arguments.
2064 void SITargetLowering::allocateSpecialInputVGPRs(
2065   CCState &CCInfo, MachineFunction &MF,
2066   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2067   const unsigned Mask = 0x3ff;
2068   ArgDescriptor Arg;
2069 
2070   if (Info.hasWorkItemIDX()) {
2071     Arg = allocateVGPR32Input(CCInfo, Mask);
2072     Info.setWorkItemIDX(Arg);
2073   }
2074 
2075   if (Info.hasWorkItemIDY()) {
2076     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
2077     Info.setWorkItemIDY(Arg);
2078   }
2079 
2080   if (Info.hasWorkItemIDZ())
2081     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
2082 }
2083 
2084 /// Allocate implicit function VGPR arguments in fixed registers.
2085 void SITargetLowering::allocateSpecialInputVGPRsFixed(
2086   CCState &CCInfo, MachineFunction &MF,
2087   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2088   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
2089   if (!Reg)
2090     report_fatal_error("failed to allocated VGPR for implicit arguments");
2091 
2092   const unsigned Mask = 0x3ff;
2093   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2094   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
2095   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
2096 }
2097 
2098 void SITargetLowering::allocateSpecialInputSGPRs(
2099   CCState &CCInfo,
2100   MachineFunction &MF,
2101   const SIRegisterInfo &TRI,
2102   SIMachineFunctionInfo &Info) const {
2103   auto &ArgInfo = Info.getArgInfo();
2104 
2105   // TODO: Unify handling with private memory pointers.
2106   if (Info.hasDispatchPtr())
2107     allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
2108 
2109   if (Info.hasQueuePtr())
2110     allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
2111 
2112   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
2113   // constant offset from the kernarg segment.
2114   if (Info.hasImplicitArgPtr())
2115     allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
2116 
2117   if (Info.hasDispatchID())
2118     allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2119 
2120   // flat_scratch_init is not applicable for non-kernel functions.
2121 
2122   if (Info.hasWorkGroupIDX())
2123     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2124 
2125   if (Info.hasWorkGroupIDY())
2126     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2127 
2128   if (Info.hasWorkGroupIDZ())
2129     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2130 }
2131 
2132 // Allocate special inputs passed in user SGPRs.
2133 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2134                                             MachineFunction &MF,
2135                                             const SIRegisterInfo &TRI,
2136                                             SIMachineFunctionInfo &Info) const {
2137   if (Info.hasImplicitBufferPtr()) {
2138     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2139     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2140     CCInfo.AllocateReg(ImplicitBufferPtrReg);
2141   }
2142 
2143   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2144   if (Info.hasPrivateSegmentBuffer()) {
2145     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2146     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2147     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2148   }
2149 
2150   if (Info.hasDispatchPtr()) {
2151     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2152     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2153     CCInfo.AllocateReg(DispatchPtrReg);
2154   }
2155 
2156   if (Info.hasQueuePtr()) {
2157     Register QueuePtrReg = Info.addQueuePtr(TRI);
2158     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2159     CCInfo.AllocateReg(QueuePtrReg);
2160   }
2161 
2162   if (Info.hasKernargSegmentPtr()) {
2163     MachineRegisterInfo &MRI = MF.getRegInfo();
2164     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2165     CCInfo.AllocateReg(InputPtrReg);
2166 
2167     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2168     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2169   }
2170 
2171   if (Info.hasDispatchID()) {
2172     Register DispatchIDReg = Info.addDispatchID(TRI);
2173     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2174     CCInfo.AllocateReg(DispatchIDReg);
2175   }
2176 
2177   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2178     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2179     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2180     CCInfo.AllocateReg(FlatScratchInitReg);
2181   }
2182 
2183   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2184   // these from the dispatch pointer.
2185 }
2186 
2187 // Allocate special input registers that are initialized per-wave.
2188 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2189                                            MachineFunction &MF,
2190                                            SIMachineFunctionInfo &Info,
2191                                            CallingConv::ID CallConv,
2192                                            bool IsShader) const {
2193   if (Info.hasWorkGroupIDX()) {
2194     Register Reg = Info.addWorkGroupIDX();
2195     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2196     CCInfo.AllocateReg(Reg);
2197   }
2198 
2199   if (Info.hasWorkGroupIDY()) {
2200     Register Reg = Info.addWorkGroupIDY();
2201     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2202     CCInfo.AllocateReg(Reg);
2203   }
2204 
2205   if (Info.hasWorkGroupIDZ()) {
2206     Register Reg = Info.addWorkGroupIDZ();
2207     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2208     CCInfo.AllocateReg(Reg);
2209   }
2210 
2211   if (Info.hasWorkGroupInfo()) {
2212     Register Reg = Info.addWorkGroupInfo();
2213     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2214     CCInfo.AllocateReg(Reg);
2215   }
2216 
2217   if (Info.hasPrivateSegmentWaveByteOffset()) {
2218     // Scratch wave offset passed in system SGPR.
2219     unsigned PrivateSegmentWaveByteOffsetReg;
2220 
2221     if (IsShader) {
2222       PrivateSegmentWaveByteOffsetReg =
2223         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2224 
2225       // This is true if the scratch wave byte offset doesn't have a fixed
2226       // location.
2227       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2228         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2229         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2230       }
2231     } else
2232       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2233 
2234     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2235     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2236   }
2237 }
2238 
2239 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2240                                      MachineFunction &MF,
2241                                      const SIRegisterInfo &TRI,
2242                                      SIMachineFunctionInfo &Info) {
2243   // Now that we've figured out where the scratch register inputs are, see if
2244   // should reserve the arguments and use them directly.
2245   MachineFrameInfo &MFI = MF.getFrameInfo();
2246   bool HasStackObjects = MFI.hasStackObjects();
2247   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2248 
2249   // Record that we know we have non-spill stack objects so we don't need to
2250   // check all stack objects later.
2251   if (HasStackObjects)
2252     Info.setHasNonSpillStackObjects(true);
2253 
2254   // Everything live out of a block is spilled with fast regalloc, so it's
2255   // almost certain that spilling will be required.
2256   if (TM.getOptLevel() == CodeGenOpt::None)
2257     HasStackObjects = true;
2258 
2259   // For now assume stack access is needed in any callee functions, so we need
2260   // the scratch registers to pass in.
2261   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2262 
2263   if (!ST.enableFlatScratch()) {
2264     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2265       // If we have stack objects, we unquestionably need the private buffer
2266       // resource. For the Code Object V2 ABI, this will be the first 4 user
2267       // SGPR inputs. We can reserve those and use them directly.
2268 
2269       Register PrivateSegmentBufferReg =
2270           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2271       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2272     } else {
2273       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2274       // We tentatively reserve the last registers (skipping the last registers
2275       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2276       // we'll replace these with the ones immediately after those which were
2277       // really allocated. In the prologue copies will be inserted from the
2278       // argument to these reserved registers.
2279 
2280       // Without HSA, relocations are used for the scratch pointer and the
2281       // buffer resource setup is always inserted in the prologue. Scratch wave
2282       // offset is still in an input SGPR.
2283       Info.setScratchRSrcReg(ReservedBufferReg);
2284     }
2285   }
2286 
2287   MachineRegisterInfo &MRI = MF.getRegInfo();
2288 
2289   // For entry functions we have to set up the stack pointer if we use it,
2290   // whereas non-entry functions get this "for free". This means there is no
2291   // intrinsic advantage to using S32 over S34 in cases where we do not have
2292   // calls but do need a frame pointer (i.e. if we are requested to have one
2293   // because frame pointer elimination is disabled). To keep things simple we
2294   // only ever use S32 as the call ABI stack pointer, and so using it does not
2295   // imply we need a separate frame pointer.
2296   //
2297   // Try to use s32 as the SP, but move it if it would interfere with input
2298   // arguments. This won't work with calls though.
2299   //
2300   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2301   // registers.
2302   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2303     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2304   } else {
2305     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2306 
2307     if (MFI.hasCalls())
2308       report_fatal_error("call in graphics shader with too many input SGPRs");
2309 
2310     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2311       if (!MRI.isLiveIn(Reg)) {
2312         Info.setStackPtrOffsetReg(Reg);
2313         break;
2314       }
2315     }
2316 
2317     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2318       report_fatal_error("failed to find register for SP");
2319   }
2320 
2321   // hasFP should be accurate for entry functions even before the frame is
2322   // finalized, because it does not rely on the known stack size, only
2323   // properties like whether variable sized objects are present.
2324   if (ST.getFrameLowering()->hasFP(MF)) {
2325     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2326   }
2327 }
2328 
2329 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2330   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2331   return !Info->isEntryFunction();
2332 }
2333 
2334 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2335 
2336 }
2337 
2338 void SITargetLowering::insertCopiesSplitCSR(
2339   MachineBasicBlock *Entry,
2340   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2341   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2342 
2343   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2344   if (!IStart)
2345     return;
2346 
2347   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2348   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2349   MachineBasicBlock::iterator MBBI = Entry->begin();
2350   for (const MCPhysReg *I = IStart; *I; ++I) {
2351     const TargetRegisterClass *RC = nullptr;
2352     if (AMDGPU::SReg_64RegClass.contains(*I))
2353       RC = &AMDGPU::SGPR_64RegClass;
2354     else if (AMDGPU::SReg_32RegClass.contains(*I))
2355       RC = &AMDGPU::SGPR_32RegClass;
2356     else
2357       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2358 
2359     Register NewVR = MRI->createVirtualRegister(RC);
2360     // Create copy from CSR to a virtual register.
2361     Entry->addLiveIn(*I);
2362     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2363       .addReg(*I);
2364 
2365     // Insert the copy-back instructions right before the terminator.
2366     for (auto *Exit : Exits)
2367       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2368               TII->get(TargetOpcode::COPY), *I)
2369         .addReg(NewVR);
2370   }
2371 }
2372 
2373 SDValue SITargetLowering::LowerFormalArguments(
2374     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2375     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2376     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2377   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2378 
2379   MachineFunction &MF = DAG.getMachineFunction();
2380   const Function &Fn = MF.getFunction();
2381   FunctionType *FType = MF.getFunction().getFunctionType();
2382   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2383 
2384   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2385     DiagnosticInfoUnsupported NoGraphicsHSA(
2386         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2387     DAG.getContext()->diagnose(NoGraphicsHSA);
2388     return DAG.getEntryNode();
2389   }
2390 
2391   Info->allocateModuleLDSGlobal(Fn.getParent());
2392 
2393   SmallVector<ISD::InputArg, 16> Splits;
2394   SmallVector<CCValAssign, 16> ArgLocs;
2395   BitVector Skipped(Ins.size());
2396   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2397                  *DAG.getContext());
2398 
2399   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2400   bool IsKernel = AMDGPU::isKernel(CallConv);
2401   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2402 
2403   if (IsGraphics) {
2404     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2405            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2406            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2407            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2408            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2409            !Info->hasWorkItemIDZ());
2410   }
2411 
2412   if (CallConv == CallingConv::AMDGPU_PS) {
2413     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2414 
2415     // At least one interpolation mode must be enabled or else the GPU will
2416     // hang.
2417     //
2418     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2419     // set PSInputAddr, the user wants to enable some bits after the compilation
2420     // based on run-time states. Since we can't know what the final PSInputEna
2421     // will look like, so we shouldn't do anything here and the user should take
2422     // responsibility for the correct programming.
2423     //
2424     // Otherwise, the following restrictions apply:
2425     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2426     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2427     //   enabled too.
2428     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2429         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2430       CCInfo.AllocateReg(AMDGPU::VGPR0);
2431       CCInfo.AllocateReg(AMDGPU::VGPR1);
2432       Info->markPSInputAllocated(0);
2433       Info->markPSInputEnabled(0);
2434     }
2435     if (Subtarget->isAmdPalOS()) {
2436       // For isAmdPalOS, the user does not enable some bits after compilation
2437       // based on run-time states; the register values being generated here are
2438       // the final ones set in hardware. Therefore we need to apply the
2439       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2440       // a bit is set in PSInputAddr but not PSInputEnable is where the
2441       // frontend set up an input arg for a particular interpolation mode, but
2442       // nothing uses that input arg. Really we should have an earlier pass
2443       // that removes such an arg.)
2444       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2445       if ((PsInputBits & 0x7F) == 0 ||
2446           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2447         Info->markPSInputEnabled(
2448             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2449     }
2450   } else if (IsKernel) {
2451     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2452   } else {
2453     Splits.append(Ins.begin(), Ins.end());
2454   }
2455 
2456   if (IsEntryFunc) {
2457     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2458     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2459   } else if (!IsGraphics) {
2460     // For the fixed ABI, pass workitem IDs in the last argument register.
2461     allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2462   }
2463 
2464   if (IsKernel) {
2465     analyzeFormalArgumentsCompute(CCInfo, Ins);
2466   } else {
2467     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2468     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2469   }
2470 
2471   SmallVector<SDValue, 16> Chains;
2472 
2473   // FIXME: This is the minimum kernel argument alignment. We should improve
2474   // this to the maximum alignment of the arguments.
2475   //
2476   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2477   // kern arg offset.
2478   const Align KernelArgBaseAlign = Align(16);
2479 
2480   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2481     const ISD::InputArg &Arg = Ins[i];
2482     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2483       InVals.push_back(DAG.getUNDEF(Arg.VT));
2484       continue;
2485     }
2486 
2487     CCValAssign &VA = ArgLocs[ArgIdx++];
2488     MVT VT = VA.getLocVT();
2489 
2490     if (IsEntryFunc && VA.isMemLoc()) {
2491       VT = Ins[i].VT;
2492       EVT MemVT = VA.getLocVT();
2493 
2494       const uint64_t Offset = VA.getLocMemOffset();
2495       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2496 
2497       if (Arg.Flags.isByRef()) {
2498         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2499 
2500         const GCNTargetMachine &TM =
2501             static_cast<const GCNTargetMachine &>(getTargetMachine());
2502         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2503                                     Arg.Flags.getPointerAddrSpace())) {
2504           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2505                                      Arg.Flags.getPointerAddrSpace());
2506         }
2507 
2508         InVals.push_back(Ptr);
2509         continue;
2510       }
2511 
2512       SDValue Arg = lowerKernargMemParameter(
2513         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2514       Chains.push_back(Arg.getValue(1));
2515 
2516       auto *ParamTy =
2517         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2518       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2519           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2520                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2521         // On SI local pointers are just offsets into LDS, so they are always
2522         // less than 16-bits.  On CI and newer they could potentially be
2523         // real pointers, so we can't guarantee their size.
2524         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2525                           DAG.getValueType(MVT::i16));
2526       }
2527 
2528       InVals.push_back(Arg);
2529       continue;
2530     } else if (!IsEntryFunc && VA.isMemLoc()) {
2531       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2532       InVals.push_back(Val);
2533       if (!Arg.Flags.isByVal())
2534         Chains.push_back(Val.getValue(1));
2535       continue;
2536     }
2537 
2538     assert(VA.isRegLoc() && "Parameter must be in a register!");
2539 
2540     Register Reg = VA.getLocReg();
2541     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2542     EVT ValVT = VA.getValVT();
2543 
2544     Reg = MF.addLiveIn(Reg, RC);
2545     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2546 
2547     if (Arg.Flags.isSRet()) {
2548       // The return object should be reasonably addressable.
2549 
2550       // FIXME: This helps when the return is a real sret. If it is a
2551       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2552       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2553       unsigned NumBits
2554         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2555       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2556         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2557     }
2558 
2559     // If this is an 8 or 16-bit value, it is really passed promoted
2560     // to 32 bits. Insert an assert[sz]ext to capture this, then
2561     // truncate to the right size.
2562     switch (VA.getLocInfo()) {
2563     case CCValAssign::Full:
2564       break;
2565     case CCValAssign::BCvt:
2566       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2567       break;
2568     case CCValAssign::SExt:
2569       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2570                         DAG.getValueType(ValVT));
2571       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2572       break;
2573     case CCValAssign::ZExt:
2574       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2575                         DAG.getValueType(ValVT));
2576       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2577       break;
2578     case CCValAssign::AExt:
2579       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2580       break;
2581     default:
2582       llvm_unreachable("Unknown loc info!");
2583     }
2584 
2585     InVals.push_back(Val);
2586   }
2587 
2588   // Start adding system SGPRs.
2589   if (IsEntryFunc) {
2590     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2591   } else {
2592     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2593     if (!IsGraphics)
2594       allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2595   }
2596 
2597   auto &ArgUsageInfo =
2598     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2599   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2600 
2601   unsigned StackArgSize = CCInfo.getNextStackOffset();
2602   Info->setBytesInStackArgArea(StackArgSize);
2603 
2604   return Chains.empty() ? Chain :
2605     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2606 }
2607 
2608 // TODO: If return values can't fit in registers, we should return as many as
2609 // possible in registers before passing on stack.
2610 bool SITargetLowering::CanLowerReturn(
2611   CallingConv::ID CallConv,
2612   MachineFunction &MF, bool IsVarArg,
2613   const SmallVectorImpl<ISD::OutputArg> &Outs,
2614   LLVMContext &Context) const {
2615   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2616   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2617   // for shaders. Vector types should be explicitly handled by CC.
2618   if (AMDGPU::isEntryFunctionCC(CallConv))
2619     return true;
2620 
2621   SmallVector<CCValAssign, 16> RVLocs;
2622   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2623   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2624 }
2625 
2626 SDValue
2627 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2628                               bool isVarArg,
2629                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2630                               const SmallVectorImpl<SDValue> &OutVals,
2631                               const SDLoc &DL, SelectionDAG &DAG) const {
2632   MachineFunction &MF = DAG.getMachineFunction();
2633   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2634 
2635   if (AMDGPU::isKernel(CallConv)) {
2636     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2637                                              OutVals, DL, DAG);
2638   }
2639 
2640   bool IsShader = AMDGPU::isShader(CallConv);
2641 
2642   Info->setIfReturnsVoid(Outs.empty());
2643   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2644 
2645   // CCValAssign - represent the assignment of the return value to a location.
2646   SmallVector<CCValAssign, 48> RVLocs;
2647   SmallVector<ISD::OutputArg, 48> Splits;
2648 
2649   // CCState - Info about the registers and stack slots.
2650   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2651                  *DAG.getContext());
2652 
2653   // Analyze outgoing return values.
2654   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2655 
2656   SDValue Flag;
2657   SmallVector<SDValue, 48> RetOps;
2658   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2659 
2660   // Add return address for callable functions.
2661   if (!Info->isEntryFunction()) {
2662     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2663     SDValue ReturnAddrReg = CreateLiveInRegister(
2664       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2665 
2666     SDValue ReturnAddrVirtualReg =
2667         DAG.getRegister(MF.getRegInfo().createVirtualRegister(
2668                             CallConv != CallingConv::AMDGPU_Gfx
2669                                 ? &AMDGPU::CCR_SGPR_64RegClass
2670                                 : &AMDGPU::Gfx_CCR_SGPR_64RegClass),
2671                         MVT::i64);
2672     Chain =
2673         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2674     Flag = Chain.getValue(1);
2675     RetOps.push_back(ReturnAddrVirtualReg);
2676   }
2677 
2678   // Copy the result values into the output registers.
2679   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2680        ++I, ++RealRVLocIdx) {
2681     CCValAssign &VA = RVLocs[I];
2682     assert(VA.isRegLoc() && "Can only return in registers!");
2683     // TODO: Partially return in registers if return values don't fit.
2684     SDValue Arg = OutVals[RealRVLocIdx];
2685 
2686     // Copied from other backends.
2687     switch (VA.getLocInfo()) {
2688     case CCValAssign::Full:
2689       break;
2690     case CCValAssign::BCvt:
2691       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2692       break;
2693     case CCValAssign::SExt:
2694       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2695       break;
2696     case CCValAssign::ZExt:
2697       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2698       break;
2699     case CCValAssign::AExt:
2700       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2701       break;
2702     default:
2703       llvm_unreachable("Unknown loc info!");
2704     }
2705 
2706     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2707     Flag = Chain.getValue(1);
2708     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2709   }
2710 
2711   // FIXME: Does sret work properly?
2712   if (!Info->isEntryFunction()) {
2713     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2714     const MCPhysReg *I =
2715       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2716     if (I) {
2717       for (; *I; ++I) {
2718         if (AMDGPU::SReg_64RegClass.contains(*I))
2719           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2720         else if (AMDGPU::SReg_32RegClass.contains(*I))
2721           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2722         else
2723           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2724       }
2725     }
2726   }
2727 
2728   // Update chain and glue.
2729   RetOps[0] = Chain;
2730   if (Flag.getNode())
2731     RetOps.push_back(Flag);
2732 
2733   unsigned Opc = AMDGPUISD::ENDPGM;
2734   if (!IsWaveEnd) {
2735     if (IsShader)
2736       Opc = AMDGPUISD::RETURN_TO_EPILOG;
2737     else if (CallConv == CallingConv::AMDGPU_Gfx)
2738       Opc = AMDGPUISD::RET_GFX_FLAG;
2739     else
2740       Opc = AMDGPUISD::RET_FLAG;
2741   }
2742 
2743   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2744 }
2745 
2746 SDValue SITargetLowering::LowerCallResult(
2747     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2748     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2749     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2750     SDValue ThisVal) const {
2751   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2752 
2753   // Assign locations to each value returned by this call.
2754   SmallVector<CCValAssign, 16> RVLocs;
2755   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2756                  *DAG.getContext());
2757   CCInfo.AnalyzeCallResult(Ins, RetCC);
2758 
2759   // Copy all of the result registers out of their specified physreg.
2760   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2761     CCValAssign VA = RVLocs[i];
2762     SDValue Val;
2763 
2764     if (VA.isRegLoc()) {
2765       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2766       Chain = Val.getValue(1);
2767       InFlag = Val.getValue(2);
2768     } else if (VA.isMemLoc()) {
2769       report_fatal_error("TODO: return values in memory");
2770     } else
2771       llvm_unreachable("unknown argument location type");
2772 
2773     switch (VA.getLocInfo()) {
2774     case CCValAssign::Full:
2775       break;
2776     case CCValAssign::BCvt:
2777       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2778       break;
2779     case CCValAssign::ZExt:
2780       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2781                         DAG.getValueType(VA.getValVT()));
2782       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2783       break;
2784     case CCValAssign::SExt:
2785       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2786                         DAG.getValueType(VA.getValVT()));
2787       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2788       break;
2789     case CCValAssign::AExt:
2790       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2791       break;
2792     default:
2793       llvm_unreachable("Unknown loc info!");
2794     }
2795 
2796     InVals.push_back(Val);
2797   }
2798 
2799   return Chain;
2800 }
2801 
2802 // Add code to pass special inputs required depending on used features separate
2803 // from the explicit user arguments present in the IR.
2804 void SITargetLowering::passSpecialInputs(
2805     CallLoweringInfo &CLI,
2806     CCState &CCInfo,
2807     const SIMachineFunctionInfo &Info,
2808     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2809     SmallVectorImpl<SDValue> &MemOpChains,
2810     SDValue Chain) const {
2811   // If we don't have a call site, this was a call inserted by
2812   // legalization. These can never use special inputs.
2813   if (!CLI.CB)
2814     return;
2815 
2816   SelectionDAG &DAG = CLI.DAG;
2817   const SDLoc &DL = CLI.DL;
2818   const Function &F = DAG.getMachineFunction().getFunction();
2819 
2820   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2821   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2822 
2823   const AMDGPUFunctionArgInfo *CalleeArgInfo
2824     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2825   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2826     auto &ArgUsageInfo =
2827       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2828     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2829   }
2830 
2831   // TODO: Unify with private memory register handling. This is complicated by
2832   // the fact that at least in kernels, the input argument is not necessarily
2833   // in the same location as the input.
2834   static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
2835                              StringLiteral> ImplicitAttrs[] = {
2836     {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"},
2837     {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" },
2838     {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"},
2839     {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"},
2840     {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"},
2841     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"},
2842     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"}
2843   };
2844 
2845   for (auto Attr : ImplicitAttrs) {
2846     const ArgDescriptor *OutgoingArg;
2847     const TargetRegisterClass *ArgRC;
2848     LLT ArgTy;
2849 
2850     AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first;
2851 
2852     // If the callee does not use the attribute value, skip copying the value.
2853     if (CLI.CB->hasFnAttr(Attr.second))
2854       continue;
2855 
2856     std::tie(OutgoingArg, ArgRC, ArgTy) =
2857         CalleeArgInfo->getPreloadedValue(InputID);
2858     if (!OutgoingArg)
2859       continue;
2860 
2861     const ArgDescriptor *IncomingArg;
2862     const TargetRegisterClass *IncomingArgRC;
2863     LLT Ty;
2864     std::tie(IncomingArg, IncomingArgRC, Ty) =
2865         CallerArgInfo.getPreloadedValue(InputID);
2866     assert(IncomingArgRC == ArgRC);
2867 
2868     // All special arguments are ints for now.
2869     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2870     SDValue InputReg;
2871 
2872     if (IncomingArg) {
2873       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2874     } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
2875       // The implicit arg ptr is special because it doesn't have a corresponding
2876       // input for kernels, and is computed from the kernarg segment pointer.
2877       InputReg = getImplicitArgPtr(DAG, DL);
2878     } else {
2879       // We may have proven the input wasn't needed, although the ABI is
2880       // requiring it. We just need to allocate the register appropriately.
2881       InputReg = DAG.getUNDEF(ArgVT);
2882     }
2883 
2884     if (OutgoingArg->isRegister()) {
2885       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2886       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2887         report_fatal_error("failed to allocate implicit input argument");
2888     } else {
2889       unsigned SpecialArgOffset =
2890           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2891       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2892                                               SpecialArgOffset);
2893       MemOpChains.push_back(ArgStore);
2894     }
2895   }
2896 
2897   // Pack workitem IDs into a single register or pass it as is if already
2898   // packed.
2899   const ArgDescriptor *OutgoingArg;
2900   const TargetRegisterClass *ArgRC;
2901   LLT Ty;
2902 
2903   std::tie(OutgoingArg, ArgRC, Ty) =
2904       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2905   if (!OutgoingArg)
2906     std::tie(OutgoingArg, ArgRC, Ty) =
2907         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2908   if (!OutgoingArg)
2909     std::tie(OutgoingArg, ArgRC, Ty) =
2910         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2911   if (!OutgoingArg)
2912     return;
2913 
2914   const ArgDescriptor *IncomingArgX = std::get<0>(
2915       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2916   const ArgDescriptor *IncomingArgY = std::get<0>(
2917       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2918   const ArgDescriptor *IncomingArgZ = std::get<0>(
2919       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2920 
2921   SDValue InputReg;
2922   SDLoc SL;
2923 
2924   const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
2925   const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
2926   const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
2927 
2928   // If incoming ids are not packed we need to pack them.
2929   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
2930       NeedWorkItemIDX) {
2931     if (Subtarget->getMaxWorkitemID(F, 0) != 0) {
2932       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2933     } else {
2934       InputReg = DAG.getConstant(0, DL, MVT::i32);
2935     }
2936   }
2937 
2938   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
2939       NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) {
2940     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2941     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2942                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2943     InputReg = InputReg.getNode() ?
2944                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2945   }
2946 
2947   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
2948       NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) {
2949     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2950     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2951                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2952     InputReg = InputReg.getNode() ?
2953                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2954   }
2955 
2956   if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
2957     if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) {
2958       // We're in a situation where the outgoing function requires the workitem
2959       // ID, but the calling function does not have it (e.g a graphics function
2960       // calling a C calling convention function). This is illegal, but we need
2961       // to produce something.
2962       InputReg = DAG.getUNDEF(MVT::i32);
2963     } else {
2964       // Workitem ids are already packed, any of present incoming arguments
2965       // will carry all required fields.
2966       ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2967         IncomingArgX ? *IncomingArgX :
2968         IncomingArgY ? *IncomingArgY :
2969         *IncomingArgZ, ~0u);
2970       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2971     }
2972   }
2973 
2974   if (OutgoingArg->isRegister()) {
2975     if (InputReg)
2976       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2977 
2978     CCInfo.AllocateReg(OutgoingArg->getRegister());
2979   } else {
2980     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2981     if (InputReg) {
2982       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2983                                               SpecialArgOffset);
2984       MemOpChains.push_back(ArgStore);
2985     }
2986   }
2987 }
2988 
2989 static bool canGuaranteeTCO(CallingConv::ID CC) {
2990   return CC == CallingConv::Fast;
2991 }
2992 
2993 /// Return true if we might ever do TCO for calls with this calling convention.
2994 static bool mayTailCallThisCC(CallingConv::ID CC) {
2995   switch (CC) {
2996   case CallingConv::C:
2997   case CallingConv::AMDGPU_Gfx:
2998     return true;
2999   default:
3000     return canGuaranteeTCO(CC);
3001   }
3002 }
3003 
3004 bool SITargetLowering::isEligibleForTailCallOptimization(
3005     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
3006     const SmallVectorImpl<ISD::OutputArg> &Outs,
3007     const SmallVectorImpl<SDValue> &OutVals,
3008     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3009   if (!mayTailCallThisCC(CalleeCC))
3010     return false;
3011 
3012   // For a divergent call target, we need to do a waterfall loop over the
3013   // possible callees which precludes us from using a simple jump.
3014   if (Callee->isDivergent())
3015     return false;
3016 
3017   MachineFunction &MF = DAG.getMachineFunction();
3018   const Function &CallerF = MF.getFunction();
3019   CallingConv::ID CallerCC = CallerF.getCallingConv();
3020   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3021   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3022 
3023   // Kernels aren't callable, and don't have a live in return address so it
3024   // doesn't make sense to do a tail call with entry functions.
3025   if (!CallerPreserved)
3026     return false;
3027 
3028   bool CCMatch = CallerCC == CalleeCC;
3029 
3030   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3031     if (canGuaranteeTCO(CalleeCC) && CCMatch)
3032       return true;
3033     return false;
3034   }
3035 
3036   // TODO: Can we handle var args?
3037   if (IsVarArg)
3038     return false;
3039 
3040   for (const Argument &Arg : CallerF.args()) {
3041     if (Arg.hasByValAttr())
3042       return false;
3043   }
3044 
3045   LLVMContext &Ctx = *DAG.getContext();
3046 
3047   // Check that the call results are passed in the same way.
3048   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
3049                                   CCAssignFnForCall(CalleeCC, IsVarArg),
3050                                   CCAssignFnForCall(CallerCC, IsVarArg)))
3051     return false;
3052 
3053   // The callee has to preserve all registers the caller needs to preserve.
3054   if (!CCMatch) {
3055     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3056     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3057       return false;
3058   }
3059 
3060   // Nothing more to check if the callee is taking no arguments.
3061   if (Outs.empty())
3062     return true;
3063 
3064   SmallVector<CCValAssign, 16> ArgLocs;
3065   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
3066 
3067   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
3068 
3069   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
3070   // If the stack arguments for this call do not fit into our own save area then
3071   // the call cannot be made tail.
3072   // TODO: Is this really necessary?
3073   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3074     return false;
3075 
3076   const MachineRegisterInfo &MRI = MF.getRegInfo();
3077   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
3078 }
3079 
3080 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3081   if (!CI->isTailCall())
3082     return false;
3083 
3084   const Function *ParentFn = CI->getParent()->getParent();
3085   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
3086     return false;
3087   return true;
3088 }
3089 
3090 // The wave scratch offset register is used as the global base pointer.
3091 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
3092                                     SmallVectorImpl<SDValue> &InVals) const {
3093   SelectionDAG &DAG = CLI.DAG;
3094   const SDLoc &DL = CLI.DL;
3095   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3096   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3097   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3098   SDValue Chain = CLI.Chain;
3099   SDValue Callee = CLI.Callee;
3100   bool &IsTailCall = CLI.IsTailCall;
3101   CallingConv::ID CallConv = CLI.CallConv;
3102   bool IsVarArg = CLI.IsVarArg;
3103   bool IsSibCall = false;
3104   bool IsThisReturn = false;
3105   MachineFunction &MF = DAG.getMachineFunction();
3106 
3107   if (Callee.isUndef() || isNullConstant(Callee)) {
3108     if (!CLI.IsTailCall) {
3109       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
3110         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
3111     }
3112 
3113     return Chain;
3114   }
3115 
3116   if (IsVarArg) {
3117     return lowerUnhandledCall(CLI, InVals,
3118                               "unsupported call to variadic function ");
3119   }
3120 
3121   if (!CLI.CB)
3122     report_fatal_error("unsupported libcall legalization");
3123 
3124   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
3125     return lowerUnhandledCall(CLI, InVals,
3126                               "unsupported required tail call to function ");
3127   }
3128 
3129   if (AMDGPU::isShader(CallConv)) {
3130     // Note the issue is with the CC of the called function, not of the call
3131     // itself.
3132     return lowerUnhandledCall(CLI, InVals,
3133                               "unsupported call to a shader function ");
3134   }
3135 
3136   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
3137       CallConv != CallingConv::AMDGPU_Gfx) {
3138     // Only allow calls with specific calling conventions.
3139     return lowerUnhandledCall(CLI, InVals,
3140                               "unsupported calling convention for call from "
3141                               "graphics shader of function ");
3142   }
3143 
3144   if (IsTailCall) {
3145     IsTailCall = isEligibleForTailCallOptimization(
3146       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3147     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
3148       report_fatal_error("failed to perform tail call elimination on a call "
3149                          "site marked musttail");
3150     }
3151 
3152     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3153 
3154     // A sibling call is one where we're under the usual C ABI and not planning
3155     // to change that but can still do a tail call:
3156     if (!TailCallOpt && IsTailCall)
3157       IsSibCall = true;
3158 
3159     if (IsTailCall)
3160       ++NumTailCalls;
3161   }
3162 
3163   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3164   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3165   SmallVector<SDValue, 8> MemOpChains;
3166 
3167   // Analyze operands of the call, assigning locations to each operand.
3168   SmallVector<CCValAssign, 16> ArgLocs;
3169   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3170   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3171 
3172   if (CallConv != CallingConv::AMDGPU_Gfx) {
3173     // With a fixed ABI, allocate fixed registers before user arguments.
3174     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3175   }
3176 
3177   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3178 
3179   // Get a count of how many bytes are to be pushed on the stack.
3180   unsigned NumBytes = CCInfo.getNextStackOffset();
3181 
3182   if (IsSibCall) {
3183     // Since we're not changing the ABI to make this a tail call, the memory
3184     // operands are already available in the caller's incoming argument space.
3185     NumBytes = 0;
3186   }
3187 
3188   // FPDiff is the byte offset of the call's argument area from the callee's.
3189   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3190   // by this amount for a tail call. In a sibling call it must be 0 because the
3191   // caller will deallocate the entire stack and the callee still expects its
3192   // arguments to begin at SP+0. Completely unused for non-tail calls.
3193   int32_t FPDiff = 0;
3194   MachineFrameInfo &MFI = MF.getFrameInfo();
3195 
3196   // Adjust the stack pointer for the new arguments...
3197   // These operations are automatically eliminated by the prolog/epilog pass
3198   if (!IsSibCall) {
3199     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3200 
3201     if (!Subtarget->enableFlatScratch()) {
3202       SmallVector<SDValue, 4> CopyFromChains;
3203 
3204       // In the HSA case, this should be an identity copy.
3205       SDValue ScratchRSrcReg
3206         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3207       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3208       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3209       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3210     }
3211   }
3212 
3213   MVT PtrVT = MVT::i32;
3214 
3215   // Walk the register/memloc assignments, inserting copies/loads.
3216   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3217     CCValAssign &VA = ArgLocs[i];
3218     SDValue Arg = OutVals[i];
3219 
3220     // Promote the value if needed.
3221     switch (VA.getLocInfo()) {
3222     case CCValAssign::Full:
3223       break;
3224     case CCValAssign::BCvt:
3225       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3226       break;
3227     case CCValAssign::ZExt:
3228       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3229       break;
3230     case CCValAssign::SExt:
3231       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3232       break;
3233     case CCValAssign::AExt:
3234       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3235       break;
3236     case CCValAssign::FPExt:
3237       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3238       break;
3239     default:
3240       llvm_unreachable("Unknown loc info!");
3241     }
3242 
3243     if (VA.isRegLoc()) {
3244       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3245     } else {
3246       assert(VA.isMemLoc());
3247 
3248       SDValue DstAddr;
3249       MachinePointerInfo DstInfo;
3250 
3251       unsigned LocMemOffset = VA.getLocMemOffset();
3252       int32_t Offset = LocMemOffset;
3253 
3254       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3255       MaybeAlign Alignment;
3256 
3257       if (IsTailCall) {
3258         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3259         unsigned OpSize = Flags.isByVal() ?
3260           Flags.getByValSize() : VA.getValVT().getStoreSize();
3261 
3262         // FIXME: We can have better than the minimum byval required alignment.
3263         Alignment =
3264             Flags.isByVal()
3265                 ? Flags.getNonZeroByValAlign()
3266                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3267 
3268         Offset = Offset + FPDiff;
3269         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3270 
3271         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3272         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3273 
3274         // Make sure any stack arguments overlapping with where we're storing
3275         // are loaded before this eventual operation. Otherwise they'll be
3276         // clobbered.
3277 
3278         // FIXME: Why is this really necessary? This seems to just result in a
3279         // lot of code to copy the stack and write them back to the same
3280         // locations, which are supposed to be immutable?
3281         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3282       } else {
3283         // Stores to the argument stack area are relative to the stack pointer.
3284         SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3285                                         MVT::i32);
3286         DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3287         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3288         Alignment =
3289             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3290       }
3291 
3292       if (Outs[i].Flags.isByVal()) {
3293         SDValue SizeNode =
3294             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3295         SDValue Cpy =
3296             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3297                           Outs[i].Flags.getNonZeroByValAlign(),
3298                           /*isVol = */ false, /*AlwaysInline = */ true,
3299                           /*isTailCall = */ false, DstInfo,
3300                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3301 
3302         MemOpChains.push_back(Cpy);
3303       } else {
3304         SDValue Store =
3305             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3306         MemOpChains.push_back(Store);
3307       }
3308     }
3309   }
3310 
3311   if (!MemOpChains.empty())
3312     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3313 
3314   // Build a sequence of copy-to-reg nodes chained together with token chain
3315   // and flag operands which copy the outgoing args into the appropriate regs.
3316   SDValue InFlag;
3317   for (auto &RegToPass : RegsToPass) {
3318     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3319                              RegToPass.second, InFlag);
3320     InFlag = Chain.getValue(1);
3321   }
3322 
3323 
3324   SDValue PhysReturnAddrReg;
3325   if (IsTailCall) {
3326     // Since the return is being combined with the call, we need to pass on the
3327     // return address.
3328 
3329     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3330     SDValue ReturnAddrReg = CreateLiveInRegister(
3331       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3332 
3333     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3334                                         MVT::i64);
3335     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3336     InFlag = Chain.getValue(1);
3337   }
3338 
3339   // We don't usually want to end the call-sequence here because we would tidy
3340   // the frame up *after* the call, however in the ABI-changing tail-call case
3341   // we've carefully laid out the parameters so that when sp is reset they'll be
3342   // in the correct location.
3343   if (IsTailCall && !IsSibCall) {
3344     Chain = DAG.getCALLSEQ_END(Chain,
3345                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3346                                DAG.getTargetConstant(0, DL, MVT::i32),
3347                                InFlag, DL);
3348     InFlag = Chain.getValue(1);
3349   }
3350 
3351   std::vector<SDValue> Ops;
3352   Ops.push_back(Chain);
3353   Ops.push_back(Callee);
3354   // Add a redundant copy of the callee global which will not be legalized, as
3355   // we need direct access to the callee later.
3356   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3357     const GlobalValue *GV = GSD->getGlobal();
3358     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3359   } else {
3360     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3361   }
3362 
3363   if (IsTailCall) {
3364     // Each tail call may have to adjust the stack by a different amount, so
3365     // this information must travel along with the operation for eventual
3366     // consumption by emitEpilogue.
3367     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3368 
3369     Ops.push_back(PhysReturnAddrReg);
3370   }
3371 
3372   // Add argument registers to the end of the list so that they are known live
3373   // into the call.
3374   for (auto &RegToPass : RegsToPass) {
3375     Ops.push_back(DAG.getRegister(RegToPass.first,
3376                                   RegToPass.second.getValueType()));
3377   }
3378 
3379   // Add a register mask operand representing the call-preserved registers.
3380 
3381   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3382   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3383   assert(Mask && "Missing call preserved mask for calling convention");
3384   Ops.push_back(DAG.getRegisterMask(Mask));
3385 
3386   if (InFlag.getNode())
3387     Ops.push_back(InFlag);
3388 
3389   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3390 
3391   // If we're doing a tall call, use a TC_RETURN here rather than an
3392   // actual call instruction.
3393   if (IsTailCall) {
3394     MFI.setHasTailCall();
3395     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3396   }
3397 
3398   // Returns a chain and a flag for retval copy to use.
3399   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3400   Chain = Call.getValue(0);
3401   InFlag = Call.getValue(1);
3402 
3403   uint64_t CalleePopBytes = NumBytes;
3404   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3405                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3406                              InFlag, DL);
3407   if (!Ins.empty())
3408     InFlag = Chain.getValue(1);
3409 
3410   // Handle result values, copying them out of physregs into vregs that we
3411   // return.
3412   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3413                          InVals, IsThisReturn,
3414                          IsThisReturn ? OutVals[0] : SDValue());
3415 }
3416 
3417 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3418 // except for applying the wave size scale to the increment amount.
3419 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3420     SDValue Op, SelectionDAG &DAG) const {
3421   const MachineFunction &MF = DAG.getMachineFunction();
3422   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3423 
3424   SDLoc dl(Op);
3425   EVT VT = Op.getValueType();
3426   SDValue Tmp1 = Op;
3427   SDValue Tmp2 = Op.getValue(1);
3428   SDValue Tmp3 = Op.getOperand(2);
3429   SDValue Chain = Tmp1.getOperand(0);
3430 
3431   Register SPReg = Info->getStackPtrOffsetReg();
3432 
3433   // Chain the dynamic stack allocation so that it doesn't modify the stack
3434   // pointer when other instructions are using the stack.
3435   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3436 
3437   SDValue Size  = Tmp2.getOperand(1);
3438   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3439   Chain = SP.getValue(1);
3440   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3441   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3442   const TargetFrameLowering *TFL = ST.getFrameLowering();
3443   unsigned Opc =
3444     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3445     ISD::ADD : ISD::SUB;
3446 
3447   SDValue ScaledSize = DAG.getNode(
3448       ISD::SHL, dl, VT, Size,
3449       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3450 
3451   Align StackAlign = TFL->getStackAlign();
3452   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3453   if (Alignment && *Alignment > StackAlign) {
3454     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3455                        DAG.getConstant(-(uint64_t)Alignment->value()
3456                                            << ST.getWavefrontSizeLog2(),
3457                                        dl, VT));
3458   }
3459 
3460   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3461   Tmp2 = DAG.getCALLSEQ_END(
3462       Chain, DAG.getIntPtrConstant(0, dl, true),
3463       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3464 
3465   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3466 }
3467 
3468 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3469                                                   SelectionDAG &DAG) const {
3470   // We only handle constant sizes here to allow non-entry block, static sized
3471   // allocas. A truly dynamic value is more difficult to support because we
3472   // don't know if the size value is uniform or not. If the size isn't uniform,
3473   // we would need to do a wave reduction to get the maximum size to know how
3474   // much to increment the uniform stack pointer.
3475   SDValue Size = Op.getOperand(1);
3476   if (isa<ConstantSDNode>(Size))
3477       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3478 
3479   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3480 }
3481 
3482 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3483                                              const MachineFunction &MF) const {
3484   Register Reg = StringSwitch<Register>(RegName)
3485     .Case("m0", AMDGPU::M0)
3486     .Case("exec", AMDGPU::EXEC)
3487     .Case("exec_lo", AMDGPU::EXEC_LO)
3488     .Case("exec_hi", AMDGPU::EXEC_HI)
3489     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3490     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3491     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3492     .Default(Register());
3493 
3494   if (Reg == AMDGPU::NoRegister) {
3495     report_fatal_error(Twine("invalid register name \""
3496                              + StringRef(RegName)  + "\"."));
3497 
3498   }
3499 
3500   if (!Subtarget->hasFlatScrRegister() &&
3501        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3502     report_fatal_error(Twine("invalid register \""
3503                              + StringRef(RegName)  + "\" for subtarget."));
3504   }
3505 
3506   switch (Reg) {
3507   case AMDGPU::M0:
3508   case AMDGPU::EXEC_LO:
3509   case AMDGPU::EXEC_HI:
3510   case AMDGPU::FLAT_SCR_LO:
3511   case AMDGPU::FLAT_SCR_HI:
3512     if (VT.getSizeInBits() == 32)
3513       return Reg;
3514     break;
3515   case AMDGPU::EXEC:
3516   case AMDGPU::FLAT_SCR:
3517     if (VT.getSizeInBits() == 64)
3518       return Reg;
3519     break;
3520   default:
3521     llvm_unreachable("missing register type checking");
3522   }
3523 
3524   report_fatal_error(Twine("invalid type for register \""
3525                            + StringRef(RegName) + "\"."));
3526 }
3527 
3528 // If kill is not the last instruction, split the block so kill is always a
3529 // proper terminator.
3530 MachineBasicBlock *
3531 SITargetLowering::splitKillBlock(MachineInstr &MI,
3532                                  MachineBasicBlock *BB) const {
3533   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3534   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3535   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3536   return SplitBB;
3537 }
3538 
3539 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3540 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3541 // be the first instruction in the remainder block.
3542 //
3543 /// \returns { LoopBody, Remainder }
3544 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3545 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3546   MachineFunction *MF = MBB.getParent();
3547   MachineBasicBlock::iterator I(&MI);
3548 
3549   // To insert the loop we need to split the block. Move everything after this
3550   // point to a new block, and insert a new empty block between the two.
3551   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3552   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3553   MachineFunction::iterator MBBI(MBB);
3554   ++MBBI;
3555 
3556   MF->insert(MBBI, LoopBB);
3557   MF->insert(MBBI, RemainderBB);
3558 
3559   LoopBB->addSuccessor(LoopBB);
3560   LoopBB->addSuccessor(RemainderBB);
3561 
3562   // Move the rest of the block into a new block.
3563   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3564 
3565   if (InstInLoop) {
3566     auto Next = std::next(I);
3567 
3568     // Move instruction to loop body.
3569     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3570 
3571     // Move the rest of the block.
3572     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3573   } else {
3574     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3575   }
3576 
3577   MBB.addSuccessor(LoopBB);
3578 
3579   return std::make_pair(LoopBB, RemainderBB);
3580 }
3581 
3582 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3583 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3584   MachineBasicBlock *MBB = MI.getParent();
3585   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3586   auto I = MI.getIterator();
3587   auto E = std::next(I);
3588 
3589   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3590     .addImm(0);
3591 
3592   MIBundleBuilder Bundler(*MBB, I, E);
3593   finalizeBundle(*MBB, Bundler.begin());
3594 }
3595 
3596 MachineBasicBlock *
3597 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3598                                          MachineBasicBlock *BB) const {
3599   const DebugLoc &DL = MI.getDebugLoc();
3600 
3601   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3602 
3603   MachineBasicBlock *LoopBB;
3604   MachineBasicBlock *RemainderBB;
3605   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3606 
3607   // Apparently kill flags are only valid if the def is in the same block?
3608   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3609     Src->setIsKill(false);
3610 
3611   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3612 
3613   MachineBasicBlock::iterator I = LoopBB->end();
3614 
3615   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3616     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3617 
3618   // Clear TRAP_STS.MEM_VIOL
3619   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3620     .addImm(0)
3621     .addImm(EncodedReg);
3622 
3623   bundleInstWithWaitcnt(MI);
3624 
3625   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3626 
3627   // Load and check TRAP_STS.MEM_VIOL
3628   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3629     .addImm(EncodedReg);
3630 
3631   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3632   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3633     .addReg(Reg, RegState::Kill)
3634     .addImm(0);
3635   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3636     .addMBB(LoopBB);
3637 
3638   return RemainderBB;
3639 }
3640 
3641 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3642 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3643 // will only do one iteration. In the worst case, this will loop 64 times.
3644 //
3645 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3646 static MachineBasicBlock::iterator
3647 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3648                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3649                        const DebugLoc &DL, const MachineOperand &Idx,
3650                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3651                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3652                        Register &SGPRIdxReg) {
3653 
3654   MachineFunction *MF = OrigBB.getParent();
3655   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3656   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3657   MachineBasicBlock::iterator I = LoopBB.begin();
3658 
3659   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3660   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3661   Register NewExec = MRI.createVirtualRegister(BoolRC);
3662   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3663   Register CondReg = MRI.createVirtualRegister(BoolRC);
3664 
3665   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3666     .addReg(InitReg)
3667     .addMBB(&OrigBB)
3668     .addReg(ResultReg)
3669     .addMBB(&LoopBB);
3670 
3671   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3672     .addReg(InitSaveExecReg)
3673     .addMBB(&OrigBB)
3674     .addReg(NewExec)
3675     .addMBB(&LoopBB);
3676 
3677   // Read the next variant <- also loop target.
3678   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3679       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3680 
3681   // Compare the just read M0 value to all possible Idx values.
3682   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3683       .addReg(CurrentIdxReg)
3684       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3685 
3686   // Update EXEC, save the original EXEC value to VCC.
3687   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3688                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3689           NewExec)
3690     .addReg(CondReg, RegState::Kill);
3691 
3692   MRI.setSimpleHint(NewExec, CondReg);
3693 
3694   if (UseGPRIdxMode) {
3695     if (Offset == 0) {
3696       SGPRIdxReg = CurrentIdxReg;
3697     } else {
3698       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3699       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3700           .addReg(CurrentIdxReg, RegState::Kill)
3701           .addImm(Offset);
3702     }
3703   } else {
3704     // Move index from VCC into M0
3705     if (Offset == 0) {
3706       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3707         .addReg(CurrentIdxReg, RegState::Kill);
3708     } else {
3709       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3710         .addReg(CurrentIdxReg, RegState::Kill)
3711         .addImm(Offset);
3712     }
3713   }
3714 
3715   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3716   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3717   MachineInstr *InsertPt =
3718     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3719                                                   : AMDGPU::S_XOR_B64_term), Exec)
3720       .addReg(Exec)
3721       .addReg(NewExec);
3722 
3723   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3724   // s_cbranch_scc0?
3725 
3726   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3727   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3728     .addMBB(&LoopBB);
3729 
3730   return InsertPt->getIterator();
3731 }
3732 
3733 // This has slightly sub-optimal regalloc when the source vector is killed by
3734 // the read. The register allocator does not understand that the kill is
3735 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3736 // subregister from it, using 1 more VGPR than necessary. This was saved when
3737 // this was expanded after register allocation.
3738 static MachineBasicBlock::iterator
3739 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3740                unsigned InitResultReg, unsigned PhiReg, int Offset,
3741                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3742   MachineFunction *MF = MBB.getParent();
3743   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3744   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3745   MachineRegisterInfo &MRI = MF->getRegInfo();
3746   const DebugLoc &DL = MI.getDebugLoc();
3747   MachineBasicBlock::iterator I(&MI);
3748 
3749   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3750   Register DstReg = MI.getOperand(0).getReg();
3751   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3752   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3753   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3754   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3755 
3756   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3757 
3758   // Save the EXEC mask
3759   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3760     .addReg(Exec);
3761 
3762   MachineBasicBlock *LoopBB;
3763   MachineBasicBlock *RemainderBB;
3764   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3765 
3766   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3767 
3768   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3769                                       InitResultReg, DstReg, PhiReg, TmpExec,
3770                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3771 
3772   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3773   MachineFunction::iterator MBBI(LoopBB);
3774   ++MBBI;
3775   MF->insert(MBBI, LandingPad);
3776   LoopBB->removeSuccessor(RemainderBB);
3777   LandingPad->addSuccessor(RemainderBB);
3778   LoopBB->addSuccessor(LandingPad);
3779   MachineBasicBlock::iterator First = LandingPad->begin();
3780   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3781     .addReg(SaveExec);
3782 
3783   return InsPt;
3784 }
3785 
3786 // Returns subreg index, offset
3787 static std::pair<unsigned, int>
3788 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3789                             const TargetRegisterClass *SuperRC,
3790                             unsigned VecReg,
3791                             int Offset) {
3792   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3793 
3794   // Skip out of bounds offsets, or else we would end up using an undefined
3795   // register.
3796   if (Offset >= NumElts || Offset < 0)
3797     return std::make_pair(AMDGPU::sub0, Offset);
3798 
3799   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3800 }
3801 
3802 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3803                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3804                                  int Offset) {
3805   MachineBasicBlock *MBB = MI.getParent();
3806   const DebugLoc &DL = MI.getDebugLoc();
3807   MachineBasicBlock::iterator I(&MI);
3808 
3809   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3810 
3811   assert(Idx->getReg() != AMDGPU::NoRegister);
3812 
3813   if (Offset == 0) {
3814     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3815   } else {
3816     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3817         .add(*Idx)
3818         .addImm(Offset);
3819   }
3820 }
3821 
3822 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3823                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3824                                    int Offset) {
3825   MachineBasicBlock *MBB = MI.getParent();
3826   const DebugLoc &DL = MI.getDebugLoc();
3827   MachineBasicBlock::iterator I(&MI);
3828 
3829   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3830 
3831   if (Offset == 0)
3832     return Idx->getReg();
3833 
3834   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3835   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3836       .add(*Idx)
3837       .addImm(Offset);
3838   return Tmp;
3839 }
3840 
3841 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3842                                           MachineBasicBlock &MBB,
3843                                           const GCNSubtarget &ST) {
3844   const SIInstrInfo *TII = ST.getInstrInfo();
3845   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3846   MachineFunction *MF = MBB.getParent();
3847   MachineRegisterInfo &MRI = MF->getRegInfo();
3848 
3849   Register Dst = MI.getOperand(0).getReg();
3850   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3851   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3852   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3853 
3854   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3855   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3856 
3857   unsigned SubReg;
3858   std::tie(SubReg, Offset)
3859     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3860 
3861   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3862 
3863   // Check for a SGPR index.
3864   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3865     MachineBasicBlock::iterator I(&MI);
3866     const DebugLoc &DL = MI.getDebugLoc();
3867 
3868     if (UseGPRIdxMode) {
3869       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3870       // to avoid interfering with other uses, so probably requires a new
3871       // optimization pass.
3872       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3873 
3874       const MCInstrDesc &GPRIDXDesc =
3875           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3876       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3877           .addReg(SrcReg)
3878           .addReg(Idx)
3879           .addImm(SubReg);
3880     } else {
3881       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3882 
3883       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3884         .addReg(SrcReg, 0, SubReg)
3885         .addReg(SrcReg, RegState::Implicit);
3886     }
3887 
3888     MI.eraseFromParent();
3889 
3890     return &MBB;
3891   }
3892 
3893   // Control flow needs to be inserted if indexing with a VGPR.
3894   const DebugLoc &DL = MI.getDebugLoc();
3895   MachineBasicBlock::iterator I(&MI);
3896 
3897   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3898   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3899 
3900   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3901 
3902   Register SGPRIdxReg;
3903   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3904                               UseGPRIdxMode, SGPRIdxReg);
3905 
3906   MachineBasicBlock *LoopBB = InsPt->getParent();
3907 
3908   if (UseGPRIdxMode) {
3909     const MCInstrDesc &GPRIDXDesc =
3910         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3911 
3912     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3913         .addReg(SrcReg)
3914         .addReg(SGPRIdxReg)
3915         .addImm(SubReg);
3916   } else {
3917     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3918       .addReg(SrcReg, 0, SubReg)
3919       .addReg(SrcReg, RegState::Implicit);
3920   }
3921 
3922   MI.eraseFromParent();
3923 
3924   return LoopBB;
3925 }
3926 
3927 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3928                                           MachineBasicBlock &MBB,
3929                                           const GCNSubtarget &ST) {
3930   const SIInstrInfo *TII = ST.getInstrInfo();
3931   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3932   MachineFunction *MF = MBB.getParent();
3933   MachineRegisterInfo &MRI = MF->getRegInfo();
3934 
3935   Register Dst = MI.getOperand(0).getReg();
3936   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3937   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3938   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3939   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3940   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3941   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3942 
3943   // This can be an immediate, but will be folded later.
3944   assert(Val->getReg());
3945 
3946   unsigned SubReg;
3947   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3948                                                          SrcVec->getReg(),
3949                                                          Offset);
3950   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3951 
3952   if (Idx->getReg() == AMDGPU::NoRegister) {
3953     MachineBasicBlock::iterator I(&MI);
3954     const DebugLoc &DL = MI.getDebugLoc();
3955 
3956     assert(Offset == 0);
3957 
3958     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3959         .add(*SrcVec)
3960         .add(*Val)
3961         .addImm(SubReg);
3962 
3963     MI.eraseFromParent();
3964     return &MBB;
3965   }
3966 
3967   // Check for a SGPR index.
3968   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3969     MachineBasicBlock::iterator I(&MI);
3970     const DebugLoc &DL = MI.getDebugLoc();
3971 
3972     if (UseGPRIdxMode) {
3973       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3974 
3975       const MCInstrDesc &GPRIDXDesc =
3976           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3977       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3978           .addReg(SrcVec->getReg())
3979           .add(*Val)
3980           .addReg(Idx)
3981           .addImm(SubReg);
3982     } else {
3983       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3984 
3985       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3986           TRI.getRegSizeInBits(*VecRC), 32, false);
3987       BuildMI(MBB, I, DL, MovRelDesc, Dst)
3988           .addReg(SrcVec->getReg())
3989           .add(*Val)
3990           .addImm(SubReg);
3991     }
3992     MI.eraseFromParent();
3993     return &MBB;
3994   }
3995 
3996   // Control flow needs to be inserted if indexing with a VGPR.
3997   if (Val->isReg())
3998     MRI.clearKillFlags(Val->getReg());
3999 
4000   const DebugLoc &DL = MI.getDebugLoc();
4001 
4002   Register PhiReg = MRI.createVirtualRegister(VecRC);
4003 
4004   Register SGPRIdxReg;
4005   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
4006                               UseGPRIdxMode, SGPRIdxReg);
4007   MachineBasicBlock *LoopBB = InsPt->getParent();
4008 
4009   if (UseGPRIdxMode) {
4010     const MCInstrDesc &GPRIDXDesc =
4011         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
4012 
4013     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
4014         .addReg(PhiReg)
4015         .add(*Val)
4016         .addReg(SGPRIdxReg)
4017         .addImm(AMDGPU::sub0);
4018   } else {
4019     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
4020         TRI.getRegSizeInBits(*VecRC), 32, false);
4021     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
4022         .addReg(PhiReg)
4023         .add(*Val)
4024         .addImm(AMDGPU::sub0);
4025   }
4026 
4027   MI.eraseFromParent();
4028   return LoopBB;
4029 }
4030 
4031 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
4032   MachineInstr &MI, MachineBasicBlock *BB) const {
4033 
4034   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4035   MachineFunction *MF = BB->getParent();
4036   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
4037 
4038   switch (MI.getOpcode()) {
4039   case AMDGPU::S_UADDO_PSEUDO:
4040   case AMDGPU::S_USUBO_PSEUDO: {
4041     const DebugLoc &DL = MI.getDebugLoc();
4042     MachineOperand &Dest0 = MI.getOperand(0);
4043     MachineOperand &Dest1 = MI.getOperand(1);
4044     MachineOperand &Src0 = MI.getOperand(2);
4045     MachineOperand &Src1 = MI.getOperand(3);
4046 
4047     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
4048                        ? AMDGPU::S_ADD_I32
4049                        : AMDGPU::S_SUB_I32;
4050     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
4051 
4052     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
4053         .addImm(1)
4054         .addImm(0);
4055 
4056     MI.eraseFromParent();
4057     return BB;
4058   }
4059   case AMDGPU::S_ADD_U64_PSEUDO:
4060   case AMDGPU::S_SUB_U64_PSEUDO: {
4061     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4062     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4063     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4064     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
4065     const DebugLoc &DL = MI.getDebugLoc();
4066 
4067     MachineOperand &Dest = MI.getOperand(0);
4068     MachineOperand &Src0 = MI.getOperand(1);
4069     MachineOperand &Src1 = MI.getOperand(2);
4070 
4071     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4072     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4073 
4074     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
4075         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4076     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
4077         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4078 
4079     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
4080         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4081     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
4082         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4083 
4084     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
4085 
4086     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
4087     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
4088     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
4089     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
4090     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4091         .addReg(DestSub0)
4092         .addImm(AMDGPU::sub0)
4093         .addReg(DestSub1)
4094         .addImm(AMDGPU::sub1);
4095     MI.eraseFromParent();
4096     return BB;
4097   }
4098   case AMDGPU::V_ADD_U64_PSEUDO:
4099   case AMDGPU::V_SUB_U64_PSEUDO: {
4100     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4101     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4102     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4103     const DebugLoc &DL = MI.getDebugLoc();
4104 
4105     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
4106 
4107     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4108 
4109     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4110     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4111 
4112     Register CarryReg = MRI.createVirtualRegister(CarryRC);
4113     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
4114 
4115     MachineOperand &Dest = MI.getOperand(0);
4116     MachineOperand &Src0 = MI.getOperand(1);
4117     MachineOperand &Src1 = MI.getOperand(2);
4118 
4119     const TargetRegisterClass *Src0RC = Src0.isReg()
4120                                             ? MRI.getRegClass(Src0.getReg())
4121                                             : &AMDGPU::VReg_64RegClass;
4122     const TargetRegisterClass *Src1RC = Src1.isReg()
4123                                             ? MRI.getRegClass(Src1.getReg())
4124                                             : &AMDGPU::VReg_64RegClass;
4125 
4126     const TargetRegisterClass *Src0SubRC =
4127         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
4128     const TargetRegisterClass *Src1SubRC =
4129         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
4130 
4131     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
4132         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
4133     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
4134         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
4135 
4136     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
4137         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
4138     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
4139         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
4140 
4141     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
4142     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
4143                                .addReg(CarryReg, RegState::Define)
4144                                .add(SrcReg0Sub0)
4145                                .add(SrcReg1Sub0)
4146                                .addImm(0); // clamp bit
4147 
4148     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
4149     MachineInstr *HiHalf =
4150         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4151             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4152             .add(SrcReg0Sub1)
4153             .add(SrcReg1Sub1)
4154             .addReg(CarryReg, RegState::Kill)
4155             .addImm(0); // clamp bit
4156 
4157     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4158         .addReg(DestSub0)
4159         .addImm(AMDGPU::sub0)
4160         .addReg(DestSub1)
4161         .addImm(AMDGPU::sub1);
4162     TII->legalizeOperands(*LoHalf);
4163     TII->legalizeOperands(*HiHalf);
4164     MI.eraseFromParent();
4165     return BB;
4166   }
4167   case AMDGPU::S_ADD_CO_PSEUDO:
4168   case AMDGPU::S_SUB_CO_PSEUDO: {
4169     // This pseudo has a chance to be selected
4170     // only from uniform add/subcarry node. All the VGPR operands
4171     // therefore assumed to be splat vectors.
4172     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4173     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4174     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4175     MachineBasicBlock::iterator MII = MI;
4176     const DebugLoc &DL = MI.getDebugLoc();
4177     MachineOperand &Dest = MI.getOperand(0);
4178     MachineOperand &CarryDest = MI.getOperand(1);
4179     MachineOperand &Src0 = MI.getOperand(2);
4180     MachineOperand &Src1 = MI.getOperand(3);
4181     MachineOperand &Src2 = MI.getOperand(4);
4182     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4183                        ? AMDGPU::S_ADDC_U32
4184                        : AMDGPU::S_SUBB_U32;
4185     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4186       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4187       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4188           .addReg(Src0.getReg());
4189       Src0.setReg(RegOp0);
4190     }
4191     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4192       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4193       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4194           .addReg(Src1.getReg());
4195       Src1.setReg(RegOp1);
4196     }
4197     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4198     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4199       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4200           .addReg(Src2.getReg());
4201       Src2.setReg(RegOp2);
4202     }
4203 
4204     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4205     unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC);
4206     assert(WaveSize == 64 || WaveSize == 32);
4207 
4208     if (WaveSize == 64) {
4209       if (ST.hasScalarCompareEq64()) {
4210         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4211             .addReg(Src2.getReg())
4212             .addImm(0);
4213       } else {
4214         const TargetRegisterClass *SubRC =
4215             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4216         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4217             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4218         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4219             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4220         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4221 
4222         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4223             .add(Src2Sub0)
4224             .add(Src2Sub1);
4225 
4226         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4227             .addReg(Src2_32, RegState::Kill)
4228             .addImm(0);
4229       }
4230     } else {
4231       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4232           .addReg(Src2.getReg())
4233           .addImm(0);
4234     }
4235 
4236     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4237 
4238     unsigned SelOpc =
4239         (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
4240 
4241     BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg())
4242         .addImm(-1)
4243         .addImm(0);
4244 
4245     MI.eraseFromParent();
4246     return BB;
4247   }
4248   case AMDGPU::SI_INIT_M0: {
4249     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4250             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4251         .add(MI.getOperand(0));
4252     MI.eraseFromParent();
4253     return BB;
4254   }
4255   case AMDGPU::GET_GROUPSTATICSIZE: {
4256     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4257            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4258     DebugLoc DL = MI.getDebugLoc();
4259     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4260         .add(MI.getOperand(0))
4261         .addImm(MFI->getLDSSize());
4262     MI.eraseFromParent();
4263     return BB;
4264   }
4265   case AMDGPU::SI_INDIRECT_SRC_V1:
4266   case AMDGPU::SI_INDIRECT_SRC_V2:
4267   case AMDGPU::SI_INDIRECT_SRC_V4:
4268   case AMDGPU::SI_INDIRECT_SRC_V8:
4269   case AMDGPU::SI_INDIRECT_SRC_V16:
4270   case AMDGPU::SI_INDIRECT_SRC_V32:
4271     return emitIndirectSrc(MI, *BB, *getSubtarget());
4272   case AMDGPU::SI_INDIRECT_DST_V1:
4273   case AMDGPU::SI_INDIRECT_DST_V2:
4274   case AMDGPU::SI_INDIRECT_DST_V4:
4275   case AMDGPU::SI_INDIRECT_DST_V8:
4276   case AMDGPU::SI_INDIRECT_DST_V16:
4277   case AMDGPU::SI_INDIRECT_DST_V32:
4278     return emitIndirectDst(MI, *BB, *getSubtarget());
4279   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4280   case AMDGPU::SI_KILL_I1_PSEUDO:
4281     return splitKillBlock(MI, BB);
4282   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4283     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4284     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4285     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4286 
4287     Register Dst = MI.getOperand(0).getReg();
4288     Register Src0 = MI.getOperand(1).getReg();
4289     Register Src1 = MI.getOperand(2).getReg();
4290     const DebugLoc &DL = MI.getDebugLoc();
4291     Register SrcCond = MI.getOperand(3).getReg();
4292 
4293     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4294     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4295     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4296     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4297 
4298     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4299       .addReg(SrcCond);
4300     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4301       .addImm(0)
4302       .addReg(Src0, 0, AMDGPU::sub0)
4303       .addImm(0)
4304       .addReg(Src1, 0, AMDGPU::sub0)
4305       .addReg(SrcCondCopy);
4306     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4307       .addImm(0)
4308       .addReg(Src0, 0, AMDGPU::sub1)
4309       .addImm(0)
4310       .addReg(Src1, 0, AMDGPU::sub1)
4311       .addReg(SrcCondCopy);
4312 
4313     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4314       .addReg(DstLo)
4315       .addImm(AMDGPU::sub0)
4316       .addReg(DstHi)
4317       .addImm(AMDGPU::sub1);
4318     MI.eraseFromParent();
4319     return BB;
4320   }
4321   case AMDGPU::SI_BR_UNDEF: {
4322     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4323     const DebugLoc &DL = MI.getDebugLoc();
4324     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4325                            .add(MI.getOperand(0));
4326     Br->getOperand(1).setIsUndef(true); // read undef SCC
4327     MI.eraseFromParent();
4328     return BB;
4329   }
4330   case AMDGPU::ADJCALLSTACKUP:
4331   case AMDGPU::ADJCALLSTACKDOWN: {
4332     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4333     MachineInstrBuilder MIB(*MF, &MI);
4334     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4335        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4336     return BB;
4337   }
4338   case AMDGPU::SI_CALL_ISEL: {
4339     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4340     const DebugLoc &DL = MI.getDebugLoc();
4341 
4342     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4343 
4344     MachineInstrBuilder MIB;
4345     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4346 
4347     for (const MachineOperand &MO : MI.operands())
4348       MIB.add(MO);
4349 
4350     MIB.cloneMemRefs(MI);
4351     MI.eraseFromParent();
4352     return BB;
4353   }
4354   case AMDGPU::V_ADD_CO_U32_e32:
4355   case AMDGPU::V_SUB_CO_U32_e32:
4356   case AMDGPU::V_SUBREV_CO_U32_e32: {
4357     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4358     const DebugLoc &DL = MI.getDebugLoc();
4359     unsigned Opc = MI.getOpcode();
4360 
4361     bool NeedClampOperand = false;
4362     if (TII->pseudoToMCOpcode(Opc) == -1) {
4363       Opc = AMDGPU::getVOPe64(Opc);
4364       NeedClampOperand = true;
4365     }
4366 
4367     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4368     if (TII->isVOP3(*I)) {
4369       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4370       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4371       I.addReg(TRI->getVCC(), RegState::Define);
4372     }
4373     I.add(MI.getOperand(1))
4374      .add(MI.getOperand(2));
4375     if (NeedClampOperand)
4376       I.addImm(0); // clamp bit for e64 encoding
4377 
4378     TII->legalizeOperands(*I);
4379 
4380     MI.eraseFromParent();
4381     return BB;
4382   }
4383   case AMDGPU::V_ADDC_U32_e32:
4384   case AMDGPU::V_SUBB_U32_e32:
4385   case AMDGPU::V_SUBBREV_U32_e32:
4386     // These instructions have an implicit use of vcc which counts towards the
4387     // constant bus limit.
4388     TII->legalizeOperands(MI);
4389     return BB;
4390   case AMDGPU::DS_GWS_INIT:
4391   case AMDGPU::DS_GWS_SEMA_BR:
4392   case AMDGPU::DS_GWS_BARRIER:
4393     if (Subtarget->needsAlignedVGPRs()) {
4394       // Add implicit aligned super-reg to force alignment on the data operand.
4395       const DebugLoc &DL = MI.getDebugLoc();
4396       MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4397       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
4398       MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0);
4399       Register DataReg = Op->getReg();
4400       bool IsAGPR = TRI->isAGPR(MRI, DataReg);
4401       Register Undef = MRI.createVirtualRegister(
4402           IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass);
4403       BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef);
4404       Register NewVR =
4405           MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass
4406                                            : &AMDGPU::VReg_64_Align2RegClass);
4407       BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR)
4408           .addReg(DataReg, 0, Op->getSubReg())
4409           .addImm(AMDGPU::sub0)
4410           .addReg(Undef)
4411           .addImm(AMDGPU::sub1);
4412       Op->setReg(NewVR);
4413       Op->setSubReg(AMDGPU::sub0);
4414       MI.addOperand(MachineOperand::CreateReg(NewVR, false, true));
4415     }
4416     LLVM_FALLTHROUGH;
4417   case AMDGPU::DS_GWS_SEMA_V:
4418   case AMDGPU::DS_GWS_SEMA_P:
4419   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4420     // A s_waitcnt 0 is required to be the instruction immediately following.
4421     if (getSubtarget()->hasGWSAutoReplay()) {
4422       bundleInstWithWaitcnt(MI);
4423       return BB;
4424     }
4425 
4426     return emitGWSMemViolTestLoop(MI, BB);
4427   case AMDGPU::S_SETREG_B32: {
4428     // Try to optimize cases that only set the denormal mode or rounding mode.
4429     //
4430     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4431     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4432     // instead.
4433     //
4434     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4435     // allow you to have a no side effect instruction in the output of a
4436     // sideeffecting pattern.
4437     unsigned ID, Offset, Width;
4438     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4439     if (ID != AMDGPU::Hwreg::ID_MODE)
4440       return BB;
4441 
4442     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4443     const unsigned SetMask = WidthMask << Offset;
4444 
4445     if (getSubtarget()->hasDenormModeInst()) {
4446       unsigned SetDenormOp = 0;
4447       unsigned SetRoundOp = 0;
4448 
4449       // The dedicated instructions can only set the whole denorm or round mode
4450       // at once, not a subset of bits in either.
4451       if (SetMask ==
4452           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4453         // If this fully sets both the round and denorm mode, emit the two
4454         // dedicated instructions for these.
4455         SetRoundOp = AMDGPU::S_ROUND_MODE;
4456         SetDenormOp = AMDGPU::S_DENORM_MODE;
4457       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4458         SetRoundOp = AMDGPU::S_ROUND_MODE;
4459       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4460         SetDenormOp = AMDGPU::S_DENORM_MODE;
4461       }
4462 
4463       if (SetRoundOp || SetDenormOp) {
4464         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4465         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4466         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4467           unsigned ImmVal = Def->getOperand(1).getImm();
4468           if (SetRoundOp) {
4469             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4470                 .addImm(ImmVal & 0xf);
4471 
4472             // If we also have the denorm mode, get just the denorm mode bits.
4473             ImmVal >>= 4;
4474           }
4475 
4476           if (SetDenormOp) {
4477             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4478                 .addImm(ImmVal & 0xf);
4479           }
4480 
4481           MI.eraseFromParent();
4482           return BB;
4483         }
4484       }
4485     }
4486 
4487     // If only FP bits are touched, used the no side effects pseudo.
4488     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4489                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4490       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4491 
4492     return BB;
4493   }
4494   default:
4495     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4496   }
4497 }
4498 
4499 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4500   return isTypeLegal(VT.getScalarType());
4501 }
4502 
4503 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4504   // This currently forces unfolding various combinations of fsub into fma with
4505   // free fneg'd operands. As long as we have fast FMA (controlled by
4506   // isFMAFasterThanFMulAndFAdd), we should perform these.
4507 
4508   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4509   // most of these combines appear to be cycle neutral but save on instruction
4510   // count / code size.
4511   return true;
4512 }
4513 
4514 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; }
4515 
4516 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4517                                          EVT VT) const {
4518   if (!VT.isVector()) {
4519     return MVT::i1;
4520   }
4521   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4522 }
4523 
4524 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4525   // TODO: Should i16 be used always if legal? For now it would force VALU
4526   // shifts.
4527   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4528 }
4529 
4530 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4531   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4532              ? Ty.changeElementSize(16)
4533              : Ty.changeElementSize(32);
4534 }
4535 
4536 // Answering this is somewhat tricky and depends on the specific device which
4537 // have different rates for fma or all f64 operations.
4538 //
4539 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4540 // regardless of which device (although the number of cycles differs between
4541 // devices), so it is always profitable for f64.
4542 //
4543 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4544 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4545 // which we can always do even without fused FP ops since it returns the same
4546 // result as the separate operations and since it is always full
4547 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4548 // however does not support denormals, so we do report fma as faster if we have
4549 // a fast fma device and require denormals.
4550 //
4551 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4552                                                   EVT VT) const {
4553   VT = VT.getScalarType();
4554 
4555   switch (VT.getSimpleVT().SimpleTy) {
4556   case MVT::f32: {
4557     // If mad is not available this depends only on if f32 fma is full rate.
4558     if (!Subtarget->hasMadMacF32Insts())
4559       return Subtarget->hasFastFMAF32();
4560 
4561     // Otherwise f32 mad is always full rate and returns the same result as
4562     // the separate operations so should be preferred over fma.
4563     // However does not support denomals.
4564     if (hasFP32Denormals(MF))
4565       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4566 
4567     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4568     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4569   }
4570   case MVT::f64:
4571     return true;
4572   case MVT::f16:
4573     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4574   default:
4575     break;
4576   }
4577 
4578   return false;
4579 }
4580 
4581 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4582                                                   LLT Ty) const {
4583   switch (Ty.getScalarSizeInBits()) {
4584   case 16:
4585     return isFMAFasterThanFMulAndFAdd(MF, MVT::f16);
4586   case 32:
4587     return isFMAFasterThanFMulAndFAdd(MF, MVT::f32);
4588   case 64:
4589     return isFMAFasterThanFMulAndFAdd(MF, MVT::f64);
4590   default:
4591     break;
4592   }
4593 
4594   return false;
4595 }
4596 
4597 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const {
4598   if (!Ty.isScalar())
4599     return false;
4600 
4601   if (Ty.getScalarSizeInBits() == 16)
4602     return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF());
4603   if (Ty.getScalarSizeInBits() == 32)
4604     return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF());
4605 
4606   return false;
4607 }
4608 
4609 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4610                                    const SDNode *N) const {
4611   // TODO: Check future ftz flag
4612   // v_mad_f32/v_mac_f32 do not support denormals.
4613   EVT VT = N->getValueType(0);
4614   if (VT == MVT::f32)
4615     return Subtarget->hasMadMacF32Insts() &&
4616            !hasFP32Denormals(DAG.getMachineFunction());
4617   if (VT == MVT::f16) {
4618     return Subtarget->hasMadF16() &&
4619            !hasFP64FP16Denormals(DAG.getMachineFunction());
4620   }
4621 
4622   return false;
4623 }
4624 
4625 //===----------------------------------------------------------------------===//
4626 // Custom DAG Lowering Operations
4627 //===----------------------------------------------------------------------===//
4628 
4629 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4630 // wider vector type is legal.
4631 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4632                                              SelectionDAG &DAG) const {
4633   unsigned Opc = Op.getOpcode();
4634   EVT VT = Op.getValueType();
4635   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4636 
4637   SDValue Lo, Hi;
4638   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4639 
4640   SDLoc SL(Op);
4641   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4642                              Op->getFlags());
4643   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4644                              Op->getFlags());
4645 
4646   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4647 }
4648 
4649 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4650 // wider vector type is legal.
4651 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4652                                               SelectionDAG &DAG) const {
4653   unsigned Opc = Op.getOpcode();
4654   EVT VT = Op.getValueType();
4655   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4656          VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8f32 ||
4657          VT == MVT::v16f32 || VT == MVT::v32f32);
4658 
4659   SDValue Lo0, Hi0;
4660   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4661   SDValue Lo1, Hi1;
4662   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4663 
4664   SDLoc SL(Op);
4665 
4666   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4667                              Op->getFlags());
4668   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4669                              Op->getFlags());
4670 
4671   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4672 }
4673 
4674 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4675                                               SelectionDAG &DAG) const {
4676   unsigned Opc = Op.getOpcode();
4677   EVT VT = Op.getValueType();
4678   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 ||
4679          VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v8f32 ||
4680          VT == MVT::v16f32 || VT == MVT::v32f32);
4681 
4682   SDValue Lo0, Hi0;
4683   SDValue Op0 = Op.getOperand(0);
4684   std::tie(Lo0, Hi0) = Op0.getValueType().isVector()
4685                          ? DAG.SplitVectorOperand(Op.getNode(), 0)
4686                          : std::make_pair(Op0, Op0);
4687   SDValue Lo1, Hi1;
4688   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4689   SDValue Lo2, Hi2;
4690   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4691 
4692   SDLoc SL(Op);
4693   auto ResVT = DAG.GetSplitDestVTs(VT);
4694 
4695   SDValue OpLo = DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2,
4696                              Op->getFlags());
4697   SDValue OpHi = DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2,
4698                              Op->getFlags());
4699 
4700   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4701 }
4702 
4703 
4704 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4705   switch (Op.getOpcode()) {
4706   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4707   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4708   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4709   case ISD::LOAD: {
4710     SDValue Result = LowerLOAD(Op, DAG);
4711     assert((!Result.getNode() ||
4712             Result.getNode()->getNumValues() == 2) &&
4713            "Load should return a value and a chain");
4714     return Result;
4715   }
4716 
4717   case ISD::FSIN:
4718   case ISD::FCOS:
4719     return LowerTrig(Op, DAG);
4720   case ISD::SELECT: return LowerSELECT(Op, DAG);
4721   case ISD::FDIV: return LowerFDIV(Op, DAG);
4722   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4723   case ISD::STORE: return LowerSTORE(Op, DAG);
4724   case ISD::GlobalAddress: {
4725     MachineFunction &MF = DAG.getMachineFunction();
4726     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4727     return LowerGlobalAddress(MFI, Op, DAG);
4728   }
4729   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4730   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4731   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4732   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4733   case ISD::INSERT_SUBVECTOR:
4734     return lowerINSERT_SUBVECTOR(Op, DAG);
4735   case ISD::INSERT_VECTOR_ELT:
4736     return lowerINSERT_VECTOR_ELT(Op, DAG);
4737   case ISD::EXTRACT_VECTOR_ELT:
4738     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4739   case ISD::VECTOR_SHUFFLE:
4740     return lowerVECTOR_SHUFFLE(Op, DAG);
4741   case ISD::BUILD_VECTOR:
4742     return lowerBUILD_VECTOR(Op, DAG);
4743   case ISD::FP_ROUND:
4744     return lowerFP_ROUND(Op, DAG);
4745   case ISD::TRAP:
4746     return lowerTRAP(Op, DAG);
4747   case ISD::DEBUGTRAP:
4748     return lowerDEBUGTRAP(Op, DAG);
4749   case ISD::FABS:
4750   case ISD::FNEG:
4751   case ISD::FCANONICALIZE:
4752   case ISD::BSWAP:
4753     return splitUnaryVectorOp(Op, DAG);
4754   case ISD::FMINNUM:
4755   case ISD::FMAXNUM:
4756     return lowerFMINNUM_FMAXNUM(Op, DAG);
4757   case ISD::FMA:
4758     return splitTernaryVectorOp(Op, DAG);
4759   case ISD::FP_TO_SINT:
4760   case ISD::FP_TO_UINT:
4761     return LowerFP_TO_INT(Op, DAG);
4762   case ISD::SHL:
4763   case ISD::SRA:
4764   case ISD::SRL:
4765   case ISD::ADD:
4766   case ISD::SUB:
4767   case ISD::MUL:
4768   case ISD::SMIN:
4769   case ISD::SMAX:
4770   case ISD::UMIN:
4771   case ISD::UMAX:
4772   case ISD::FADD:
4773   case ISD::FMUL:
4774   case ISD::FMINNUM_IEEE:
4775   case ISD::FMAXNUM_IEEE:
4776   case ISD::UADDSAT:
4777   case ISD::USUBSAT:
4778   case ISD::SADDSAT:
4779   case ISD::SSUBSAT:
4780     return splitBinaryVectorOp(Op, DAG);
4781   case ISD::SMULO:
4782   case ISD::UMULO:
4783     return lowerXMULO(Op, DAG);
4784   case ISD::SMUL_LOHI:
4785   case ISD::UMUL_LOHI:
4786     return lowerXMUL_LOHI(Op, DAG);
4787   case ISD::DYNAMIC_STACKALLOC:
4788     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4789   }
4790   return SDValue();
4791 }
4792 
4793 // Used for D16: Casts the result of an instruction into the right vector,
4794 // packs values if loads return unpacked values.
4795 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4796                                        const SDLoc &DL,
4797                                        SelectionDAG &DAG, bool Unpacked) {
4798   if (!LoadVT.isVector())
4799     return Result;
4800 
4801   // Cast back to the original packed type or to a larger type that is a
4802   // multiple of 32 bit for D16. Widening the return type is a required for
4803   // legalization.
4804   EVT FittingLoadVT = LoadVT;
4805   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4806     FittingLoadVT =
4807         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4808                          LoadVT.getVectorNumElements() + 1);
4809   }
4810 
4811   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4812     // Truncate to v2i16/v4i16.
4813     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4814 
4815     // Workaround legalizer not scalarizing truncate after vector op
4816     // legalization but not creating intermediate vector trunc.
4817     SmallVector<SDValue, 4> Elts;
4818     DAG.ExtractVectorElements(Result, Elts);
4819     for (SDValue &Elt : Elts)
4820       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4821 
4822     // Pad illegal v1i16/v3fi6 to v4i16
4823     if ((LoadVT.getVectorNumElements() % 2) == 1)
4824       Elts.push_back(DAG.getUNDEF(MVT::i16));
4825 
4826     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4827 
4828     // Bitcast to original type (v2f16/v4f16).
4829     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4830   }
4831 
4832   // Cast back to the original packed type.
4833   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4834 }
4835 
4836 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4837                                               MemSDNode *M,
4838                                               SelectionDAG &DAG,
4839                                               ArrayRef<SDValue> Ops,
4840                                               bool IsIntrinsic) const {
4841   SDLoc DL(M);
4842 
4843   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4844   EVT LoadVT = M->getValueType(0);
4845 
4846   EVT EquivLoadVT = LoadVT;
4847   if (LoadVT.isVector()) {
4848     if (Unpacked) {
4849       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4850                                      LoadVT.getVectorNumElements());
4851     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4852       // Widen v3f16 to legal type
4853       EquivLoadVT =
4854           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4855                            LoadVT.getVectorNumElements() + 1);
4856     }
4857   }
4858 
4859   // Change from v4f16/v2f16 to EquivLoadVT.
4860   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4861 
4862   SDValue Load
4863     = DAG.getMemIntrinsicNode(
4864       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4865       VTList, Ops, M->getMemoryVT(),
4866       M->getMemOperand());
4867 
4868   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4869 
4870   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4871 }
4872 
4873 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4874                                              SelectionDAG &DAG,
4875                                              ArrayRef<SDValue> Ops) const {
4876   SDLoc DL(M);
4877   EVT LoadVT = M->getValueType(0);
4878   EVT EltType = LoadVT.getScalarType();
4879   EVT IntVT = LoadVT.changeTypeToInteger();
4880 
4881   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4882 
4883   unsigned Opc =
4884       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4885 
4886   if (IsD16) {
4887     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4888   }
4889 
4890   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4891   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4892     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4893 
4894   if (isTypeLegal(LoadVT)) {
4895     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4896                                M->getMemOperand(), DAG);
4897   }
4898 
4899   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4900   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4901   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4902                                         M->getMemOperand(), DAG);
4903   return DAG.getMergeValues(
4904       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4905       DL);
4906 }
4907 
4908 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4909                                   SDNode *N, SelectionDAG &DAG) {
4910   EVT VT = N->getValueType(0);
4911   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4912   unsigned CondCode = CD->getZExtValue();
4913   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4914     return DAG.getUNDEF(VT);
4915 
4916   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4917 
4918   SDValue LHS = N->getOperand(1);
4919   SDValue RHS = N->getOperand(2);
4920 
4921   SDLoc DL(N);
4922 
4923   EVT CmpVT = LHS.getValueType();
4924   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4925     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4926       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4927     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4928     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4929   }
4930 
4931   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4932 
4933   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4934   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4935 
4936   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4937                               DAG.getCondCode(CCOpcode));
4938   if (VT.bitsEq(CCVT))
4939     return SetCC;
4940   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4941 }
4942 
4943 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4944                                   SDNode *N, SelectionDAG &DAG) {
4945   EVT VT = N->getValueType(0);
4946   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4947 
4948   unsigned CondCode = CD->getZExtValue();
4949   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4950     return DAG.getUNDEF(VT);
4951 
4952   SDValue Src0 = N->getOperand(1);
4953   SDValue Src1 = N->getOperand(2);
4954   EVT CmpVT = Src0.getValueType();
4955   SDLoc SL(N);
4956 
4957   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4958     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4959     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4960   }
4961 
4962   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4963   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4964   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4965   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4966   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4967                               Src1, DAG.getCondCode(CCOpcode));
4968   if (VT.bitsEq(CCVT))
4969     return SetCC;
4970   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4971 }
4972 
4973 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4974                                     SelectionDAG &DAG) {
4975   EVT VT = N->getValueType(0);
4976   SDValue Src = N->getOperand(1);
4977   SDLoc SL(N);
4978 
4979   if (Src.getOpcode() == ISD::SETCC) {
4980     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4981     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4982                        Src.getOperand(1), Src.getOperand(2));
4983   }
4984   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4985     // (ballot 0) -> 0
4986     if (Arg->isZero())
4987       return DAG.getConstant(0, SL, VT);
4988 
4989     // (ballot 1) -> EXEC/EXEC_LO
4990     if (Arg->isOne()) {
4991       Register Exec;
4992       if (VT.getScalarSizeInBits() == 32)
4993         Exec = AMDGPU::EXEC_LO;
4994       else if (VT.getScalarSizeInBits() == 64)
4995         Exec = AMDGPU::EXEC;
4996       else
4997         return SDValue();
4998 
4999       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
5000     }
5001   }
5002 
5003   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
5004   // ISD::SETNE)
5005   return DAG.getNode(
5006       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
5007       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
5008 }
5009 
5010 void SITargetLowering::ReplaceNodeResults(SDNode *N,
5011                                           SmallVectorImpl<SDValue> &Results,
5012                                           SelectionDAG &DAG) const {
5013   switch (N->getOpcode()) {
5014   case ISD::INSERT_VECTOR_ELT: {
5015     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
5016       Results.push_back(Res);
5017     return;
5018   }
5019   case ISD::EXTRACT_VECTOR_ELT: {
5020     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
5021       Results.push_back(Res);
5022     return;
5023   }
5024   case ISD::INTRINSIC_WO_CHAIN: {
5025     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5026     switch (IID) {
5027     case Intrinsic::amdgcn_cvt_pkrtz: {
5028       SDValue Src0 = N->getOperand(1);
5029       SDValue Src1 = N->getOperand(2);
5030       SDLoc SL(N);
5031       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
5032                                 Src0, Src1);
5033       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
5034       return;
5035     }
5036     case Intrinsic::amdgcn_cvt_pknorm_i16:
5037     case Intrinsic::amdgcn_cvt_pknorm_u16:
5038     case Intrinsic::amdgcn_cvt_pk_i16:
5039     case Intrinsic::amdgcn_cvt_pk_u16: {
5040       SDValue Src0 = N->getOperand(1);
5041       SDValue Src1 = N->getOperand(2);
5042       SDLoc SL(N);
5043       unsigned Opcode;
5044 
5045       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
5046         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
5047       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
5048         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
5049       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
5050         Opcode = AMDGPUISD::CVT_PK_I16_I32;
5051       else
5052         Opcode = AMDGPUISD::CVT_PK_U16_U32;
5053 
5054       EVT VT = N->getValueType(0);
5055       if (isTypeLegal(VT))
5056         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
5057       else {
5058         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
5059         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
5060       }
5061       return;
5062     }
5063     }
5064     break;
5065   }
5066   case ISD::INTRINSIC_W_CHAIN: {
5067     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
5068       if (Res.getOpcode() == ISD::MERGE_VALUES) {
5069         // FIXME: Hacky
5070         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
5071           Results.push_back(Res.getOperand(I));
5072         }
5073       } else {
5074         Results.push_back(Res);
5075         Results.push_back(Res.getValue(1));
5076       }
5077       return;
5078     }
5079 
5080     break;
5081   }
5082   case ISD::SELECT: {
5083     SDLoc SL(N);
5084     EVT VT = N->getValueType(0);
5085     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
5086     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
5087     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
5088 
5089     EVT SelectVT = NewVT;
5090     if (NewVT.bitsLT(MVT::i32)) {
5091       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
5092       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
5093       SelectVT = MVT::i32;
5094     }
5095 
5096     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
5097                                     N->getOperand(0), LHS, RHS);
5098 
5099     if (NewVT != SelectVT)
5100       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
5101     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
5102     return;
5103   }
5104   case ISD::FNEG: {
5105     if (N->getValueType(0) != MVT::v2f16)
5106       break;
5107 
5108     SDLoc SL(N);
5109     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5110 
5111     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
5112                              BC,
5113                              DAG.getConstant(0x80008000, SL, MVT::i32));
5114     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5115     return;
5116   }
5117   case ISD::FABS: {
5118     if (N->getValueType(0) != MVT::v2f16)
5119       break;
5120 
5121     SDLoc SL(N);
5122     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5123 
5124     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
5125                              BC,
5126                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
5127     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5128     return;
5129   }
5130   default:
5131     break;
5132   }
5133 }
5134 
5135 /// Helper function for LowerBRCOND
5136 static SDNode *findUser(SDValue Value, unsigned Opcode) {
5137 
5138   SDNode *Parent = Value.getNode();
5139   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
5140        I != E; ++I) {
5141 
5142     if (I.getUse().get() != Value)
5143       continue;
5144 
5145     if (I->getOpcode() == Opcode)
5146       return *I;
5147   }
5148   return nullptr;
5149 }
5150 
5151 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
5152   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
5153     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
5154     case Intrinsic::amdgcn_if:
5155       return AMDGPUISD::IF;
5156     case Intrinsic::amdgcn_else:
5157       return AMDGPUISD::ELSE;
5158     case Intrinsic::amdgcn_loop:
5159       return AMDGPUISD::LOOP;
5160     case Intrinsic::amdgcn_end_cf:
5161       llvm_unreachable("should not occur");
5162     default:
5163       return 0;
5164     }
5165   }
5166 
5167   // break, if_break, else_break are all only used as inputs to loop, not
5168   // directly as branch conditions.
5169   return 0;
5170 }
5171 
5172 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
5173   const Triple &TT = getTargetMachine().getTargetTriple();
5174   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5175           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5176          AMDGPU::shouldEmitConstantsToTextSection(TT);
5177 }
5178 
5179 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
5180   // FIXME: Either avoid relying on address space here or change the default
5181   // address space for functions to avoid the explicit check.
5182   return (GV->getValueType()->isFunctionTy() ||
5183           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
5184          !shouldEmitFixup(GV) &&
5185          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
5186 }
5187 
5188 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
5189   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
5190 }
5191 
5192 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
5193   if (!GV->hasExternalLinkage())
5194     return true;
5195 
5196   const auto OS = getTargetMachine().getTargetTriple().getOS();
5197   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
5198 }
5199 
5200 /// This transforms the control flow intrinsics to get the branch destination as
5201 /// last parameter, also switches branch target with BR if the need arise
5202 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
5203                                       SelectionDAG &DAG) const {
5204   SDLoc DL(BRCOND);
5205 
5206   SDNode *Intr = BRCOND.getOperand(1).getNode();
5207   SDValue Target = BRCOND.getOperand(2);
5208   SDNode *BR = nullptr;
5209   SDNode *SetCC = nullptr;
5210 
5211   if (Intr->getOpcode() == ISD::SETCC) {
5212     // As long as we negate the condition everything is fine
5213     SetCC = Intr;
5214     Intr = SetCC->getOperand(0).getNode();
5215 
5216   } else {
5217     // Get the target from BR if we don't negate the condition
5218     BR = findUser(BRCOND, ISD::BR);
5219     assert(BR && "brcond missing unconditional branch user");
5220     Target = BR->getOperand(1);
5221   }
5222 
5223   unsigned CFNode = isCFIntrinsic(Intr);
5224   if (CFNode == 0) {
5225     // This is a uniform branch so we don't need to legalize.
5226     return BRCOND;
5227   }
5228 
5229   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5230                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5231 
5232   assert(!SetCC ||
5233         (SetCC->getConstantOperandVal(1) == 1 &&
5234          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5235                                                              ISD::SETNE));
5236 
5237   // operands of the new intrinsic call
5238   SmallVector<SDValue, 4> Ops;
5239   if (HaveChain)
5240     Ops.push_back(BRCOND.getOperand(0));
5241 
5242   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5243   Ops.push_back(Target);
5244 
5245   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5246 
5247   // build the new intrinsic call
5248   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5249 
5250   if (!HaveChain) {
5251     SDValue Ops[] =  {
5252       SDValue(Result, 0),
5253       BRCOND.getOperand(0)
5254     };
5255 
5256     Result = DAG.getMergeValues(Ops, DL).getNode();
5257   }
5258 
5259   if (BR) {
5260     // Give the branch instruction our target
5261     SDValue Ops[] = {
5262       BR->getOperand(0),
5263       BRCOND.getOperand(2)
5264     };
5265     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5266     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5267   }
5268 
5269   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5270 
5271   // Copy the intrinsic results to registers
5272   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5273     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5274     if (!CopyToReg)
5275       continue;
5276 
5277     Chain = DAG.getCopyToReg(
5278       Chain, DL,
5279       CopyToReg->getOperand(1),
5280       SDValue(Result, i - 1),
5281       SDValue());
5282 
5283     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5284   }
5285 
5286   // Remove the old intrinsic from the chain
5287   DAG.ReplaceAllUsesOfValueWith(
5288     SDValue(Intr, Intr->getNumValues() - 1),
5289     Intr->getOperand(0));
5290 
5291   return Chain;
5292 }
5293 
5294 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5295                                           SelectionDAG &DAG) const {
5296   MVT VT = Op.getSimpleValueType();
5297   SDLoc DL(Op);
5298   // Checking the depth
5299   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5300     return DAG.getConstant(0, DL, VT);
5301 
5302   MachineFunction &MF = DAG.getMachineFunction();
5303   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5304   // Check for kernel and shader functions
5305   if (Info->isEntryFunction())
5306     return DAG.getConstant(0, DL, VT);
5307 
5308   MachineFrameInfo &MFI = MF.getFrameInfo();
5309   // There is a call to @llvm.returnaddress in this function
5310   MFI.setReturnAddressIsTaken(true);
5311 
5312   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5313   // Get the return address reg and mark it as an implicit live-in
5314   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5315 
5316   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5317 }
5318 
5319 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5320                                             SDValue Op,
5321                                             const SDLoc &DL,
5322                                             EVT VT) const {
5323   return Op.getValueType().bitsLE(VT) ?
5324       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5325     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5326                 DAG.getTargetConstant(0, DL, MVT::i32));
5327 }
5328 
5329 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5330   assert(Op.getValueType() == MVT::f16 &&
5331          "Do not know how to custom lower FP_ROUND for non-f16 type");
5332 
5333   SDValue Src = Op.getOperand(0);
5334   EVT SrcVT = Src.getValueType();
5335   if (SrcVT != MVT::f64)
5336     return Op;
5337 
5338   SDLoc DL(Op);
5339 
5340   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5341   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5342   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5343 }
5344 
5345 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5346                                                SelectionDAG &DAG) const {
5347   EVT VT = Op.getValueType();
5348   const MachineFunction &MF = DAG.getMachineFunction();
5349   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5350   bool IsIEEEMode = Info->getMode().IEEE;
5351 
5352   // FIXME: Assert during selection that this is only selected for
5353   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5354   // mode functions, but this happens to be OK since it's only done in cases
5355   // where there is known no sNaN.
5356   if (IsIEEEMode)
5357     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5358 
5359   if (VT == MVT::v4f16 || VT == MVT::v8f16)
5360     return splitBinaryVectorOp(Op, DAG);
5361   return Op;
5362 }
5363 
5364 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5365   EVT VT = Op.getValueType();
5366   SDLoc SL(Op);
5367   SDValue LHS = Op.getOperand(0);
5368   SDValue RHS = Op.getOperand(1);
5369   bool isSigned = Op.getOpcode() == ISD::SMULO;
5370 
5371   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5372     const APInt &C = RHSC->getAPIntValue();
5373     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5374     if (C.isPowerOf2()) {
5375       // smulo(x, signed_min) is same as umulo(x, signed_min).
5376       bool UseArithShift = isSigned && !C.isMinSignedValue();
5377       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5378       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5379       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5380           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5381                       SL, VT, Result, ShiftAmt),
5382           LHS, ISD::SETNE);
5383       return DAG.getMergeValues({ Result, Overflow }, SL);
5384     }
5385   }
5386 
5387   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5388   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5389                             SL, VT, LHS, RHS);
5390 
5391   SDValue Sign = isSigned
5392     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5393                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5394     : DAG.getConstant(0, SL, VT);
5395   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5396 
5397   return DAG.getMergeValues({ Result, Overflow }, SL);
5398 }
5399 
5400 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const {
5401   if (Op->isDivergent()) {
5402     // Select to V_MAD_[IU]64_[IU]32.
5403     return Op;
5404   }
5405   if (Subtarget->hasSMulHi()) {
5406     // Expand to S_MUL_I32 + S_MUL_HI_[IU]32.
5407     return SDValue();
5408   }
5409   // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to
5410   // calculate the high part, so we might as well do the whole thing with
5411   // V_MAD_[IU]64_[IU]32.
5412   return Op;
5413 }
5414 
5415 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5416   if (!Subtarget->isTrapHandlerEnabled() ||
5417       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5418     return lowerTrapEndpgm(Op, DAG);
5419 
5420   if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) {
5421     switch (*HsaAbiVer) {
5422     case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
5423     case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
5424       return lowerTrapHsaQueuePtr(Op, DAG);
5425     case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
5426       return Subtarget->supportsGetDoorbellID() ?
5427           lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG);
5428     }
5429   }
5430 
5431   llvm_unreachable("Unknown trap handler");
5432 }
5433 
5434 SDValue SITargetLowering::lowerTrapEndpgm(
5435     SDValue Op, SelectionDAG &DAG) const {
5436   SDLoc SL(Op);
5437   SDValue Chain = Op.getOperand(0);
5438   return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5439 }
5440 
5441 SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5442     SDValue Op, SelectionDAG &DAG) const {
5443   SDLoc SL(Op);
5444   SDValue Chain = Op.getOperand(0);
5445 
5446   MachineFunction &MF = DAG.getMachineFunction();
5447   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5448   Register UserSGPR = Info->getQueuePtrUserSGPR();
5449 
5450   SDValue QueuePtr;
5451   if (UserSGPR == AMDGPU::NoRegister) {
5452     // We probably are in a function incorrectly marked with
5453     // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the trap,
5454     // so just use a null pointer.
5455     QueuePtr = DAG.getConstant(0, SL, MVT::i64);
5456   } else {
5457     QueuePtr = CreateLiveInRegister(
5458       DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5459   }
5460 
5461   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5462   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5463                                    QueuePtr, SDValue());
5464 
5465   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5466   SDValue Ops[] = {
5467     ToReg,
5468     DAG.getTargetConstant(TrapID, SL, MVT::i16),
5469     SGPR01,
5470     ToReg.getValue(1)
5471   };
5472   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5473 }
5474 
5475 SDValue SITargetLowering::lowerTrapHsa(
5476     SDValue Op, SelectionDAG &DAG) const {
5477   SDLoc SL(Op);
5478   SDValue Chain = Op.getOperand(0);
5479 
5480   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5481   SDValue Ops[] = {
5482     Chain,
5483     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5484   };
5485   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5486 }
5487 
5488 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5489   SDLoc SL(Op);
5490   SDValue Chain = Op.getOperand(0);
5491   MachineFunction &MF = DAG.getMachineFunction();
5492 
5493   if (!Subtarget->isTrapHandlerEnabled() ||
5494       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5495     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5496                                      "debugtrap handler not supported",
5497                                      Op.getDebugLoc(),
5498                                      DS_Warning);
5499     LLVMContext &Ctx = MF.getFunction().getContext();
5500     Ctx.diagnose(NoTrap);
5501     return Chain;
5502   }
5503 
5504   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5505   SDValue Ops[] = {
5506     Chain,
5507     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5508   };
5509   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5510 }
5511 
5512 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5513                                              SelectionDAG &DAG) const {
5514   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5515   if (Subtarget->hasApertureRegs()) {
5516     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5517         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5518         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5519     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5520         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5521         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5522     unsigned Encoding =
5523         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5524         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5525         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5526 
5527     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5528     SDValue ApertureReg = SDValue(
5529         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5530     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5531     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5532   }
5533 
5534   MachineFunction &MF = DAG.getMachineFunction();
5535   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5536   Register UserSGPR = Info->getQueuePtrUserSGPR();
5537   if (UserSGPR == AMDGPU::NoRegister) {
5538     // We probably are in a function incorrectly marked with
5539     // amdgpu-no-queue-ptr. This is undefined.
5540     return DAG.getUNDEF(MVT::i32);
5541   }
5542 
5543   SDValue QueuePtr = CreateLiveInRegister(
5544     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5545 
5546   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5547   // private_segment_aperture_base_hi.
5548   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5549 
5550   SDValue Ptr =
5551       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5552 
5553   // TODO: Use custom target PseudoSourceValue.
5554   // TODO: We should use the value from the IR intrinsic call, but it might not
5555   // be available and how do we get it?
5556   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5557   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5558                      commonAlignment(Align(64), StructOffset),
5559                      MachineMemOperand::MODereferenceable |
5560                          MachineMemOperand::MOInvariant);
5561 }
5562 
5563 /// Return true if the value is a known valid address, such that a null check is
5564 /// not necessary.
5565 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG,
5566                            const AMDGPUTargetMachine &TM, unsigned AddrSpace) {
5567   if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) ||
5568       isa<BasicBlockSDNode>(Val))
5569     return true;
5570 
5571   if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val))
5572     return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace);
5573 
5574   // TODO: Search through arithmetic, handle arguments and loads
5575   // marked nonnull.
5576   return false;
5577 }
5578 
5579 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5580                                              SelectionDAG &DAG) const {
5581   SDLoc SL(Op);
5582   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5583 
5584   SDValue Src = ASC->getOperand(0);
5585   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5586   unsigned SrcAS = ASC->getSrcAddressSpace();
5587 
5588   const AMDGPUTargetMachine &TM =
5589     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5590 
5591   // flat -> local/private
5592   if (SrcAS == AMDGPUAS::FLAT_ADDRESS) {
5593     unsigned DestAS = ASC->getDestAddressSpace();
5594 
5595     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5596         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5597       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5598 
5599       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5600         return Ptr;
5601 
5602       unsigned NullVal = TM.getNullPointerValue(DestAS);
5603       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5604       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5605 
5606       return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr,
5607                          SegmentNullPtr);
5608     }
5609   }
5610 
5611   // local/private -> flat
5612   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5613     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5614         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5615 
5616       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5617       SDValue CvtPtr =
5618           DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5619       CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr);
5620 
5621       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5622         return CvtPtr;
5623 
5624       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5625       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5626 
5627       SDValue NonNull
5628         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5629 
5630       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr,
5631                          FlatNullPtr);
5632     }
5633   }
5634 
5635   if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5636       Op.getValueType() == MVT::i64) {
5637     const SIMachineFunctionInfo *Info =
5638         DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>();
5639     SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32);
5640     SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi);
5641     return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
5642   }
5643 
5644   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5645       Src.getValueType() == MVT::i64)
5646     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5647 
5648   // global <-> flat are no-ops and never emitted.
5649 
5650   const MachineFunction &MF = DAG.getMachineFunction();
5651   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5652     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5653   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5654 
5655   return DAG.getUNDEF(ASC->getValueType(0));
5656 }
5657 
5658 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5659 // the small vector and inserting them into the big vector. That is better than
5660 // the default expansion of doing it via a stack slot. Even though the use of
5661 // the stack slot would be optimized away afterwards, the stack slot itself
5662 // remains.
5663 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5664                                                 SelectionDAG &DAG) const {
5665   SDValue Vec = Op.getOperand(0);
5666   SDValue Ins = Op.getOperand(1);
5667   SDValue Idx = Op.getOperand(2);
5668   EVT VecVT = Vec.getValueType();
5669   EVT InsVT = Ins.getValueType();
5670   EVT EltVT = VecVT.getVectorElementType();
5671   unsigned InsNumElts = InsVT.getVectorNumElements();
5672   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5673   SDLoc SL(Op);
5674 
5675   for (unsigned I = 0; I != InsNumElts; ++I) {
5676     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5677                               DAG.getConstant(I, SL, MVT::i32));
5678     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5679                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5680   }
5681   return Vec;
5682 }
5683 
5684 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5685                                                  SelectionDAG &DAG) const {
5686   SDValue Vec = Op.getOperand(0);
5687   SDValue InsVal = Op.getOperand(1);
5688   SDValue Idx = Op.getOperand(2);
5689   EVT VecVT = Vec.getValueType();
5690   EVT EltVT = VecVT.getVectorElementType();
5691   unsigned VecSize = VecVT.getSizeInBits();
5692   unsigned EltSize = EltVT.getSizeInBits();
5693 
5694 
5695   assert(VecSize <= 64);
5696 
5697   unsigned NumElts = VecVT.getVectorNumElements();
5698   SDLoc SL(Op);
5699   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5700 
5701   if (NumElts == 4 && EltSize == 16 && KIdx) {
5702     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5703 
5704     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5705                                  DAG.getConstant(0, SL, MVT::i32));
5706     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5707                                  DAG.getConstant(1, SL, MVT::i32));
5708 
5709     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5710     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5711 
5712     unsigned Idx = KIdx->getZExtValue();
5713     bool InsertLo = Idx < 2;
5714     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5715       InsertLo ? LoVec : HiVec,
5716       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5717       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5718 
5719     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5720 
5721     SDValue Concat = InsertLo ?
5722       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5723       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5724 
5725     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5726   }
5727 
5728   if (isa<ConstantSDNode>(Idx))
5729     return SDValue();
5730 
5731   MVT IntVT = MVT::getIntegerVT(VecSize);
5732 
5733   // Avoid stack access for dynamic indexing.
5734   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5735 
5736   // Create a congruent vector with the target value in each element so that
5737   // the required element can be masked and ORed into the target vector.
5738   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5739                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5740 
5741   assert(isPowerOf2_32(EltSize));
5742   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5743 
5744   // Convert vector index to bit-index.
5745   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5746 
5747   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5748   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5749                             DAG.getConstant(0xffff, SL, IntVT),
5750                             ScaledIdx);
5751 
5752   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5753   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5754                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5755 
5756   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5757   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5758 }
5759 
5760 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5761                                                   SelectionDAG &DAG) const {
5762   SDLoc SL(Op);
5763 
5764   EVT ResultVT = Op.getValueType();
5765   SDValue Vec = Op.getOperand(0);
5766   SDValue Idx = Op.getOperand(1);
5767   EVT VecVT = Vec.getValueType();
5768   unsigned VecSize = VecVT.getSizeInBits();
5769   EVT EltVT = VecVT.getVectorElementType();
5770 
5771   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5772 
5773   // Make sure we do any optimizations that will make it easier to fold
5774   // source modifiers before obscuring it with bit operations.
5775 
5776   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5777   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5778     return Combined;
5779 
5780   if (VecSize == 128) {
5781     SDValue Lo, Hi;
5782     EVT LoVT, HiVT;
5783     SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec);
5784     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5785     Lo =
5786         DAG.getBitcast(LoVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5787                                          V2, DAG.getConstant(0, SL, MVT::i32)));
5788     Hi =
5789         DAG.getBitcast(HiVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5790                                          V2, DAG.getConstant(1, SL, MVT::i32)));
5791     EVT IdxVT = Idx.getValueType();
5792     unsigned NElem = VecVT.getVectorNumElements();
5793     assert(isPowerOf2_32(NElem));
5794     SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT);
5795     SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask);
5796     SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT);
5797     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx);
5798   }
5799 
5800   assert(VecSize <= 64);
5801 
5802   unsigned EltSize = EltVT.getSizeInBits();
5803   assert(isPowerOf2_32(EltSize));
5804 
5805   MVT IntVT = MVT::getIntegerVT(VecSize);
5806   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5807 
5808   // Convert vector index to bit-index (* EltSize)
5809   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5810 
5811   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5812   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5813 
5814   if (ResultVT == MVT::f16) {
5815     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5816     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5817   }
5818 
5819   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5820 }
5821 
5822 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5823   assert(Elt % 2 == 0);
5824   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5825 }
5826 
5827 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5828                                               SelectionDAG &DAG) const {
5829   SDLoc SL(Op);
5830   EVT ResultVT = Op.getValueType();
5831   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5832 
5833   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5834   EVT EltVT = PackVT.getVectorElementType();
5835   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5836 
5837   // vector_shuffle <0,1,6,7> lhs, rhs
5838   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5839   //
5840   // vector_shuffle <6,7,2,3> lhs, rhs
5841   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5842   //
5843   // vector_shuffle <6,7,0,1> lhs, rhs
5844   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5845 
5846   // Avoid scalarizing when both halves are reading from consecutive elements.
5847   SmallVector<SDValue, 4> Pieces;
5848   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5849     if (elementPairIsContiguous(SVN->getMask(), I)) {
5850       const int Idx = SVN->getMaskElt(I);
5851       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5852       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5853       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5854                                     PackVT, SVN->getOperand(VecIdx),
5855                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5856       Pieces.push_back(SubVec);
5857     } else {
5858       const int Idx0 = SVN->getMaskElt(I);
5859       const int Idx1 = SVN->getMaskElt(I + 1);
5860       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5861       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5862       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5863       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5864 
5865       SDValue Vec0 = SVN->getOperand(VecIdx0);
5866       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5867                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5868 
5869       SDValue Vec1 = SVN->getOperand(VecIdx1);
5870       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5871                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5872       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5873     }
5874   }
5875 
5876   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5877 }
5878 
5879 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5880                                             SelectionDAG &DAG) const {
5881   SDLoc SL(Op);
5882   EVT VT = Op.getValueType();
5883 
5884   if (VT == MVT::v4i16 || VT == MVT::v4f16 ||
5885       VT == MVT::v8i16 || VT == MVT::v8f16) {
5886     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(),
5887                                   VT.getVectorNumElements() / 2);
5888     MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits());
5889 
5890     // Turn into pair of packed build_vectors.
5891     // TODO: Special case for constants that can be materialized with s_mov_b64.
5892     SmallVector<SDValue, 4> LoOps, HiOps;
5893     for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) {
5894       LoOps.push_back(Op.getOperand(I));
5895       HiOps.push_back(Op.getOperand(I + E));
5896     }
5897     SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps);
5898     SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps);
5899 
5900     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo);
5901     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi);
5902 
5903     SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL,
5904                                        { CastLo, CastHi });
5905     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5906   }
5907 
5908   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5909   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5910 
5911   SDValue Lo = Op.getOperand(0);
5912   SDValue Hi = Op.getOperand(1);
5913 
5914   // Avoid adding defined bits with the zero_extend.
5915   if (Hi.isUndef()) {
5916     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5917     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5918     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5919   }
5920 
5921   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5922   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5923 
5924   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5925                               DAG.getConstant(16, SL, MVT::i32));
5926   if (Lo.isUndef())
5927     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5928 
5929   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5930   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5931 
5932   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5933   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5934 }
5935 
5936 bool
5937 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5938   // We can fold offsets for anything that doesn't require a GOT relocation.
5939   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5940           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5941           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5942          !shouldEmitGOTReloc(GA->getGlobal());
5943 }
5944 
5945 static SDValue
5946 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5947                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5948                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5949   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5950   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5951   // lowered to the following code sequence:
5952   //
5953   // For constant address space:
5954   //   s_getpc_b64 s[0:1]
5955   //   s_add_u32 s0, s0, $symbol
5956   //   s_addc_u32 s1, s1, 0
5957   //
5958   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5959   //   a fixup or relocation is emitted to replace $symbol with a literal
5960   //   constant, which is a pc-relative offset from the encoding of the $symbol
5961   //   operand to the global variable.
5962   //
5963   // For global address space:
5964   //   s_getpc_b64 s[0:1]
5965   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5966   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5967   //
5968   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5969   //   fixups or relocations are emitted to replace $symbol@*@lo and
5970   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5971   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5972   //   operand to the global variable.
5973   //
5974   // What we want here is an offset from the value returned by s_getpc
5975   // (which is the address of the s_add_u32 instruction) to the global
5976   // variable, but since the encoding of $symbol starts 4 bytes after the start
5977   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5978   // small. This requires us to add 4 to the global variable offset in order to
5979   // compute the correct address. Similarly for the s_addc_u32 instruction, the
5980   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
5981   // instruction.
5982   SDValue PtrLo =
5983       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5984   SDValue PtrHi;
5985   if (GAFlags == SIInstrInfo::MO_NONE) {
5986     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5987   } else {
5988     PtrHi =
5989         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
5990   }
5991   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5992 }
5993 
5994 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5995                                              SDValue Op,
5996                                              SelectionDAG &DAG) const {
5997   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5998   SDLoc DL(GSD);
5999   EVT PtrVT = Op.getValueType();
6000 
6001   const GlobalValue *GV = GSD->getGlobal();
6002   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
6003        shouldUseLDSConstAddress(GV)) ||
6004       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
6005       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
6006     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
6007         GV->hasExternalLinkage()) {
6008       Type *Ty = GV->getValueType();
6009       // HIP uses an unsized array `extern __shared__ T s[]` or similar
6010       // zero-sized type in other languages to declare the dynamic shared
6011       // memory which size is not known at the compile time. They will be
6012       // allocated by the runtime and placed directly after the static
6013       // allocated ones. They all share the same offset.
6014       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
6015         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
6016         // Adjust alignment for that dynamic shared memory array.
6017         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
6018         return SDValue(
6019             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
6020       }
6021     }
6022     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
6023   }
6024 
6025   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
6026     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
6027                                             SIInstrInfo::MO_ABS32_LO);
6028     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
6029   }
6030 
6031   if (shouldEmitFixup(GV))
6032     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
6033   else if (shouldEmitPCReloc(GV))
6034     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
6035                                    SIInstrInfo::MO_REL32);
6036 
6037   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
6038                                             SIInstrInfo::MO_GOTPCREL32);
6039 
6040   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
6041   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
6042   const DataLayout &DataLayout = DAG.getDataLayout();
6043   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
6044   MachinePointerInfo PtrInfo
6045     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
6046 
6047   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
6048                      MachineMemOperand::MODereferenceable |
6049                          MachineMemOperand::MOInvariant);
6050 }
6051 
6052 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
6053                                    const SDLoc &DL, SDValue V) const {
6054   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
6055   // the destination register.
6056   //
6057   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
6058   // so we will end up with redundant moves to m0.
6059   //
6060   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
6061 
6062   // A Null SDValue creates a glue result.
6063   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
6064                                   V, Chain);
6065   return SDValue(M0, 0);
6066 }
6067 
6068 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
6069                                                  SDValue Op,
6070                                                  MVT VT,
6071                                                  unsigned Offset) const {
6072   SDLoc SL(Op);
6073   SDValue Param = lowerKernargMemParameter(
6074       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
6075   // The local size values will have the hi 16-bits as zero.
6076   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
6077                      DAG.getValueType(VT));
6078 }
6079 
6080 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6081                                         EVT VT) {
6082   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6083                                       "non-hsa intrinsic with hsa target",
6084                                       DL.getDebugLoc());
6085   DAG.getContext()->diagnose(BadIntrin);
6086   return DAG.getUNDEF(VT);
6087 }
6088 
6089 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6090                                          EVT VT) {
6091   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6092                                       "intrinsic not supported on subtarget",
6093                                       DL.getDebugLoc());
6094   DAG.getContext()->diagnose(BadIntrin);
6095   return DAG.getUNDEF(VT);
6096 }
6097 
6098 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
6099                                     ArrayRef<SDValue> Elts) {
6100   assert(!Elts.empty());
6101   MVT Type;
6102   unsigned NumElts = Elts.size();
6103 
6104   if (NumElts <= 8) {
6105     Type = MVT::getVectorVT(MVT::f32, NumElts);
6106   } else {
6107     assert(Elts.size() <= 16);
6108     Type = MVT::v16f32;
6109     NumElts = 16;
6110   }
6111 
6112   SmallVector<SDValue, 16> VecElts(NumElts);
6113   for (unsigned i = 0; i < Elts.size(); ++i) {
6114     SDValue Elt = Elts[i];
6115     if (Elt.getValueType() != MVT::f32)
6116       Elt = DAG.getBitcast(MVT::f32, Elt);
6117     VecElts[i] = Elt;
6118   }
6119   for (unsigned i = Elts.size(); i < NumElts; ++i)
6120     VecElts[i] = DAG.getUNDEF(MVT::f32);
6121 
6122   if (NumElts == 1)
6123     return VecElts[0];
6124   return DAG.getBuildVector(Type, DL, VecElts);
6125 }
6126 
6127 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
6128                               SDValue Src, int ExtraElts) {
6129   EVT SrcVT = Src.getValueType();
6130 
6131   SmallVector<SDValue, 8> Elts;
6132 
6133   if (SrcVT.isVector())
6134     DAG.ExtractVectorElements(Src, Elts);
6135   else
6136     Elts.push_back(Src);
6137 
6138   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
6139   while (ExtraElts--)
6140     Elts.push_back(Undef);
6141 
6142   return DAG.getBuildVector(CastVT, DL, Elts);
6143 }
6144 
6145 // Re-construct the required return value for a image load intrinsic.
6146 // This is more complicated due to the optional use TexFailCtrl which means the required
6147 // return type is an aggregate
6148 static SDValue constructRetValue(SelectionDAG &DAG,
6149                                  MachineSDNode *Result,
6150                                  ArrayRef<EVT> ResultTypes,
6151                                  bool IsTexFail, bool Unpacked, bool IsD16,
6152                                  int DMaskPop, int NumVDataDwords,
6153                                  const SDLoc &DL) {
6154   // Determine the required return type. This is the same regardless of IsTexFail flag
6155   EVT ReqRetVT = ResultTypes[0];
6156   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
6157   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6158     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
6159 
6160   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6161     DMaskPop : (DMaskPop + 1) / 2;
6162 
6163   MVT DataDwordVT = NumDataDwords == 1 ?
6164     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
6165 
6166   MVT MaskPopVT = MaskPopDwords == 1 ?
6167     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
6168 
6169   SDValue Data(Result, 0);
6170   SDValue TexFail;
6171 
6172   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
6173     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
6174     if (MaskPopVT.isVector()) {
6175       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
6176                          SDValue(Result, 0), ZeroIdx);
6177     } else {
6178       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
6179                          SDValue(Result, 0), ZeroIdx);
6180     }
6181   }
6182 
6183   if (DataDwordVT.isVector())
6184     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
6185                           NumDataDwords - MaskPopDwords);
6186 
6187   if (IsD16)
6188     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
6189 
6190   EVT LegalReqRetVT = ReqRetVT;
6191   if (!ReqRetVT.isVector()) {
6192     if (!Data.getValueType().isInteger())
6193       Data = DAG.getNode(ISD::BITCAST, DL,
6194                          Data.getValueType().changeTypeToInteger(), Data);
6195     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
6196   } else {
6197     // We need to widen the return vector to a legal type
6198     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
6199         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
6200       LegalReqRetVT =
6201           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
6202                            ReqRetVT.getVectorNumElements() + 1);
6203     }
6204   }
6205   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
6206 
6207   if (IsTexFail) {
6208     TexFail =
6209         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
6210                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
6211 
6212     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
6213   }
6214 
6215   if (Result->getNumValues() == 1)
6216     return Data;
6217 
6218   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
6219 }
6220 
6221 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
6222                          SDValue *LWE, bool &IsTexFail) {
6223   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
6224 
6225   uint64_t Value = TexFailCtrlConst->getZExtValue();
6226   if (Value) {
6227     IsTexFail = true;
6228   }
6229 
6230   SDLoc DL(TexFailCtrlConst);
6231   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
6232   Value &= ~(uint64_t)0x1;
6233   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
6234   Value &= ~(uint64_t)0x2;
6235 
6236   return Value == 0;
6237 }
6238 
6239 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
6240                                       MVT PackVectorVT,
6241                                       SmallVectorImpl<SDValue> &PackedAddrs,
6242                                       unsigned DimIdx, unsigned EndIdx,
6243                                       unsigned NumGradients) {
6244   SDLoc DL(Op);
6245   for (unsigned I = DimIdx; I < EndIdx; I++) {
6246     SDValue Addr = Op.getOperand(I);
6247 
6248     // Gradients are packed with undef for each coordinate.
6249     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
6250     // 1D: undef,dx/dh; undef,dx/dv
6251     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
6252     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
6253     if (((I + 1) >= EndIdx) ||
6254         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
6255                                          I == DimIdx + NumGradients - 1))) {
6256       if (Addr.getValueType() != MVT::i16)
6257         Addr = DAG.getBitcast(MVT::i16, Addr);
6258       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
6259     } else {
6260       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
6261       I++;
6262     }
6263     Addr = DAG.getBitcast(MVT::f32, Addr);
6264     PackedAddrs.push_back(Addr);
6265   }
6266 }
6267 
6268 SDValue SITargetLowering::lowerImage(SDValue Op,
6269                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
6270                                      SelectionDAG &DAG, bool WithChain) const {
6271   SDLoc DL(Op);
6272   MachineFunction &MF = DAG.getMachineFunction();
6273   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
6274   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
6275       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
6276   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
6277   unsigned IntrOpcode = Intr->BaseOpcode;
6278   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6279 
6280   SmallVector<EVT, 3> ResultTypes(Op->values());
6281   SmallVector<EVT, 3> OrigResultTypes(Op->values());
6282   bool IsD16 = false;
6283   bool IsG16 = false;
6284   bool IsA16 = false;
6285   SDValue VData;
6286   int NumVDataDwords;
6287   bool AdjustRetType = false;
6288 
6289   // Offset of intrinsic arguments
6290   const unsigned ArgOffset = WithChain ? 2 : 1;
6291 
6292   unsigned DMask;
6293   unsigned DMaskLanes = 0;
6294 
6295   if (BaseOpcode->Atomic) {
6296     VData = Op.getOperand(2);
6297 
6298     bool Is64Bit = VData.getValueType() == MVT::i64;
6299     if (BaseOpcode->AtomicX2) {
6300       SDValue VData2 = Op.getOperand(3);
6301       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6302                                  {VData, VData2});
6303       if (Is64Bit)
6304         VData = DAG.getBitcast(MVT::v4i32, VData);
6305 
6306       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6307       DMask = Is64Bit ? 0xf : 0x3;
6308       NumVDataDwords = Is64Bit ? 4 : 2;
6309     } else {
6310       DMask = Is64Bit ? 0x3 : 0x1;
6311       NumVDataDwords = Is64Bit ? 2 : 1;
6312     }
6313   } else {
6314     auto *DMaskConst =
6315         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6316     DMask = DMaskConst->getZExtValue();
6317     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6318 
6319     if (BaseOpcode->Store) {
6320       VData = Op.getOperand(2);
6321 
6322       MVT StoreVT = VData.getSimpleValueType();
6323       if (StoreVT.getScalarType() == MVT::f16) {
6324         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6325           return Op; // D16 is unsupported for this instruction
6326 
6327         IsD16 = true;
6328         VData = handleD16VData(VData, DAG, true);
6329       }
6330 
6331       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6332     } else {
6333       // Work out the num dwords based on the dmask popcount and underlying type
6334       // and whether packing is supported.
6335       MVT LoadVT = ResultTypes[0].getSimpleVT();
6336       if (LoadVT.getScalarType() == MVT::f16) {
6337         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6338           return Op; // D16 is unsupported for this instruction
6339 
6340         IsD16 = true;
6341       }
6342 
6343       // Confirm that the return type is large enough for the dmask specified
6344       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6345           (!LoadVT.isVector() && DMaskLanes > 1))
6346           return Op;
6347 
6348       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6349       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6350       // instructions.
6351       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6352           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6353         NumVDataDwords = (DMaskLanes + 1) / 2;
6354       else
6355         NumVDataDwords = DMaskLanes;
6356 
6357       AdjustRetType = true;
6358     }
6359   }
6360 
6361   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6362   SmallVector<SDValue, 4> VAddrs;
6363 
6364   // Check for 16 bit addresses or derivatives and pack if true.
6365   MVT VAddrVT =
6366       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6367   MVT VAddrScalarVT = VAddrVT.getScalarType();
6368   MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6369   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6370 
6371   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6372   VAddrScalarVT = VAddrVT.getScalarType();
6373   MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6374   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6375 
6376   // Push back extra arguments.
6377   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) {
6378     if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) {
6379       assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument");
6380       // Special handling of bias when A16 is on. Bias is of type half but
6381       // occupies full 32-bit.
6382       SDValue Bias = DAG.getBuildVector(
6383           MVT::v2f16, DL,
6384           {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)});
6385       VAddrs.push_back(Bias);
6386     } else {
6387       assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) &&
6388              "Bias needs to be converted to 16 bit in A16 mode");
6389       VAddrs.push_back(Op.getOperand(ArgOffset + I));
6390     }
6391   }
6392 
6393   if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
6394     // 16 bit gradients are supported, but are tied to the A16 control
6395     // so both gradients and addresses must be 16 bit
6396     LLVM_DEBUG(
6397         dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6398                   "require 16 bit args for both gradients and addresses");
6399     return Op;
6400   }
6401 
6402   if (IsA16) {
6403     if (!ST->hasA16()) {
6404       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6405                            "support 16 bit addresses\n");
6406       return Op;
6407     }
6408   }
6409 
6410   // We've dealt with incorrect input so we know that if IsA16, IsG16
6411   // are set then we have to compress/pack operands (either address,
6412   // gradient or both)
6413   // In the case where a16 and gradients are tied (no G16 support) then we
6414   // have already verified that both IsA16 and IsG16 are true
6415   if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
6416     // Activate g16
6417     const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6418         AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6419     IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6420   }
6421 
6422   // Add gradients (packed or unpacked)
6423   if (IsG16) {
6424     // Pack the gradients
6425     // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6426     packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
6427                               ArgOffset + Intr->GradientStart,
6428                               ArgOffset + Intr->CoordStart, Intr->NumGradients);
6429   } else {
6430     for (unsigned I = ArgOffset + Intr->GradientStart;
6431          I < ArgOffset + Intr->CoordStart; I++)
6432       VAddrs.push_back(Op.getOperand(I));
6433   }
6434 
6435   // Add addresses (packed or unpacked)
6436   if (IsA16) {
6437     packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
6438                               ArgOffset + Intr->CoordStart, VAddrEnd,
6439                               0 /* No gradients */);
6440   } else {
6441     // Add uncompressed address
6442     for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6443       VAddrs.push_back(Op.getOperand(I));
6444   }
6445 
6446   // If the register allocator cannot place the address registers contiguously
6447   // without introducing moves, then using the non-sequential address encoding
6448   // is always preferable, since it saves VALU instructions and is usually a
6449   // wash in terms of code size or even better.
6450   //
6451   // However, we currently have no way of hinting to the register allocator that
6452   // MIMG addresses should be placed contiguously when it is possible to do so,
6453   // so force non-NSA for the common 2-address case as a heuristic.
6454   //
6455   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6456   // allocation when possible.
6457   bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) &&
6458                 VAddrs.size() >= 3 &&
6459                 VAddrs.size() <= (unsigned)ST->getNSAMaxSize();
6460   SDValue VAddr;
6461   if (!UseNSA)
6462     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6463 
6464   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6465   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6466   SDValue Unorm;
6467   if (!BaseOpcode->Sampler) {
6468     Unorm = True;
6469   } else {
6470     auto UnormConst =
6471         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6472 
6473     Unorm = UnormConst->getZExtValue() ? True : False;
6474   }
6475 
6476   SDValue TFE;
6477   SDValue LWE;
6478   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6479   bool IsTexFail = false;
6480   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6481     return Op;
6482 
6483   if (IsTexFail) {
6484     if (!DMaskLanes) {
6485       // Expecting to get an error flag since TFC is on - and dmask is 0
6486       // Force dmask to be at least 1 otherwise the instruction will fail
6487       DMask = 0x1;
6488       DMaskLanes = 1;
6489       NumVDataDwords = 1;
6490     }
6491     NumVDataDwords += 1;
6492     AdjustRetType = true;
6493   }
6494 
6495   // Has something earlier tagged that the return type needs adjusting
6496   // This happens if the instruction is a load or has set TexFailCtrl flags
6497   if (AdjustRetType) {
6498     // NumVDataDwords reflects the true number of dwords required in the return type
6499     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6500       // This is a no-op load. This can be eliminated
6501       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6502       if (isa<MemSDNode>(Op))
6503         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6504       return Undef;
6505     }
6506 
6507     EVT NewVT = NumVDataDwords > 1 ?
6508                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6509                 : MVT::i32;
6510 
6511     ResultTypes[0] = NewVT;
6512     if (ResultTypes.size() == 3) {
6513       // Original result was aggregate type used for TexFailCtrl results
6514       // The actual instruction returns as a vector type which has now been
6515       // created. Remove the aggregate result.
6516       ResultTypes.erase(&ResultTypes[1]);
6517     }
6518   }
6519 
6520   unsigned CPol = cast<ConstantSDNode>(
6521       Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6522   if (BaseOpcode->Atomic)
6523     CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6524   if (CPol & ~AMDGPU::CPol::ALL)
6525     return Op;
6526 
6527   SmallVector<SDValue, 26> Ops;
6528   if (BaseOpcode->Store || BaseOpcode->Atomic)
6529     Ops.push_back(VData); // vdata
6530   if (UseNSA)
6531     append_range(Ops, VAddrs);
6532   else
6533     Ops.push_back(VAddr);
6534   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6535   if (BaseOpcode->Sampler)
6536     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6537   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6538   if (IsGFX10Plus)
6539     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6540   Ops.push_back(Unorm);
6541   Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6542   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6543                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6544   if (IsGFX10Plus)
6545     Ops.push_back(IsA16 ? True : False);
6546   if (!Subtarget->hasGFX90AInsts()) {
6547     Ops.push_back(TFE); //tfe
6548   } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6549     report_fatal_error("TFE is not supported on this GPU");
6550   }
6551   Ops.push_back(LWE); // lwe
6552   if (!IsGFX10Plus)
6553     Ops.push_back(DimInfo->DA ? True : False);
6554   if (BaseOpcode->HasD16)
6555     Ops.push_back(IsD16 ? True : False);
6556   if (isa<MemSDNode>(Op))
6557     Ops.push_back(Op.getOperand(0)); // chain
6558 
6559   int NumVAddrDwords =
6560       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6561   int Opcode = -1;
6562 
6563   if (IsGFX10Plus) {
6564     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6565                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6566                                           : AMDGPU::MIMGEncGfx10Default,
6567                                    NumVDataDwords, NumVAddrDwords);
6568   } else {
6569     if (Subtarget->hasGFX90AInsts()) {
6570       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6571                                      NumVDataDwords, NumVAddrDwords);
6572       if (Opcode == -1)
6573         report_fatal_error(
6574             "requested image instruction is not supported on this GPU");
6575     }
6576     if (Opcode == -1 &&
6577         Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6578       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6579                                      NumVDataDwords, NumVAddrDwords);
6580     if (Opcode == -1)
6581       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6582                                      NumVDataDwords, NumVAddrDwords);
6583   }
6584   assert(Opcode != -1);
6585 
6586   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6587   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6588     MachineMemOperand *MemRef = MemOp->getMemOperand();
6589     DAG.setNodeMemRefs(NewNode, {MemRef});
6590   }
6591 
6592   if (BaseOpcode->AtomicX2) {
6593     SmallVector<SDValue, 1> Elt;
6594     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6595     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6596   }
6597   if (BaseOpcode->Store)
6598     return SDValue(NewNode, 0);
6599   return constructRetValue(DAG, NewNode,
6600                            OrigResultTypes, IsTexFail,
6601                            Subtarget->hasUnpackedD16VMem(), IsD16,
6602                            DMaskLanes, NumVDataDwords, DL);
6603 }
6604 
6605 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6606                                        SDValue Offset, SDValue CachePolicy,
6607                                        SelectionDAG &DAG) const {
6608   MachineFunction &MF = DAG.getMachineFunction();
6609 
6610   const DataLayout &DataLayout = DAG.getDataLayout();
6611   Align Alignment =
6612       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6613 
6614   MachineMemOperand *MMO = MF.getMachineMemOperand(
6615       MachinePointerInfo(),
6616       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6617           MachineMemOperand::MOInvariant,
6618       VT.getStoreSize(), Alignment);
6619 
6620   if (!Offset->isDivergent()) {
6621     SDValue Ops[] = {
6622         Rsrc,
6623         Offset, // Offset
6624         CachePolicy
6625     };
6626 
6627     // Widen vec3 load to vec4.
6628     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6629       EVT WidenedVT =
6630           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6631       auto WidenedOp = DAG.getMemIntrinsicNode(
6632           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6633           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6634       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6635                                    DAG.getVectorIdxConstant(0, DL));
6636       return Subvector;
6637     }
6638 
6639     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6640                                    DAG.getVTList(VT), Ops, VT, MMO);
6641   }
6642 
6643   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6644   // assume that the buffer is unswizzled.
6645   SmallVector<SDValue, 4> Loads;
6646   unsigned NumLoads = 1;
6647   MVT LoadVT = VT.getSimpleVT();
6648   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6649   assert((LoadVT.getScalarType() == MVT::i32 ||
6650           LoadVT.getScalarType() == MVT::f32));
6651 
6652   if (NumElts == 8 || NumElts == 16) {
6653     NumLoads = NumElts / 4;
6654     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6655   }
6656 
6657   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6658   SDValue Ops[] = {
6659       DAG.getEntryNode(),                               // Chain
6660       Rsrc,                                             // rsrc
6661       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6662       {},                                               // voffset
6663       {},                                               // soffset
6664       {},                                               // offset
6665       CachePolicy,                                      // cachepolicy
6666       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6667   };
6668 
6669   // Use the alignment to ensure that the required offsets will fit into the
6670   // immediate offsets.
6671   setBufferOffsets(Offset, DAG, &Ops[3],
6672                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6673 
6674   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6675   for (unsigned i = 0; i < NumLoads; ++i) {
6676     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6677     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6678                                         LoadVT, MMO, DAG));
6679   }
6680 
6681   if (NumElts == 8 || NumElts == 16)
6682     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6683 
6684   return Loads[0];
6685 }
6686 
6687 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6688                                                   SelectionDAG &DAG) const {
6689   MachineFunction &MF = DAG.getMachineFunction();
6690   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6691 
6692   EVT VT = Op.getValueType();
6693   SDLoc DL(Op);
6694   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6695 
6696   // TODO: Should this propagate fast-math-flags?
6697 
6698   switch (IntrinsicID) {
6699   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6700     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6701       return emitNonHSAIntrinsicError(DAG, DL, VT);
6702     return getPreloadedValue(DAG, *MFI, VT,
6703                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6704   }
6705   case Intrinsic::amdgcn_dispatch_ptr:
6706   case Intrinsic::amdgcn_queue_ptr: {
6707     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6708       DiagnosticInfoUnsupported BadIntrin(
6709           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6710           DL.getDebugLoc());
6711       DAG.getContext()->diagnose(BadIntrin);
6712       return DAG.getUNDEF(VT);
6713     }
6714 
6715     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6716       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6717     return getPreloadedValue(DAG, *MFI, VT, RegID);
6718   }
6719   case Intrinsic::amdgcn_implicitarg_ptr: {
6720     if (MFI->isEntryFunction())
6721       return getImplicitArgPtr(DAG, DL);
6722     return getPreloadedValue(DAG, *MFI, VT,
6723                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6724   }
6725   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6726     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6727       // This only makes sense to call in a kernel, so just lower to null.
6728       return DAG.getConstant(0, DL, VT);
6729     }
6730 
6731     return getPreloadedValue(DAG, *MFI, VT,
6732                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6733   }
6734   case Intrinsic::amdgcn_dispatch_id: {
6735     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6736   }
6737   case Intrinsic::amdgcn_rcp:
6738     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6739   case Intrinsic::amdgcn_rsq:
6740     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6741   case Intrinsic::amdgcn_rsq_legacy:
6742     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6743       return emitRemovedIntrinsicError(DAG, DL, VT);
6744     return SDValue();
6745   case Intrinsic::amdgcn_rcp_legacy:
6746     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6747       return emitRemovedIntrinsicError(DAG, DL, VT);
6748     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6749   case Intrinsic::amdgcn_rsq_clamp: {
6750     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6751       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6752 
6753     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6754     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6755     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6756 
6757     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6758     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6759                               DAG.getConstantFP(Max, DL, VT));
6760     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6761                        DAG.getConstantFP(Min, DL, VT));
6762   }
6763   case Intrinsic::r600_read_ngroups_x:
6764     if (Subtarget->isAmdHsaOS())
6765       return emitNonHSAIntrinsicError(DAG, DL, VT);
6766 
6767     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6768                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6769                                     false);
6770   case Intrinsic::r600_read_ngroups_y:
6771     if (Subtarget->isAmdHsaOS())
6772       return emitNonHSAIntrinsicError(DAG, DL, VT);
6773 
6774     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6775                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6776                                     false);
6777   case Intrinsic::r600_read_ngroups_z:
6778     if (Subtarget->isAmdHsaOS())
6779       return emitNonHSAIntrinsicError(DAG, DL, VT);
6780 
6781     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6782                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6783                                     false);
6784   case Intrinsic::r600_read_global_size_x:
6785     if (Subtarget->isAmdHsaOS())
6786       return emitNonHSAIntrinsicError(DAG, DL, VT);
6787 
6788     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6789                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6790                                     Align(4), false);
6791   case Intrinsic::r600_read_global_size_y:
6792     if (Subtarget->isAmdHsaOS())
6793       return emitNonHSAIntrinsicError(DAG, DL, VT);
6794 
6795     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6796                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6797                                     Align(4), false);
6798   case Intrinsic::r600_read_global_size_z:
6799     if (Subtarget->isAmdHsaOS())
6800       return emitNonHSAIntrinsicError(DAG, DL, VT);
6801 
6802     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6803                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6804                                     Align(4), false);
6805   case Intrinsic::r600_read_local_size_x:
6806     if (Subtarget->isAmdHsaOS())
6807       return emitNonHSAIntrinsicError(DAG, DL, VT);
6808 
6809     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6810                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6811   case Intrinsic::r600_read_local_size_y:
6812     if (Subtarget->isAmdHsaOS())
6813       return emitNonHSAIntrinsicError(DAG, DL, VT);
6814 
6815     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6816                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6817   case Intrinsic::r600_read_local_size_z:
6818     if (Subtarget->isAmdHsaOS())
6819       return emitNonHSAIntrinsicError(DAG, DL, VT);
6820 
6821     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6822                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6823   case Intrinsic::amdgcn_workgroup_id_x:
6824     return getPreloadedValue(DAG, *MFI, VT,
6825                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6826   case Intrinsic::amdgcn_workgroup_id_y:
6827     return getPreloadedValue(DAG, *MFI, VT,
6828                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6829   case Intrinsic::amdgcn_workgroup_id_z:
6830     return getPreloadedValue(DAG, *MFI, VT,
6831                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6832   case Intrinsic::amdgcn_workitem_id_x:
6833     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 0) == 0)
6834       return DAG.getConstant(0, DL, MVT::i32);
6835 
6836     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6837                           SDLoc(DAG.getEntryNode()),
6838                           MFI->getArgInfo().WorkItemIDX);
6839   case Intrinsic::amdgcn_workitem_id_y:
6840     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 1) == 0)
6841       return DAG.getConstant(0, DL, MVT::i32);
6842 
6843     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6844                           SDLoc(DAG.getEntryNode()),
6845                           MFI->getArgInfo().WorkItemIDY);
6846   case Intrinsic::amdgcn_workitem_id_z:
6847     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 2) == 0)
6848       return DAG.getConstant(0, DL, MVT::i32);
6849 
6850     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6851                           SDLoc(DAG.getEntryNode()),
6852                           MFI->getArgInfo().WorkItemIDZ);
6853   case Intrinsic::amdgcn_wavefrontsize:
6854     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6855                            SDLoc(Op), MVT::i32);
6856   case Intrinsic::amdgcn_s_buffer_load: {
6857     unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6858     if (CPol & ~AMDGPU::CPol::ALL)
6859       return Op;
6860     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6861                         DAG);
6862   }
6863   case Intrinsic::amdgcn_fdiv_fast:
6864     return lowerFDIV_FAST(Op, DAG);
6865   case Intrinsic::amdgcn_sin:
6866     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6867 
6868   case Intrinsic::amdgcn_cos:
6869     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6870 
6871   case Intrinsic::amdgcn_mul_u24:
6872     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6873   case Intrinsic::amdgcn_mul_i24:
6874     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6875 
6876   case Intrinsic::amdgcn_log_clamp: {
6877     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6878       return SDValue();
6879 
6880     return emitRemovedIntrinsicError(DAG, DL, VT);
6881   }
6882   case Intrinsic::amdgcn_ldexp:
6883     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6884                        Op.getOperand(1), Op.getOperand(2));
6885 
6886   case Intrinsic::amdgcn_fract:
6887     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6888 
6889   case Intrinsic::amdgcn_class:
6890     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6891                        Op.getOperand(1), Op.getOperand(2));
6892   case Intrinsic::amdgcn_div_fmas:
6893     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6894                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6895                        Op.getOperand(4));
6896 
6897   case Intrinsic::amdgcn_div_fixup:
6898     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6899                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6900 
6901   case Intrinsic::amdgcn_div_scale: {
6902     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6903 
6904     // Translate to the operands expected by the machine instruction. The
6905     // first parameter must be the same as the first instruction.
6906     SDValue Numerator = Op.getOperand(1);
6907     SDValue Denominator = Op.getOperand(2);
6908 
6909     // Note this order is opposite of the machine instruction's operations,
6910     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6911     // intrinsic has the numerator as the first operand to match a normal
6912     // division operation.
6913 
6914     SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator;
6915 
6916     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6917                        Denominator, Numerator);
6918   }
6919   case Intrinsic::amdgcn_icmp: {
6920     // There is a Pat that handles this variant, so return it as-is.
6921     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6922         Op.getConstantOperandVal(2) == 0 &&
6923         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6924       return Op;
6925     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6926   }
6927   case Intrinsic::amdgcn_fcmp: {
6928     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6929   }
6930   case Intrinsic::amdgcn_ballot:
6931     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6932   case Intrinsic::amdgcn_fmed3:
6933     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6934                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6935   case Intrinsic::amdgcn_fdot2:
6936     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6937                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6938                        Op.getOperand(4));
6939   case Intrinsic::amdgcn_fmul_legacy:
6940     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6941                        Op.getOperand(1), Op.getOperand(2));
6942   case Intrinsic::amdgcn_sffbh:
6943     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6944   case Intrinsic::amdgcn_sbfe:
6945     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6946                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6947   case Intrinsic::amdgcn_ubfe:
6948     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6949                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6950   case Intrinsic::amdgcn_cvt_pkrtz:
6951   case Intrinsic::amdgcn_cvt_pknorm_i16:
6952   case Intrinsic::amdgcn_cvt_pknorm_u16:
6953   case Intrinsic::amdgcn_cvt_pk_i16:
6954   case Intrinsic::amdgcn_cvt_pk_u16: {
6955     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6956     EVT VT = Op.getValueType();
6957     unsigned Opcode;
6958 
6959     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6960       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6961     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6962       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6963     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6964       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6965     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6966       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6967     else
6968       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6969 
6970     if (isTypeLegal(VT))
6971       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6972 
6973     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6974                                Op.getOperand(1), Op.getOperand(2));
6975     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6976   }
6977   case Intrinsic::amdgcn_fmad_ftz:
6978     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6979                        Op.getOperand(2), Op.getOperand(3));
6980 
6981   case Intrinsic::amdgcn_if_break:
6982     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6983                                       Op->getOperand(1), Op->getOperand(2)), 0);
6984 
6985   case Intrinsic::amdgcn_groupstaticsize: {
6986     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6987     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6988       return Op;
6989 
6990     const Module *M = MF.getFunction().getParent();
6991     const GlobalValue *GV =
6992         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6993     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6994                                             SIInstrInfo::MO_ABS32_LO);
6995     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6996   }
6997   case Intrinsic::amdgcn_is_shared:
6998   case Intrinsic::amdgcn_is_private: {
6999     SDLoc SL(Op);
7000     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
7001       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
7002     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
7003     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
7004                                  Op.getOperand(1));
7005 
7006     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
7007                                 DAG.getConstant(1, SL, MVT::i32));
7008     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
7009   }
7010   case Intrinsic::amdgcn_perm:
7011     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
7012                        Op.getOperand(2), Op.getOperand(3));
7013   case Intrinsic::amdgcn_reloc_constant: {
7014     Module *M = const_cast<Module *>(MF.getFunction().getParent());
7015     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
7016     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
7017     auto RelocSymbol = cast<GlobalVariable>(
7018         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
7019     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
7020                                             SIInstrInfo::MO_ABS32_LO);
7021     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
7022   }
7023   default:
7024     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7025             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7026       return lowerImage(Op, ImageDimIntr, DAG, false);
7027 
7028     return Op;
7029   }
7030 }
7031 
7032 /// Update \p MMO based on the offset inputs to an intrinsic.
7033 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset,
7034                             SDValue SOffset, SDValue Offset,
7035                             SDValue VIndex = SDValue()) {
7036   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
7037       !isa<ConstantSDNode>(Offset)) {
7038     // The combined offset is not known to be constant, so we cannot represent
7039     // it in the MMO. Give up.
7040     MMO->setValue((Value *)nullptr);
7041     return;
7042   }
7043 
7044   if (VIndex && (!isa<ConstantSDNode>(VIndex) ||
7045                  !cast<ConstantSDNode>(VIndex)->isZero())) {
7046     // The strided index component of the address is not known to be zero, so we
7047     // cannot represent it in the MMO. Give up.
7048     MMO->setValue((Value *)nullptr);
7049     return;
7050   }
7051 
7052   MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() +
7053                  cast<ConstantSDNode>(SOffset)->getSExtValue() +
7054                  cast<ConstantSDNode>(Offset)->getSExtValue());
7055 }
7056 
7057 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
7058                                                      SelectionDAG &DAG,
7059                                                      unsigned NewOpcode) const {
7060   SDLoc DL(Op);
7061 
7062   SDValue VData = Op.getOperand(2);
7063   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7064   SDValue Ops[] = {
7065     Op.getOperand(0), // Chain
7066     VData,            // vdata
7067     Op.getOperand(3), // rsrc
7068     DAG.getConstant(0, DL, MVT::i32), // vindex
7069     Offsets.first,    // voffset
7070     Op.getOperand(5), // soffset
7071     Offsets.second,   // offset
7072     Op.getOperand(6), // cachepolicy
7073     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7074   };
7075 
7076   auto *M = cast<MemSDNode>(Op);
7077   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
7078 
7079   EVT MemVT = VData.getValueType();
7080   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7081                                  M->getMemOperand());
7082 }
7083 
7084 // Return a value to use for the idxen operand by examining the vindex operand.
7085 static unsigned getIdxEn(SDValue VIndex) {
7086   if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex))
7087     // No need to set idxen if vindex is known to be zero.
7088     return VIndexC->getZExtValue() != 0;
7089   return 1;
7090 }
7091 
7092 SDValue
7093 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
7094                                                 unsigned NewOpcode) const {
7095   SDLoc DL(Op);
7096 
7097   SDValue VData = Op.getOperand(2);
7098   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7099   SDValue Ops[] = {
7100     Op.getOperand(0), // Chain
7101     VData,            // vdata
7102     Op.getOperand(3), // rsrc
7103     Op.getOperand(4), // vindex
7104     Offsets.first,    // voffset
7105     Op.getOperand(6), // soffset
7106     Offsets.second,   // offset
7107     Op.getOperand(7), // cachepolicy
7108     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7109   };
7110 
7111   auto *M = cast<MemSDNode>(Op);
7112   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7113 
7114   EVT MemVT = VData.getValueType();
7115   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7116                                  M->getMemOperand());
7117 }
7118 
7119 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
7120                                                  SelectionDAG &DAG) const {
7121   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7122   SDLoc DL(Op);
7123 
7124   switch (IntrID) {
7125   case Intrinsic::amdgcn_ds_ordered_add:
7126   case Intrinsic::amdgcn_ds_ordered_swap: {
7127     MemSDNode *M = cast<MemSDNode>(Op);
7128     SDValue Chain = M->getOperand(0);
7129     SDValue M0 = M->getOperand(2);
7130     SDValue Value = M->getOperand(3);
7131     unsigned IndexOperand = M->getConstantOperandVal(7);
7132     unsigned WaveRelease = M->getConstantOperandVal(8);
7133     unsigned WaveDone = M->getConstantOperandVal(9);
7134 
7135     unsigned OrderedCountIndex = IndexOperand & 0x3f;
7136     IndexOperand &= ~0x3f;
7137     unsigned CountDw = 0;
7138 
7139     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
7140       CountDw = (IndexOperand >> 24) & 0xf;
7141       IndexOperand &= ~(0xf << 24);
7142 
7143       if (CountDw < 1 || CountDw > 4) {
7144         report_fatal_error(
7145             "ds_ordered_count: dword count must be between 1 and 4");
7146       }
7147     }
7148 
7149     if (IndexOperand)
7150       report_fatal_error("ds_ordered_count: bad index operand");
7151 
7152     if (WaveDone && !WaveRelease)
7153       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
7154 
7155     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
7156     unsigned ShaderType =
7157         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
7158     unsigned Offset0 = OrderedCountIndex << 2;
7159     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
7160                        (Instruction << 4);
7161 
7162     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
7163       Offset1 |= (CountDw - 1) << 6;
7164 
7165     unsigned Offset = Offset0 | (Offset1 << 8);
7166 
7167     SDValue Ops[] = {
7168       Chain,
7169       Value,
7170       DAG.getTargetConstant(Offset, DL, MVT::i16),
7171       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
7172     };
7173     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
7174                                    M->getVTList(), Ops, M->getMemoryVT(),
7175                                    M->getMemOperand());
7176   }
7177   case Intrinsic::amdgcn_ds_fadd: {
7178     MemSDNode *M = cast<MemSDNode>(Op);
7179     unsigned Opc;
7180     switch (IntrID) {
7181     case Intrinsic::amdgcn_ds_fadd:
7182       Opc = ISD::ATOMIC_LOAD_FADD;
7183       break;
7184     }
7185 
7186     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
7187                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
7188                          M->getMemOperand());
7189   }
7190   case Intrinsic::amdgcn_atomic_inc:
7191   case Intrinsic::amdgcn_atomic_dec:
7192   case Intrinsic::amdgcn_ds_fmin:
7193   case Intrinsic::amdgcn_ds_fmax: {
7194     MemSDNode *M = cast<MemSDNode>(Op);
7195     unsigned Opc;
7196     switch (IntrID) {
7197     case Intrinsic::amdgcn_atomic_inc:
7198       Opc = AMDGPUISD::ATOMIC_INC;
7199       break;
7200     case Intrinsic::amdgcn_atomic_dec:
7201       Opc = AMDGPUISD::ATOMIC_DEC;
7202       break;
7203     case Intrinsic::amdgcn_ds_fmin:
7204       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
7205       break;
7206     case Intrinsic::amdgcn_ds_fmax:
7207       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
7208       break;
7209     default:
7210       llvm_unreachable("Unknown intrinsic!");
7211     }
7212     SDValue Ops[] = {
7213       M->getOperand(0), // Chain
7214       M->getOperand(2), // Ptr
7215       M->getOperand(3)  // Value
7216     };
7217 
7218     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
7219                                    M->getMemoryVT(), M->getMemOperand());
7220   }
7221   case Intrinsic::amdgcn_buffer_load:
7222   case Intrinsic::amdgcn_buffer_load_format: {
7223     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
7224     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7225     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7226     SDValue Ops[] = {
7227       Op.getOperand(0), // Chain
7228       Op.getOperand(2), // rsrc
7229       Op.getOperand(3), // vindex
7230       SDValue(),        // voffset -- will be set by setBufferOffsets
7231       SDValue(),        // soffset -- will be set by setBufferOffsets
7232       SDValue(),        // offset -- will be set by setBufferOffsets
7233       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7234       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7235     };
7236     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
7237 
7238     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
7239         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
7240 
7241     EVT VT = Op.getValueType();
7242     EVT IntVT = VT.changeTypeToInteger();
7243     auto *M = cast<MemSDNode>(Op);
7244     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7245     EVT LoadVT = Op.getValueType();
7246 
7247     if (LoadVT.getScalarType() == MVT::f16)
7248       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
7249                                  M, DAG, Ops);
7250 
7251     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
7252     if (LoadVT.getScalarType() == MVT::i8 ||
7253         LoadVT.getScalarType() == MVT::i16)
7254       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
7255 
7256     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
7257                                M->getMemOperand(), DAG);
7258   }
7259   case Intrinsic::amdgcn_raw_buffer_load:
7260   case Intrinsic::amdgcn_raw_buffer_load_format: {
7261     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
7262 
7263     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7264     SDValue Ops[] = {
7265       Op.getOperand(0), // Chain
7266       Op.getOperand(2), // rsrc
7267       DAG.getConstant(0, DL, MVT::i32), // vindex
7268       Offsets.first,    // voffset
7269       Op.getOperand(4), // soffset
7270       Offsets.second,   // offset
7271       Op.getOperand(5), // cachepolicy, swizzled buffer
7272       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7273     };
7274 
7275     auto *M = cast<MemSDNode>(Op);
7276     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]);
7277     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
7278   }
7279   case Intrinsic::amdgcn_struct_buffer_load:
7280   case Intrinsic::amdgcn_struct_buffer_load_format: {
7281     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
7282 
7283     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7284     SDValue Ops[] = {
7285       Op.getOperand(0), // Chain
7286       Op.getOperand(2), // rsrc
7287       Op.getOperand(3), // vindex
7288       Offsets.first,    // voffset
7289       Op.getOperand(5), // soffset
7290       Offsets.second,   // offset
7291       Op.getOperand(6), // cachepolicy, swizzled buffer
7292       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7293     };
7294 
7295     auto *M = cast<MemSDNode>(Op);
7296     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7297     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7298   }
7299   case Intrinsic::amdgcn_tbuffer_load: {
7300     MemSDNode *M = cast<MemSDNode>(Op);
7301     EVT LoadVT = Op.getValueType();
7302 
7303     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7304     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7305     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7306     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7307     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7308     SDValue Ops[] = {
7309       Op.getOperand(0),  // Chain
7310       Op.getOperand(2),  // rsrc
7311       Op.getOperand(3),  // vindex
7312       Op.getOperand(4),  // voffset
7313       Op.getOperand(5),  // soffset
7314       Op.getOperand(6),  // offset
7315       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7316       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7317       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7318     };
7319 
7320     if (LoadVT.getScalarType() == MVT::f16)
7321       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7322                                  M, DAG, Ops);
7323     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7324                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7325                                DAG);
7326   }
7327   case Intrinsic::amdgcn_raw_tbuffer_load: {
7328     MemSDNode *M = cast<MemSDNode>(Op);
7329     EVT LoadVT = Op.getValueType();
7330     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7331 
7332     SDValue Ops[] = {
7333       Op.getOperand(0),  // Chain
7334       Op.getOperand(2),  // rsrc
7335       DAG.getConstant(0, DL, MVT::i32), // vindex
7336       Offsets.first,     // voffset
7337       Op.getOperand(4),  // soffset
7338       Offsets.second,    // offset
7339       Op.getOperand(5),  // format
7340       Op.getOperand(6),  // cachepolicy, swizzled buffer
7341       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7342     };
7343 
7344     if (LoadVT.getScalarType() == MVT::f16)
7345       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7346                                  M, DAG, Ops);
7347     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7348                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7349                                DAG);
7350   }
7351   case Intrinsic::amdgcn_struct_tbuffer_load: {
7352     MemSDNode *M = cast<MemSDNode>(Op);
7353     EVT LoadVT = Op.getValueType();
7354     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7355 
7356     SDValue Ops[] = {
7357       Op.getOperand(0),  // Chain
7358       Op.getOperand(2),  // rsrc
7359       Op.getOperand(3),  // vindex
7360       Offsets.first,     // voffset
7361       Op.getOperand(5),  // soffset
7362       Offsets.second,    // offset
7363       Op.getOperand(6),  // format
7364       Op.getOperand(7),  // cachepolicy, swizzled buffer
7365       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7366     };
7367 
7368     if (LoadVT.getScalarType() == MVT::f16)
7369       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7370                                  M, DAG, Ops);
7371     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7372                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7373                                DAG);
7374   }
7375   case Intrinsic::amdgcn_buffer_atomic_swap:
7376   case Intrinsic::amdgcn_buffer_atomic_add:
7377   case Intrinsic::amdgcn_buffer_atomic_sub:
7378   case Intrinsic::amdgcn_buffer_atomic_csub:
7379   case Intrinsic::amdgcn_buffer_atomic_smin:
7380   case Intrinsic::amdgcn_buffer_atomic_umin:
7381   case Intrinsic::amdgcn_buffer_atomic_smax:
7382   case Intrinsic::amdgcn_buffer_atomic_umax:
7383   case Intrinsic::amdgcn_buffer_atomic_and:
7384   case Intrinsic::amdgcn_buffer_atomic_or:
7385   case Intrinsic::amdgcn_buffer_atomic_xor:
7386   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7387     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7388     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7389     SDValue Ops[] = {
7390       Op.getOperand(0), // Chain
7391       Op.getOperand(2), // vdata
7392       Op.getOperand(3), // rsrc
7393       Op.getOperand(4), // vindex
7394       SDValue(),        // voffset -- will be set by setBufferOffsets
7395       SDValue(),        // soffset -- will be set by setBufferOffsets
7396       SDValue(),        // offset -- will be set by setBufferOffsets
7397       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7398       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7399     };
7400     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7401 
7402     EVT VT = Op.getValueType();
7403 
7404     auto *M = cast<MemSDNode>(Op);
7405     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7406     unsigned Opcode = 0;
7407 
7408     switch (IntrID) {
7409     case Intrinsic::amdgcn_buffer_atomic_swap:
7410       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7411       break;
7412     case Intrinsic::amdgcn_buffer_atomic_add:
7413       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7414       break;
7415     case Intrinsic::amdgcn_buffer_atomic_sub:
7416       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7417       break;
7418     case Intrinsic::amdgcn_buffer_atomic_csub:
7419       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7420       break;
7421     case Intrinsic::amdgcn_buffer_atomic_smin:
7422       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7423       break;
7424     case Intrinsic::amdgcn_buffer_atomic_umin:
7425       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7426       break;
7427     case Intrinsic::amdgcn_buffer_atomic_smax:
7428       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7429       break;
7430     case Intrinsic::amdgcn_buffer_atomic_umax:
7431       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7432       break;
7433     case Intrinsic::amdgcn_buffer_atomic_and:
7434       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7435       break;
7436     case Intrinsic::amdgcn_buffer_atomic_or:
7437       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7438       break;
7439     case Intrinsic::amdgcn_buffer_atomic_xor:
7440       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7441       break;
7442     case Intrinsic::amdgcn_buffer_atomic_fadd:
7443       if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7444         DiagnosticInfoUnsupported
7445           NoFpRet(DAG.getMachineFunction().getFunction(),
7446                   "return versions of fp atomics not supported",
7447                   DL.getDebugLoc(), DS_Error);
7448         DAG.getContext()->diagnose(NoFpRet);
7449         return SDValue();
7450       }
7451       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7452       break;
7453     default:
7454       llvm_unreachable("unhandled atomic opcode");
7455     }
7456 
7457     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7458                                    M->getMemOperand());
7459   }
7460   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7461     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7462   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7463     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7464   case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7465     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7466   case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7467     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7468   case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7469     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7470   case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7471     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7472   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7473     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7474   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7475     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7476   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7477     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7478   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7479     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7480   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7481     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7482   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7483     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7484   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7485     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7486   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7487     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7488   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7489     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7490   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7491     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7492   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7493     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7494   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7495     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7496   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7497     return lowerStructBufferAtomicIntrin(Op, DAG,
7498                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7499   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7500     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7501   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7502     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7503   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7504     return lowerStructBufferAtomicIntrin(Op, DAG,
7505                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7506   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7507     return lowerStructBufferAtomicIntrin(Op, DAG,
7508                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7509   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7510     return lowerStructBufferAtomicIntrin(Op, DAG,
7511                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7512   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7513     return lowerStructBufferAtomicIntrin(Op, DAG,
7514                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7515   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7516     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7517   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7518     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7519   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7520     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7521   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7522     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7523   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7524     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7525 
7526   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7527     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7528     unsigned IdxEn = getIdxEn(Op.getOperand(5));
7529     SDValue Ops[] = {
7530       Op.getOperand(0), // Chain
7531       Op.getOperand(2), // src
7532       Op.getOperand(3), // cmp
7533       Op.getOperand(4), // rsrc
7534       Op.getOperand(5), // vindex
7535       SDValue(),        // voffset -- will be set by setBufferOffsets
7536       SDValue(),        // soffset -- will be set by setBufferOffsets
7537       SDValue(),        // offset -- will be set by setBufferOffsets
7538       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7539       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7540     };
7541     setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7542 
7543     EVT VT = Op.getValueType();
7544     auto *M = cast<MemSDNode>(Op);
7545     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7546 
7547     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7548                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7549   }
7550   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7551     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7552     SDValue Ops[] = {
7553       Op.getOperand(0), // Chain
7554       Op.getOperand(2), // src
7555       Op.getOperand(3), // cmp
7556       Op.getOperand(4), // rsrc
7557       DAG.getConstant(0, DL, MVT::i32), // vindex
7558       Offsets.first,    // voffset
7559       Op.getOperand(6), // soffset
7560       Offsets.second,   // offset
7561       Op.getOperand(7), // cachepolicy
7562       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7563     };
7564     EVT VT = Op.getValueType();
7565     auto *M = cast<MemSDNode>(Op);
7566     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]);
7567 
7568     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7569                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7570   }
7571   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7572     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7573     SDValue Ops[] = {
7574       Op.getOperand(0), // Chain
7575       Op.getOperand(2), // src
7576       Op.getOperand(3), // cmp
7577       Op.getOperand(4), // rsrc
7578       Op.getOperand(5), // vindex
7579       Offsets.first,    // voffset
7580       Op.getOperand(7), // soffset
7581       Offsets.second,   // offset
7582       Op.getOperand(8), // cachepolicy
7583       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7584     };
7585     EVT VT = Op.getValueType();
7586     auto *M = cast<MemSDNode>(Op);
7587     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7588 
7589     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7590                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7591   }
7592   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7593     MemSDNode *M = cast<MemSDNode>(Op);
7594     SDValue NodePtr = M->getOperand(2);
7595     SDValue RayExtent = M->getOperand(3);
7596     SDValue RayOrigin = M->getOperand(4);
7597     SDValue RayDir = M->getOperand(5);
7598     SDValue RayInvDir = M->getOperand(6);
7599     SDValue TDescr = M->getOperand(7);
7600 
7601     assert(NodePtr.getValueType() == MVT::i32 ||
7602            NodePtr.getValueType() == MVT::i64);
7603     assert(RayDir.getValueType() == MVT::v3f16 ||
7604            RayDir.getValueType() == MVT::v3f32);
7605 
7606     if (!Subtarget->hasGFX10_AEncoding()) {
7607       emitRemovedIntrinsicError(DAG, DL, Op.getValueType());
7608       return SDValue();
7609     }
7610 
7611     const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7612     const bool Is64 = NodePtr.getValueType() == MVT::i64;
7613     const unsigned NumVDataDwords = 4;
7614     const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
7615     const bool UseNSA = Subtarget->hasNSAEncoding() &&
7616                         NumVAddrDwords <= Subtarget->getNSAMaxSize();
7617     const unsigned BaseOpcodes[2][2] = {
7618         {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
7619         {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
7620          AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
7621     int Opcode;
7622     if (UseNSA) {
7623       Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7624                                      AMDGPU::MIMGEncGfx10NSA, NumVDataDwords,
7625                                      NumVAddrDwords);
7626     } else {
7627       Opcode = AMDGPU::getMIMGOpcode(
7628           BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords,
7629           PowerOf2Ceil(NumVAddrDwords));
7630     }
7631     assert(Opcode != -1);
7632 
7633     SmallVector<SDValue, 16> Ops;
7634 
7635     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7636       SmallVector<SDValue, 3> Lanes;
7637       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7638       if (Lanes[0].getValueSizeInBits() == 32) {
7639         for (unsigned I = 0; I < 3; ++I)
7640           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7641       } else {
7642         if (IsAligned) {
7643           Ops.push_back(
7644             DAG.getBitcast(MVT::i32,
7645                            DAG.getBuildVector(MVT::v2f16, DL,
7646                                               { Lanes[0], Lanes[1] })));
7647           Ops.push_back(Lanes[2]);
7648         } else {
7649           SDValue Elt0 = Ops.pop_back_val();
7650           Ops.push_back(
7651             DAG.getBitcast(MVT::i32,
7652                            DAG.getBuildVector(MVT::v2f16, DL,
7653                                               { Elt0, Lanes[0] })));
7654           Ops.push_back(
7655             DAG.getBitcast(MVT::i32,
7656                            DAG.getBuildVector(MVT::v2f16, DL,
7657                                               { Lanes[1], Lanes[2] })));
7658         }
7659       }
7660     };
7661 
7662     if (Is64)
7663       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7664     else
7665       Ops.push_back(NodePtr);
7666 
7667     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7668     packLanes(RayOrigin, true);
7669     packLanes(RayDir, true);
7670     packLanes(RayInvDir, false);
7671 
7672     if (!UseNSA) {
7673       // Build a single vector containing all the operands so far prepared.
7674       if (NumVAddrDwords > 8) {
7675         SDValue Undef = DAG.getUNDEF(MVT::i32);
7676         Ops.append(16 - Ops.size(), Undef);
7677       }
7678       assert(Ops.size() == 8 || Ops.size() == 16);
7679       SDValue MergedOps = DAG.getBuildVector(
7680           Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops);
7681       Ops.clear();
7682       Ops.push_back(MergedOps);
7683     }
7684 
7685     Ops.push_back(TDescr);
7686     if (IsA16)
7687       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7688     Ops.push_back(M->getChain());
7689 
7690     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7691     MachineMemOperand *MemRef = M->getMemOperand();
7692     DAG.setNodeMemRefs(NewNode, {MemRef});
7693     return SDValue(NewNode, 0);
7694   }
7695   case Intrinsic::amdgcn_global_atomic_fadd:
7696     if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7697       DiagnosticInfoUnsupported
7698         NoFpRet(DAG.getMachineFunction().getFunction(),
7699                 "return versions of fp atomics not supported",
7700                 DL.getDebugLoc(), DS_Error);
7701       DAG.getContext()->diagnose(NoFpRet);
7702       return SDValue();
7703     }
7704     LLVM_FALLTHROUGH;
7705   case Intrinsic::amdgcn_global_atomic_fmin:
7706   case Intrinsic::amdgcn_global_atomic_fmax:
7707   case Intrinsic::amdgcn_flat_atomic_fadd:
7708   case Intrinsic::amdgcn_flat_atomic_fmin:
7709   case Intrinsic::amdgcn_flat_atomic_fmax: {
7710     MemSDNode *M = cast<MemSDNode>(Op);
7711     SDValue Ops[] = {
7712       M->getOperand(0), // Chain
7713       M->getOperand(2), // Ptr
7714       M->getOperand(3)  // Value
7715     };
7716     unsigned Opcode = 0;
7717     switch (IntrID) {
7718     case Intrinsic::amdgcn_global_atomic_fadd:
7719     case Intrinsic::amdgcn_flat_atomic_fadd: {
7720       EVT VT = Op.getOperand(3).getValueType();
7721       return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7722                            DAG.getVTList(VT, MVT::Other), Ops,
7723                            M->getMemOperand());
7724     }
7725     case Intrinsic::amdgcn_global_atomic_fmin:
7726     case Intrinsic::amdgcn_flat_atomic_fmin: {
7727       Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7728       break;
7729     }
7730     case Intrinsic::amdgcn_global_atomic_fmax:
7731     case Intrinsic::amdgcn_flat_atomic_fmax: {
7732       Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7733       break;
7734     }
7735     default:
7736       llvm_unreachable("unhandled atomic opcode");
7737     }
7738     return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7739                                    M->getVTList(), Ops, M->getMemoryVT(),
7740                                    M->getMemOperand());
7741   }
7742   default:
7743 
7744     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7745             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7746       return lowerImage(Op, ImageDimIntr, DAG, true);
7747 
7748     return SDValue();
7749   }
7750 }
7751 
7752 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7753 // dwordx4 if on SI.
7754 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7755                                               SDVTList VTList,
7756                                               ArrayRef<SDValue> Ops, EVT MemVT,
7757                                               MachineMemOperand *MMO,
7758                                               SelectionDAG &DAG) const {
7759   EVT VT = VTList.VTs[0];
7760   EVT WidenedVT = VT;
7761   EVT WidenedMemVT = MemVT;
7762   if (!Subtarget->hasDwordx3LoadStores() &&
7763       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7764     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7765                                  WidenedVT.getVectorElementType(), 4);
7766     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7767                                     WidenedMemVT.getVectorElementType(), 4);
7768     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7769   }
7770 
7771   assert(VTList.NumVTs == 2);
7772   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7773 
7774   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7775                                        WidenedMemVT, MMO);
7776   if (WidenedVT != VT) {
7777     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7778                                DAG.getVectorIdxConstant(0, DL));
7779     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7780   }
7781   return NewOp;
7782 }
7783 
7784 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7785                                          bool ImageStore) const {
7786   EVT StoreVT = VData.getValueType();
7787 
7788   // No change for f16 and legal vector D16 types.
7789   if (!StoreVT.isVector())
7790     return VData;
7791 
7792   SDLoc DL(VData);
7793   unsigned NumElements = StoreVT.getVectorNumElements();
7794 
7795   if (Subtarget->hasUnpackedD16VMem()) {
7796     // We need to unpack the packed data to store.
7797     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7798     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7799 
7800     EVT EquivStoreVT =
7801         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7802     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7803     return DAG.UnrollVectorOp(ZExt.getNode());
7804   }
7805 
7806   // The sq block of gfx8.1 does not estimate register use correctly for d16
7807   // image store instructions. The data operand is computed as if it were not a
7808   // d16 image instruction.
7809   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7810     // Bitcast to i16
7811     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7812     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7813 
7814     // Decompose into scalars
7815     SmallVector<SDValue, 4> Elts;
7816     DAG.ExtractVectorElements(IntVData, Elts);
7817 
7818     // Group pairs of i16 into v2i16 and bitcast to i32
7819     SmallVector<SDValue, 4> PackedElts;
7820     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7821       SDValue Pair =
7822           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7823       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7824       PackedElts.push_back(IntPair);
7825     }
7826     if ((NumElements % 2) == 1) {
7827       // Handle v3i16
7828       unsigned I = Elts.size() / 2;
7829       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7830                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7831       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7832       PackedElts.push_back(IntPair);
7833     }
7834 
7835     // Pad using UNDEF
7836     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7837 
7838     // Build final vector
7839     EVT VecVT =
7840         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7841     return DAG.getBuildVector(VecVT, DL, PackedElts);
7842   }
7843 
7844   if (NumElements == 3) {
7845     EVT IntStoreVT =
7846         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7847     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7848 
7849     EVT WidenedStoreVT = EVT::getVectorVT(
7850         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7851     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7852                                          WidenedStoreVT.getStoreSizeInBits());
7853     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7854     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7855   }
7856 
7857   assert(isTypeLegal(StoreVT));
7858   return VData;
7859 }
7860 
7861 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7862                                               SelectionDAG &DAG) const {
7863   SDLoc DL(Op);
7864   SDValue Chain = Op.getOperand(0);
7865   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7866   MachineFunction &MF = DAG.getMachineFunction();
7867 
7868   switch (IntrinsicID) {
7869   case Intrinsic::amdgcn_exp_compr: {
7870     SDValue Src0 = Op.getOperand(4);
7871     SDValue Src1 = Op.getOperand(5);
7872     // Hack around illegal type on SI by directly selecting it.
7873     if (isTypeLegal(Src0.getValueType()))
7874       return SDValue();
7875 
7876     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7877     SDValue Undef = DAG.getUNDEF(MVT::f32);
7878     const SDValue Ops[] = {
7879       Op.getOperand(2), // tgt
7880       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7881       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7882       Undef, // src2
7883       Undef, // src3
7884       Op.getOperand(7), // vm
7885       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7886       Op.getOperand(3), // en
7887       Op.getOperand(0) // Chain
7888     };
7889 
7890     unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7891     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7892   }
7893   case Intrinsic::amdgcn_s_barrier: {
7894     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7895       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7896       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7897       if (WGSize <= ST.getWavefrontSize())
7898         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7899                                           Op.getOperand(0)), 0);
7900     }
7901     return SDValue();
7902   };
7903   case Intrinsic::amdgcn_tbuffer_store: {
7904     SDValue VData = Op.getOperand(2);
7905     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7906     if (IsD16)
7907       VData = handleD16VData(VData, DAG);
7908     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7909     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7910     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7911     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7912     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7913     SDValue Ops[] = {
7914       Chain,
7915       VData,             // vdata
7916       Op.getOperand(3),  // rsrc
7917       Op.getOperand(4),  // vindex
7918       Op.getOperand(5),  // voffset
7919       Op.getOperand(6),  // soffset
7920       Op.getOperand(7),  // offset
7921       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7922       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7923       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7924     };
7925     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7926                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7927     MemSDNode *M = cast<MemSDNode>(Op);
7928     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7929                                    M->getMemoryVT(), M->getMemOperand());
7930   }
7931 
7932   case Intrinsic::amdgcn_struct_tbuffer_store: {
7933     SDValue VData = Op.getOperand(2);
7934     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7935     if (IsD16)
7936       VData = handleD16VData(VData, DAG);
7937     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7938     SDValue Ops[] = {
7939       Chain,
7940       VData,             // vdata
7941       Op.getOperand(3),  // rsrc
7942       Op.getOperand(4),  // vindex
7943       Offsets.first,     // voffset
7944       Op.getOperand(6),  // soffset
7945       Offsets.second,    // offset
7946       Op.getOperand(7),  // format
7947       Op.getOperand(8),  // cachepolicy, swizzled buffer
7948       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7949     };
7950     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7951                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7952     MemSDNode *M = cast<MemSDNode>(Op);
7953     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7954                                    M->getMemoryVT(), M->getMemOperand());
7955   }
7956 
7957   case Intrinsic::amdgcn_raw_tbuffer_store: {
7958     SDValue VData = Op.getOperand(2);
7959     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7960     if (IsD16)
7961       VData = handleD16VData(VData, DAG);
7962     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7963     SDValue Ops[] = {
7964       Chain,
7965       VData,             // vdata
7966       Op.getOperand(3),  // rsrc
7967       DAG.getConstant(0, DL, MVT::i32), // vindex
7968       Offsets.first,     // voffset
7969       Op.getOperand(5),  // soffset
7970       Offsets.second,    // offset
7971       Op.getOperand(6),  // format
7972       Op.getOperand(7),  // cachepolicy, swizzled buffer
7973       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7974     };
7975     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7976                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7977     MemSDNode *M = cast<MemSDNode>(Op);
7978     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7979                                    M->getMemoryVT(), M->getMemOperand());
7980   }
7981 
7982   case Intrinsic::amdgcn_buffer_store:
7983   case Intrinsic::amdgcn_buffer_store_format: {
7984     SDValue VData = Op.getOperand(2);
7985     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7986     if (IsD16)
7987       VData = handleD16VData(VData, DAG);
7988     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7989     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7990     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7991     SDValue Ops[] = {
7992       Chain,
7993       VData,
7994       Op.getOperand(3), // rsrc
7995       Op.getOperand(4), // vindex
7996       SDValue(), // voffset -- will be set by setBufferOffsets
7997       SDValue(), // soffset -- will be set by setBufferOffsets
7998       SDValue(), // offset -- will be set by setBufferOffsets
7999       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
8000       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
8001     };
8002     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
8003 
8004     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
8005                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8006     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8007     MemSDNode *M = cast<MemSDNode>(Op);
8008     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8009 
8010     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8011     EVT VDataType = VData.getValueType().getScalarType();
8012     if (VDataType == MVT::i8 || VDataType == MVT::i16)
8013       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8014 
8015     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8016                                    M->getMemoryVT(), M->getMemOperand());
8017   }
8018 
8019   case Intrinsic::amdgcn_raw_buffer_store:
8020   case Intrinsic::amdgcn_raw_buffer_store_format: {
8021     const bool IsFormat =
8022         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
8023 
8024     SDValue VData = Op.getOperand(2);
8025     EVT VDataVT = VData.getValueType();
8026     EVT EltType = VDataVT.getScalarType();
8027     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8028     if (IsD16) {
8029       VData = handleD16VData(VData, DAG);
8030       VDataVT = VData.getValueType();
8031     }
8032 
8033     if (!isTypeLegal(VDataVT)) {
8034       VData =
8035           DAG.getNode(ISD::BITCAST, DL,
8036                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8037     }
8038 
8039     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
8040     SDValue Ops[] = {
8041       Chain,
8042       VData,
8043       Op.getOperand(3), // rsrc
8044       DAG.getConstant(0, DL, MVT::i32), // vindex
8045       Offsets.first,    // voffset
8046       Op.getOperand(5), // soffset
8047       Offsets.second,   // offset
8048       Op.getOperand(6), // cachepolicy, swizzled buffer
8049       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8050     };
8051     unsigned Opc =
8052         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
8053     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8054     MemSDNode *M = cast<MemSDNode>(Op);
8055     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
8056 
8057     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8058     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8059       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
8060 
8061     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8062                                    M->getMemoryVT(), M->getMemOperand());
8063   }
8064 
8065   case Intrinsic::amdgcn_struct_buffer_store:
8066   case Intrinsic::amdgcn_struct_buffer_store_format: {
8067     const bool IsFormat =
8068         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
8069 
8070     SDValue VData = Op.getOperand(2);
8071     EVT VDataVT = VData.getValueType();
8072     EVT EltType = VDataVT.getScalarType();
8073     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8074 
8075     if (IsD16) {
8076       VData = handleD16VData(VData, DAG);
8077       VDataVT = VData.getValueType();
8078     }
8079 
8080     if (!isTypeLegal(VDataVT)) {
8081       VData =
8082           DAG.getNode(ISD::BITCAST, DL,
8083                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8084     }
8085 
8086     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
8087     SDValue Ops[] = {
8088       Chain,
8089       VData,
8090       Op.getOperand(3), // rsrc
8091       Op.getOperand(4), // vindex
8092       Offsets.first,    // voffset
8093       Op.getOperand(6), // soffset
8094       Offsets.second,   // offset
8095       Op.getOperand(7), // cachepolicy, swizzled buffer
8096       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8097     };
8098     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
8099                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8100     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8101     MemSDNode *M = cast<MemSDNode>(Op);
8102     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8103 
8104     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8105     EVT VDataType = VData.getValueType().getScalarType();
8106     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8107       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8108 
8109     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8110                                    M->getMemoryVT(), M->getMemOperand());
8111   }
8112   case Intrinsic::amdgcn_end_cf:
8113     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
8114                                       Op->getOperand(2), Chain), 0);
8115 
8116   default: {
8117     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
8118             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
8119       return lowerImage(Op, ImageDimIntr, DAG, true);
8120 
8121     return Op;
8122   }
8123   }
8124 }
8125 
8126 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
8127 // offset (the offset that is included in bounds checking and swizzling, to be
8128 // split between the instruction's voffset and immoffset fields) and soffset
8129 // (the offset that is excluded from bounds checking and swizzling, to go in
8130 // the instruction's soffset field).  This function takes the first kind of
8131 // offset and figures out how to split it between voffset and immoffset.
8132 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
8133     SDValue Offset, SelectionDAG &DAG) const {
8134   SDLoc DL(Offset);
8135   const unsigned MaxImm = 4095;
8136   SDValue N0 = Offset;
8137   ConstantSDNode *C1 = nullptr;
8138 
8139   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
8140     N0 = SDValue();
8141   else if (DAG.isBaseWithConstantOffset(N0)) {
8142     C1 = cast<ConstantSDNode>(N0.getOperand(1));
8143     N0 = N0.getOperand(0);
8144   }
8145 
8146   if (C1) {
8147     unsigned ImmOffset = C1->getZExtValue();
8148     // If the immediate value is too big for the immoffset field, put the value
8149     // and -4096 into the immoffset field so that the value that is copied/added
8150     // for the voffset field is a multiple of 4096, and it stands more chance
8151     // of being CSEd with the copy/add for another similar load/store.
8152     // However, do not do that rounding down to a multiple of 4096 if that is a
8153     // negative number, as it appears to be illegal to have a negative offset
8154     // in the vgpr, even if adding the immediate offset makes it positive.
8155     unsigned Overflow = ImmOffset & ~MaxImm;
8156     ImmOffset -= Overflow;
8157     if ((int32_t)Overflow < 0) {
8158       Overflow += ImmOffset;
8159       ImmOffset = 0;
8160     }
8161     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
8162     if (Overflow) {
8163       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
8164       if (!N0)
8165         N0 = OverflowVal;
8166       else {
8167         SDValue Ops[] = { N0, OverflowVal };
8168         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
8169       }
8170     }
8171   }
8172   if (!N0)
8173     N0 = DAG.getConstant(0, DL, MVT::i32);
8174   if (!C1)
8175     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
8176   return {N0, SDValue(C1, 0)};
8177 }
8178 
8179 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
8180 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
8181 // pointed to by Offsets.
8182 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
8183                                         SelectionDAG &DAG, SDValue *Offsets,
8184                                         Align Alignment) const {
8185   SDLoc DL(CombinedOffset);
8186   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
8187     uint32_t Imm = C->getZExtValue();
8188     uint32_t SOffset, ImmOffset;
8189     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
8190                                  Alignment)) {
8191       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
8192       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8193       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8194       return;
8195     }
8196   }
8197   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
8198     SDValue N0 = CombinedOffset.getOperand(0);
8199     SDValue N1 = CombinedOffset.getOperand(1);
8200     uint32_t SOffset, ImmOffset;
8201     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
8202     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
8203                                                 Subtarget, Alignment)) {
8204       Offsets[0] = N0;
8205       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8206       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8207       return;
8208     }
8209   }
8210   Offsets[0] = CombinedOffset;
8211   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
8212   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
8213 }
8214 
8215 // Handle 8 bit and 16 bit buffer loads
8216 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
8217                                                      EVT LoadVT, SDLoc DL,
8218                                                      ArrayRef<SDValue> Ops,
8219                                                      MemSDNode *M) const {
8220   EVT IntVT = LoadVT.changeTypeToInteger();
8221   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
8222          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
8223 
8224   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
8225   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
8226                                                Ops, IntVT,
8227                                                M->getMemOperand());
8228   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
8229   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
8230 
8231   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
8232 }
8233 
8234 // Handle 8 bit and 16 bit buffer stores
8235 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
8236                                                       EVT VDataType, SDLoc DL,
8237                                                       SDValue Ops[],
8238                                                       MemSDNode *M) const {
8239   if (VDataType == MVT::f16)
8240     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
8241 
8242   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
8243   Ops[1] = BufferStoreExt;
8244   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
8245                                  AMDGPUISD::BUFFER_STORE_SHORT;
8246   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
8247   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
8248                                      M->getMemOperand());
8249 }
8250 
8251 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
8252                                  ISD::LoadExtType ExtType, SDValue Op,
8253                                  const SDLoc &SL, EVT VT) {
8254   if (VT.bitsLT(Op.getValueType()))
8255     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
8256 
8257   switch (ExtType) {
8258   case ISD::SEXTLOAD:
8259     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
8260   case ISD::ZEXTLOAD:
8261     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
8262   case ISD::EXTLOAD:
8263     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
8264   case ISD::NON_EXTLOAD:
8265     return Op;
8266   }
8267 
8268   llvm_unreachable("invalid ext type");
8269 }
8270 
8271 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
8272   SelectionDAG &DAG = DCI.DAG;
8273   if (Ld->getAlignment() < 4 || Ld->isDivergent())
8274     return SDValue();
8275 
8276   // FIXME: Constant loads should all be marked invariant.
8277   unsigned AS = Ld->getAddressSpace();
8278   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
8279       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
8280       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
8281     return SDValue();
8282 
8283   // Don't do this early, since it may interfere with adjacent load merging for
8284   // illegal types. We can avoid losing alignment information for exotic types
8285   // pre-legalize.
8286   EVT MemVT = Ld->getMemoryVT();
8287   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
8288       MemVT.getSizeInBits() >= 32)
8289     return SDValue();
8290 
8291   SDLoc SL(Ld);
8292 
8293   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
8294          "unexpected vector extload");
8295 
8296   // TODO: Drop only high part of range.
8297   SDValue Ptr = Ld->getBasePtr();
8298   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
8299                                 MVT::i32, SL, Ld->getChain(), Ptr,
8300                                 Ld->getOffset(),
8301                                 Ld->getPointerInfo(), MVT::i32,
8302                                 Ld->getAlignment(),
8303                                 Ld->getMemOperand()->getFlags(),
8304                                 Ld->getAAInfo(),
8305                                 nullptr); // Drop ranges
8306 
8307   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
8308   if (MemVT.isFloatingPoint()) {
8309     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
8310            "unexpected fp extload");
8311     TruncVT = MemVT.changeTypeToInteger();
8312   }
8313 
8314   SDValue Cvt = NewLoad;
8315   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
8316     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
8317                       DAG.getValueType(TruncVT));
8318   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
8319              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
8320     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
8321   } else {
8322     assert(Ld->getExtensionType() == ISD::EXTLOAD);
8323   }
8324 
8325   EVT VT = Ld->getValueType(0);
8326   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8327 
8328   DCI.AddToWorklist(Cvt.getNode());
8329 
8330   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
8331   // the appropriate extension from the 32-bit load.
8332   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
8333   DCI.AddToWorklist(Cvt.getNode());
8334 
8335   // Handle conversion back to floating point if necessary.
8336   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8337 
8338   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8339 }
8340 
8341 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8342   SDLoc DL(Op);
8343   LoadSDNode *Load = cast<LoadSDNode>(Op);
8344   ISD::LoadExtType ExtType = Load->getExtensionType();
8345   EVT MemVT = Load->getMemoryVT();
8346 
8347   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8348     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8349       return SDValue();
8350 
8351     // FIXME: Copied from PPC
8352     // First, load into 32 bits, then truncate to 1 bit.
8353 
8354     SDValue Chain = Load->getChain();
8355     SDValue BasePtr = Load->getBasePtr();
8356     MachineMemOperand *MMO = Load->getMemOperand();
8357 
8358     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8359 
8360     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8361                                    BasePtr, RealMemVT, MMO);
8362 
8363     if (!MemVT.isVector()) {
8364       SDValue Ops[] = {
8365         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8366         NewLD.getValue(1)
8367       };
8368 
8369       return DAG.getMergeValues(Ops, DL);
8370     }
8371 
8372     SmallVector<SDValue, 3> Elts;
8373     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8374       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8375                                 DAG.getConstant(I, DL, MVT::i32));
8376 
8377       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8378     }
8379 
8380     SDValue Ops[] = {
8381       DAG.getBuildVector(MemVT, DL, Elts),
8382       NewLD.getValue(1)
8383     };
8384 
8385     return DAG.getMergeValues(Ops, DL);
8386   }
8387 
8388   if (!MemVT.isVector())
8389     return SDValue();
8390 
8391   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8392          "Custom lowering for non-i32 vectors hasn't been implemented.");
8393 
8394   unsigned Alignment = Load->getAlignment();
8395   unsigned AS = Load->getAddressSpace();
8396   if (Subtarget->hasLDSMisalignedBug() &&
8397       AS == AMDGPUAS::FLAT_ADDRESS &&
8398       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8399     return SplitVectorLoad(Op, DAG);
8400   }
8401 
8402   MachineFunction &MF = DAG.getMachineFunction();
8403   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8404   // If there is a possibilty that flat instruction access scratch memory
8405   // then we need to use the same legalization rules we use for private.
8406   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8407       !Subtarget->hasMultiDwordFlatScratchAddressing())
8408     AS = MFI->hasFlatScratchInit() ?
8409          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8410 
8411   unsigned NumElements = MemVT.getVectorNumElements();
8412 
8413   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8414       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8415     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8416       if (MemVT.isPow2VectorType())
8417         return SDValue();
8418       return WidenOrSplitVectorLoad(Op, DAG);
8419     }
8420     // Non-uniform loads will be selected to MUBUF instructions, so they
8421     // have the same legalization requirements as global and private
8422     // loads.
8423     //
8424   }
8425 
8426   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8427       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8428       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8429     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8430         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8431         Alignment >= 4 && NumElements < 32) {
8432       if (MemVT.isPow2VectorType())
8433         return SDValue();
8434       return WidenOrSplitVectorLoad(Op, DAG);
8435     }
8436     // Non-uniform loads will be selected to MUBUF instructions, so they
8437     // have the same legalization requirements as global and private
8438     // loads.
8439     //
8440   }
8441   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8442       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8443       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8444       AS == AMDGPUAS::FLAT_ADDRESS) {
8445     if (NumElements > 4)
8446       return SplitVectorLoad(Op, DAG);
8447     // v3 loads not supported on SI.
8448     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8449       return WidenOrSplitVectorLoad(Op, DAG);
8450 
8451     // v3 and v4 loads are supported for private and global memory.
8452     return SDValue();
8453   }
8454   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8455     // Depending on the setting of the private_element_size field in the
8456     // resource descriptor, we can only make private accesses up to a certain
8457     // size.
8458     switch (Subtarget->getMaxPrivateElementSize()) {
8459     case 4: {
8460       SDValue Ops[2];
8461       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8462       return DAG.getMergeValues(Ops, DL);
8463     }
8464     case 8:
8465       if (NumElements > 2)
8466         return SplitVectorLoad(Op, DAG);
8467       return SDValue();
8468     case 16:
8469       // Same as global/flat
8470       if (NumElements > 4)
8471         return SplitVectorLoad(Op, DAG);
8472       // v3 loads not supported on SI.
8473       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8474         return WidenOrSplitVectorLoad(Op, DAG);
8475 
8476       return SDValue();
8477     default:
8478       llvm_unreachable("unsupported private_element_size");
8479     }
8480   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8481     // Use ds_read_b128 or ds_read_b96 when possible.
8482     if (Subtarget->hasDS96AndDS128() &&
8483         ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) ||
8484          MemVT.getStoreSize() == 12) &&
8485         allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8486                                            Load->getAlign()))
8487       return SDValue();
8488 
8489     if (NumElements > 2)
8490       return SplitVectorLoad(Op, DAG);
8491 
8492     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8493     // address is negative, then the instruction is incorrectly treated as
8494     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8495     // loads here to avoid emitting ds_read2_b32. We may re-combine the
8496     // load later in the SILoadStoreOptimizer.
8497     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
8498         NumElements == 2 && MemVT.getStoreSize() == 8 &&
8499         Load->getAlignment() < 8) {
8500       return SplitVectorLoad(Op, DAG);
8501     }
8502   }
8503 
8504   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8505                                       MemVT, *Load->getMemOperand())) {
8506     SDValue Ops[2];
8507     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8508     return DAG.getMergeValues(Ops, DL);
8509   }
8510 
8511   return SDValue();
8512 }
8513 
8514 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8515   EVT VT = Op.getValueType();
8516   if (VT.getSizeInBits() == 128)
8517     return splitTernaryVectorOp(Op, DAG);
8518 
8519   assert(VT.getSizeInBits() == 64);
8520 
8521   SDLoc DL(Op);
8522   SDValue Cond = Op.getOperand(0);
8523 
8524   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8525   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8526 
8527   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8528   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8529 
8530   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8531   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8532 
8533   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8534 
8535   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8536   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8537 
8538   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8539 
8540   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8541   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8542 }
8543 
8544 // Catch division cases where we can use shortcuts with rcp and rsq
8545 // instructions.
8546 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8547                                               SelectionDAG &DAG) const {
8548   SDLoc SL(Op);
8549   SDValue LHS = Op.getOperand(0);
8550   SDValue RHS = Op.getOperand(1);
8551   EVT VT = Op.getValueType();
8552   const SDNodeFlags Flags = Op->getFlags();
8553 
8554   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8555 
8556   // Without !fpmath accuracy information, we can't do more because we don't
8557   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8558   if (!AllowInaccurateRcp)
8559     return SDValue();
8560 
8561   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8562     if (CLHS->isExactlyValue(1.0)) {
8563       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8564       // the CI documentation has a worst case error of 1 ulp.
8565       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8566       // use it as long as we aren't trying to use denormals.
8567       //
8568       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8569 
8570       // 1.0 / sqrt(x) -> rsq(x)
8571 
8572       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8573       // error seems really high at 2^29 ULP.
8574       if (RHS.getOpcode() == ISD::FSQRT)
8575         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8576 
8577       // 1.0 / x -> rcp(x)
8578       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8579     }
8580 
8581     // Same as for 1.0, but expand the sign out of the constant.
8582     if (CLHS->isExactlyValue(-1.0)) {
8583       // -1.0 / x -> rcp (fneg x)
8584       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8585       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8586     }
8587   }
8588 
8589   // Turn into multiply by the reciprocal.
8590   // x / y -> x * (1.0 / y)
8591   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8592   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8593 }
8594 
8595 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8596                                                 SelectionDAG &DAG) const {
8597   SDLoc SL(Op);
8598   SDValue X = Op.getOperand(0);
8599   SDValue Y = Op.getOperand(1);
8600   EVT VT = Op.getValueType();
8601   const SDNodeFlags Flags = Op->getFlags();
8602 
8603   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8604                             DAG.getTarget().Options.UnsafeFPMath;
8605   if (!AllowInaccurateDiv)
8606     return SDValue();
8607 
8608   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8609   SDValue One = DAG.getConstantFP(1.0, SL, VT);
8610 
8611   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8612   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8613 
8614   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8615   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8616   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8617   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8618   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8619   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8620 }
8621 
8622 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8623                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8624                           SDNodeFlags Flags) {
8625   if (GlueChain->getNumValues() <= 1) {
8626     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8627   }
8628 
8629   assert(GlueChain->getNumValues() == 3);
8630 
8631   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8632   switch (Opcode) {
8633   default: llvm_unreachable("no chain equivalent for opcode");
8634   case ISD::FMUL:
8635     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8636     break;
8637   }
8638 
8639   return DAG.getNode(Opcode, SL, VTList,
8640                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8641                      Flags);
8642 }
8643 
8644 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8645                            EVT VT, SDValue A, SDValue B, SDValue C,
8646                            SDValue GlueChain, SDNodeFlags Flags) {
8647   if (GlueChain->getNumValues() <= 1) {
8648     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8649   }
8650 
8651   assert(GlueChain->getNumValues() == 3);
8652 
8653   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8654   switch (Opcode) {
8655   default: llvm_unreachable("no chain equivalent for opcode");
8656   case ISD::FMA:
8657     Opcode = AMDGPUISD::FMA_W_CHAIN;
8658     break;
8659   }
8660 
8661   return DAG.getNode(Opcode, SL, VTList,
8662                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8663                      Flags);
8664 }
8665 
8666 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8667   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8668     return FastLowered;
8669 
8670   SDLoc SL(Op);
8671   SDValue Src0 = Op.getOperand(0);
8672   SDValue Src1 = Op.getOperand(1);
8673 
8674   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8675   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8676 
8677   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8678   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8679 
8680   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8681   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8682 
8683   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8684 }
8685 
8686 // Faster 2.5 ULP division that does not support denormals.
8687 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8688   SDLoc SL(Op);
8689   SDValue LHS = Op.getOperand(1);
8690   SDValue RHS = Op.getOperand(2);
8691 
8692   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8693 
8694   const APFloat K0Val(BitsToFloat(0x6f800000));
8695   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8696 
8697   const APFloat K1Val(BitsToFloat(0x2f800000));
8698   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8699 
8700   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8701 
8702   EVT SetCCVT =
8703     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8704 
8705   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8706 
8707   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8708 
8709   // TODO: Should this propagate fast-math-flags?
8710   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8711 
8712   // rcp does not support denormals.
8713   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8714 
8715   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8716 
8717   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8718 }
8719 
8720 // Returns immediate value for setting the F32 denorm mode when using the
8721 // S_DENORM_MODE instruction.
8722 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8723                                     const SDLoc &SL, const GCNSubtarget *ST) {
8724   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8725   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8726                                 ? FP_DENORM_FLUSH_NONE
8727                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8728 
8729   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8730   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8731 }
8732 
8733 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8734   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8735     return FastLowered;
8736 
8737   // The selection matcher assumes anything with a chain selecting to a
8738   // mayRaiseFPException machine instruction. Since we're introducing a chain
8739   // here, we need to explicitly report nofpexcept for the regular fdiv
8740   // lowering.
8741   SDNodeFlags Flags = Op->getFlags();
8742   Flags.setNoFPExcept(true);
8743 
8744   SDLoc SL(Op);
8745   SDValue LHS = Op.getOperand(0);
8746   SDValue RHS = Op.getOperand(1);
8747 
8748   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8749 
8750   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8751 
8752   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8753                                           {RHS, RHS, LHS}, Flags);
8754   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8755                                         {LHS, RHS, LHS}, Flags);
8756 
8757   // Denominator is scaled to not be denormal, so using rcp is ok.
8758   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8759                                   DenominatorScaled, Flags);
8760   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8761                                      DenominatorScaled, Flags);
8762 
8763   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8764                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8765                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8766   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8767 
8768   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8769 
8770   if (!HasFP32Denormals) {
8771     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8772     // lowering. The chain dependence is insufficient, and we need glue. We do
8773     // not need the glue variants in a strictfp function.
8774 
8775     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8776 
8777     SDNode *EnableDenorm;
8778     if (Subtarget->hasDenormModeInst()) {
8779       const SDValue EnableDenormValue =
8780           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8781 
8782       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8783                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8784     } else {
8785       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8786                                                         SL, MVT::i32);
8787       EnableDenorm =
8788           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8789                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8790     }
8791 
8792     SDValue Ops[3] = {
8793       NegDivScale0,
8794       SDValue(EnableDenorm, 0),
8795       SDValue(EnableDenorm, 1)
8796     };
8797 
8798     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8799   }
8800 
8801   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8802                              ApproxRcp, One, NegDivScale0, Flags);
8803 
8804   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8805                              ApproxRcp, Fma0, Flags);
8806 
8807   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8808                            Fma1, Fma1, Flags);
8809 
8810   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8811                              NumeratorScaled, Mul, Flags);
8812 
8813   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8814                              Fma2, Fma1, Mul, Fma2, Flags);
8815 
8816   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8817                              NumeratorScaled, Fma3, Flags);
8818 
8819   if (!HasFP32Denormals) {
8820     SDNode *DisableDenorm;
8821     if (Subtarget->hasDenormModeInst()) {
8822       const SDValue DisableDenormValue =
8823           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8824 
8825       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8826                                   Fma4.getValue(1), DisableDenormValue,
8827                                   Fma4.getValue(2)).getNode();
8828     } else {
8829       const SDValue DisableDenormValue =
8830           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8831 
8832       DisableDenorm = DAG.getMachineNode(
8833           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8834           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8835     }
8836 
8837     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8838                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8839     DAG.setRoot(OutputChain);
8840   }
8841 
8842   SDValue Scale = NumeratorScaled.getValue(1);
8843   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8844                              {Fma4, Fma1, Fma3, Scale}, Flags);
8845 
8846   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8847 }
8848 
8849 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8850   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
8851     return FastLowered;
8852 
8853   SDLoc SL(Op);
8854   SDValue X = Op.getOperand(0);
8855   SDValue Y = Op.getOperand(1);
8856 
8857   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8858 
8859   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8860 
8861   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8862 
8863   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8864 
8865   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8866 
8867   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8868 
8869   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8870 
8871   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8872 
8873   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8874 
8875   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8876   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8877 
8878   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8879                              NegDivScale0, Mul, DivScale1);
8880 
8881   SDValue Scale;
8882 
8883   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8884     // Workaround a hardware bug on SI where the condition output from div_scale
8885     // is not usable.
8886 
8887     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8888 
8889     // Figure out if the scale to use for div_fmas.
8890     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8891     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8892     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8893     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8894 
8895     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8896     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8897 
8898     SDValue Scale0Hi
8899       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8900     SDValue Scale1Hi
8901       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8902 
8903     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8904     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8905     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8906   } else {
8907     Scale = DivScale1.getValue(1);
8908   }
8909 
8910   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8911                              Fma4, Fma3, Mul, Scale);
8912 
8913   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8914 }
8915 
8916 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8917   EVT VT = Op.getValueType();
8918 
8919   if (VT == MVT::f32)
8920     return LowerFDIV32(Op, DAG);
8921 
8922   if (VT == MVT::f64)
8923     return LowerFDIV64(Op, DAG);
8924 
8925   if (VT == MVT::f16)
8926     return LowerFDIV16(Op, DAG);
8927 
8928   llvm_unreachable("Unexpected type for fdiv");
8929 }
8930 
8931 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8932   SDLoc DL(Op);
8933   StoreSDNode *Store = cast<StoreSDNode>(Op);
8934   EVT VT = Store->getMemoryVT();
8935 
8936   if (VT == MVT::i1) {
8937     return DAG.getTruncStore(Store->getChain(), DL,
8938        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8939        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8940   }
8941 
8942   assert(VT.isVector() &&
8943          Store->getValue().getValueType().getScalarType() == MVT::i32);
8944 
8945   unsigned AS = Store->getAddressSpace();
8946   if (Subtarget->hasLDSMisalignedBug() &&
8947       AS == AMDGPUAS::FLAT_ADDRESS &&
8948       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8949     return SplitVectorStore(Op, DAG);
8950   }
8951 
8952   MachineFunction &MF = DAG.getMachineFunction();
8953   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8954   // If there is a possibilty that flat instruction access scratch memory
8955   // then we need to use the same legalization rules we use for private.
8956   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8957       !Subtarget->hasMultiDwordFlatScratchAddressing())
8958     AS = MFI->hasFlatScratchInit() ?
8959          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8960 
8961   unsigned NumElements = VT.getVectorNumElements();
8962   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8963       AS == AMDGPUAS::FLAT_ADDRESS) {
8964     if (NumElements > 4)
8965       return SplitVectorStore(Op, DAG);
8966     // v3 stores not supported on SI.
8967     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8968       return SplitVectorStore(Op, DAG);
8969 
8970     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8971                                         VT, *Store->getMemOperand()))
8972       return expandUnalignedStore(Store, DAG);
8973 
8974     return SDValue();
8975   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8976     switch (Subtarget->getMaxPrivateElementSize()) {
8977     case 4:
8978       return scalarizeVectorStore(Store, DAG);
8979     case 8:
8980       if (NumElements > 2)
8981         return SplitVectorStore(Op, DAG);
8982       return SDValue();
8983     case 16:
8984       if (NumElements > 4 ||
8985           (NumElements == 3 && !Subtarget->enableFlatScratch()))
8986         return SplitVectorStore(Op, DAG);
8987       return SDValue();
8988     default:
8989       llvm_unreachable("unsupported private_element_size");
8990     }
8991   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8992     // Use ds_write_b128 or ds_write_b96 when possible.
8993     if (Subtarget->hasDS96AndDS128() &&
8994         ((Subtarget->useDS128() && VT.getStoreSize() == 16) ||
8995          (VT.getStoreSize() == 12)) &&
8996         allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
8997                                            Store->getAlign()))
8998       return SDValue();
8999 
9000     if (NumElements > 2)
9001       return SplitVectorStore(Op, DAG);
9002 
9003     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
9004     // address is negative, then the instruction is incorrectly treated as
9005     // out-of-bounds even if base + offsets is in bounds. Split vectorized
9006     // stores here to avoid emitting ds_write2_b32. We may re-combine the
9007     // store later in the SILoadStoreOptimizer.
9008     if (!Subtarget->hasUsableDSOffset() &&
9009         NumElements == 2 && VT.getStoreSize() == 8 &&
9010         Store->getAlignment() < 8) {
9011       return SplitVectorStore(Op, DAG);
9012     }
9013 
9014     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
9015                                         VT, *Store->getMemOperand())) {
9016       if (VT.isVector())
9017         return SplitVectorStore(Op, DAG);
9018       return expandUnalignedStore(Store, DAG);
9019     }
9020 
9021     return SDValue();
9022   } else {
9023     llvm_unreachable("unhandled address space");
9024   }
9025 }
9026 
9027 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
9028   SDLoc DL(Op);
9029   EVT VT = Op.getValueType();
9030   SDValue Arg = Op.getOperand(0);
9031   SDValue TrigVal;
9032 
9033   // Propagate fast-math flags so that the multiply we introduce can be folded
9034   // if Arg is already the result of a multiply by constant.
9035   auto Flags = Op->getFlags();
9036 
9037   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
9038 
9039   if (Subtarget->hasTrigReducedRange()) {
9040     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9041     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
9042   } else {
9043     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9044   }
9045 
9046   switch (Op.getOpcode()) {
9047   case ISD::FCOS:
9048     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
9049   case ISD::FSIN:
9050     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
9051   default:
9052     llvm_unreachable("Wrong trig opcode");
9053   }
9054 }
9055 
9056 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9057   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
9058   assert(AtomicNode->isCompareAndSwap());
9059   unsigned AS = AtomicNode->getAddressSpace();
9060 
9061   // No custom lowering required for local address space
9062   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
9063     return Op;
9064 
9065   // Non-local address space requires custom lowering for atomic compare
9066   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
9067   SDLoc DL(Op);
9068   SDValue ChainIn = Op.getOperand(0);
9069   SDValue Addr = Op.getOperand(1);
9070   SDValue Old = Op.getOperand(2);
9071   SDValue New = Op.getOperand(3);
9072   EVT VT = Op.getValueType();
9073   MVT SimpleVT = VT.getSimpleVT();
9074   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
9075 
9076   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
9077   SDValue Ops[] = { ChainIn, Addr, NewOld };
9078 
9079   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
9080                                  Ops, VT, AtomicNode->getMemOperand());
9081 }
9082 
9083 //===----------------------------------------------------------------------===//
9084 // Custom DAG optimizations
9085 //===----------------------------------------------------------------------===//
9086 
9087 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
9088                                                      DAGCombinerInfo &DCI) const {
9089   EVT VT = N->getValueType(0);
9090   EVT ScalarVT = VT.getScalarType();
9091   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
9092     return SDValue();
9093 
9094   SelectionDAG &DAG = DCI.DAG;
9095   SDLoc DL(N);
9096 
9097   SDValue Src = N->getOperand(0);
9098   EVT SrcVT = Src.getValueType();
9099 
9100   // TODO: We could try to match extracting the higher bytes, which would be
9101   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
9102   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
9103   // about in practice.
9104   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
9105     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
9106       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
9107       DCI.AddToWorklist(Cvt.getNode());
9108 
9109       // For the f16 case, fold to a cast to f32 and then cast back to f16.
9110       if (ScalarVT != MVT::f32) {
9111         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
9112                           DAG.getTargetConstant(0, DL, MVT::i32));
9113       }
9114       return Cvt;
9115     }
9116   }
9117 
9118   return SDValue();
9119 }
9120 
9121 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
9122 
9123 // This is a variant of
9124 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
9125 //
9126 // The normal DAG combiner will do this, but only if the add has one use since
9127 // that would increase the number of instructions.
9128 //
9129 // This prevents us from seeing a constant offset that can be folded into a
9130 // memory instruction's addressing mode. If we know the resulting add offset of
9131 // a pointer can be folded into an addressing offset, we can replace the pointer
9132 // operand with the add of new constant offset. This eliminates one of the uses,
9133 // and may allow the remaining use to also be simplified.
9134 //
9135 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
9136                                                unsigned AddrSpace,
9137                                                EVT MemVT,
9138                                                DAGCombinerInfo &DCI) const {
9139   SDValue N0 = N->getOperand(0);
9140   SDValue N1 = N->getOperand(1);
9141 
9142   // We only do this to handle cases where it's profitable when there are
9143   // multiple uses of the add, so defer to the standard combine.
9144   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
9145       N0->hasOneUse())
9146     return SDValue();
9147 
9148   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
9149   if (!CN1)
9150     return SDValue();
9151 
9152   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9153   if (!CAdd)
9154     return SDValue();
9155 
9156   // If the resulting offset is too large, we can't fold it into the addressing
9157   // mode offset.
9158   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
9159   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
9160 
9161   AddrMode AM;
9162   AM.HasBaseReg = true;
9163   AM.BaseOffs = Offset.getSExtValue();
9164   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
9165     return SDValue();
9166 
9167   SelectionDAG &DAG = DCI.DAG;
9168   SDLoc SL(N);
9169   EVT VT = N->getValueType(0);
9170 
9171   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
9172   SDValue COffset = DAG.getConstant(Offset, SL, VT);
9173 
9174   SDNodeFlags Flags;
9175   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
9176                           (N0.getOpcode() == ISD::OR ||
9177                            N0->getFlags().hasNoUnsignedWrap()));
9178 
9179   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
9180 }
9181 
9182 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
9183 /// by the chain and intrinsic ID. Theoretically we would also need to check the
9184 /// specific intrinsic, but they all place the pointer operand first.
9185 static unsigned getBasePtrIndex(const MemSDNode *N) {
9186   switch (N->getOpcode()) {
9187   case ISD::STORE:
9188   case ISD::INTRINSIC_W_CHAIN:
9189   case ISD::INTRINSIC_VOID:
9190     return 2;
9191   default:
9192     return 1;
9193   }
9194 }
9195 
9196 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
9197                                                   DAGCombinerInfo &DCI) const {
9198   SelectionDAG &DAG = DCI.DAG;
9199   SDLoc SL(N);
9200 
9201   unsigned PtrIdx = getBasePtrIndex(N);
9202   SDValue Ptr = N->getOperand(PtrIdx);
9203 
9204   // TODO: We could also do this for multiplies.
9205   if (Ptr.getOpcode() == ISD::SHL) {
9206     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
9207                                           N->getMemoryVT(), DCI);
9208     if (NewPtr) {
9209       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
9210 
9211       NewOps[PtrIdx] = NewPtr;
9212       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
9213     }
9214   }
9215 
9216   return SDValue();
9217 }
9218 
9219 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
9220   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
9221          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
9222          (Opc == ISD::XOR && Val == 0);
9223 }
9224 
9225 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
9226 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
9227 // integer combine opportunities since most 64-bit operations are decomposed
9228 // this way.  TODO: We won't want this for SALU especially if it is an inline
9229 // immediate.
9230 SDValue SITargetLowering::splitBinaryBitConstantOp(
9231   DAGCombinerInfo &DCI,
9232   const SDLoc &SL,
9233   unsigned Opc, SDValue LHS,
9234   const ConstantSDNode *CRHS) const {
9235   uint64_t Val = CRHS->getZExtValue();
9236   uint32_t ValLo = Lo_32(Val);
9237   uint32_t ValHi = Hi_32(Val);
9238   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9239 
9240     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
9241          bitOpWithConstantIsReducible(Opc, ValHi)) ||
9242         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
9243     // If we need to materialize a 64-bit immediate, it will be split up later
9244     // anyway. Avoid creating the harder to understand 64-bit immediate
9245     // materialization.
9246     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
9247   }
9248 
9249   return SDValue();
9250 }
9251 
9252 // Returns true if argument is a boolean value which is not serialized into
9253 // memory or argument and does not require v_cndmask_b32 to be deserialized.
9254 static bool isBoolSGPR(SDValue V) {
9255   if (V.getValueType() != MVT::i1)
9256     return false;
9257   switch (V.getOpcode()) {
9258   default:
9259     break;
9260   case ISD::SETCC:
9261   case AMDGPUISD::FP_CLASS:
9262     return true;
9263   case ISD::AND:
9264   case ISD::OR:
9265   case ISD::XOR:
9266     return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
9267   }
9268   return false;
9269 }
9270 
9271 // If a constant has all zeroes or all ones within each byte return it.
9272 // Otherwise return 0.
9273 static uint32_t getConstantPermuteMask(uint32_t C) {
9274   // 0xff for any zero byte in the mask
9275   uint32_t ZeroByteMask = 0;
9276   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
9277   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
9278   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
9279   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
9280   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
9281   if ((NonZeroByteMask & C) != NonZeroByteMask)
9282     return 0; // Partial bytes selected.
9283   return C;
9284 }
9285 
9286 // Check if a node selects whole bytes from its operand 0 starting at a byte
9287 // boundary while masking the rest. Returns select mask as in the v_perm_b32
9288 // or -1 if not succeeded.
9289 // Note byte select encoding:
9290 // value 0-3 selects corresponding source byte;
9291 // value 0xc selects zero;
9292 // value 0xff selects 0xff.
9293 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
9294   assert(V.getValueSizeInBits() == 32);
9295 
9296   if (V.getNumOperands() != 2)
9297     return ~0;
9298 
9299   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
9300   if (!N1)
9301     return ~0;
9302 
9303   uint32_t C = N1->getZExtValue();
9304 
9305   switch (V.getOpcode()) {
9306   default:
9307     break;
9308   case ISD::AND:
9309     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9310       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
9311     }
9312     break;
9313 
9314   case ISD::OR:
9315     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9316       return (0x03020100 & ~ConstMask) | ConstMask;
9317     }
9318     break;
9319 
9320   case ISD::SHL:
9321     if (C % 8)
9322       return ~0;
9323 
9324     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
9325 
9326   case ISD::SRL:
9327     if (C % 8)
9328       return ~0;
9329 
9330     return uint32_t(0x0c0c0c0c03020100ull >> C);
9331   }
9332 
9333   return ~0;
9334 }
9335 
9336 SDValue SITargetLowering::performAndCombine(SDNode *N,
9337                                             DAGCombinerInfo &DCI) const {
9338   if (DCI.isBeforeLegalize())
9339     return SDValue();
9340 
9341   SelectionDAG &DAG = DCI.DAG;
9342   EVT VT = N->getValueType(0);
9343   SDValue LHS = N->getOperand(0);
9344   SDValue RHS = N->getOperand(1);
9345 
9346 
9347   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9348   if (VT == MVT::i64 && CRHS) {
9349     if (SDValue Split
9350         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9351       return Split;
9352   }
9353 
9354   if (CRHS && VT == MVT::i32) {
9355     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9356     // nb = number of trailing zeroes in mask
9357     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9358     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9359     uint64_t Mask = CRHS->getZExtValue();
9360     unsigned Bits = countPopulation(Mask);
9361     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9362         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9363       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9364         unsigned Shift = CShift->getZExtValue();
9365         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9366         unsigned Offset = NB + Shift;
9367         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9368           SDLoc SL(N);
9369           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9370                                     LHS->getOperand(0),
9371                                     DAG.getConstant(Offset, SL, MVT::i32),
9372                                     DAG.getConstant(Bits, SL, MVT::i32));
9373           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9374           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9375                                     DAG.getValueType(NarrowVT));
9376           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9377                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9378           return Shl;
9379         }
9380       }
9381     }
9382 
9383     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9384     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9385         isa<ConstantSDNode>(LHS.getOperand(2))) {
9386       uint32_t Sel = getConstantPermuteMask(Mask);
9387       if (!Sel)
9388         return SDValue();
9389 
9390       // Select 0xc for all zero bytes
9391       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9392       SDLoc DL(N);
9393       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9394                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9395     }
9396   }
9397 
9398   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9399   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9400   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9401     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9402     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9403 
9404     SDValue X = LHS.getOperand(0);
9405     SDValue Y = RHS.getOperand(0);
9406     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9407       return SDValue();
9408 
9409     if (LCC == ISD::SETO) {
9410       if (X != LHS.getOperand(1))
9411         return SDValue();
9412 
9413       if (RCC == ISD::SETUNE) {
9414         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9415         if (!C1 || !C1->isInfinity() || C1->isNegative())
9416           return SDValue();
9417 
9418         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9419                               SIInstrFlags::N_SUBNORMAL |
9420                               SIInstrFlags::N_ZERO |
9421                               SIInstrFlags::P_ZERO |
9422                               SIInstrFlags::P_SUBNORMAL |
9423                               SIInstrFlags::P_NORMAL;
9424 
9425         static_assert(((~(SIInstrFlags::S_NAN |
9426                           SIInstrFlags::Q_NAN |
9427                           SIInstrFlags::N_INFINITY |
9428                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9429                       "mask not equal");
9430 
9431         SDLoc DL(N);
9432         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9433                            X, DAG.getConstant(Mask, DL, MVT::i32));
9434       }
9435     }
9436   }
9437 
9438   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9439     std::swap(LHS, RHS);
9440 
9441   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9442       RHS.hasOneUse()) {
9443     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9444     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9445     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9446     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9447     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9448         (RHS.getOperand(0) == LHS.getOperand(0) &&
9449          LHS.getOperand(0) == LHS.getOperand(1))) {
9450       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9451       unsigned NewMask = LCC == ISD::SETO ?
9452         Mask->getZExtValue() & ~OrdMask :
9453         Mask->getZExtValue() & OrdMask;
9454 
9455       SDLoc DL(N);
9456       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9457                          DAG.getConstant(NewMask, DL, MVT::i32));
9458     }
9459   }
9460 
9461   if (VT == MVT::i32 &&
9462       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9463     // and x, (sext cc from i1) => select cc, x, 0
9464     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9465       std::swap(LHS, RHS);
9466     if (isBoolSGPR(RHS.getOperand(0)))
9467       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9468                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9469   }
9470 
9471   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9472   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9473   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9474       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9475     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9476     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9477     if (LHSMask != ~0u && RHSMask != ~0u) {
9478       // Canonicalize the expression in an attempt to have fewer unique masks
9479       // and therefore fewer registers used to hold the masks.
9480       if (LHSMask > RHSMask) {
9481         std::swap(LHSMask, RHSMask);
9482         std::swap(LHS, RHS);
9483       }
9484 
9485       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9486       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9487       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9488       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9489 
9490       // Check of we need to combine values from two sources within a byte.
9491       if (!(LHSUsedLanes & RHSUsedLanes) &&
9492           // If we select high and lower word keep it for SDWA.
9493           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9494           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9495         // Each byte in each mask is either selector mask 0-3, or has higher
9496         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9497         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9498         // mask which is not 0xff wins. By anding both masks we have a correct
9499         // result except that 0x0c shall be corrected to give 0x0c only.
9500         uint32_t Mask = LHSMask & RHSMask;
9501         for (unsigned I = 0; I < 32; I += 8) {
9502           uint32_t ByteSel = 0xff << I;
9503           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9504             Mask &= (0x0c << I) & 0xffffffff;
9505         }
9506 
9507         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9508         // or 0x0c.
9509         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9510         SDLoc DL(N);
9511 
9512         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9513                            LHS.getOperand(0), RHS.getOperand(0),
9514                            DAG.getConstant(Sel, DL, MVT::i32));
9515       }
9516     }
9517   }
9518 
9519   return SDValue();
9520 }
9521 
9522 SDValue SITargetLowering::performOrCombine(SDNode *N,
9523                                            DAGCombinerInfo &DCI) const {
9524   SelectionDAG &DAG = DCI.DAG;
9525   SDValue LHS = N->getOperand(0);
9526   SDValue RHS = N->getOperand(1);
9527 
9528   EVT VT = N->getValueType(0);
9529   if (VT == MVT::i1) {
9530     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9531     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9532         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9533       SDValue Src = LHS.getOperand(0);
9534       if (Src != RHS.getOperand(0))
9535         return SDValue();
9536 
9537       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9538       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9539       if (!CLHS || !CRHS)
9540         return SDValue();
9541 
9542       // Only 10 bits are used.
9543       static const uint32_t MaxMask = 0x3ff;
9544 
9545       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9546       SDLoc DL(N);
9547       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9548                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9549     }
9550 
9551     return SDValue();
9552   }
9553 
9554   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9555   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9556       LHS.getOpcode() == AMDGPUISD::PERM &&
9557       isa<ConstantSDNode>(LHS.getOperand(2))) {
9558     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9559     if (!Sel)
9560       return SDValue();
9561 
9562     Sel |= LHS.getConstantOperandVal(2);
9563     SDLoc DL(N);
9564     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9565                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9566   }
9567 
9568   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9569   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9570   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9571       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9572     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9573     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9574     if (LHSMask != ~0u && RHSMask != ~0u) {
9575       // Canonicalize the expression in an attempt to have fewer unique masks
9576       // and therefore fewer registers used to hold the masks.
9577       if (LHSMask > RHSMask) {
9578         std::swap(LHSMask, RHSMask);
9579         std::swap(LHS, RHS);
9580       }
9581 
9582       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9583       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9584       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9585       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9586 
9587       // Check of we need to combine values from two sources within a byte.
9588       if (!(LHSUsedLanes & RHSUsedLanes) &&
9589           // If we select high and lower word keep it for SDWA.
9590           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9591           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9592         // Kill zero bytes selected by other mask. Zero value is 0xc.
9593         LHSMask &= ~RHSUsedLanes;
9594         RHSMask &= ~LHSUsedLanes;
9595         // Add 4 to each active LHS lane
9596         LHSMask |= LHSUsedLanes & 0x04040404;
9597         // Combine masks
9598         uint32_t Sel = LHSMask | RHSMask;
9599         SDLoc DL(N);
9600 
9601         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9602                            LHS.getOperand(0), RHS.getOperand(0),
9603                            DAG.getConstant(Sel, DL, MVT::i32));
9604       }
9605     }
9606   }
9607 
9608   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9609     return SDValue();
9610 
9611   // TODO: This could be a generic combine with a predicate for extracting the
9612   // high half of an integer being free.
9613 
9614   // (or i64:x, (zero_extend i32:y)) ->
9615   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9616   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9617       RHS.getOpcode() != ISD::ZERO_EXTEND)
9618     std::swap(LHS, RHS);
9619 
9620   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9621     SDValue ExtSrc = RHS.getOperand(0);
9622     EVT SrcVT = ExtSrc.getValueType();
9623     if (SrcVT == MVT::i32) {
9624       SDLoc SL(N);
9625       SDValue LowLHS, HiBits;
9626       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9627       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9628 
9629       DCI.AddToWorklist(LowOr.getNode());
9630       DCI.AddToWorklist(HiBits.getNode());
9631 
9632       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9633                                 LowOr, HiBits);
9634       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9635     }
9636   }
9637 
9638   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9639   if (CRHS) {
9640     if (SDValue Split
9641           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR,
9642                                      N->getOperand(0), CRHS))
9643       return Split;
9644   }
9645 
9646   return SDValue();
9647 }
9648 
9649 SDValue SITargetLowering::performXorCombine(SDNode *N,
9650                                             DAGCombinerInfo &DCI) const {
9651   if (SDValue RV = reassociateScalarOps(N, DCI.DAG))
9652     return RV;
9653 
9654   EVT VT = N->getValueType(0);
9655   if (VT != MVT::i64)
9656     return SDValue();
9657 
9658   SDValue LHS = N->getOperand(0);
9659   SDValue RHS = N->getOperand(1);
9660 
9661   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9662   if (CRHS) {
9663     if (SDValue Split
9664           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9665       return Split;
9666   }
9667 
9668   return SDValue();
9669 }
9670 
9671 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9672                                                    DAGCombinerInfo &DCI) const {
9673   if (!Subtarget->has16BitInsts() ||
9674       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9675     return SDValue();
9676 
9677   EVT VT = N->getValueType(0);
9678   if (VT != MVT::i32)
9679     return SDValue();
9680 
9681   SDValue Src = N->getOperand(0);
9682   if (Src.getValueType() != MVT::i16)
9683     return SDValue();
9684 
9685   return SDValue();
9686 }
9687 
9688 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9689                                                         DAGCombinerInfo &DCI)
9690                                                         const {
9691   SDValue Src = N->getOperand(0);
9692   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9693 
9694   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9695       VTSign->getVT() == MVT::i8) ||
9696       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9697       VTSign->getVT() == MVT::i16)) &&
9698       Src.hasOneUse()) {
9699     auto *M = cast<MemSDNode>(Src);
9700     SDValue Ops[] = {
9701       Src.getOperand(0), // Chain
9702       Src.getOperand(1), // rsrc
9703       Src.getOperand(2), // vindex
9704       Src.getOperand(3), // voffset
9705       Src.getOperand(4), // soffset
9706       Src.getOperand(5), // offset
9707       Src.getOperand(6),
9708       Src.getOperand(7)
9709     };
9710     // replace with BUFFER_LOAD_BYTE/SHORT
9711     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9712                                          Src.getOperand(0).getValueType());
9713     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9714                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9715     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9716                                                           ResList,
9717                                                           Ops, M->getMemoryVT(),
9718                                                           M->getMemOperand());
9719     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9720                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9721   }
9722   return SDValue();
9723 }
9724 
9725 SDValue SITargetLowering::performClassCombine(SDNode *N,
9726                                               DAGCombinerInfo &DCI) const {
9727   SelectionDAG &DAG = DCI.DAG;
9728   SDValue Mask = N->getOperand(1);
9729 
9730   // fp_class x, 0 -> false
9731   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9732     if (CMask->isZero())
9733       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9734   }
9735 
9736   if (N->getOperand(0).isUndef())
9737     return DAG.getUNDEF(MVT::i1);
9738 
9739   return SDValue();
9740 }
9741 
9742 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9743                                             DAGCombinerInfo &DCI) const {
9744   EVT VT = N->getValueType(0);
9745   SDValue N0 = N->getOperand(0);
9746 
9747   if (N0.isUndef())
9748     return N0;
9749 
9750   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9751                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9752     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9753                            N->getFlags());
9754   }
9755 
9756   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9757     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9758                            N0.getOperand(0), N->getFlags());
9759   }
9760 
9761   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9762 }
9763 
9764 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9765                                        unsigned MaxDepth) const {
9766   unsigned Opcode = Op.getOpcode();
9767   if (Opcode == ISD::FCANONICALIZE)
9768     return true;
9769 
9770   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9771     auto F = CFP->getValueAPF();
9772     if (F.isNaN() && F.isSignaling())
9773       return false;
9774     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9775   }
9776 
9777   // If source is a result of another standard FP operation it is already in
9778   // canonical form.
9779   if (MaxDepth == 0)
9780     return false;
9781 
9782   switch (Opcode) {
9783   // These will flush denorms if required.
9784   case ISD::FADD:
9785   case ISD::FSUB:
9786   case ISD::FMUL:
9787   case ISD::FCEIL:
9788   case ISD::FFLOOR:
9789   case ISD::FMA:
9790   case ISD::FMAD:
9791   case ISD::FSQRT:
9792   case ISD::FDIV:
9793   case ISD::FREM:
9794   case ISD::FP_ROUND:
9795   case ISD::FP_EXTEND:
9796   case AMDGPUISD::FMUL_LEGACY:
9797   case AMDGPUISD::FMAD_FTZ:
9798   case AMDGPUISD::RCP:
9799   case AMDGPUISD::RSQ:
9800   case AMDGPUISD::RSQ_CLAMP:
9801   case AMDGPUISD::RCP_LEGACY:
9802   case AMDGPUISD::RCP_IFLAG:
9803   case AMDGPUISD::DIV_SCALE:
9804   case AMDGPUISD::DIV_FMAS:
9805   case AMDGPUISD::DIV_FIXUP:
9806   case AMDGPUISD::FRACT:
9807   case AMDGPUISD::LDEXP:
9808   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9809   case AMDGPUISD::CVT_F32_UBYTE0:
9810   case AMDGPUISD::CVT_F32_UBYTE1:
9811   case AMDGPUISD::CVT_F32_UBYTE2:
9812   case AMDGPUISD::CVT_F32_UBYTE3:
9813     return true;
9814 
9815   // It can/will be lowered or combined as a bit operation.
9816   // Need to check their input recursively to handle.
9817   case ISD::FNEG:
9818   case ISD::FABS:
9819   case ISD::FCOPYSIGN:
9820     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9821 
9822   case ISD::FSIN:
9823   case ISD::FCOS:
9824   case ISD::FSINCOS:
9825     return Op.getValueType().getScalarType() != MVT::f16;
9826 
9827   case ISD::FMINNUM:
9828   case ISD::FMAXNUM:
9829   case ISD::FMINNUM_IEEE:
9830   case ISD::FMAXNUM_IEEE:
9831   case AMDGPUISD::CLAMP:
9832   case AMDGPUISD::FMED3:
9833   case AMDGPUISD::FMAX3:
9834   case AMDGPUISD::FMIN3: {
9835     // FIXME: Shouldn't treat the generic operations different based these.
9836     // However, we aren't really required to flush the result from
9837     // minnum/maxnum..
9838 
9839     // snans will be quieted, so we only need to worry about denormals.
9840     if (Subtarget->supportsMinMaxDenormModes() ||
9841         denormalsEnabledForType(DAG, Op.getValueType()))
9842       return true;
9843 
9844     // Flushing may be required.
9845     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9846     // targets need to check their input recursively.
9847 
9848     // FIXME: Does this apply with clamp? It's implemented with max.
9849     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9850       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9851         return false;
9852     }
9853 
9854     return true;
9855   }
9856   case ISD::SELECT: {
9857     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9858            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9859   }
9860   case ISD::BUILD_VECTOR: {
9861     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9862       SDValue SrcOp = Op.getOperand(i);
9863       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9864         return false;
9865     }
9866 
9867     return true;
9868   }
9869   case ISD::EXTRACT_VECTOR_ELT:
9870   case ISD::EXTRACT_SUBVECTOR: {
9871     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9872   }
9873   case ISD::INSERT_VECTOR_ELT: {
9874     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9875            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9876   }
9877   case ISD::UNDEF:
9878     // Could be anything.
9879     return false;
9880 
9881   case ISD::BITCAST:
9882     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9883   case ISD::TRUNCATE: {
9884     // Hack round the mess we make when legalizing extract_vector_elt
9885     if (Op.getValueType() == MVT::i16) {
9886       SDValue TruncSrc = Op.getOperand(0);
9887       if (TruncSrc.getValueType() == MVT::i32 &&
9888           TruncSrc.getOpcode() == ISD::BITCAST &&
9889           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9890         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9891       }
9892     }
9893     return false;
9894   }
9895   case ISD::INTRINSIC_WO_CHAIN: {
9896     unsigned IntrinsicID
9897       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9898     // TODO: Handle more intrinsics
9899     switch (IntrinsicID) {
9900     case Intrinsic::amdgcn_cvt_pkrtz:
9901     case Intrinsic::amdgcn_cubeid:
9902     case Intrinsic::amdgcn_frexp_mant:
9903     case Intrinsic::amdgcn_fdot2:
9904     case Intrinsic::amdgcn_rcp:
9905     case Intrinsic::amdgcn_rsq:
9906     case Intrinsic::amdgcn_rsq_clamp:
9907     case Intrinsic::amdgcn_rcp_legacy:
9908     case Intrinsic::amdgcn_rsq_legacy:
9909     case Intrinsic::amdgcn_trig_preop:
9910       return true;
9911     default:
9912       break;
9913     }
9914 
9915     LLVM_FALLTHROUGH;
9916   }
9917   default:
9918     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9919            DAG.isKnownNeverSNaN(Op);
9920   }
9921 
9922   llvm_unreachable("invalid operation");
9923 }
9924 
9925 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
9926                                        unsigned MaxDepth) const {
9927   MachineRegisterInfo &MRI = MF.getRegInfo();
9928   MachineInstr *MI = MRI.getVRegDef(Reg);
9929   unsigned Opcode = MI->getOpcode();
9930 
9931   if (Opcode == AMDGPU::G_FCANONICALIZE)
9932     return true;
9933 
9934   Optional<FPValueAndVReg> FCR;
9935   // Constant splat (can be padded with undef) or scalar constant.
9936   if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) {
9937     if (FCR->Value.isSignaling())
9938       return false;
9939     return !FCR->Value.isDenormal() ||
9940            denormalsEnabledForType(MRI.getType(FCR->VReg), MF);
9941   }
9942 
9943   if (MaxDepth == 0)
9944     return false;
9945 
9946   switch (Opcode) {
9947   case AMDGPU::G_FMINNUM_IEEE:
9948   case AMDGPU::G_FMAXNUM_IEEE: {
9949     if (Subtarget->supportsMinMaxDenormModes() ||
9950         denormalsEnabledForType(MRI.getType(Reg), MF))
9951       return true;
9952     for (const MachineOperand &MO : llvm::drop_begin(MI->operands()))
9953       if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1))
9954         return false;
9955     return true;
9956   }
9957   default:
9958     return denormalsEnabledForType(MRI.getType(Reg), MF) &&
9959            isKnownNeverSNaN(Reg, MRI);
9960   }
9961 
9962   llvm_unreachable("invalid operation");
9963 }
9964 
9965 // Constant fold canonicalize.
9966 SDValue SITargetLowering::getCanonicalConstantFP(
9967   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9968   // Flush denormals to 0 if not enabled.
9969   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9970     return DAG.getConstantFP(0.0, SL, VT);
9971 
9972   if (C.isNaN()) {
9973     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9974     if (C.isSignaling()) {
9975       // Quiet a signaling NaN.
9976       // FIXME: Is this supposed to preserve payload bits?
9977       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9978     }
9979 
9980     // Make sure it is the canonical NaN bitpattern.
9981     //
9982     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9983     // immediate?
9984     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9985       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9986   }
9987 
9988   // Already canonical.
9989   return DAG.getConstantFP(C, SL, VT);
9990 }
9991 
9992 static bool vectorEltWillFoldAway(SDValue Op) {
9993   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9994 }
9995 
9996 SDValue SITargetLowering::performFCanonicalizeCombine(
9997   SDNode *N,
9998   DAGCombinerInfo &DCI) const {
9999   SelectionDAG &DAG = DCI.DAG;
10000   SDValue N0 = N->getOperand(0);
10001   EVT VT = N->getValueType(0);
10002 
10003   // fcanonicalize undef -> qnan
10004   if (N0.isUndef()) {
10005     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
10006     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
10007   }
10008 
10009   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
10010     EVT VT = N->getValueType(0);
10011     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
10012   }
10013 
10014   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
10015   //                                                   (fcanonicalize k)
10016   //
10017   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
10018 
10019   // TODO: This could be better with wider vectors that will be split to v2f16,
10020   // and to consider uses since there aren't that many packed operations.
10021   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
10022       isTypeLegal(MVT::v2f16)) {
10023     SDLoc SL(N);
10024     SDValue NewElts[2];
10025     SDValue Lo = N0.getOperand(0);
10026     SDValue Hi = N0.getOperand(1);
10027     EVT EltVT = Lo.getValueType();
10028 
10029     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
10030       for (unsigned I = 0; I != 2; ++I) {
10031         SDValue Op = N0.getOperand(I);
10032         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
10033           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
10034                                               CFP->getValueAPF());
10035         } else if (Op.isUndef()) {
10036           // Handled below based on what the other operand is.
10037           NewElts[I] = Op;
10038         } else {
10039           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
10040         }
10041       }
10042 
10043       // If one half is undef, and one is constant, perfer a splat vector rather
10044       // than the normal qNaN. If it's a register, prefer 0.0 since that's
10045       // cheaper to use and may be free with a packed operation.
10046       if (NewElts[0].isUndef()) {
10047         if (isa<ConstantFPSDNode>(NewElts[1]))
10048           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
10049             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
10050       }
10051 
10052       if (NewElts[1].isUndef()) {
10053         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
10054           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
10055       }
10056 
10057       return DAG.getBuildVector(VT, SL, NewElts);
10058     }
10059   }
10060 
10061   unsigned SrcOpc = N0.getOpcode();
10062 
10063   // If it's free to do so, push canonicalizes further up the source, which may
10064   // find a canonical source.
10065   //
10066   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
10067   // sNaNs.
10068   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
10069     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10070     if (CRHS && N0.hasOneUse()) {
10071       SDLoc SL(N);
10072       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
10073                                    N0.getOperand(0));
10074       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
10075       DCI.AddToWorklist(Canon0.getNode());
10076 
10077       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
10078     }
10079   }
10080 
10081   return isCanonicalized(DAG, N0) ? N0 : SDValue();
10082 }
10083 
10084 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
10085   switch (Opc) {
10086   case ISD::FMAXNUM:
10087   case ISD::FMAXNUM_IEEE:
10088     return AMDGPUISD::FMAX3;
10089   case ISD::SMAX:
10090     return AMDGPUISD::SMAX3;
10091   case ISD::UMAX:
10092     return AMDGPUISD::UMAX3;
10093   case ISD::FMINNUM:
10094   case ISD::FMINNUM_IEEE:
10095     return AMDGPUISD::FMIN3;
10096   case ISD::SMIN:
10097     return AMDGPUISD::SMIN3;
10098   case ISD::UMIN:
10099     return AMDGPUISD::UMIN3;
10100   default:
10101     llvm_unreachable("Not a min/max opcode");
10102   }
10103 }
10104 
10105 SDValue SITargetLowering::performIntMed3ImmCombine(
10106   SelectionDAG &DAG, const SDLoc &SL,
10107   SDValue Op0, SDValue Op1, bool Signed) const {
10108   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
10109   if (!K1)
10110     return SDValue();
10111 
10112   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
10113   if (!K0)
10114     return SDValue();
10115 
10116   if (Signed) {
10117     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
10118       return SDValue();
10119   } else {
10120     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
10121       return SDValue();
10122   }
10123 
10124   EVT VT = K0->getValueType(0);
10125   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
10126   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
10127     return DAG.getNode(Med3Opc, SL, VT,
10128                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
10129   }
10130 
10131   // If there isn't a 16-bit med3 operation, convert to 32-bit.
10132   if (VT == MVT::i16) {
10133     MVT NVT = MVT::i32;
10134     unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
10135 
10136     SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
10137     SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
10138     SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
10139 
10140     SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
10141     return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
10142   }
10143 
10144   return SDValue();
10145 }
10146 
10147 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
10148   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
10149     return C;
10150 
10151   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
10152     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
10153       return C;
10154   }
10155 
10156   return nullptr;
10157 }
10158 
10159 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
10160                                                   const SDLoc &SL,
10161                                                   SDValue Op0,
10162                                                   SDValue Op1) const {
10163   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
10164   if (!K1)
10165     return SDValue();
10166 
10167   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
10168   if (!K0)
10169     return SDValue();
10170 
10171   // Ordered >= (although NaN inputs should have folded away by now).
10172   if (K0->getValueAPF() > K1->getValueAPF())
10173     return SDValue();
10174 
10175   const MachineFunction &MF = DAG.getMachineFunction();
10176   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10177 
10178   // TODO: Check IEEE bit enabled?
10179   EVT VT = Op0.getValueType();
10180   if (Info->getMode().DX10Clamp) {
10181     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
10182     // hardware fmed3 behavior converting to a min.
10183     // FIXME: Should this be allowing -0.0?
10184     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
10185       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
10186   }
10187 
10188   // med3 for f16 is only available on gfx9+, and not available for v2f16.
10189   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
10190     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
10191     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
10192     // then give the other result, which is different from med3 with a NaN
10193     // input.
10194     SDValue Var = Op0.getOperand(0);
10195     if (!DAG.isKnownNeverSNaN(Var))
10196       return SDValue();
10197 
10198     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10199 
10200     if ((!K0->hasOneUse() ||
10201          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
10202         (!K1->hasOneUse() ||
10203          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
10204       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
10205                          Var, SDValue(K0, 0), SDValue(K1, 0));
10206     }
10207   }
10208 
10209   return SDValue();
10210 }
10211 
10212 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
10213                                                DAGCombinerInfo &DCI) const {
10214   SelectionDAG &DAG = DCI.DAG;
10215 
10216   EVT VT = N->getValueType(0);
10217   unsigned Opc = N->getOpcode();
10218   SDValue Op0 = N->getOperand(0);
10219   SDValue Op1 = N->getOperand(1);
10220 
10221   // Only do this if the inner op has one use since this will just increases
10222   // register pressure for no benefit.
10223 
10224   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
10225       !VT.isVector() &&
10226       (VT == MVT::i32 || VT == MVT::f32 ||
10227        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
10228     // max(max(a, b), c) -> max3(a, b, c)
10229     // min(min(a, b), c) -> min3(a, b, c)
10230     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
10231       SDLoc DL(N);
10232       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10233                          DL,
10234                          N->getValueType(0),
10235                          Op0.getOperand(0),
10236                          Op0.getOperand(1),
10237                          Op1);
10238     }
10239 
10240     // Try commuted.
10241     // max(a, max(b, c)) -> max3(a, b, c)
10242     // min(a, min(b, c)) -> min3(a, b, c)
10243     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
10244       SDLoc DL(N);
10245       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10246                          DL,
10247                          N->getValueType(0),
10248                          Op0,
10249                          Op1.getOperand(0),
10250                          Op1.getOperand(1));
10251     }
10252   }
10253 
10254   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
10255   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
10256     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
10257       return Med3;
10258   }
10259 
10260   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
10261     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
10262       return Med3;
10263   }
10264 
10265   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
10266   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
10267        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
10268        (Opc == AMDGPUISD::FMIN_LEGACY &&
10269         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
10270       (VT == MVT::f32 || VT == MVT::f64 ||
10271        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
10272        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
10273       Op0.hasOneUse()) {
10274     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
10275       return Res;
10276   }
10277 
10278   return SDValue();
10279 }
10280 
10281 static bool isClampZeroToOne(SDValue A, SDValue B) {
10282   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
10283     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
10284       // FIXME: Should this be allowing -0.0?
10285       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
10286              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
10287     }
10288   }
10289 
10290   return false;
10291 }
10292 
10293 // FIXME: Should only worry about snans for version with chain.
10294 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
10295                                               DAGCombinerInfo &DCI) const {
10296   EVT VT = N->getValueType(0);
10297   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
10298   // NaNs. With a NaN input, the order of the operands may change the result.
10299 
10300   SelectionDAG &DAG = DCI.DAG;
10301   SDLoc SL(N);
10302 
10303   SDValue Src0 = N->getOperand(0);
10304   SDValue Src1 = N->getOperand(1);
10305   SDValue Src2 = N->getOperand(2);
10306 
10307   if (isClampZeroToOne(Src0, Src1)) {
10308     // const_a, const_b, x -> clamp is safe in all cases including signaling
10309     // nans.
10310     // FIXME: Should this be allowing -0.0?
10311     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
10312   }
10313 
10314   const MachineFunction &MF = DAG.getMachineFunction();
10315   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10316 
10317   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
10318   // handling no dx10-clamp?
10319   if (Info->getMode().DX10Clamp) {
10320     // If NaNs is clamped to 0, we are free to reorder the inputs.
10321 
10322     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10323       std::swap(Src0, Src1);
10324 
10325     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10326       std::swap(Src1, Src2);
10327 
10328     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10329       std::swap(Src0, Src1);
10330 
10331     if (isClampZeroToOne(Src1, Src2))
10332       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10333   }
10334 
10335   return SDValue();
10336 }
10337 
10338 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10339                                                  DAGCombinerInfo &DCI) const {
10340   SDValue Src0 = N->getOperand(0);
10341   SDValue Src1 = N->getOperand(1);
10342   if (Src0.isUndef() && Src1.isUndef())
10343     return DCI.DAG.getUNDEF(N->getValueType(0));
10344   return SDValue();
10345 }
10346 
10347 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10348 // expanded into a set of cmp/select instructions.
10349 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10350                                                 unsigned NumElem,
10351                                                 bool IsDivergentIdx) {
10352   if (UseDivergentRegisterIndexing)
10353     return false;
10354 
10355   unsigned VecSize = EltSize * NumElem;
10356 
10357   // Sub-dword vectors of size 2 dword or less have better implementation.
10358   if (VecSize <= 64 && EltSize < 32)
10359     return false;
10360 
10361   // Always expand the rest of sub-dword instructions, otherwise it will be
10362   // lowered via memory.
10363   if (EltSize < 32)
10364     return true;
10365 
10366   // Always do this if var-idx is divergent, otherwise it will become a loop.
10367   if (IsDivergentIdx)
10368     return true;
10369 
10370   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10371   unsigned NumInsts = NumElem /* Number of compares */ +
10372                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10373   return NumInsts <= 16;
10374 }
10375 
10376 static bool shouldExpandVectorDynExt(SDNode *N) {
10377   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10378   if (isa<ConstantSDNode>(Idx))
10379     return false;
10380 
10381   SDValue Vec = N->getOperand(0);
10382   EVT VecVT = Vec.getValueType();
10383   EVT EltVT = VecVT.getVectorElementType();
10384   unsigned EltSize = EltVT.getSizeInBits();
10385   unsigned NumElem = VecVT.getVectorNumElements();
10386 
10387   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
10388                                                     Idx->isDivergent());
10389 }
10390 
10391 SDValue SITargetLowering::performExtractVectorEltCombine(
10392   SDNode *N, DAGCombinerInfo &DCI) const {
10393   SDValue Vec = N->getOperand(0);
10394   SelectionDAG &DAG = DCI.DAG;
10395 
10396   EVT VecVT = Vec.getValueType();
10397   EVT EltVT = VecVT.getVectorElementType();
10398 
10399   if ((Vec.getOpcode() == ISD::FNEG ||
10400        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10401     SDLoc SL(N);
10402     EVT EltVT = N->getValueType(0);
10403     SDValue Idx = N->getOperand(1);
10404     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10405                               Vec.getOperand(0), Idx);
10406     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10407   }
10408 
10409   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10410   //    =>
10411   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10412   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10413   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10414   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10415     SDLoc SL(N);
10416     EVT EltVT = N->getValueType(0);
10417     SDValue Idx = N->getOperand(1);
10418     unsigned Opc = Vec.getOpcode();
10419 
10420     switch(Opc) {
10421     default:
10422       break;
10423       // TODO: Support other binary operations.
10424     case ISD::FADD:
10425     case ISD::FSUB:
10426     case ISD::FMUL:
10427     case ISD::ADD:
10428     case ISD::UMIN:
10429     case ISD::UMAX:
10430     case ISD::SMIN:
10431     case ISD::SMAX:
10432     case ISD::FMAXNUM:
10433     case ISD::FMINNUM:
10434     case ISD::FMAXNUM_IEEE:
10435     case ISD::FMINNUM_IEEE: {
10436       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10437                                  Vec.getOperand(0), Idx);
10438       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10439                                  Vec.getOperand(1), Idx);
10440 
10441       DCI.AddToWorklist(Elt0.getNode());
10442       DCI.AddToWorklist(Elt1.getNode());
10443       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10444     }
10445     }
10446   }
10447 
10448   unsigned VecSize = VecVT.getSizeInBits();
10449   unsigned EltSize = EltVT.getSizeInBits();
10450 
10451   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10452   if (::shouldExpandVectorDynExt(N)) {
10453     SDLoc SL(N);
10454     SDValue Idx = N->getOperand(1);
10455     SDValue V;
10456     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10457       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10458       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10459       if (I == 0)
10460         V = Elt;
10461       else
10462         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10463     }
10464     return V;
10465   }
10466 
10467   if (!DCI.isBeforeLegalize())
10468     return SDValue();
10469 
10470   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10471   // elements. This exposes more load reduction opportunities by replacing
10472   // multiple small extract_vector_elements with a single 32-bit extract.
10473   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10474   if (isa<MemSDNode>(Vec) &&
10475       EltSize <= 16 &&
10476       EltVT.isByteSized() &&
10477       VecSize > 32 &&
10478       VecSize % 32 == 0 &&
10479       Idx) {
10480     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10481 
10482     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10483     unsigned EltIdx = BitIndex / 32;
10484     unsigned LeftoverBitIdx = BitIndex % 32;
10485     SDLoc SL(N);
10486 
10487     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10488     DCI.AddToWorklist(Cast.getNode());
10489 
10490     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10491                               DAG.getConstant(EltIdx, SL, MVT::i32));
10492     DCI.AddToWorklist(Elt.getNode());
10493     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10494                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10495     DCI.AddToWorklist(Srl.getNode());
10496 
10497     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10498     DCI.AddToWorklist(Trunc.getNode());
10499     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10500   }
10501 
10502   return SDValue();
10503 }
10504 
10505 SDValue
10506 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10507                                                 DAGCombinerInfo &DCI) const {
10508   SDValue Vec = N->getOperand(0);
10509   SDValue Idx = N->getOperand(2);
10510   EVT VecVT = Vec.getValueType();
10511   EVT EltVT = VecVT.getVectorElementType();
10512 
10513   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10514   // => BUILD_VECTOR n x select (e, const-idx)
10515   if (!::shouldExpandVectorDynExt(N))
10516     return SDValue();
10517 
10518   SelectionDAG &DAG = DCI.DAG;
10519   SDLoc SL(N);
10520   SDValue Ins = N->getOperand(1);
10521   EVT IdxVT = Idx.getValueType();
10522 
10523   SmallVector<SDValue, 16> Ops;
10524   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10525     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10526     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10527     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10528     Ops.push_back(V);
10529   }
10530 
10531   return DAG.getBuildVector(VecVT, SL, Ops);
10532 }
10533 
10534 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10535                                           const SDNode *N0,
10536                                           const SDNode *N1) const {
10537   EVT VT = N0->getValueType(0);
10538 
10539   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10540   // support denormals ever.
10541   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10542        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10543         getSubtarget()->hasMadF16())) &&
10544        isOperationLegal(ISD::FMAD, VT))
10545     return ISD::FMAD;
10546 
10547   const TargetOptions &Options = DAG.getTarget().Options;
10548   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10549        (N0->getFlags().hasAllowContract() &&
10550         N1->getFlags().hasAllowContract())) &&
10551       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10552     return ISD::FMA;
10553   }
10554 
10555   return 0;
10556 }
10557 
10558 // For a reassociatable opcode perform:
10559 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10560 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10561                                                SelectionDAG &DAG) const {
10562   EVT VT = N->getValueType(0);
10563   if (VT != MVT::i32 && VT != MVT::i64)
10564     return SDValue();
10565 
10566   if (DAG.isBaseWithConstantOffset(SDValue(N, 0)))
10567     return SDValue();
10568 
10569   unsigned Opc = N->getOpcode();
10570   SDValue Op0 = N->getOperand(0);
10571   SDValue Op1 = N->getOperand(1);
10572 
10573   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10574     return SDValue();
10575 
10576   if (Op0->isDivergent())
10577     std::swap(Op0, Op1);
10578 
10579   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10580     return SDValue();
10581 
10582   SDValue Op2 = Op1.getOperand(1);
10583   Op1 = Op1.getOperand(0);
10584   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10585     return SDValue();
10586 
10587   if (Op1->isDivergent())
10588     std::swap(Op1, Op2);
10589 
10590   SDLoc SL(N);
10591   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10592   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10593 }
10594 
10595 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10596                            EVT VT,
10597                            SDValue N0, SDValue N1, SDValue N2,
10598                            bool Signed) {
10599   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10600   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10601   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10602   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10603 }
10604 
10605 SDValue SITargetLowering::performAddCombine(SDNode *N,
10606                                             DAGCombinerInfo &DCI) const {
10607   SelectionDAG &DAG = DCI.DAG;
10608   EVT VT = N->getValueType(0);
10609   SDLoc SL(N);
10610   SDValue LHS = N->getOperand(0);
10611   SDValue RHS = N->getOperand(1);
10612 
10613   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10614       && Subtarget->hasMad64_32() &&
10615       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10616       VT.getScalarSizeInBits() <= 64) {
10617     if (LHS.getOpcode() != ISD::MUL)
10618       std::swap(LHS, RHS);
10619 
10620     SDValue MulLHS = LHS.getOperand(0);
10621     SDValue MulRHS = LHS.getOperand(1);
10622     SDValue AddRHS = RHS;
10623 
10624     // TODO: Maybe restrict if SGPR inputs.
10625     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10626         numBitsUnsigned(MulRHS, DAG) <= 32) {
10627       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10628       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10629       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10630       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10631     }
10632 
10633     if (numBitsSigned(MulLHS, DAG) <= 32 && numBitsSigned(MulRHS, DAG) <= 32) {
10634       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10635       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10636       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10637       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10638     }
10639 
10640     return SDValue();
10641   }
10642 
10643   if (SDValue V = reassociateScalarOps(N, DAG)) {
10644     return V;
10645   }
10646 
10647   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10648     return SDValue();
10649 
10650   // add x, zext (setcc) => addcarry x, 0, setcc
10651   // add x, sext (setcc) => subcarry x, 0, setcc
10652   unsigned Opc = LHS.getOpcode();
10653   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10654       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10655     std::swap(RHS, LHS);
10656 
10657   Opc = RHS.getOpcode();
10658   switch (Opc) {
10659   default: break;
10660   case ISD::ZERO_EXTEND:
10661   case ISD::SIGN_EXTEND:
10662   case ISD::ANY_EXTEND: {
10663     auto Cond = RHS.getOperand(0);
10664     // If this won't be a real VOPC output, we would still need to insert an
10665     // extra instruction anyway.
10666     if (!isBoolSGPR(Cond))
10667       break;
10668     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10669     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10670     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10671     return DAG.getNode(Opc, SL, VTList, Args);
10672   }
10673   case ISD::ADDCARRY: {
10674     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10675     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10676     if (!C || C->getZExtValue() != 0) break;
10677     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10678     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10679   }
10680   }
10681   return SDValue();
10682 }
10683 
10684 SDValue SITargetLowering::performSubCombine(SDNode *N,
10685                                             DAGCombinerInfo &DCI) const {
10686   SelectionDAG &DAG = DCI.DAG;
10687   EVT VT = N->getValueType(0);
10688 
10689   if (VT != MVT::i32)
10690     return SDValue();
10691 
10692   SDLoc SL(N);
10693   SDValue LHS = N->getOperand(0);
10694   SDValue RHS = N->getOperand(1);
10695 
10696   // sub x, zext (setcc) => subcarry x, 0, setcc
10697   // sub x, sext (setcc) => addcarry x, 0, setcc
10698   unsigned Opc = RHS.getOpcode();
10699   switch (Opc) {
10700   default: break;
10701   case ISD::ZERO_EXTEND:
10702   case ISD::SIGN_EXTEND:
10703   case ISD::ANY_EXTEND: {
10704     auto Cond = RHS.getOperand(0);
10705     // If this won't be a real VOPC output, we would still need to insert an
10706     // extra instruction anyway.
10707     if (!isBoolSGPR(Cond))
10708       break;
10709     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10710     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10711     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10712     return DAG.getNode(Opc, SL, VTList, Args);
10713   }
10714   }
10715 
10716   if (LHS.getOpcode() == ISD::SUBCARRY) {
10717     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10718     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10719     if (!C || !C->isZero())
10720       return SDValue();
10721     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10722     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10723   }
10724   return SDValue();
10725 }
10726 
10727 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10728   DAGCombinerInfo &DCI) const {
10729 
10730   if (N->getValueType(0) != MVT::i32)
10731     return SDValue();
10732 
10733   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10734   if (!C || C->getZExtValue() != 0)
10735     return SDValue();
10736 
10737   SelectionDAG &DAG = DCI.DAG;
10738   SDValue LHS = N->getOperand(0);
10739 
10740   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10741   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10742   unsigned LHSOpc = LHS.getOpcode();
10743   unsigned Opc = N->getOpcode();
10744   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10745       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10746     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10747     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10748   }
10749   return SDValue();
10750 }
10751 
10752 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10753                                              DAGCombinerInfo &DCI) const {
10754   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10755     return SDValue();
10756 
10757   SelectionDAG &DAG = DCI.DAG;
10758   EVT VT = N->getValueType(0);
10759 
10760   SDLoc SL(N);
10761   SDValue LHS = N->getOperand(0);
10762   SDValue RHS = N->getOperand(1);
10763 
10764   // These should really be instruction patterns, but writing patterns with
10765   // source modiifiers is a pain.
10766 
10767   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10768   if (LHS.getOpcode() == ISD::FADD) {
10769     SDValue A = LHS.getOperand(0);
10770     if (A == LHS.getOperand(1)) {
10771       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10772       if (FusedOp != 0) {
10773         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10774         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10775       }
10776     }
10777   }
10778 
10779   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10780   if (RHS.getOpcode() == ISD::FADD) {
10781     SDValue A = RHS.getOperand(0);
10782     if (A == RHS.getOperand(1)) {
10783       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10784       if (FusedOp != 0) {
10785         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10786         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10787       }
10788     }
10789   }
10790 
10791   return SDValue();
10792 }
10793 
10794 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10795                                              DAGCombinerInfo &DCI) const {
10796   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10797     return SDValue();
10798 
10799   SelectionDAG &DAG = DCI.DAG;
10800   SDLoc SL(N);
10801   EVT VT = N->getValueType(0);
10802   assert(!VT.isVector());
10803 
10804   // Try to get the fneg to fold into the source modifier. This undoes generic
10805   // DAG combines and folds them into the mad.
10806   //
10807   // Only do this if we are not trying to support denormals. v_mad_f32 does
10808   // not support denormals ever.
10809   SDValue LHS = N->getOperand(0);
10810   SDValue RHS = N->getOperand(1);
10811   if (LHS.getOpcode() == ISD::FADD) {
10812     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10813     SDValue A = LHS.getOperand(0);
10814     if (A == LHS.getOperand(1)) {
10815       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10816       if (FusedOp != 0){
10817         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10818         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10819 
10820         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10821       }
10822     }
10823   }
10824 
10825   if (RHS.getOpcode() == ISD::FADD) {
10826     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10827 
10828     SDValue A = RHS.getOperand(0);
10829     if (A == RHS.getOperand(1)) {
10830       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10831       if (FusedOp != 0){
10832         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10833         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10834       }
10835     }
10836   }
10837 
10838   return SDValue();
10839 }
10840 
10841 SDValue SITargetLowering::performFMACombine(SDNode *N,
10842                                             DAGCombinerInfo &DCI) const {
10843   SelectionDAG &DAG = DCI.DAG;
10844   EVT VT = N->getValueType(0);
10845   SDLoc SL(N);
10846 
10847   if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
10848     return SDValue();
10849 
10850   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10851   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10852   SDValue Op1 = N->getOperand(0);
10853   SDValue Op2 = N->getOperand(1);
10854   SDValue FMA = N->getOperand(2);
10855 
10856   if (FMA.getOpcode() != ISD::FMA ||
10857       Op1.getOpcode() != ISD::FP_EXTEND ||
10858       Op2.getOpcode() != ISD::FP_EXTEND)
10859     return SDValue();
10860 
10861   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10862   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10863   // is sufficient to allow generaing fdot2.
10864   const TargetOptions &Options = DAG.getTarget().Options;
10865   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10866       (N->getFlags().hasAllowContract() &&
10867        FMA->getFlags().hasAllowContract())) {
10868     Op1 = Op1.getOperand(0);
10869     Op2 = Op2.getOperand(0);
10870     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10871         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10872       return SDValue();
10873 
10874     SDValue Vec1 = Op1.getOperand(0);
10875     SDValue Idx1 = Op1.getOperand(1);
10876     SDValue Vec2 = Op2.getOperand(0);
10877 
10878     SDValue FMAOp1 = FMA.getOperand(0);
10879     SDValue FMAOp2 = FMA.getOperand(1);
10880     SDValue FMAAcc = FMA.getOperand(2);
10881 
10882     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10883         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10884       return SDValue();
10885 
10886     FMAOp1 = FMAOp1.getOperand(0);
10887     FMAOp2 = FMAOp2.getOperand(0);
10888     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10889         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10890       return SDValue();
10891 
10892     SDValue Vec3 = FMAOp1.getOperand(0);
10893     SDValue Vec4 = FMAOp2.getOperand(0);
10894     SDValue Idx2 = FMAOp1.getOperand(1);
10895 
10896     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10897         // Idx1 and Idx2 cannot be the same.
10898         Idx1 == Idx2)
10899       return SDValue();
10900 
10901     if (Vec1 == Vec2 || Vec3 == Vec4)
10902       return SDValue();
10903 
10904     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10905       return SDValue();
10906 
10907     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10908         (Vec1 == Vec4 && Vec2 == Vec3)) {
10909       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10910                          DAG.getTargetConstant(0, SL, MVT::i1));
10911     }
10912   }
10913   return SDValue();
10914 }
10915 
10916 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10917                                               DAGCombinerInfo &DCI) const {
10918   SelectionDAG &DAG = DCI.DAG;
10919   SDLoc SL(N);
10920 
10921   SDValue LHS = N->getOperand(0);
10922   SDValue RHS = N->getOperand(1);
10923   EVT VT = LHS.getValueType();
10924   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10925 
10926   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10927   if (!CRHS) {
10928     CRHS = dyn_cast<ConstantSDNode>(LHS);
10929     if (CRHS) {
10930       std::swap(LHS, RHS);
10931       CC = getSetCCSwappedOperands(CC);
10932     }
10933   }
10934 
10935   if (CRHS) {
10936     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10937         isBoolSGPR(LHS.getOperand(0))) {
10938       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10939       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10940       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10941       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10942       if ((CRHS->isAllOnes() &&
10943            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10944           (CRHS->isZero() &&
10945            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10946         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10947                            DAG.getConstant(-1, SL, MVT::i1));
10948       if ((CRHS->isAllOnes() &&
10949            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10950           (CRHS->isZero() &&
10951            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10952         return LHS.getOperand(0);
10953     }
10954 
10955     const APInt &CRHSVal = CRHS->getAPIntValue();
10956     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10957         LHS.getOpcode() == ISD::SELECT &&
10958         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10959         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10960         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10961         isBoolSGPR(LHS.getOperand(0))) {
10962       // Given CT != FT:
10963       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10964       // setcc (select cc, CT, CF), CF, ne => cc
10965       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10966       // setcc (select cc, CT, CF), CT, eq => cc
10967       const APInt &CT = LHS.getConstantOperandAPInt(1);
10968       const APInt &CF = LHS.getConstantOperandAPInt(2);
10969 
10970       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10971           (CT == CRHSVal && CC == ISD::SETNE))
10972         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10973                            DAG.getConstant(-1, SL, MVT::i1));
10974       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10975           (CT == CRHSVal && CC == ISD::SETEQ))
10976         return LHS.getOperand(0);
10977     }
10978   }
10979 
10980   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10981                                            VT != MVT::f16))
10982     return SDValue();
10983 
10984   // Match isinf/isfinite pattern
10985   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10986   // (fcmp one (fabs x), inf) -> (fp_class x,
10987   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10988   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10989     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10990     if (!CRHS)
10991       return SDValue();
10992 
10993     const APFloat &APF = CRHS->getValueAPF();
10994     if (APF.isInfinity() && !APF.isNegative()) {
10995       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10996                                  SIInstrFlags::N_INFINITY;
10997       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10998                                     SIInstrFlags::P_ZERO |
10999                                     SIInstrFlags::N_NORMAL |
11000                                     SIInstrFlags::P_NORMAL |
11001                                     SIInstrFlags::N_SUBNORMAL |
11002                                     SIInstrFlags::P_SUBNORMAL;
11003       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
11004       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
11005                          DAG.getConstant(Mask, SL, MVT::i32));
11006     }
11007   }
11008 
11009   return SDValue();
11010 }
11011 
11012 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
11013                                                      DAGCombinerInfo &DCI) const {
11014   SelectionDAG &DAG = DCI.DAG;
11015   SDLoc SL(N);
11016   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
11017 
11018   SDValue Src = N->getOperand(0);
11019   SDValue Shift = N->getOperand(0);
11020 
11021   // TODO: Extend type shouldn't matter (assuming legal types).
11022   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
11023     Shift = Shift.getOperand(0);
11024 
11025   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
11026     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
11027     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
11028     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
11029     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
11030     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
11031     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
11032       SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0),
11033                                  SDLoc(Shift.getOperand(0)), MVT::i32);
11034 
11035       unsigned ShiftOffset = 8 * Offset;
11036       if (Shift.getOpcode() == ISD::SHL)
11037         ShiftOffset -= C->getZExtValue();
11038       else
11039         ShiftOffset += C->getZExtValue();
11040 
11041       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
11042         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
11043                            MVT::f32, Shifted);
11044       }
11045     }
11046   }
11047 
11048   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11049   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
11050   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
11051     // We simplified Src. If this node is not dead, visit it again so it is
11052     // folded properly.
11053     if (N->getOpcode() != ISD::DELETED_NODE)
11054       DCI.AddToWorklist(N);
11055     return SDValue(N, 0);
11056   }
11057 
11058   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
11059   if (SDValue DemandedSrc =
11060           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
11061     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
11062 
11063   return SDValue();
11064 }
11065 
11066 SDValue SITargetLowering::performClampCombine(SDNode *N,
11067                                               DAGCombinerInfo &DCI) const {
11068   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
11069   if (!CSrc)
11070     return SDValue();
11071 
11072   const MachineFunction &MF = DCI.DAG.getMachineFunction();
11073   const APFloat &F = CSrc->getValueAPF();
11074   APFloat Zero = APFloat::getZero(F.getSemantics());
11075   if (F < Zero ||
11076       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
11077     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
11078   }
11079 
11080   APFloat One(F.getSemantics(), "1.0");
11081   if (F > One)
11082     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
11083 
11084   return SDValue(CSrc, 0);
11085 }
11086 
11087 
11088 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
11089                                             DAGCombinerInfo &DCI) const {
11090   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
11091     return SDValue();
11092   switch (N->getOpcode()) {
11093   case ISD::ADD:
11094     return performAddCombine(N, DCI);
11095   case ISD::SUB:
11096     return performSubCombine(N, DCI);
11097   case ISD::ADDCARRY:
11098   case ISD::SUBCARRY:
11099     return performAddCarrySubCarryCombine(N, DCI);
11100   case ISD::FADD:
11101     return performFAddCombine(N, DCI);
11102   case ISD::FSUB:
11103     return performFSubCombine(N, DCI);
11104   case ISD::SETCC:
11105     return performSetCCCombine(N, DCI);
11106   case ISD::FMAXNUM:
11107   case ISD::FMINNUM:
11108   case ISD::FMAXNUM_IEEE:
11109   case ISD::FMINNUM_IEEE:
11110   case ISD::SMAX:
11111   case ISD::SMIN:
11112   case ISD::UMAX:
11113   case ISD::UMIN:
11114   case AMDGPUISD::FMIN_LEGACY:
11115   case AMDGPUISD::FMAX_LEGACY:
11116     return performMinMaxCombine(N, DCI);
11117   case ISD::FMA:
11118     return performFMACombine(N, DCI);
11119   case ISD::AND:
11120     return performAndCombine(N, DCI);
11121   case ISD::OR:
11122     return performOrCombine(N, DCI);
11123   case ISD::XOR:
11124     return performXorCombine(N, DCI);
11125   case ISD::ZERO_EXTEND:
11126     return performZeroExtendCombine(N, DCI);
11127   case ISD::SIGN_EXTEND_INREG:
11128     return performSignExtendInRegCombine(N , DCI);
11129   case AMDGPUISD::FP_CLASS:
11130     return performClassCombine(N, DCI);
11131   case ISD::FCANONICALIZE:
11132     return performFCanonicalizeCombine(N, DCI);
11133   case AMDGPUISD::RCP:
11134     return performRcpCombine(N, DCI);
11135   case AMDGPUISD::FRACT:
11136   case AMDGPUISD::RSQ:
11137   case AMDGPUISD::RCP_LEGACY:
11138   case AMDGPUISD::RCP_IFLAG:
11139   case AMDGPUISD::RSQ_CLAMP:
11140   case AMDGPUISD::LDEXP: {
11141     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
11142     SDValue Src = N->getOperand(0);
11143     if (Src.isUndef())
11144       return Src;
11145     break;
11146   }
11147   case ISD::SINT_TO_FP:
11148   case ISD::UINT_TO_FP:
11149     return performUCharToFloatCombine(N, DCI);
11150   case AMDGPUISD::CVT_F32_UBYTE0:
11151   case AMDGPUISD::CVT_F32_UBYTE1:
11152   case AMDGPUISD::CVT_F32_UBYTE2:
11153   case AMDGPUISD::CVT_F32_UBYTE3:
11154     return performCvtF32UByteNCombine(N, DCI);
11155   case AMDGPUISD::FMED3:
11156     return performFMed3Combine(N, DCI);
11157   case AMDGPUISD::CVT_PKRTZ_F16_F32:
11158     return performCvtPkRTZCombine(N, DCI);
11159   case AMDGPUISD::CLAMP:
11160     return performClampCombine(N, DCI);
11161   case ISD::SCALAR_TO_VECTOR: {
11162     SelectionDAG &DAG = DCI.DAG;
11163     EVT VT = N->getValueType(0);
11164 
11165     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
11166     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
11167       SDLoc SL(N);
11168       SDValue Src = N->getOperand(0);
11169       EVT EltVT = Src.getValueType();
11170       if (EltVT == MVT::f16)
11171         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
11172 
11173       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
11174       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
11175     }
11176 
11177     break;
11178   }
11179   case ISD::EXTRACT_VECTOR_ELT:
11180     return performExtractVectorEltCombine(N, DCI);
11181   case ISD::INSERT_VECTOR_ELT:
11182     return performInsertVectorEltCombine(N, DCI);
11183   case ISD::LOAD: {
11184     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
11185       return Widended;
11186     LLVM_FALLTHROUGH;
11187   }
11188   default: {
11189     if (!DCI.isBeforeLegalize()) {
11190       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
11191         return performMemSDNodeCombine(MemNode, DCI);
11192     }
11193 
11194     break;
11195   }
11196   }
11197 
11198   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
11199 }
11200 
11201 /// Helper function for adjustWritemask
11202 static unsigned SubIdx2Lane(unsigned Idx) {
11203   switch (Idx) {
11204   default: return ~0u;
11205   case AMDGPU::sub0: return 0;
11206   case AMDGPU::sub1: return 1;
11207   case AMDGPU::sub2: return 2;
11208   case AMDGPU::sub3: return 3;
11209   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
11210   }
11211 }
11212 
11213 /// Adjust the writemask of MIMG instructions
11214 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
11215                                           SelectionDAG &DAG) const {
11216   unsigned Opcode = Node->getMachineOpcode();
11217 
11218   // Subtract 1 because the vdata output is not a MachineSDNode operand.
11219   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
11220   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
11221     return Node; // not implemented for D16
11222 
11223   SDNode *Users[5] = { nullptr };
11224   unsigned Lane = 0;
11225   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
11226   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
11227   unsigned NewDmask = 0;
11228   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
11229   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
11230   bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
11231                   Node->getConstantOperandVal(LWEIdx))
11232                      ? true
11233                      : false;
11234   unsigned TFCLane = 0;
11235   bool HasChain = Node->getNumValues() > 1;
11236 
11237   if (OldDmask == 0) {
11238     // These are folded out, but on the chance it happens don't assert.
11239     return Node;
11240   }
11241 
11242   unsigned OldBitsSet = countPopulation(OldDmask);
11243   // Work out which is the TFE/LWE lane if that is enabled.
11244   if (UsesTFC) {
11245     TFCLane = OldBitsSet;
11246   }
11247 
11248   // Try to figure out the used register components
11249   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
11250        I != E; ++I) {
11251 
11252     // Don't look at users of the chain.
11253     if (I.getUse().getResNo() != 0)
11254       continue;
11255 
11256     // Abort if we can't understand the usage
11257     if (!I->isMachineOpcode() ||
11258         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
11259       return Node;
11260 
11261     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
11262     // Note that subregs are packed, i.e. Lane==0 is the first bit set
11263     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
11264     // set, etc.
11265     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
11266     if (Lane == ~0u)
11267       return Node;
11268 
11269     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
11270     if (UsesTFC && Lane == TFCLane) {
11271       Users[Lane] = *I;
11272     } else {
11273       // Set which texture component corresponds to the lane.
11274       unsigned Comp;
11275       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
11276         Comp = countTrailingZeros(Dmask);
11277         Dmask &= ~(1 << Comp);
11278       }
11279 
11280       // Abort if we have more than one user per component.
11281       if (Users[Lane])
11282         return Node;
11283 
11284       Users[Lane] = *I;
11285       NewDmask |= 1 << Comp;
11286     }
11287   }
11288 
11289   // Don't allow 0 dmask, as hardware assumes one channel enabled.
11290   bool NoChannels = !NewDmask;
11291   if (NoChannels) {
11292     if (!UsesTFC) {
11293       // No uses of the result and not using TFC. Then do nothing.
11294       return Node;
11295     }
11296     // If the original dmask has one channel - then nothing to do
11297     if (OldBitsSet == 1)
11298       return Node;
11299     // Use an arbitrary dmask - required for the instruction to work
11300     NewDmask = 1;
11301   }
11302   // Abort if there's no change
11303   if (NewDmask == OldDmask)
11304     return Node;
11305 
11306   unsigned BitsSet = countPopulation(NewDmask);
11307 
11308   // Check for TFE or LWE - increase the number of channels by one to account
11309   // for the extra return value
11310   // This will need adjustment for D16 if this is also included in
11311   // adjustWriteMask (this function) but at present D16 are excluded.
11312   unsigned NewChannels = BitsSet + UsesTFC;
11313 
11314   int NewOpcode =
11315       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
11316   assert(NewOpcode != -1 &&
11317          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
11318          "failed to find equivalent MIMG op");
11319 
11320   // Adjust the writemask in the node
11321   SmallVector<SDValue, 12> Ops;
11322   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
11323   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
11324   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11325 
11326   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11327 
11328   MVT ResultVT = NewChannels == 1 ?
11329     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11330                            NewChannels == 5 ? 8 : NewChannels);
11331   SDVTList NewVTList = HasChain ?
11332     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11333 
11334 
11335   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11336                                               NewVTList, Ops);
11337 
11338   if (HasChain) {
11339     // Update chain.
11340     DAG.setNodeMemRefs(NewNode, Node->memoperands());
11341     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11342   }
11343 
11344   if (NewChannels == 1) {
11345     assert(Node->hasNUsesOfValue(1, 0));
11346     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11347                                       SDLoc(Node), Users[Lane]->getValueType(0),
11348                                       SDValue(NewNode, 0));
11349     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11350     return nullptr;
11351   }
11352 
11353   // Update the users of the node with the new indices
11354   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11355     SDNode *User = Users[i];
11356     if (!User) {
11357       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11358       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11359       if (i || !NoChannels)
11360         continue;
11361     } else {
11362       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11363       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11364     }
11365 
11366     switch (Idx) {
11367     default: break;
11368     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11369     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11370     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11371     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11372     }
11373   }
11374 
11375   DAG.RemoveDeadNode(Node);
11376   return nullptr;
11377 }
11378 
11379 static bool isFrameIndexOp(SDValue Op) {
11380   if (Op.getOpcode() == ISD::AssertZext)
11381     Op = Op.getOperand(0);
11382 
11383   return isa<FrameIndexSDNode>(Op);
11384 }
11385 
11386 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11387 /// with frame index operands.
11388 /// LLVM assumes that inputs are to these instructions are registers.
11389 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11390                                                         SelectionDAG &DAG) const {
11391   if (Node->getOpcode() == ISD::CopyToReg) {
11392     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11393     SDValue SrcVal = Node->getOperand(2);
11394 
11395     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11396     // to try understanding copies to physical registers.
11397     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11398       SDLoc SL(Node);
11399       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11400       SDValue VReg = DAG.getRegister(
11401         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11402 
11403       SDNode *Glued = Node->getGluedNode();
11404       SDValue ToVReg
11405         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11406                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11407       SDValue ToResultReg
11408         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11409                            VReg, ToVReg.getValue(1));
11410       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11411       DAG.RemoveDeadNode(Node);
11412       return ToResultReg.getNode();
11413     }
11414   }
11415 
11416   SmallVector<SDValue, 8> Ops;
11417   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11418     if (!isFrameIndexOp(Node->getOperand(i))) {
11419       Ops.push_back(Node->getOperand(i));
11420       continue;
11421     }
11422 
11423     SDLoc DL(Node);
11424     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11425                                      Node->getOperand(i).getValueType(),
11426                                      Node->getOperand(i)), 0));
11427   }
11428 
11429   return DAG.UpdateNodeOperands(Node, Ops);
11430 }
11431 
11432 /// Fold the instructions after selecting them.
11433 /// Returns null if users were already updated.
11434 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11435                                           SelectionDAG &DAG) const {
11436   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11437   unsigned Opcode = Node->getMachineOpcode();
11438 
11439   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11440       !TII->isGather4(Opcode) &&
11441       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11442     return adjustWritemask(Node, DAG);
11443   }
11444 
11445   if (Opcode == AMDGPU::INSERT_SUBREG ||
11446       Opcode == AMDGPU::REG_SEQUENCE) {
11447     legalizeTargetIndependentNode(Node, DAG);
11448     return Node;
11449   }
11450 
11451   switch (Opcode) {
11452   case AMDGPU::V_DIV_SCALE_F32_e64:
11453   case AMDGPU::V_DIV_SCALE_F64_e64: {
11454     // Satisfy the operand register constraint when one of the inputs is
11455     // undefined. Ordinarily each undef value will have its own implicit_def of
11456     // a vreg, so force these to use a single register.
11457     SDValue Src0 = Node->getOperand(1);
11458     SDValue Src1 = Node->getOperand(3);
11459     SDValue Src2 = Node->getOperand(5);
11460 
11461     if ((Src0.isMachineOpcode() &&
11462          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11463         (Src0 == Src1 || Src0 == Src2))
11464       break;
11465 
11466     MVT VT = Src0.getValueType().getSimpleVT();
11467     const TargetRegisterClass *RC =
11468         getRegClassFor(VT, Src0.getNode()->isDivergent());
11469 
11470     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11471     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11472 
11473     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11474                                       UndefReg, Src0, SDValue());
11475 
11476     // src0 must be the same register as src1 or src2, even if the value is
11477     // undefined, so make sure we don't violate this constraint.
11478     if (Src0.isMachineOpcode() &&
11479         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11480       if (Src1.isMachineOpcode() &&
11481           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11482         Src0 = Src1;
11483       else if (Src2.isMachineOpcode() &&
11484                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11485         Src0 = Src2;
11486       else {
11487         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11488         Src0 = UndefReg;
11489         Src1 = UndefReg;
11490       }
11491     } else
11492       break;
11493 
11494     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11495     Ops[1] = Src0;
11496     Ops[3] = Src1;
11497     Ops[5] = Src2;
11498     Ops.push_back(ImpDef.getValue(1));
11499     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11500   }
11501   default:
11502     break;
11503   }
11504 
11505   return Node;
11506 }
11507 
11508 // Any MIMG instructions that use tfe or lwe require an initialization of the
11509 // result register that will be written in the case of a memory access failure.
11510 // The required code is also added to tie this init code to the result of the
11511 // img instruction.
11512 void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
11513   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11514   const SIRegisterInfo &TRI = TII->getRegisterInfo();
11515   MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11516   MachineBasicBlock &MBB = *MI.getParent();
11517 
11518   MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
11519   MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
11520   MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
11521 
11522   if (!TFE && !LWE) // intersect_ray
11523     return;
11524 
11525   unsigned TFEVal = TFE ? TFE->getImm() : 0;
11526   unsigned LWEVal = LWE->getImm();
11527   unsigned D16Val = D16 ? D16->getImm() : 0;
11528 
11529   if (!TFEVal && !LWEVal)
11530     return;
11531 
11532   // At least one of TFE or LWE are non-zero
11533   // We have to insert a suitable initialization of the result value and
11534   // tie this to the dest of the image instruction.
11535 
11536   const DebugLoc &DL = MI.getDebugLoc();
11537 
11538   int DstIdx =
11539       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
11540 
11541   // Calculate which dword we have to initialize to 0.
11542   MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
11543 
11544   // check that dmask operand is found.
11545   assert(MO_Dmask && "Expected dmask operand in instruction");
11546 
11547   unsigned dmask = MO_Dmask->getImm();
11548   // Determine the number of active lanes taking into account the
11549   // Gather4 special case
11550   unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask);
11551 
11552   bool Packed = !Subtarget->hasUnpackedD16VMem();
11553 
11554   unsigned InitIdx =
11555       D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
11556 
11557   // Abandon attempt if the dst size isn't large enough
11558   // - this is in fact an error but this is picked up elsewhere and
11559   // reported correctly.
11560   uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
11561   if (DstSize < InitIdx)
11562     return;
11563 
11564   // Create a register for the intialization value.
11565   Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11566   unsigned NewDst = 0; // Final initialized value will be in here
11567 
11568   // If PRTStrictNull feature is enabled (the default) then initialize
11569   // all the result registers to 0, otherwise just the error indication
11570   // register (VGPRn+1)
11571   unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
11572   unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
11573 
11574   BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
11575   for (; SizeLeft; SizeLeft--, CurrIdx++) {
11576     NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11577     // Initialize dword
11578     Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
11579     BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
11580       .addImm(0);
11581     // Insert into the super-reg
11582     BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
11583       .addReg(PrevDst)
11584       .addReg(SubReg)
11585       .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
11586 
11587     PrevDst = NewDst;
11588   }
11589 
11590   // Add as an implicit operand
11591   MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
11592 
11593   // Tie the just added implicit operand to the dst
11594   MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
11595 }
11596 
11597 /// Assign the register class depending on the number of
11598 /// bits set in the writemask
11599 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11600                                                      SDNode *Node) const {
11601   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11602 
11603   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11604 
11605   if (TII->isVOP3(MI.getOpcode())) {
11606     // Make sure constant bus requirements are respected.
11607     TII->legalizeOperandsVOP3(MRI, MI);
11608 
11609     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11610     // This saves a chain-copy of registers and better ballance register
11611     // use between vgpr and agpr as agpr tuples tend to be big.
11612     if (MI.getDesc().OpInfo) {
11613       unsigned Opc = MI.getOpcode();
11614       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11615       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11616                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11617         if (I == -1)
11618           break;
11619         MachineOperand &Op = MI.getOperand(I);
11620         if (!Op.isReg() || !Op.getReg().isVirtual())
11621           continue;
11622         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11623         if (!TRI->hasAGPRs(RC))
11624           continue;
11625         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11626         if (!Src || !Src->isCopy() ||
11627             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11628           continue;
11629         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11630         // All uses of agpr64 and agpr32 can also accept vgpr except for
11631         // v_accvgpr_read, but we do not produce agpr reads during selection,
11632         // so no use checks are needed.
11633         MRI.setRegClass(Op.getReg(), NewRC);
11634       }
11635     }
11636 
11637     return;
11638   }
11639 
11640   // Replace unused atomics with the no return version.
11641   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11642   if (NoRetAtomicOp != -1) {
11643     if (!Node->hasAnyUseOfValue(0)) {
11644       int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
11645                                                AMDGPU::OpName::cpol);
11646       if (CPolIdx != -1) {
11647         MachineOperand &CPol = MI.getOperand(CPolIdx);
11648         CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC);
11649       }
11650       MI.RemoveOperand(0);
11651       MI.setDesc(TII->get(NoRetAtomicOp));
11652       return;
11653     }
11654 
11655     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11656     // instruction, because the return type of these instructions is a vec2 of
11657     // the memory type, so it can be tied to the input operand.
11658     // This means these instructions always have a use, so we need to add a
11659     // special case to check if the atomic has only one extract_subreg use,
11660     // which itself has no uses.
11661     if ((Node->hasNUsesOfValue(1, 0) &&
11662          Node->use_begin()->isMachineOpcode() &&
11663          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11664          !Node->use_begin()->hasAnyUseOfValue(0))) {
11665       Register Def = MI.getOperand(0).getReg();
11666 
11667       // Change this into a noret atomic.
11668       MI.setDesc(TII->get(NoRetAtomicOp));
11669       MI.RemoveOperand(0);
11670 
11671       // If we only remove the def operand from the atomic instruction, the
11672       // extract_subreg will be left with a use of a vreg without a def.
11673       // So we need to insert an implicit_def to avoid machine verifier
11674       // errors.
11675       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11676               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11677     }
11678     return;
11679   }
11680 
11681   if (TII->isMIMG(MI) && !MI.mayStore())
11682     AddIMGInit(MI);
11683 }
11684 
11685 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11686                               uint64_t Val) {
11687   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11688   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11689 }
11690 
11691 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11692                                                 const SDLoc &DL,
11693                                                 SDValue Ptr) const {
11694   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11695 
11696   // Build the half of the subregister with the constants before building the
11697   // full 128-bit register. If we are building multiple resource descriptors,
11698   // this will allow CSEing of the 2-component register.
11699   const SDValue Ops0[] = {
11700     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11701     buildSMovImm32(DAG, DL, 0),
11702     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11703     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11704     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11705   };
11706 
11707   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11708                                                 MVT::v2i32, Ops0), 0);
11709 
11710   // Combine the constants and the pointer.
11711   const SDValue Ops1[] = {
11712     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11713     Ptr,
11714     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11715     SubRegHi,
11716     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11717   };
11718 
11719   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11720 }
11721 
11722 /// Return a resource descriptor with the 'Add TID' bit enabled
11723 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11724 ///        of the resource descriptor) to create an offset, which is added to
11725 ///        the resource pointer.
11726 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11727                                            SDValue Ptr, uint32_t RsrcDword1,
11728                                            uint64_t RsrcDword2And3) const {
11729   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11730   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11731   if (RsrcDword1) {
11732     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11733                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11734                     0);
11735   }
11736 
11737   SDValue DataLo = buildSMovImm32(DAG, DL,
11738                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11739   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11740 
11741   const SDValue Ops[] = {
11742     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11743     PtrLo,
11744     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11745     PtrHi,
11746     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11747     DataLo,
11748     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11749     DataHi,
11750     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11751   };
11752 
11753   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11754 }
11755 
11756 //===----------------------------------------------------------------------===//
11757 //                         SI Inline Assembly Support
11758 //===----------------------------------------------------------------------===//
11759 
11760 std::pair<unsigned, const TargetRegisterClass *>
11761 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
11762                                                StringRef Constraint,
11763                                                MVT VT) const {
11764   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
11765 
11766   const TargetRegisterClass *RC = nullptr;
11767   if (Constraint.size() == 1) {
11768     const unsigned BitWidth = VT.getSizeInBits();
11769     switch (Constraint[0]) {
11770     default:
11771       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11772     case 's':
11773     case 'r':
11774       switch (BitWidth) {
11775       case 16:
11776         RC = &AMDGPU::SReg_32RegClass;
11777         break;
11778       case 64:
11779         RC = &AMDGPU::SGPR_64RegClass;
11780         break;
11781       default:
11782         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11783         if (!RC)
11784           return std::make_pair(0U, nullptr);
11785         break;
11786       }
11787       break;
11788     case 'v':
11789       switch (BitWidth) {
11790       case 16:
11791         RC = &AMDGPU::VGPR_32RegClass;
11792         break;
11793       default:
11794         RC = TRI->getVGPRClassForBitWidth(BitWidth);
11795         if (!RC)
11796           return std::make_pair(0U, nullptr);
11797         break;
11798       }
11799       break;
11800     case 'a':
11801       if (!Subtarget->hasMAIInsts())
11802         break;
11803       switch (BitWidth) {
11804       case 16:
11805         RC = &AMDGPU::AGPR_32RegClass;
11806         break;
11807       default:
11808         RC = TRI->getAGPRClassForBitWidth(BitWidth);
11809         if (!RC)
11810           return std::make_pair(0U, nullptr);
11811         break;
11812       }
11813       break;
11814     }
11815     // We actually support i128, i16 and f16 as inline parameters
11816     // even if they are not reported as legal
11817     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11818                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11819       return std::make_pair(0U, RC);
11820   }
11821 
11822   if (Constraint.startswith("{") && Constraint.endswith("}")) {
11823     StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
11824     if (RegName.consume_front("v")) {
11825       RC = &AMDGPU::VGPR_32RegClass;
11826     } else if (RegName.consume_front("s")) {
11827       RC = &AMDGPU::SGPR_32RegClass;
11828     } else if (RegName.consume_front("a")) {
11829       RC = &AMDGPU::AGPR_32RegClass;
11830     }
11831 
11832     if (RC) {
11833       uint32_t Idx;
11834       if (RegName.consume_front("[")) {
11835         uint32_t End;
11836         bool Failed = RegName.consumeInteger(10, Idx);
11837         Failed |= !RegName.consume_front(":");
11838         Failed |= RegName.consumeInteger(10, End);
11839         Failed |= !RegName.consume_back("]");
11840         if (!Failed) {
11841           uint32_t Width = (End - Idx + 1) * 32;
11842           MCRegister Reg = RC->getRegister(Idx);
11843           if (SIRegisterInfo::isVGPRClass(RC))
11844             RC = TRI->getVGPRClassForBitWidth(Width);
11845           else if (SIRegisterInfo::isSGPRClass(RC))
11846             RC = TRI->getSGPRClassForBitWidth(Width);
11847           else if (SIRegisterInfo::isAGPRClass(RC))
11848             RC = TRI->getAGPRClassForBitWidth(Width);
11849           if (RC) {
11850             Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC);
11851             return std::make_pair(Reg, RC);
11852           }
11853         }
11854       } else {
11855         bool Failed = RegName.getAsInteger(10, Idx);
11856         if (!Failed && Idx < RC->getNumRegs())
11857           return std::make_pair(RC->getRegister(Idx), RC);
11858       }
11859     }
11860   }
11861 
11862   auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11863   if (Ret.first)
11864     Ret.second = TRI->getPhysRegClass(Ret.first);
11865 
11866   return Ret;
11867 }
11868 
11869 static bool isImmConstraint(StringRef Constraint) {
11870   if (Constraint.size() == 1) {
11871     switch (Constraint[0]) {
11872     default: break;
11873     case 'I':
11874     case 'J':
11875     case 'A':
11876     case 'B':
11877     case 'C':
11878       return true;
11879     }
11880   } else if (Constraint == "DA" ||
11881              Constraint == "DB") {
11882     return true;
11883   }
11884   return false;
11885 }
11886 
11887 SITargetLowering::ConstraintType
11888 SITargetLowering::getConstraintType(StringRef Constraint) const {
11889   if (Constraint.size() == 1) {
11890     switch (Constraint[0]) {
11891     default: break;
11892     case 's':
11893     case 'v':
11894     case 'a':
11895       return C_RegisterClass;
11896     }
11897   }
11898   if (isImmConstraint(Constraint)) {
11899     return C_Other;
11900   }
11901   return TargetLowering::getConstraintType(Constraint);
11902 }
11903 
11904 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11905   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11906     Val = Val & maskTrailingOnes<uint64_t>(Size);
11907   }
11908   return Val;
11909 }
11910 
11911 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11912                                                     std::string &Constraint,
11913                                                     std::vector<SDValue> &Ops,
11914                                                     SelectionDAG &DAG) const {
11915   if (isImmConstraint(Constraint)) {
11916     uint64_t Val;
11917     if (getAsmOperandConstVal(Op, Val) &&
11918         checkAsmConstraintVal(Op, Constraint, Val)) {
11919       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11920       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11921     }
11922   } else {
11923     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11924   }
11925 }
11926 
11927 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11928   unsigned Size = Op.getScalarValueSizeInBits();
11929   if (Size > 64)
11930     return false;
11931 
11932   if (Size == 16 && !Subtarget->has16BitInsts())
11933     return false;
11934 
11935   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11936     Val = C->getSExtValue();
11937     return true;
11938   }
11939   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11940     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11941     return true;
11942   }
11943   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11944     if (Size != 16 || Op.getNumOperands() != 2)
11945       return false;
11946     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11947       return false;
11948     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11949       Val = C->getSExtValue();
11950       return true;
11951     }
11952     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11953       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11954       return true;
11955     }
11956   }
11957 
11958   return false;
11959 }
11960 
11961 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11962                                              const std::string &Constraint,
11963                                              uint64_t Val) const {
11964   if (Constraint.size() == 1) {
11965     switch (Constraint[0]) {
11966     case 'I':
11967       return AMDGPU::isInlinableIntLiteral(Val);
11968     case 'J':
11969       return isInt<16>(Val);
11970     case 'A':
11971       return checkAsmConstraintValA(Op, Val);
11972     case 'B':
11973       return isInt<32>(Val);
11974     case 'C':
11975       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11976              AMDGPU::isInlinableIntLiteral(Val);
11977     default:
11978       break;
11979     }
11980   } else if (Constraint.size() == 2) {
11981     if (Constraint == "DA") {
11982       int64_t HiBits = static_cast<int32_t>(Val >> 32);
11983       int64_t LoBits = static_cast<int32_t>(Val);
11984       return checkAsmConstraintValA(Op, HiBits, 32) &&
11985              checkAsmConstraintValA(Op, LoBits, 32);
11986     }
11987     if (Constraint == "DB") {
11988       return true;
11989     }
11990   }
11991   llvm_unreachable("Invalid asm constraint");
11992 }
11993 
11994 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
11995                                               uint64_t Val,
11996                                               unsigned MaxSize) const {
11997   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
11998   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11999   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
12000       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
12001       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
12002     return true;
12003   }
12004   return false;
12005 }
12006 
12007 static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
12008   switch (UnalignedClassID) {
12009   case AMDGPU::VReg_64RegClassID:
12010     return AMDGPU::VReg_64_Align2RegClassID;
12011   case AMDGPU::VReg_96RegClassID:
12012     return AMDGPU::VReg_96_Align2RegClassID;
12013   case AMDGPU::VReg_128RegClassID:
12014     return AMDGPU::VReg_128_Align2RegClassID;
12015   case AMDGPU::VReg_160RegClassID:
12016     return AMDGPU::VReg_160_Align2RegClassID;
12017   case AMDGPU::VReg_192RegClassID:
12018     return AMDGPU::VReg_192_Align2RegClassID;
12019   case AMDGPU::VReg_224RegClassID:
12020     return AMDGPU::VReg_224_Align2RegClassID;
12021   case AMDGPU::VReg_256RegClassID:
12022     return AMDGPU::VReg_256_Align2RegClassID;
12023   case AMDGPU::VReg_512RegClassID:
12024     return AMDGPU::VReg_512_Align2RegClassID;
12025   case AMDGPU::VReg_1024RegClassID:
12026     return AMDGPU::VReg_1024_Align2RegClassID;
12027   case AMDGPU::AReg_64RegClassID:
12028     return AMDGPU::AReg_64_Align2RegClassID;
12029   case AMDGPU::AReg_96RegClassID:
12030     return AMDGPU::AReg_96_Align2RegClassID;
12031   case AMDGPU::AReg_128RegClassID:
12032     return AMDGPU::AReg_128_Align2RegClassID;
12033   case AMDGPU::AReg_160RegClassID:
12034     return AMDGPU::AReg_160_Align2RegClassID;
12035   case AMDGPU::AReg_192RegClassID:
12036     return AMDGPU::AReg_192_Align2RegClassID;
12037   case AMDGPU::AReg_256RegClassID:
12038     return AMDGPU::AReg_256_Align2RegClassID;
12039   case AMDGPU::AReg_512RegClassID:
12040     return AMDGPU::AReg_512_Align2RegClassID;
12041   case AMDGPU::AReg_1024RegClassID:
12042     return AMDGPU::AReg_1024_Align2RegClassID;
12043   default:
12044     return -1;
12045   }
12046 }
12047 
12048 // Figure out which registers should be reserved for stack access. Only after
12049 // the function is legalized do we know all of the non-spill stack objects or if
12050 // calls are present.
12051 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
12052   MachineRegisterInfo &MRI = MF.getRegInfo();
12053   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12054   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
12055   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12056   const SIInstrInfo *TII = ST.getInstrInfo();
12057 
12058   if (Info->isEntryFunction()) {
12059     // Callable functions have fixed registers used for stack access.
12060     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
12061   }
12062 
12063   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
12064                              Info->getStackPtrOffsetReg()));
12065   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
12066     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
12067 
12068   // We need to worry about replacing the default register with itself in case
12069   // of MIR testcases missing the MFI.
12070   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
12071     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
12072 
12073   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
12074     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
12075 
12076   Info->limitOccupancy(MF);
12077 
12078   if (ST.isWave32() && !MF.empty()) {
12079     for (auto &MBB : MF) {
12080       for (auto &MI : MBB) {
12081         TII->fixImplicitOperands(MI);
12082       }
12083     }
12084   }
12085 
12086   // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
12087   // classes if required. Ideally the register class constraints would differ
12088   // per-subtarget, but there's no easy way to achieve that right now. This is
12089   // not a problem for VGPRs because the correctly aligned VGPR class is implied
12090   // from using them as the register class for legal types.
12091   if (ST.needsAlignedVGPRs()) {
12092     for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
12093       const Register Reg = Register::index2VirtReg(I);
12094       const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
12095       if (!RC)
12096         continue;
12097       int NewClassID = getAlignedAGPRClassID(RC->getID());
12098       if (NewClassID != -1)
12099         MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
12100     }
12101   }
12102 
12103   TargetLoweringBase::finalizeLowering(MF);
12104 }
12105 
12106 void SITargetLowering::computeKnownBitsForFrameIndex(
12107   const int FI, KnownBits &Known, const MachineFunction &MF) const {
12108   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
12109 
12110   // Set the high bits to zero based on the maximum allowed scratch size per
12111   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
12112   // calculation won't overflow, so assume the sign bit is never set.
12113   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
12114 }
12115 
12116 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
12117                                    KnownBits &Known, unsigned Dim) {
12118   unsigned MaxValue =
12119       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
12120   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
12121 }
12122 
12123 void SITargetLowering::computeKnownBitsForTargetInstr(
12124     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
12125     const MachineRegisterInfo &MRI, unsigned Depth) const {
12126   const MachineInstr *MI = MRI.getVRegDef(R);
12127   switch (MI->getOpcode()) {
12128   case AMDGPU::G_INTRINSIC: {
12129     switch (MI->getIntrinsicID()) {
12130     case Intrinsic::amdgcn_workitem_id_x:
12131       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
12132       break;
12133     case Intrinsic::amdgcn_workitem_id_y:
12134       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
12135       break;
12136     case Intrinsic::amdgcn_workitem_id_z:
12137       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
12138       break;
12139     case Intrinsic::amdgcn_mbcnt_lo:
12140     case Intrinsic::amdgcn_mbcnt_hi: {
12141       // These return at most the wavefront size - 1.
12142       unsigned Size = MRI.getType(R).getSizeInBits();
12143       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
12144       break;
12145     }
12146     case Intrinsic::amdgcn_groupstaticsize: {
12147       // We can report everything over the maximum size as 0. We can't report
12148       // based on the actual size because we don't know if it's accurate or not
12149       // at any given point.
12150       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
12151       break;
12152     }
12153     }
12154     break;
12155   }
12156   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
12157     Known.Zero.setHighBits(24);
12158     break;
12159   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
12160     Known.Zero.setHighBits(16);
12161     break;
12162   }
12163 }
12164 
12165 Align SITargetLowering::computeKnownAlignForTargetInstr(
12166   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
12167   unsigned Depth) const {
12168   const MachineInstr *MI = MRI.getVRegDef(R);
12169   switch (MI->getOpcode()) {
12170   case AMDGPU::G_INTRINSIC:
12171   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
12172     // FIXME: Can this move to generic code? What about the case where the call
12173     // site specifies a lower alignment?
12174     Intrinsic::ID IID = MI->getIntrinsicID();
12175     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
12176     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
12177     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
12178       return *RetAlign;
12179     return Align(1);
12180   }
12181   default:
12182     return Align(1);
12183   }
12184 }
12185 
12186 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12187   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
12188   const Align CacheLineAlign = Align(64);
12189 
12190   // Pre-GFX10 target did not benefit from loop alignment
12191   if (!ML || DisableLoopAlignment ||
12192       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
12193       getSubtarget()->hasInstFwdPrefetchBug())
12194     return PrefAlign;
12195 
12196   // On GFX10 I$ is 4 x 64 bytes cache lines.
12197   // By default prefetcher keeps one cache line behind and reads two ahead.
12198   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
12199   // behind and one ahead.
12200   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
12201   // If loop fits 64 bytes it always spans no more than two cache lines and
12202   // does not need an alignment.
12203   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
12204   // Else if loop is less or equal 192 bytes we need two lines behind.
12205 
12206   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12207   const MachineBasicBlock *Header = ML->getHeader();
12208   if (Header->getAlignment() != PrefAlign)
12209     return Header->getAlignment(); // Already processed.
12210 
12211   unsigned LoopSize = 0;
12212   for (const MachineBasicBlock *MBB : ML->blocks()) {
12213     // If inner loop block is aligned assume in average half of the alignment
12214     // size to be added as nops.
12215     if (MBB != Header)
12216       LoopSize += MBB->getAlignment().value() / 2;
12217 
12218     for (const MachineInstr &MI : *MBB) {
12219       LoopSize += TII->getInstSizeInBytes(MI);
12220       if (LoopSize > 192)
12221         return PrefAlign;
12222     }
12223   }
12224 
12225   if (LoopSize <= 64)
12226     return PrefAlign;
12227 
12228   if (LoopSize <= 128)
12229     return CacheLineAlign;
12230 
12231   // If any of parent loops is surrounded by prefetch instructions do not
12232   // insert new for inner loop, which would reset parent's settings.
12233   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
12234     if (MachineBasicBlock *Exit = P->getExitBlock()) {
12235       auto I = Exit->getFirstNonDebugInstr();
12236       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
12237         return CacheLineAlign;
12238     }
12239   }
12240 
12241   MachineBasicBlock *Pre = ML->getLoopPreheader();
12242   MachineBasicBlock *Exit = ML->getExitBlock();
12243 
12244   if (Pre && Exit) {
12245     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
12246             TII->get(AMDGPU::S_INST_PREFETCH))
12247       .addImm(1); // prefetch 2 lines behind PC
12248 
12249     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
12250             TII->get(AMDGPU::S_INST_PREFETCH))
12251       .addImm(2); // prefetch 1 line behind PC
12252   }
12253 
12254   return CacheLineAlign;
12255 }
12256 
12257 LLVM_ATTRIBUTE_UNUSED
12258 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
12259   assert(N->getOpcode() == ISD::CopyFromReg);
12260   do {
12261     // Follow the chain until we find an INLINEASM node.
12262     N = N->getOperand(0).getNode();
12263     if (N->getOpcode() == ISD::INLINEASM ||
12264         N->getOpcode() == ISD::INLINEASM_BR)
12265       return true;
12266   } while (N->getOpcode() == ISD::CopyFromReg);
12267   return false;
12268 }
12269 
12270 bool SITargetLowering::isSDNodeSourceOfDivergence(
12271     const SDNode *N, FunctionLoweringInfo *FLI,
12272     LegacyDivergenceAnalysis *KDA) const {
12273   switch (N->getOpcode()) {
12274   case ISD::CopyFromReg: {
12275     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
12276     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
12277     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12278     Register Reg = R->getReg();
12279 
12280     // FIXME: Why does this need to consider isLiveIn?
12281     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
12282       return !TRI->isSGPRReg(MRI, Reg);
12283 
12284     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
12285       return KDA->isDivergent(V);
12286 
12287     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
12288     return !TRI->isSGPRReg(MRI, Reg);
12289   }
12290   case ISD::LOAD: {
12291     const LoadSDNode *L = cast<LoadSDNode>(N);
12292     unsigned AS = L->getAddressSpace();
12293     // A flat load may access private memory.
12294     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
12295   }
12296   case ISD::CALLSEQ_END:
12297     return true;
12298   case ISD::INTRINSIC_WO_CHAIN:
12299     return AMDGPU::isIntrinsicSourceOfDivergence(
12300         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
12301   case ISD::INTRINSIC_W_CHAIN:
12302     return AMDGPU::isIntrinsicSourceOfDivergence(
12303         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
12304   case AMDGPUISD::ATOMIC_CMP_SWAP:
12305   case AMDGPUISD::ATOMIC_INC:
12306   case AMDGPUISD::ATOMIC_DEC:
12307   case AMDGPUISD::ATOMIC_LOAD_FMIN:
12308   case AMDGPUISD::ATOMIC_LOAD_FMAX:
12309   case AMDGPUISD::BUFFER_ATOMIC_SWAP:
12310   case AMDGPUISD::BUFFER_ATOMIC_ADD:
12311   case AMDGPUISD::BUFFER_ATOMIC_SUB:
12312   case AMDGPUISD::BUFFER_ATOMIC_SMIN:
12313   case AMDGPUISD::BUFFER_ATOMIC_UMIN:
12314   case AMDGPUISD::BUFFER_ATOMIC_SMAX:
12315   case AMDGPUISD::BUFFER_ATOMIC_UMAX:
12316   case AMDGPUISD::BUFFER_ATOMIC_AND:
12317   case AMDGPUISD::BUFFER_ATOMIC_OR:
12318   case AMDGPUISD::BUFFER_ATOMIC_XOR:
12319   case AMDGPUISD::BUFFER_ATOMIC_INC:
12320   case AMDGPUISD::BUFFER_ATOMIC_DEC:
12321   case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
12322   case AMDGPUISD::BUFFER_ATOMIC_CSUB:
12323   case AMDGPUISD::BUFFER_ATOMIC_FADD:
12324   case AMDGPUISD::BUFFER_ATOMIC_FMIN:
12325   case AMDGPUISD::BUFFER_ATOMIC_FMAX:
12326     // Target-specific read-modify-write atomics are sources of divergence.
12327     return true;
12328   default:
12329     if (auto *A = dyn_cast<AtomicSDNode>(N)) {
12330       // Generic read-modify-write atomics are sources of divergence.
12331       return A->readMem() && A->writeMem();
12332     }
12333     return false;
12334   }
12335 }
12336 
12337 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
12338                                                EVT VT) const {
12339   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
12340   case MVT::f32:
12341     return hasFP32Denormals(DAG.getMachineFunction());
12342   case MVT::f64:
12343   case MVT::f16:
12344     return hasFP64FP16Denormals(DAG.getMachineFunction());
12345   default:
12346     return false;
12347   }
12348 }
12349 
12350 bool SITargetLowering::denormalsEnabledForType(LLT Ty,
12351                                                MachineFunction &MF) const {
12352   switch (Ty.getScalarSizeInBits()) {
12353   case 32:
12354     return hasFP32Denormals(MF);
12355   case 64:
12356   case 16:
12357     return hasFP64FP16Denormals(MF);
12358   default:
12359     return false;
12360   }
12361 }
12362 
12363 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
12364                                                     const SelectionDAG &DAG,
12365                                                     bool SNaN,
12366                                                     unsigned Depth) const {
12367   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
12368     const MachineFunction &MF = DAG.getMachineFunction();
12369     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12370 
12371     if (Info->getMode().DX10Clamp)
12372       return true; // Clamped to 0.
12373     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
12374   }
12375 
12376   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
12377                                                             SNaN, Depth);
12378 }
12379 
12380 // Global FP atomic instructions have a hardcoded FP mode and do not support
12381 // FP32 denormals, and only support v2f16 denormals.
12382 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
12383   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
12384   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
12385   if (&Flt == &APFloat::IEEEsingle())
12386     return DenormMode == DenormalMode::getPreserveSign();
12387   return DenormMode == DenormalMode::getIEEE();
12388 }
12389 
12390 TargetLowering::AtomicExpansionKind
12391 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
12392 
12393   auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) {
12394     OptimizationRemarkEmitter ORE(RMW->getFunction());
12395     LLVMContext &Ctx = RMW->getFunction()->getContext();
12396     SmallVector<StringRef> SSNs;
12397     Ctx.getSyncScopeNames(SSNs);
12398     auto MemScope = SSNs[RMW->getSyncScopeID()].empty()
12399                         ? "system"
12400                         : SSNs[RMW->getSyncScopeID()];
12401     ORE.emit([&]() {
12402       return OptimizationRemark(DEBUG_TYPE, "Passed", RMW)
12403              << "Hardware instruction generated for atomic "
12404              << RMW->getOperationName(RMW->getOperation())
12405              << " operation at memory scope " << MemScope
12406              << " due to an unsafe request.";
12407     });
12408     return Kind;
12409   };
12410 
12411   switch (RMW->getOperation()) {
12412   case AtomicRMWInst::FAdd: {
12413     Type *Ty = RMW->getType();
12414 
12415     // We don't have a way to support 16-bit atomics now, so just leave them
12416     // as-is.
12417     if (Ty->isHalfTy())
12418       return AtomicExpansionKind::None;
12419 
12420     if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
12421       return AtomicExpansionKind::CmpXChg;
12422 
12423     unsigned AS = RMW->getPointerAddressSpace();
12424 
12425     if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) &&
12426          Subtarget->hasAtomicFaddInsts()) {
12427       // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
12428       // floating point atomic instructions. May generate more efficient code,
12429       // but may not respect rounding and denormal modes, and may give incorrect
12430       // results for certain memory destinations.
12431       if (RMW->getFunction()
12432               ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12433               .getValueAsString() != "true")
12434         return AtomicExpansionKind::CmpXChg;
12435 
12436       if (Subtarget->hasGFX90AInsts()) {
12437         if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS)
12438           return AtomicExpansionKind::CmpXChg;
12439 
12440         auto SSID = RMW->getSyncScopeID();
12441         if (SSID == SyncScope::System ||
12442             SSID == RMW->getContext().getOrInsertSyncScopeID("one-as"))
12443           return AtomicExpansionKind::CmpXChg;
12444 
12445         return ReportUnsafeHWInst(AtomicExpansionKind::None);
12446       }
12447 
12448       if (AS == AMDGPUAS::FLAT_ADDRESS)
12449         return AtomicExpansionKind::CmpXChg;
12450 
12451       return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12452                               : AtomicExpansionKind::CmpXChg;
12453     }
12454 
12455     // DS FP atomics do repect the denormal mode, but the rounding mode is fixed
12456     // to round-to-nearest-even.
12457     // The only exception is DS_ADD_F64 which never flushes regardless of mode.
12458     if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) {
12459       if (!Ty->isDoubleTy())
12460         return AtomicExpansionKind::None;
12461 
12462       if (fpModeMatchesGlobalFPAtomicMode(RMW))
12463         return AtomicExpansionKind::None;
12464 
12465       return RMW->getFunction()
12466                          ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12467                          .getValueAsString() == "true"
12468                  ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12469                  : AtomicExpansionKind::CmpXChg;
12470     }
12471 
12472     return AtomicExpansionKind::CmpXChg;
12473   }
12474   default:
12475     break;
12476   }
12477 
12478   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
12479 }
12480 
12481 const TargetRegisterClass *
12482 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
12483   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
12484   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12485   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
12486     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
12487                                                : &AMDGPU::SReg_32RegClass;
12488   if (!TRI->isSGPRClass(RC) && !isDivergent)
12489     return TRI->getEquivalentSGPRClass(RC);
12490   else if (TRI->isSGPRClass(RC) && isDivergent)
12491     return TRI->getEquivalentVGPRClass(RC);
12492 
12493   return RC;
12494 }
12495 
12496 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
12497 // uniform values (as produced by the mask results of control flow intrinsics)
12498 // used outside of divergent blocks. The phi users need to also be treated as
12499 // always uniform.
12500 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
12501                       unsigned WaveSize) {
12502   // FIXME: We asssume we never cast the mask results of a control flow
12503   // intrinsic.
12504   // Early exit if the type won't be consistent as a compile time hack.
12505   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
12506   if (!IT || IT->getBitWidth() != WaveSize)
12507     return false;
12508 
12509   if (!isa<Instruction>(V))
12510     return false;
12511   if (!Visited.insert(V).second)
12512     return false;
12513   bool Result = false;
12514   for (auto U : V->users()) {
12515     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
12516       if (V == U->getOperand(1)) {
12517         switch (Intrinsic->getIntrinsicID()) {
12518         default:
12519           Result = false;
12520           break;
12521         case Intrinsic::amdgcn_if_break:
12522         case Intrinsic::amdgcn_if:
12523         case Intrinsic::amdgcn_else:
12524           Result = true;
12525           break;
12526         }
12527       }
12528       if (V == U->getOperand(0)) {
12529         switch (Intrinsic->getIntrinsicID()) {
12530         default:
12531           Result = false;
12532           break;
12533         case Intrinsic::amdgcn_end_cf:
12534         case Intrinsic::amdgcn_loop:
12535           Result = true;
12536           break;
12537         }
12538       }
12539     } else {
12540       Result = hasCFUser(U, Visited, WaveSize);
12541     }
12542     if (Result)
12543       break;
12544   }
12545   return Result;
12546 }
12547 
12548 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
12549                                                const Value *V) const {
12550   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
12551     if (CI->isInlineAsm()) {
12552       // FIXME: This cannot give a correct answer. This should only trigger in
12553       // the case where inline asm returns mixed SGPR and VGPR results, used
12554       // outside the defining block. We don't have a specific result to
12555       // consider, so this assumes if any value is SGPR, the overall register
12556       // also needs to be SGPR.
12557       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
12558       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
12559           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
12560       for (auto &TC : TargetConstraints) {
12561         if (TC.Type == InlineAsm::isOutput) {
12562           ComputeConstraintToUse(TC, SDValue());
12563           const TargetRegisterClass *RC = getRegForInlineAsmConstraint(
12564               SIRI, TC.ConstraintCode, TC.ConstraintVT).second;
12565           if (RC && SIRI->isSGPRClass(RC))
12566             return true;
12567         }
12568       }
12569     }
12570   }
12571   SmallPtrSet<const Value *, 16> Visited;
12572   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
12573 }
12574 
12575 std::pair<InstructionCost, MVT>
12576 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
12577                                           Type *Ty) const {
12578   std::pair<InstructionCost, MVT> Cost =
12579       TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
12580   auto Size = DL.getTypeSizeInBits(Ty);
12581   // Maximum load or store can handle 8 dwords for scalar and 4 for
12582   // vector ALU. Let's assume anything above 8 dwords is expensive
12583   // even if legal.
12584   if (Size <= 256)
12585     return Cost;
12586 
12587   Cost.first += (Size + 255) / 256;
12588   return Cost;
12589 }
12590 
12591 bool SITargetLowering::hasMemSDNodeUser(SDNode *N) const {
12592   SDNode::use_iterator I = N->use_begin(), E = N->use_end();
12593   for (; I != E; ++I) {
12594     if (MemSDNode *M = dyn_cast<MemSDNode>(*I)) {
12595       if (getBasePtrIndex(M) == I.getOperandNo())
12596         return true;
12597     }
12598   }
12599   return false;
12600 }
12601 
12602 bool SITargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0,
12603                                            SDValue N1) const {
12604   if (!N0.hasOneUse())
12605     return false;
12606   // Take care of the oportunity to keep N0 uniform
12607   if (N0->isDivergent() || !N1->isDivergent())
12608     return true;
12609   // Check if we have a good chance to form the memory access pattern with the
12610   // base and offset
12611   return (DAG.isBaseWithConstantOffset(N0) &&
12612           hasMemSDNodeUser(*N0->use_begin()));
12613 }
12614