1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// Custom DAG lowering for SI
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "SIISelLowering.h"
15 #include "AMDGPU.h"
16 #include "AMDGPUInstrInfo.h"
17 #include "AMDGPUTargetMachine.h"
18 #include "SIMachineFunctionInfo.h"
19 #include "SIRegisterInfo.h"
20 #include "llvm/ADT/FloatingPointMode.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
23 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
24 #include "llvm/BinaryFormat/ELF.h"
25 #include "llvm/CodeGen/Analysis.h"
26 #include "llvm/CodeGen/FunctionLoweringInfo.h"
27 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
28 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineLoopInfo.h"
32 #include "llvm/IR/DiagnosticInfo.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/IntrinsicsAMDGPU.h"
35 #include "llvm/IR/IntrinsicsR600.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/KnownBits.h"
38 
39 using namespace llvm;
40 
41 #define DEBUG_TYPE "si-lower"
42 
43 STATISTIC(NumTailCalls, "Number of tail calls");
44 
45 static cl::opt<bool> DisableLoopAlignment(
46   "amdgpu-disable-loop-alignment",
47   cl::desc("Do not align and prefetch loops"),
48   cl::init(false));
49 
50 static cl::opt<bool> UseDivergentRegisterIndexing(
51   "amdgpu-use-divergent-register-indexing",
52   cl::Hidden,
53   cl::desc("Use indirect register addressing for divergent indexes"),
54   cl::init(false));
55 
56 static bool hasFP32Denormals(const MachineFunction &MF) {
57   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
58   return Info->getMode().allFP32Denormals();
59 }
60 
61 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
62   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
63   return Info->getMode().allFP64FP16Denormals();
64 }
65 
66 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
67   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
68   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
69     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
70       return AMDGPU::SGPR0 + Reg;
71     }
72   }
73   llvm_unreachable("Cannot allocate sgpr");
74 }
75 
76 SITargetLowering::SITargetLowering(const TargetMachine &TM,
77                                    const GCNSubtarget &STI)
78     : AMDGPUTargetLowering(TM, STI),
79       Subtarget(&STI) {
80   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
81   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
82 
83   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
84   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
85 
86   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
87 
88   const SIRegisterInfo *TRI = STI.getRegisterInfo();
89   const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class();
90 
91   addRegisterClass(MVT::f64, V64RegClass);
92   addRegisterClass(MVT::v2f32, V64RegClass);
93 
94   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
95   addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96));
96 
97   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
98   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
99 
100   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
101   addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128));
102 
103   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
104   addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160));
105 
106   addRegisterClass(MVT::v6i32, &AMDGPU::SGPR_192RegClass);
107   addRegisterClass(MVT::v6f32, TRI->getVGPRClassForBitWidth(192));
108 
109   addRegisterClass(MVT::v3i64, &AMDGPU::SGPR_192RegClass);
110   addRegisterClass(MVT::v3f64, TRI->getVGPRClassForBitWidth(192));
111 
112   addRegisterClass(MVT::v7i32, &AMDGPU::SGPR_224RegClass);
113   addRegisterClass(MVT::v7f32, TRI->getVGPRClassForBitWidth(224));
114 
115   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
116   addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256));
117 
118   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
119   addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256));
120 
121   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
122   addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512));
123 
124   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
125   addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512));
126 
127   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
128   addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024));
129 
130   if (Subtarget->has16BitInsts()) {
131     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
132     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
133 
134     // Unless there are also VOP3P operations, not operations are really legal.
135     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
136     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
137     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
138     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
139     addRegisterClass(MVT::v8i16, &AMDGPU::SGPR_128RegClass);
140     addRegisterClass(MVT::v8f16, &AMDGPU::SGPR_128RegClass);
141   }
142 
143   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
144   addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024));
145 
146   computeRegisterProperties(Subtarget->getRegisterInfo());
147 
148   // The boolean content concept here is too inflexible. Compares only ever
149   // really produce a 1-bit result. Any copy/extend from these will turn into a
150   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
151   // it's what most targets use.
152   setBooleanContents(ZeroOrOneBooleanContent);
153   setBooleanVectorContents(ZeroOrOneBooleanContent);
154 
155   // We need to custom lower vector stores from local memory
156   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
157   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
158   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
159   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
160   setOperationAction(ISD::LOAD, MVT::v6i32, Custom);
161   setOperationAction(ISD::LOAD, MVT::v7i32, Custom);
162   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
163   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
164   setOperationAction(ISD::LOAD, MVT::i1, Custom);
165   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
166 
167   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
168   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
169   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
170   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
171   setOperationAction(ISD::STORE, MVT::v6i32, Custom);
172   setOperationAction(ISD::STORE, MVT::v7i32, Custom);
173   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
174   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
175   setOperationAction(ISD::STORE, MVT::i1, Custom);
176   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
177 
178   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
179   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
180   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
181   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
182   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
183   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
184   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
185   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
186   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
187   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
188   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
189   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
190   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
191   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
192   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
193   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
194 
195   setTruncStoreAction(MVT::v3i64, MVT::v3i16, Expand);
196   setTruncStoreAction(MVT::v3i64, MVT::v3i32, Expand);
197   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
198   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
199   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
200   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
201   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
202 
203   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
204   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
205 
206   setOperationAction(ISD::SELECT, MVT::i1, Promote);
207   setOperationAction(ISD::SELECT, MVT::i64, Custom);
208   setOperationAction(ISD::SELECT, MVT::f64, Promote);
209   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
210 
211   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
212   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
213   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
214   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
215   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
216 
217   setOperationAction(ISD::SETCC, MVT::i1, Promote);
218   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
219   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
220   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
221 
222   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
223   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
224   setOperationAction(ISD::TRUNCATE, MVT::v3i32, Expand);
225   setOperationAction(ISD::FP_ROUND, MVT::v3f32, Expand);
226   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
227   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
228   setOperationAction(ISD::TRUNCATE, MVT::v5i32, Expand);
229   setOperationAction(ISD::FP_ROUND, MVT::v5f32, Expand);
230   setOperationAction(ISD::TRUNCATE, MVT::v6i32, Expand);
231   setOperationAction(ISD::FP_ROUND, MVT::v6f32, Expand);
232   setOperationAction(ISD::TRUNCATE, MVT::v7i32, Expand);
233   setOperationAction(ISD::FP_ROUND, MVT::v7f32, Expand);
234   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
235   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
236   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
237   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
238 
239   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
240   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
241   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
242   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
243   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
244   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
245   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
246   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
247 
248   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
249   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
250   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
251   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
252   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
253   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
254 
255   setOperationAction(ISD::UADDO, MVT::i32, Legal);
256   setOperationAction(ISD::USUBO, MVT::i32, Legal);
257 
258   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
259   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
260 
261   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
262   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
263   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
264 
265 #if 0
266   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
267   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
268 #endif
269 
270   // We only support LOAD/STORE and vector manipulation ops for vectors
271   // with > 4 elements.
272   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
273                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
274                   MVT::v3i64, MVT::v3f64, MVT::v6i32, MVT::v6f32,
275                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
276                   MVT::v8i16, MVT::v8f16, MVT::v16i64, MVT::v16f64,
277                   MVT::v32i32, MVT::v32f32 }) {
278     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
279       switch (Op) {
280       case ISD::LOAD:
281       case ISD::STORE:
282       case ISD::BUILD_VECTOR:
283       case ISD::BITCAST:
284       case ISD::EXTRACT_VECTOR_ELT:
285       case ISD::INSERT_VECTOR_ELT:
286       case ISD::EXTRACT_SUBVECTOR:
287       case ISD::SCALAR_TO_VECTOR:
288         break;
289       case ISD::INSERT_SUBVECTOR:
290       case ISD::CONCAT_VECTORS:
291         setOperationAction(Op, VT, Custom);
292         break;
293       default:
294         setOperationAction(Op, VT, Expand);
295         break;
296       }
297     }
298   }
299 
300   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
301 
302   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
303   // is expanded to avoid having two separate loops in case the index is a VGPR.
304 
305   // Most operations are naturally 32-bit vector operations. We only support
306   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
307   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
308     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
309     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
310 
311     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
312     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
313 
314     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
315     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
316 
317     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
318     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
319   }
320 
321   for (MVT Vec64 : { MVT::v3i64, MVT::v3f64 }) {
322     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
323     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v6i32);
324 
325     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
326     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v6i32);
327 
328     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
329     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v6i32);
330 
331     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
332     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v6i32);
333   }
334 
335   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
336     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
337     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
338 
339     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
340     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
341 
342     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
343     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
344 
345     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
346     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
347   }
348 
349   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
350     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
351     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
352 
353     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
354     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
355 
356     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
357     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
358 
359     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
360     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
361   }
362 
363   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
364     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
365     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
366 
367     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
368     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
369 
370     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
371     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
372 
373     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
374     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
375   }
376 
377   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
378   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
379   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
380   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
381 
382   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
383   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
384 
385   // Avoid stack access for these.
386   // TODO: Generalize to more vector types.
387   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
388   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
389   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
390   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
391 
392   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
393   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
394   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
395   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
396   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
397   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
398 
399   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
400   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
401   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
402   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
403 
404   // Deal with vec3 vector operations when widened to vec4.
405   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
406   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
407   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
408   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
409 
410   // Deal with vec5/6/7 vector operations when widened to vec8.
411   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
412   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
413   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6i32, Custom);
414   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v6f32, Custom);
415   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7i32, Custom);
416   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v7f32, Custom);
417   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
418   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
419 
420   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
421   // and output demarshalling
422   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
423   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
424 
425   // We can't return success/failure, only the old value,
426   // let LLVM add the comparison
427   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
428   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
429 
430   if (Subtarget->hasFlatAddressSpace()) {
431     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
432     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
433   }
434 
435   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
436   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
437 
438   // FIXME: This should be narrowed to i32, but that only happens if i64 is
439   // illegal.
440   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
441   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
442   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
443 
444   // On SI this is s_memtime and s_memrealtime on VI.
445   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
446   setOperationAction(ISD::TRAP, MVT::Other, Custom);
447   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
448 
449   if (Subtarget->has16BitInsts()) {
450     setOperationAction(ISD::FPOW, MVT::f16, Promote);
451     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
452     setOperationAction(ISD::FLOG, MVT::f16, Custom);
453     setOperationAction(ISD::FEXP, MVT::f16, Custom);
454     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
455   }
456 
457   if (Subtarget->hasMadMacF32Insts())
458     setOperationAction(ISD::FMAD, MVT::f32, Legal);
459 
460   if (!Subtarget->hasBFI()) {
461     // fcopysign can be done in a single instruction with BFI.
462     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
463     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
464   }
465 
466   if (!Subtarget->hasBCNT(32))
467     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
468 
469   if (!Subtarget->hasBCNT(64))
470     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
471 
472   if (Subtarget->hasFFBH()) {
473     setOperationAction(ISD::CTLZ, MVT::i32, Custom);
474     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
475   }
476 
477   if (Subtarget->hasFFBL()) {
478     setOperationAction(ISD::CTTZ, MVT::i32, Custom);
479     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
480   }
481 
482   // We only really have 32-bit BFE instructions (and 16-bit on VI).
483   //
484   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
485   // effort to match them now. We want this to be false for i64 cases when the
486   // extraction isn't restricted to the upper or lower half. Ideally we would
487   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
488   // span the midpoint are probably relatively rare, so don't worry about them
489   // for now.
490   if (Subtarget->hasBFE())
491     setHasExtractBitsInsn(true);
492 
493   // Clamp modifier on add/sub
494   if (Subtarget->hasIntClamp()) {
495     setOperationAction(ISD::UADDSAT, MVT::i32, Legal);
496     setOperationAction(ISD::USUBSAT, MVT::i32, Legal);
497   }
498 
499   if (Subtarget->hasAddNoCarry()) {
500     setOperationAction(ISD::SADDSAT, MVT::i16, Legal);
501     setOperationAction(ISD::SSUBSAT, MVT::i16, Legal);
502     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
503     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
504   }
505 
506   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
507   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
508   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
509   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
510 
511 
512   // These are really only legal for ieee_mode functions. We should be avoiding
513   // them for functions that don't have ieee_mode enabled, so just say they are
514   // legal.
515   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
516   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
517   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
518   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
519 
520 
521   if (Subtarget->haveRoundOpsF64()) {
522     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
523     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
524     setOperationAction(ISD::FRINT, MVT::f64, Legal);
525   } else {
526     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
527     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
528     setOperationAction(ISD::FRINT, MVT::f64, Custom);
529     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
530   }
531 
532   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
533 
534   setOperationAction(ISD::FSIN, MVT::f32, Custom);
535   setOperationAction(ISD::FCOS, MVT::f32, Custom);
536   setOperationAction(ISD::FDIV, MVT::f32, Custom);
537   setOperationAction(ISD::FDIV, MVT::f64, Custom);
538 
539   if (Subtarget->has16BitInsts()) {
540     setOperationAction(ISD::Constant, MVT::i16, Legal);
541 
542     setOperationAction(ISD::SMIN, MVT::i16, Legal);
543     setOperationAction(ISD::SMAX, MVT::i16, Legal);
544 
545     setOperationAction(ISD::UMIN, MVT::i16, Legal);
546     setOperationAction(ISD::UMAX, MVT::i16, Legal);
547 
548     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
549     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
550 
551     setOperationAction(ISD::ROTR, MVT::i16, Expand);
552     setOperationAction(ISD::ROTL, MVT::i16, Expand);
553 
554     setOperationAction(ISD::SDIV, MVT::i16, Promote);
555     setOperationAction(ISD::UDIV, MVT::i16, Promote);
556     setOperationAction(ISD::SREM, MVT::i16, Promote);
557     setOperationAction(ISD::UREM, MVT::i16, Promote);
558     setOperationAction(ISD::UADDSAT, MVT::i16, Legal);
559     setOperationAction(ISD::USUBSAT, MVT::i16, Legal);
560 
561     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
562 
563     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
564     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
565     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
566     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
567     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
568 
569     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
570 
571     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
572 
573     setOperationAction(ISD::LOAD, MVT::i16, Custom);
574 
575     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
576 
577     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
578     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
579     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
580     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
581 
582     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Custom);
583     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Custom);
584 
585     // F16 - Constant Actions.
586     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
587 
588     // F16 - Load/Store Actions.
589     setOperationAction(ISD::LOAD, MVT::f16, Promote);
590     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
591     setOperationAction(ISD::STORE, MVT::f16, Promote);
592     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
593 
594     // F16 - VOP1 Actions.
595     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
596     setOperationAction(ISD::FCOS, MVT::f16, Custom);
597     setOperationAction(ISD::FSIN, MVT::f16, Custom);
598 
599     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
600     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
601 
602     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
603     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
604     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
605     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
606     setOperationAction(ISD::FROUND, MVT::f16, Custom);
607     setOperationAction(ISD::FPTRUNC_ROUND, MVT::f16, Custom);
608 
609     // F16 - VOP2 Actions.
610     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
611     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
612 
613     setOperationAction(ISD::FDIV, MVT::f16, Custom);
614 
615     // F16 - VOP3 Actions.
616     setOperationAction(ISD::FMA, MVT::f16, Legal);
617     if (STI.hasMadF16())
618       setOperationAction(ISD::FMAD, MVT::f16, Legal);
619 
620     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16, MVT::v8i16,
621                    MVT::v8f16}) {
622       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
623         switch (Op) {
624         case ISD::LOAD:
625         case ISD::STORE:
626         case ISD::BUILD_VECTOR:
627         case ISD::BITCAST:
628         case ISD::EXTRACT_VECTOR_ELT:
629         case ISD::INSERT_VECTOR_ELT:
630         case ISD::INSERT_SUBVECTOR:
631         case ISD::EXTRACT_SUBVECTOR:
632         case ISD::SCALAR_TO_VECTOR:
633           break;
634         case ISD::CONCAT_VECTORS:
635           setOperationAction(Op, VT, Custom);
636           break;
637         default:
638           setOperationAction(Op, VT, Expand);
639           break;
640         }
641       }
642     }
643 
644     // v_perm_b32 can handle either of these.
645     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
646     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
647     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
648 
649     // XXX - Do these do anything? Vector constants turn into build_vector.
650     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
651     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
652 
653     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
654     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
655 
656     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
657     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
658     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
659     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
660 
661     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
662     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
663     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
664     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
665 
666     setOperationAction(ISD::AND, MVT::v2i16, Promote);
667     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
668     setOperationAction(ISD::OR, MVT::v2i16, Promote);
669     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
670     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
671     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
672 
673     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
674     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
675     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
676     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
677 
678     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
679     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
680     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
681     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
682 
683     setOperationAction(ISD::LOAD, MVT::v8i16, Promote);
684     AddPromotedToType(ISD::LOAD, MVT::v8i16, MVT::v4i32);
685     setOperationAction(ISD::LOAD, MVT::v8f16, Promote);
686     AddPromotedToType(ISD::LOAD, MVT::v8f16, MVT::v4i32);
687 
688     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
689     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
690     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
691     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
692 
693     setOperationAction(ISD::STORE, MVT::v8i16, Promote);
694     AddPromotedToType(ISD::STORE, MVT::v8i16, MVT::v4i32);
695     setOperationAction(ISD::STORE, MVT::v8f16, Promote);
696     AddPromotedToType(ISD::STORE, MVT::v8f16, MVT::v4i32);
697 
698     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
699     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
700     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
701     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
702 
703     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
704     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
705     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
706 
707     setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Expand);
708     setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Expand);
709     setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Expand);
710 
711     if (!Subtarget->hasVOP3PInsts()) {
712       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
713       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
714     }
715 
716     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
717     // This isn't really legal, but this avoids the legalizer unrolling it (and
718     // allows matching fneg (fabs x) patterns)
719     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
720 
721     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
722     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
723     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
724     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
725 
726     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
727     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
728     setOperationAction(ISD::FMINNUM_IEEE, MVT::v8f16, Custom);
729     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v8f16, Custom);
730 
731     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
732     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
733     setOperationAction(ISD::FMINNUM, MVT::v8f16, Expand);
734     setOperationAction(ISD::FMAXNUM, MVT::v8f16, Expand);
735 
736     for (MVT Vec16 : { MVT::v8i16, MVT::v8f16 }) {
737       setOperationAction(ISD::BUILD_VECTOR, Vec16, Custom);
738       setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec16, Custom);
739       setOperationAction(ISD::INSERT_VECTOR_ELT, Vec16, Expand);
740       setOperationAction(ISD::SCALAR_TO_VECTOR, Vec16, Expand);
741     }
742   }
743 
744   if (Subtarget->hasVOP3PInsts()) {
745     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
746     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
747     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
748     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
749     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
750     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
751     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
752     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
753     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
754     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
755 
756     setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal);
757     setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal);
758     setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal);
759     setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal);
760 
761     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
762     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
763     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
764 
765     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
766     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
767 
768     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
769 
770     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
771     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
772 
773     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
774     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
775     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f16, Custom);
776     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i16, Custom);
777 
778     for (MVT VT : { MVT::v4i16, MVT::v8i16 }) {
779       // Split vector operations.
780       setOperationAction(ISD::SHL, VT, Custom);
781       setOperationAction(ISD::SRA, VT, Custom);
782       setOperationAction(ISD::SRL, VT, Custom);
783       setOperationAction(ISD::ADD, VT, Custom);
784       setOperationAction(ISD::SUB, VT, Custom);
785       setOperationAction(ISD::MUL, VT, Custom);
786 
787       setOperationAction(ISD::SMIN, VT, Custom);
788       setOperationAction(ISD::SMAX, VT, Custom);
789       setOperationAction(ISD::UMIN, VT, Custom);
790       setOperationAction(ISD::UMAX, VT, Custom);
791 
792       setOperationAction(ISD::UADDSAT, VT, Custom);
793       setOperationAction(ISD::SADDSAT, VT, Custom);
794       setOperationAction(ISD::USUBSAT, VT, Custom);
795       setOperationAction(ISD::SSUBSAT, VT, Custom);
796     }
797 
798     for (MVT VT : { MVT::v4f16, MVT::v8f16 }) {
799       // Split vector operations.
800       setOperationAction(ISD::FADD, VT, Custom);
801       setOperationAction(ISD::FMUL, VT, Custom);
802       setOperationAction(ISD::FMA, VT, Custom);
803       setOperationAction(ISD::FCANONICALIZE, VT, Custom);
804     }
805 
806     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
807     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
808 
809     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
810     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
811 
812     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
813     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
814     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
815 
816     if (Subtarget->hasPackedFP32Ops()) {
817       setOperationAction(ISD::FADD, MVT::v2f32, Legal);
818       setOperationAction(ISD::FMUL, MVT::v2f32, Legal);
819       setOperationAction(ISD::FMA,  MVT::v2f32, Legal);
820       setOperationAction(ISD::FNEG, MVT::v2f32, Legal);
821 
822       for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) {
823         setOperationAction(ISD::FADD, VT, Custom);
824         setOperationAction(ISD::FMUL, VT, Custom);
825         setOperationAction(ISD::FMA, VT, Custom);
826       }
827     }
828   }
829 
830   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
831   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
832 
833   if (Subtarget->has16BitInsts()) {
834     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
835     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
836     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
837     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
838   } else {
839     // Legalization hack.
840     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
841     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
842 
843     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
844     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
845   }
846 
847   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8,
848                   MVT::v8i16, MVT::v8f16 }) {
849     setOperationAction(ISD::SELECT, VT, Custom);
850   }
851 
852   setOperationAction(ISD::SMULO, MVT::i64, Custom);
853   setOperationAction(ISD::UMULO, MVT::i64, Custom);
854 
855   if (Subtarget->hasMad64_32()) {
856     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Custom);
857     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Custom);
858   }
859 
860   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
861   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
862   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
863   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
864   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
865   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
866   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
867 
868   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
869   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
870   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom);
871   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom);
872   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
873   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
874   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
875   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
876   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
877   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
878   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
879 
880   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
881   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
882   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
883   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom);
884   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom);
885   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
886   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
887   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
888   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
889   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
890 
891   setTargetDAGCombine(ISD::ADD);
892   setTargetDAGCombine(ISD::ADDCARRY);
893   setTargetDAGCombine(ISD::SUB);
894   setTargetDAGCombine(ISD::SUBCARRY);
895   setTargetDAGCombine(ISD::FADD);
896   setTargetDAGCombine(ISD::FSUB);
897   setTargetDAGCombine(ISD::FMINNUM);
898   setTargetDAGCombine(ISD::FMAXNUM);
899   setTargetDAGCombine(ISD::FMINNUM_IEEE);
900   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
901   setTargetDAGCombine(ISD::FMA);
902   setTargetDAGCombine(ISD::SMIN);
903   setTargetDAGCombine(ISD::SMAX);
904   setTargetDAGCombine(ISD::UMIN);
905   setTargetDAGCombine(ISD::UMAX);
906   setTargetDAGCombine(ISD::SETCC);
907   setTargetDAGCombine(ISD::AND);
908   setTargetDAGCombine(ISD::OR);
909   setTargetDAGCombine(ISD::XOR);
910   setTargetDAGCombine(ISD::SINT_TO_FP);
911   setTargetDAGCombine(ISD::UINT_TO_FP);
912   setTargetDAGCombine(ISD::FCANONICALIZE);
913   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
914   setTargetDAGCombine(ISD::ZERO_EXTEND);
915   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
916   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
917   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
918 
919   // All memory operations. Some folding on the pointer operand is done to help
920   // matching the constant offsets in the addressing modes.
921   setTargetDAGCombine(ISD::LOAD);
922   setTargetDAGCombine(ISD::STORE);
923   setTargetDAGCombine(ISD::ATOMIC_LOAD);
924   setTargetDAGCombine(ISD::ATOMIC_STORE);
925   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
926   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
927   setTargetDAGCombine(ISD::ATOMIC_SWAP);
928   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
929   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
930   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
931   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
932   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
933   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
934   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
935   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
936   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
937   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
938   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
939   setTargetDAGCombine(ISD::INTRINSIC_VOID);
940   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
941 
942   // FIXME: In other contexts we pretend this is a per-function property.
943   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
944 
945   setSchedulingPreference(Sched::RegPressure);
946 }
947 
948 const GCNSubtarget *SITargetLowering::getSubtarget() const {
949   return Subtarget;
950 }
951 
952 //===----------------------------------------------------------------------===//
953 // TargetLowering queries
954 //===----------------------------------------------------------------------===//
955 
956 // v_mad_mix* support a conversion from f16 to f32.
957 //
958 // There is only one special case when denormals are enabled we don't currently,
959 // where this is OK to use.
960 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
961                                        EVT DestVT, EVT SrcVT) const {
962   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
963           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
964     DestVT.getScalarType() == MVT::f32 &&
965     SrcVT.getScalarType() == MVT::f16 &&
966     // TODO: This probably only requires no input flushing?
967     !hasFP32Denormals(DAG.getMachineFunction());
968 }
969 
970 bool SITargetLowering::isFPExtFoldable(const MachineInstr &MI, unsigned Opcode,
971                                        LLT DestTy, LLT SrcTy) const {
972   return ((Opcode == TargetOpcode::G_FMAD && Subtarget->hasMadMixInsts()) ||
973           (Opcode == TargetOpcode::G_FMA && Subtarget->hasFmaMixInsts())) &&
974          DestTy.getScalarSizeInBits() == 32 &&
975          SrcTy.getScalarSizeInBits() == 16 &&
976          // TODO: This probably only requires no input flushing?
977          !hasFP32Denormals(*MI.getMF());
978 }
979 
980 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
981   // SI has some legal vector types, but no legal vector operations. Say no
982   // shuffles are legal in order to prefer scalarizing some vector operations.
983   return false;
984 }
985 
986 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
987                                                     CallingConv::ID CC,
988                                                     EVT VT) const {
989   if (CC == CallingConv::AMDGPU_KERNEL)
990     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
991 
992   if (VT.isVector()) {
993     EVT ScalarVT = VT.getScalarType();
994     unsigned Size = ScalarVT.getSizeInBits();
995     if (Size == 16) {
996       if (Subtarget->has16BitInsts())
997         return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
998       return VT.isInteger() ? MVT::i32 : MVT::f32;
999     }
1000 
1001     if (Size < 16)
1002       return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
1003     return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
1004   }
1005 
1006   if (VT.getSizeInBits() > 32)
1007     return MVT::i32;
1008 
1009   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1010 }
1011 
1012 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1013                                                          CallingConv::ID CC,
1014                                                          EVT VT) const {
1015   if (CC == CallingConv::AMDGPU_KERNEL)
1016     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1017 
1018   if (VT.isVector()) {
1019     unsigned NumElts = VT.getVectorNumElements();
1020     EVT ScalarVT = VT.getScalarType();
1021     unsigned Size = ScalarVT.getSizeInBits();
1022 
1023     // FIXME: Should probably promote 8-bit vectors to i16.
1024     if (Size == 16 && Subtarget->has16BitInsts())
1025       return (NumElts + 1) / 2;
1026 
1027     if (Size <= 32)
1028       return NumElts;
1029 
1030     if (Size > 32)
1031       return NumElts * ((Size + 31) / 32);
1032   } else if (VT.getSizeInBits() > 32)
1033     return (VT.getSizeInBits() + 31) / 32;
1034 
1035   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1036 }
1037 
1038 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
1039   LLVMContext &Context, CallingConv::ID CC,
1040   EVT VT, EVT &IntermediateVT,
1041   unsigned &NumIntermediates, MVT &RegisterVT) const {
1042   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
1043     unsigned NumElts = VT.getVectorNumElements();
1044     EVT ScalarVT = VT.getScalarType();
1045     unsigned Size = ScalarVT.getSizeInBits();
1046     // FIXME: We should fix the ABI to be the same on targets without 16-bit
1047     // support, but unless we can properly handle 3-vectors, it will be still be
1048     // inconsistent.
1049     if (Size == 16 && Subtarget->has16BitInsts()) {
1050       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
1051       IntermediateVT = RegisterVT;
1052       NumIntermediates = (NumElts + 1) / 2;
1053       return NumIntermediates;
1054     }
1055 
1056     if (Size == 32) {
1057       RegisterVT = ScalarVT.getSimpleVT();
1058       IntermediateVT = RegisterVT;
1059       NumIntermediates = NumElts;
1060       return NumIntermediates;
1061     }
1062 
1063     if (Size < 16 && Subtarget->has16BitInsts()) {
1064       // FIXME: Should probably form v2i16 pieces
1065       RegisterVT = MVT::i16;
1066       IntermediateVT = ScalarVT;
1067       NumIntermediates = NumElts;
1068       return NumIntermediates;
1069     }
1070 
1071 
1072     if (Size != 16 && Size <= 32) {
1073       RegisterVT = MVT::i32;
1074       IntermediateVT = ScalarVT;
1075       NumIntermediates = NumElts;
1076       return NumIntermediates;
1077     }
1078 
1079     if (Size > 32) {
1080       RegisterVT = MVT::i32;
1081       IntermediateVT = RegisterVT;
1082       NumIntermediates = NumElts * ((Size + 31) / 32);
1083       return NumIntermediates;
1084     }
1085   }
1086 
1087   return TargetLowering::getVectorTypeBreakdownForCallingConv(
1088     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
1089 }
1090 
1091 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
1092   assert(DMaskLanes != 0);
1093 
1094   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1095     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
1096     return EVT::getVectorVT(Ty->getContext(),
1097                             EVT::getEVT(VT->getElementType()),
1098                             NumElts);
1099   }
1100 
1101   return EVT::getEVT(Ty);
1102 }
1103 
1104 // Peek through TFE struct returns to only use the data size.
1105 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
1106   auto *ST = dyn_cast<StructType>(Ty);
1107   if (!ST)
1108     return memVTFromImageData(Ty, DMaskLanes);
1109 
1110   // Some intrinsics return an aggregate type - special case to work out the
1111   // correct memVT.
1112   //
1113   // Only limited forms of aggregate type currently expected.
1114   if (ST->getNumContainedTypes() != 2 ||
1115       !ST->getContainedType(1)->isIntegerTy(32))
1116     return EVT();
1117   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
1118 }
1119 
1120 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1121                                           const CallInst &CI,
1122                                           MachineFunction &MF,
1123                                           unsigned IntrID) const {
1124   Info.flags = MachineMemOperand::MONone;
1125   if (CI.hasMetadata(LLVMContext::MD_invariant_load))
1126     Info.flags |= MachineMemOperand::MOInvariant;
1127 
1128   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1129           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1130     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1131                                                   (Intrinsic::ID)IntrID);
1132     if (Attr.hasFnAttr(Attribute::ReadNone))
1133       return false;
1134 
1135     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1136 
1137     if (RsrcIntr->IsImage) {
1138       Info.ptrVal =
1139           MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1140       Info.align.reset();
1141     } else {
1142       Info.ptrVal =
1143           MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1144     }
1145 
1146     Info.flags |= MachineMemOperand::MODereferenceable;
1147     if (Attr.hasFnAttr(Attribute::ReadOnly)) {
1148       unsigned DMaskLanes = 4;
1149 
1150       if (RsrcIntr->IsImage) {
1151         const AMDGPU::ImageDimIntrinsicInfo *Intr
1152           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1153         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1154           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1155 
1156         if (!BaseOpcode->Gather4) {
1157           // If this isn't a gather, we may have excess loaded elements in the
1158           // IR type. Check the dmask for the real number of elements loaded.
1159           unsigned DMask
1160             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1161           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1162         }
1163 
1164         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1165       } else
1166         Info.memVT = EVT::getEVT(CI.getType());
1167 
1168       // FIXME: What does alignment mean for an image?
1169       Info.opc = ISD::INTRINSIC_W_CHAIN;
1170       Info.flags |= MachineMemOperand::MOLoad;
1171     } else if (Attr.hasFnAttr(Attribute::WriteOnly)) {
1172       Info.opc = ISD::INTRINSIC_VOID;
1173 
1174       Type *DataTy = CI.getArgOperand(0)->getType();
1175       if (RsrcIntr->IsImage) {
1176         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1177         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1178         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1179       } else
1180         Info.memVT = EVT::getEVT(DataTy);
1181 
1182       Info.flags |= MachineMemOperand::MOStore;
1183     } else {
1184       // Atomic
1185       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1186                                             ISD::INTRINSIC_W_CHAIN;
1187       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1188       Info.flags |= MachineMemOperand::MOLoad |
1189                     MachineMemOperand::MOStore |
1190                     MachineMemOperand::MODereferenceable;
1191 
1192       // XXX - Should this be volatile without known ordering?
1193       Info.flags |= MachineMemOperand::MOVolatile;
1194     }
1195     return true;
1196   }
1197 
1198   switch (IntrID) {
1199   case Intrinsic::amdgcn_atomic_inc:
1200   case Intrinsic::amdgcn_atomic_dec:
1201   case Intrinsic::amdgcn_ds_ordered_add:
1202   case Intrinsic::amdgcn_ds_ordered_swap:
1203   case Intrinsic::amdgcn_ds_fadd:
1204   case Intrinsic::amdgcn_ds_fmin:
1205   case Intrinsic::amdgcn_ds_fmax: {
1206     Info.opc = ISD::INTRINSIC_W_CHAIN;
1207     Info.memVT = MVT::getVT(CI.getType());
1208     Info.ptrVal = CI.getOperand(0);
1209     Info.align.reset();
1210     Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1211 
1212     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1213     if (!Vol->isZero())
1214       Info.flags |= MachineMemOperand::MOVolatile;
1215 
1216     return true;
1217   }
1218   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1219     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1220 
1221     Info.opc = ISD::INTRINSIC_W_CHAIN;
1222     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1223     Info.ptrVal =
1224         MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1225     Info.align.reset();
1226     Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1227 
1228     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1229     if (!Vol || !Vol->isZero())
1230       Info.flags |= MachineMemOperand::MOVolatile;
1231 
1232     return true;
1233   }
1234   case Intrinsic::amdgcn_ds_append:
1235   case Intrinsic::amdgcn_ds_consume: {
1236     Info.opc = ISD::INTRINSIC_W_CHAIN;
1237     Info.memVT = MVT::getVT(CI.getType());
1238     Info.ptrVal = CI.getOperand(0);
1239     Info.align.reset();
1240     Info.flags |= MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1241 
1242     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1243     if (!Vol->isZero())
1244       Info.flags |= MachineMemOperand::MOVolatile;
1245 
1246     return true;
1247   }
1248   case Intrinsic::amdgcn_global_atomic_csub: {
1249     Info.opc = ISD::INTRINSIC_W_CHAIN;
1250     Info.memVT = MVT::getVT(CI.getType());
1251     Info.ptrVal = CI.getOperand(0);
1252     Info.align.reset();
1253     Info.flags |= MachineMemOperand::MOLoad |
1254                   MachineMemOperand::MOStore |
1255                   MachineMemOperand::MOVolatile;
1256     return true;
1257   }
1258   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1259     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1260     Info.opc = ISD::INTRINSIC_W_CHAIN;
1261     Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1262     Info.ptrVal =
1263         MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1264     Info.align.reset();
1265     Info.flags |= MachineMemOperand::MOLoad |
1266                   MachineMemOperand::MODereferenceable;
1267     return true;
1268   }
1269   case Intrinsic::amdgcn_global_atomic_fadd:
1270   case Intrinsic::amdgcn_global_atomic_fmin:
1271   case Intrinsic::amdgcn_global_atomic_fmax:
1272   case Intrinsic::amdgcn_flat_atomic_fadd:
1273   case Intrinsic::amdgcn_flat_atomic_fmin:
1274   case Intrinsic::amdgcn_flat_atomic_fmax:
1275   case Intrinsic::amdgcn_global_atomic_fadd_v2bf16:
1276   case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16: {
1277     Info.opc = ISD::INTRINSIC_W_CHAIN;
1278     Info.memVT = MVT::getVT(CI.getType());
1279     Info.ptrVal = CI.getOperand(0);
1280     Info.align.reset();
1281     Info.flags |= MachineMemOperand::MOLoad |
1282                   MachineMemOperand::MOStore |
1283                   MachineMemOperand::MODereferenceable |
1284                   MachineMemOperand::MOVolatile;
1285     return true;
1286   }
1287   case Intrinsic::amdgcn_ds_gws_init:
1288   case Intrinsic::amdgcn_ds_gws_barrier:
1289   case Intrinsic::amdgcn_ds_gws_sema_v:
1290   case Intrinsic::amdgcn_ds_gws_sema_br:
1291   case Intrinsic::amdgcn_ds_gws_sema_p:
1292   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1293     Info.opc = ISD::INTRINSIC_VOID;
1294 
1295     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1296     Info.ptrVal =
1297         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1298 
1299     // This is an abstract access, but we need to specify a type and size.
1300     Info.memVT = MVT::i32;
1301     Info.size = 4;
1302     Info.align = Align(4);
1303 
1304     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1305       Info.flags |= MachineMemOperand::MOLoad;
1306     else
1307       Info.flags |= MachineMemOperand::MOStore;
1308     return true;
1309   }
1310   default:
1311     return false;
1312   }
1313 }
1314 
1315 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1316                                             SmallVectorImpl<Value*> &Ops,
1317                                             Type *&AccessTy) const {
1318   switch (II->getIntrinsicID()) {
1319   case Intrinsic::amdgcn_atomic_inc:
1320   case Intrinsic::amdgcn_atomic_dec:
1321   case Intrinsic::amdgcn_ds_ordered_add:
1322   case Intrinsic::amdgcn_ds_ordered_swap:
1323   case Intrinsic::amdgcn_ds_append:
1324   case Intrinsic::amdgcn_ds_consume:
1325   case Intrinsic::amdgcn_ds_fadd:
1326   case Intrinsic::amdgcn_ds_fmin:
1327   case Intrinsic::amdgcn_ds_fmax:
1328   case Intrinsic::amdgcn_global_atomic_fadd:
1329   case Intrinsic::amdgcn_flat_atomic_fadd:
1330   case Intrinsic::amdgcn_flat_atomic_fmin:
1331   case Intrinsic::amdgcn_flat_atomic_fmax:
1332   case Intrinsic::amdgcn_global_atomic_fadd_v2bf16:
1333   case Intrinsic::amdgcn_flat_atomic_fadd_v2bf16:
1334   case Intrinsic::amdgcn_global_atomic_csub: {
1335     Value *Ptr = II->getArgOperand(0);
1336     AccessTy = II->getType();
1337     Ops.push_back(Ptr);
1338     return true;
1339   }
1340   default:
1341     return false;
1342   }
1343 }
1344 
1345 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1346   if (!Subtarget->hasFlatInstOffsets()) {
1347     // Flat instructions do not have offsets, and only have the register
1348     // address.
1349     return AM.BaseOffs == 0 && AM.Scale == 0;
1350   }
1351 
1352   return AM.Scale == 0 &&
1353          (AM.BaseOffs == 0 ||
1354           Subtarget->getInstrInfo()->isLegalFLATOffset(
1355               AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, SIInstrFlags::FLAT));
1356 }
1357 
1358 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1359   if (Subtarget->hasFlatGlobalInsts())
1360     return AM.Scale == 0 &&
1361            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1362                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1363                                     SIInstrFlags::FlatGlobal));
1364 
1365   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1366       // Assume the we will use FLAT for all global memory accesses
1367       // on VI.
1368       // FIXME: This assumption is currently wrong.  On VI we still use
1369       // MUBUF instructions for the r + i addressing mode.  As currently
1370       // implemented, the MUBUF instructions only work on buffer < 4GB.
1371       // It may be possible to support > 4GB buffers with MUBUF instructions,
1372       // by setting the stride value in the resource descriptor which would
1373       // increase the size limit to (stride * 4GB).  However, this is risky,
1374       // because it has never been validated.
1375     return isLegalFlatAddressingMode(AM);
1376   }
1377 
1378   return isLegalMUBUFAddressingMode(AM);
1379 }
1380 
1381 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1382   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1383   // additionally can do r + r + i with addr64. 32-bit has more addressing
1384   // mode options. Depending on the resource constant, it can also do
1385   // (i64 r0) + (i32 r1) * (i14 i).
1386   //
1387   // Private arrays end up using a scratch buffer most of the time, so also
1388   // assume those use MUBUF instructions. Scratch loads / stores are currently
1389   // implemented as mubuf instructions with offen bit set, so slightly
1390   // different than the normal addr64.
1391   if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1392     return false;
1393 
1394   // FIXME: Since we can split immediate into soffset and immediate offset,
1395   // would it make sense to allow any immediate?
1396 
1397   switch (AM.Scale) {
1398   case 0: // r + i or just i, depending on HasBaseReg.
1399     return true;
1400   case 1:
1401     return true; // We have r + r or r + i.
1402   case 2:
1403     if (AM.HasBaseReg) {
1404       // Reject 2 * r + r.
1405       return false;
1406     }
1407 
1408     // Allow 2 * r as r + r
1409     // Or  2 * r + i is allowed as r + r + i.
1410     return true;
1411   default: // Don't allow n * r
1412     return false;
1413   }
1414 }
1415 
1416 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1417                                              const AddrMode &AM, Type *Ty,
1418                                              unsigned AS, Instruction *I) const {
1419   // No global is ever allowed as a base.
1420   if (AM.BaseGV)
1421     return false;
1422 
1423   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1424     return isLegalGlobalAddressingMode(AM);
1425 
1426   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1427       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1428       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1429     // If the offset isn't a multiple of 4, it probably isn't going to be
1430     // correctly aligned.
1431     // FIXME: Can we get the real alignment here?
1432     if (AM.BaseOffs % 4 != 0)
1433       return isLegalMUBUFAddressingMode(AM);
1434 
1435     // There are no SMRD extloads, so if we have to do a small type access we
1436     // will use a MUBUF load.
1437     // FIXME?: We also need to do this if unaligned, but we don't know the
1438     // alignment here.
1439     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1440       return isLegalGlobalAddressingMode(AM);
1441 
1442     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1443       // SMRD instructions have an 8-bit, dword offset on SI.
1444       if (!isUInt<8>(AM.BaseOffs / 4))
1445         return false;
1446     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1447       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1448       // in 8-bits, it can use a smaller encoding.
1449       if (!isUInt<32>(AM.BaseOffs / 4))
1450         return false;
1451     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1452       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1453       if (!isUInt<20>(AM.BaseOffs))
1454         return false;
1455     } else
1456       llvm_unreachable("unhandled generation");
1457 
1458     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1459       return true;
1460 
1461     if (AM.Scale == 1 && AM.HasBaseReg)
1462       return true;
1463 
1464     return false;
1465 
1466   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1467     return isLegalMUBUFAddressingMode(AM);
1468   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1469              AS == AMDGPUAS::REGION_ADDRESS) {
1470     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1471     // field.
1472     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1473     // an 8-bit dword offset but we don't know the alignment here.
1474     if (!isUInt<16>(AM.BaseOffs))
1475       return false;
1476 
1477     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1478       return true;
1479 
1480     if (AM.Scale == 1 && AM.HasBaseReg)
1481       return true;
1482 
1483     return false;
1484   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1485              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1486     // For an unknown address space, this usually means that this is for some
1487     // reason being used for pure arithmetic, and not based on some addressing
1488     // computation. We don't have instructions that compute pointers with any
1489     // addressing modes, so treat them as having no offset like flat
1490     // instructions.
1491     return isLegalFlatAddressingMode(AM);
1492   }
1493 
1494   // Assume a user alias of global for unknown address spaces.
1495   return isLegalGlobalAddressingMode(AM);
1496 }
1497 
1498 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1499                                         const MachineFunction &MF) const {
1500   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1501     return (MemVT.getSizeInBits() <= 4 * 32);
1502   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1503     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1504     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1505   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1506     return (MemVT.getSizeInBits() <= 2 * 32);
1507   }
1508   return true;
1509 }
1510 
1511 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1512     unsigned Size, unsigned AddrSpace, Align Alignment,
1513     MachineMemOperand::Flags Flags, bool *IsFast) const {
1514   if (IsFast)
1515     *IsFast = false;
1516 
1517   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1518       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1519     // Check if alignment requirements for ds_read/write instructions are
1520     // disabled.
1521     if (Subtarget->hasUnalignedDSAccessEnabled() &&
1522         !Subtarget->hasLDSMisalignedBug()) {
1523       if (IsFast)
1524         *IsFast = Alignment != Align(2);
1525       return true;
1526     }
1527 
1528     // Either, the alignment requirements are "enabled", or there is an
1529     // unaligned LDS access related hardware bug though alignment requirements
1530     // are "disabled". In either case, we need to check for proper alignment
1531     // requirements.
1532     //
1533     if (Size == 64) {
1534       // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
1535       // can do a 4 byte aligned, 8 byte access in a single operation using
1536       // ds_read2/write2_b32 with adjacent offsets.
1537       bool AlignedBy4 = Alignment >= Align(4);
1538       if (IsFast)
1539         *IsFast = AlignedBy4;
1540 
1541       return AlignedBy4;
1542     }
1543     if (Size == 96) {
1544       // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
1545       // gfx8 and older.
1546       bool AlignedBy16 = Alignment >= Align(16);
1547       if (IsFast)
1548         *IsFast = AlignedBy16;
1549 
1550       return AlignedBy16;
1551     }
1552     if (Size == 128) {
1553       // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
1554       // gfx8 and older, but  we can do a 8 byte aligned, 16 byte access in a
1555       // single operation using ds_read2/write2_b64.
1556       bool AlignedBy8 = Alignment >= Align(8);
1557       if (IsFast)
1558         *IsFast = AlignedBy8;
1559 
1560       return AlignedBy8;
1561     }
1562   }
1563 
1564   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1565     bool AlignedBy4 = Alignment >= Align(4);
1566     if (IsFast)
1567       *IsFast = AlignedBy4;
1568 
1569     return AlignedBy4 ||
1570            Subtarget->enableFlatScratch() ||
1571            Subtarget->hasUnalignedScratchAccess();
1572   }
1573 
1574   // FIXME: We have to be conservative here and assume that flat operations
1575   // will access scratch.  If we had access to the IR function, then we
1576   // could determine if any private memory was used in the function.
1577   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1578       !Subtarget->hasUnalignedScratchAccess()) {
1579     bool AlignedBy4 = Alignment >= Align(4);
1580     if (IsFast)
1581       *IsFast = AlignedBy4;
1582 
1583     return AlignedBy4;
1584   }
1585 
1586   if (Subtarget->hasUnalignedBufferAccessEnabled() &&
1587       !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1588         AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1589     // If we have a uniform constant load, it still requires using a slow
1590     // buffer instruction if unaligned.
1591     if (IsFast) {
1592       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1593       // 2-byte alignment is worse than 1 unless doing a 2-byte access.
1594       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1595                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1596         Alignment >= Align(4) : Alignment != Align(2);
1597     }
1598 
1599     return true;
1600   }
1601 
1602   // Smaller than dword value must be aligned.
1603   if (Size < 32)
1604     return false;
1605 
1606   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1607   // byte-address are ignored, thus forcing Dword alignment.
1608   // This applies to private, global, and constant memory.
1609   if (IsFast)
1610     *IsFast = true;
1611 
1612   return Size >= 32 && Alignment >= Align(4);
1613 }
1614 
1615 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1616     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1617     bool *IsFast) const {
1618   if (IsFast)
1619     *IsFast = false;
1620 
1621   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1622   // which isn't a simple VT.
1623   // Until MVT is extended to handle this, simply check for the size and
1624   // rely on the condition below: allow accesses if the size is a multiple of 4.
1625   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1626                            VT.getStoreSize() > 16)) {
1627     return false;
1628   }
1629 
1630   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1631                                             Alignment, Flags, IsFast);
1632 }
1633 
1634 EVT SITargetLowering::getOptimalMemOpType(
1635     const MemOp &Op, const AttributeList &FuncAttributes) const {
1636   // FIXME: Should account for address space here.
1637 
1638   // The default fallback uses the private pointer size as a guess for a type to
1639   // use. Make sure we switch these to 64-bit accesses.
1640 
1641   if (Op.size() >= 16 &&
1642       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1643     return MVT::v4i32;
1644 
1645   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1646     return MVT::v2i32;
1647 
1648   // Use the default.
1649   return MVT::Other;
1650 }
1651 
1652 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1653   const MemSDNode *MemNode = cast<MemSDNode>(N);
1654   return MemNode->getMemOperand()->getFlags() & MONoClobber;
1655 }
1656 
1657 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1658   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1659          AS == AMDGPUAS::PRIVATE_ADDRESS;
1660 }
1661 
1662 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1663                                            unsigned DestAS) const {
1664   // Flat -> private/local is a simple truncate.
1665   // Flat -> global is no-op
1666   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1667     return true;
1668 
1669   const GCNTargetMachine &TM =
1670       static_cast<const GCNTargetMachine &>(getTargetMachine());
1671   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1672 }
1673 
1674 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1675   const MemSDNode *MemNode = cast<MemSDNode>(N);
1676 
1677   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1678 }
1679 
1680 TargetLoweringBase::LegalizeTypeAction
1681 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1682   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1683       VT.getScalarType().bitsLE(MVT::i16))
1684     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1685   return TargetLoweringBase::getPreferredVectorAction(VT);
1686 }
1687 
1688 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1689                                                          Type *Ty) const {
1690   // FIXME: Could be smarter if called for vector constants.
1691   return true;
1692 }
1693 
1694 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1695   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1696     switch (Op) {
1697     case ISD::LOAD:
1698     case ISD::STORE:
1699 
1700     // These operations are done with 32-bit instructions anyway.
1701     case ISD::AND:
1702     case ISD::OR:
1703     case ISD::XOR:
1704     case ISD::SELECT:
1705       // TODO: Extensions?
1706       return true;
1707     default:
1708       return false;
1709     }
1710   }
1711 
1712   // SimplifySetCC uses this function to determine whether or not it should
1713   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1714   if (VT == MVT::i1 && Op == ISD::SETCC)
1715     return false;
1716 
1717   return TargetLowering::isTypeDesirableForOp(Op, VT);
1718 }
1719 
1720 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1721                                                    const SDLoc &SL,
1722                                                    SDValue Chain,
1723                                                    uint64_t Offset) const {
1724   const DataLayout &DL = DAG.getDataLayout();
1725   MachineFunction &MF = DAG.getMachineFunction();
1726   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1727 
1728   const ArgDescriptor *InputPtrReg;
1729   const TargetRegisterClass *RC;
1730   LLT ArgTy;
1731   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1732 
1733   std::tie(InputPtrReg, RC, ArgTy) =
1734       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1735 
1736   // We may not have the kernarg segment argument if we have no kernel
1737   // arguments.
1738   if (!InputPtrReg)
1739     return DAG.getConstant(0, SL, PtrVT);
1740 
1741   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1742   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1743     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1744 
1745   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1746 }
1747 
1748 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1749                                             const SDLoc &SL) const {
1750   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1751                                                FIRST_IMPLICIT);
1752   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1753 }
1754 
1755 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1756                                          const SDLoc &SL, SDValue Val,
1757                                          bool Signed,
1758                                          const ISD::InputArg *Arg) const {
1759   // First, if it is a widened vector, narrow it.
1760   if (VT.isVector() &&
1761       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1762     EVT NarrowedVT =
1763         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1764                          VT.getVectorNumElements());
1765     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1766                       DAG.getConstant(0, SL, MVT::i32));
1767   }
1768 
1769   // Then convert the vector elements or scalar value.
1770   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1771       VT.bitsLT(MemVT)) {
1772     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1773     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1774   }
1775 
1776   if (MemVT.isFloatingPoint())
1777     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1778   else if (Signed)
1779     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1780   else
1781     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1782 
1783   return Val;
1784 }
1785 
1786 SDValue SITargetLowering::lowerKernargMemParameter(
1787     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1788     uint64_t Offset, Align Alignment, bool Signed,
1789     const ISD::InputArg *Arg) const {
1790   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1791 
1792   // Try to avoid using an extload by loading earlier than the argument address,
1793   // and extracting the relevant bits. The load should hopefully be merged with
1794   // the previous argument.
1795   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1796     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1797     int64_t AlignDownOffset = alignDown(Offset, 4);
1798     int64_t OffsetDiff = Offset - AlignDownOffset;
1799 
1800     EVT IntVT = MemVT.changeTypeToInteger();
1801 
1802     // TODO: If we passed in the base kernel offset we could have a better
1803     // alignment than 4, but we don't really need it.
1804     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1805     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1806                                MachineMemOperand::MODereferenceable |
1807                                    MachineMemOperand::MOInvariant);
1808 
1809     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1810     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1811 
1812     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1813     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1814     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1815 
1816 
1817     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1818   }
1819 
1820   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1821   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1822                              MachineMemOperand::MODereferenceable |
1823                                  MachineMemOperand::MOInvariant);
1824 
1825   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1826   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1827 }
1828 
1829 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1830                                               const SDLoc &SL, SDValue Chain,
1831                                               const ISD::InputArg &Arg) const {
1832   MachineFunction &MF = DAG.getMachineFunction();
1833   MachineFrameInfo &MFI = MF.getFrameInfo();
1834 
1835   if (Arg.Flags.isByVal()) {
1836     unsigned Size = Arg.Flags.getByValSize();
1837     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1838     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1839   }
1840 
1841   unsigned ArgOffset = VA.getLocMemOffset();
1842   unsigned ArgSize = VA.getValVT().getStoreSize();
1843 
1844   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1845 
1846   // Create load nodes to retrieve arguments from the stack.
1847   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1848   SDValue ArgValue;
1849 
1850   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1851   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1852   MVT MemVT = VA.getValVT();
1853 
1854   switch (VA.getLocInfo()) {
1855   default:
1856     break;
1857   case CCValAssign::BCvt:
1858     MemVT = VA.getLocVT();
1859     break;
1860   case CCValAssign::SExt:
1861     ExtType = ISD::SEXTLOAD;
1862     break;
1863   case CCValAssign::ZExt:
1864     ExtType = ISD::ZEXTLOAD;
1865     break;
1866   case CCValAssign::AExt:
1867     ExtType = ISD::EXTLOAD;
1868     break;
1869   }
1870 
1871   ArgValue = DAG.getExtLoad(
1872     ExtType, SL, VA.getLocVT(), Chain, FIN,
1873     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1874     MemVT);
1875   return ArgValue;
1876 }
1877 
1878 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1879   const SIMachineFunctionInfo &MFI,
1880   EVT VT,
1881   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1882   const ArgDescriptor *Reg;
1883   const TargetRegisterClass *RC;
1884   LLT Ty;
1885 
1886   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1887   if (!Reg) {
1888     if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) {
1889       // It's possible for a kernarg intrinsic call to appear in a kernel with
1890       // no allocated segment, in which case we do not add the user sgpr
1891       // argument, so just return null.
1892       return DAG.getConstant(0, SDLoc(), VT);
1893     }
1894 
1895     // It's undefined behavior if a function marked with the amdgpu-no-*
1896     // attributes uses the corresponding intrinsic.
1897     return DAG.getUNDEF(VT);
1898   }
1899 
1900   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1901 }
1902 
1903 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1904                                CallingConv::ID CallConv,
1905                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1906                                FunctionType *FType,
1907                                SIMachineFunctionInfo *Info) {
1908   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1909     const ISD::InputArg *Arg = &Ins[I];
1910 
1911     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1912            "vector type argument should have been split");
1913 
1914     // First check if it's a PS input addr.
1915     if (CallConv == CallingConv::AMDGPU_PS &&
1916         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1917       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1918 
1919       // Inconveniently only the first part of the split is marked as isSplit,
1920       // so skip to the end. We only want to increment PSInputNum once for the
1921       // entire split argument.
1922       if (Arg->Flags.isSplit()) {
1923         while (!Arg->Flags.isSplitEnd()) {
1924           assert((!Arg->VT.isVector() ||
1925                   Arg->VT.getScalarSizeInBits() == 16) &&
1926                  "unexpected vector split in ps argument type");
1927           if (!SkipArg)
1928             Splits.push_back(*Arg);
1929           Arg = &Ins[++I];
1930         }
1931       }
1932 
1933       if (SkipArg) {
1934         // We can safely skip PS inputs.
1935         Skipped.set(Arg->getOrigArgIndex());
1936         ++PSInputNum;
1937         continue;
1938       }
1939 
1940       Info->markPSInputAllocated(PSInputNum);
1941       if (Arg->Used)
1942         Info->markPSInputEnabled(PSInputNum);
1943 
1944       ++PSInputNum;
1945     }
1946 
1947     Splits.push_back(*Arg);
1948   }
1949 }
1950 
1951 // Allocate special inputs passed in VGPRs.
1952 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1953                                                       MachineFunction &MF,
1954                                                       const SIRegisterInfo &TRI,
1955                                                       SIMachineFunctionInfo &Info) const {
1956   const LLT S32 = LLT::scalar(32);
1957   MachineRegisterInfo &MRI = MF.getRegInfo();
1958 
1959   if (Info.hasWorkItemIDX()) {
1960     Register Reg = AMDGPU::VGPR0;
1961     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1962 
1963     CCInfo.AllocateReg(Reg);
1964     unsigned Mask = (Subtarget->hasPackedTID() &&
1965                      Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
1966     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1967   }
1968 
1969   if (Info.hasWorkItemIDY()) {
1970     assert(Info.hasWorkItemIDX());
1971     if (Subtarget->hasPackedTID()) {
1972       Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1973                                                         0x3ff << 10));
1974     } else {
1975       unsigned Reg = AMDGPU::VGPR1;
1976       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1977 
1978       CCInfo.AllocateReg(Reg);
1979       Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1980     }
1981   }
1982 
1983   if (Info.hasWorkItemIDZ()) {
1984     assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
1985     if (Subtarget->hasPackedTID()) {
1986       Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
1987                                                         0x3ff << 20));
1988     } else {
1989       unsigned Reg = AMDGPU::VGPR2;
1990       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1991 
1992       CCInfo.AllocateReg(Reg);
1993       Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1994     }
1995   }
1996 }
1997 
1998 // Try to allocate a VGPR at the end of the argument list, or if no argument
1999 // VGPRs are left allocating a stack slot.
2000 // If \p Mask is is given it indicates bitfield position in the register.
2001 // If \p Arg is given use it with new ]p Mask instead of allocating new.
2002 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
2003                                          ArgDescriptor Arg = ArgDescriptor()) {
2004   if (Arg.isSet())
2005     return ArgDescriptor::createArg(Arg, Mask);
2006 
2007   ArrayRef<MCPhysReg> ArgVGPRs
2008     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
2009   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
2010   if (RegIdx == ArgVGPRs.size()) {
2011     // Spill to stack required.
2012     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
2013 
2014     return ArgDescriptor::createStack(Offset, Mask);
2015   }
2016 
2017   unsigned Reg = ArgVGPRs[RegIdx];
2018   Reg = CCInfo.AllocateReg(Reg);
2019   assert(Reg != AMDGPU::NoRegister);
2020 
2021   MachineFunction &MF = CCInfo.getMachineFunction();
2022   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
2023   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
2024   return ArgDescriptor::createRegister(Reg, Mask);
2025 }
2026 
2027 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
2028                                              const TargetRegisterClass *RC,
2029                                              unsigned NumArgRegs) {
2030   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
2031   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
2032   if (RegIdx == ArgSGPRs.size())
2033     report_fatal_error("ran out of SGPRs for arguments");
2034 
2035   unsigned Reg = ArgSGPRs[RegIdx];
2036   Reg = CCInfo.AllocateReg(Reg);
2037   assert(Reg != AMDGPU::NoRegister);
2038 
2039   MachineFunction &MF = CCInfo.getMachineFunction();
2040   MF.addLiveIn(Reg, RC);
2041   return ArgDescriptor::createRegister(Reg);
2042 }
2043 
2044 // If this has a fixed position, we still should allocate the register in the
2045 // CCInfo state. Technically we could get away with this for values passed
2046 // outside of the normal argument range.
2047 static void allocateFixedSGPRInputImpl(CCState &CCInfo,
2048                                        const TargetRegisterClass *RC,
2049                                        MCRegister Reg) {
2050   Reg = CCInfo.AllocateReg(Reg);
2051   assert(Reg != AMDGPU::NoRegister);
2052   MachineFunction &MF = CCInfo.getMachineFunction();
2053   MF.addLiveIn(Reg, RC);
2054 }
2055 
2056 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
2057   if (Arg) {
2058     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
2059                                Arg.getRegister());
2060   } else
2061     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
2062 }
2063 
2064 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
2065   if (Arg) {
2066     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
2067                                Arg.getRegister());
2068   } else
2069     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
2070 }
2071 
2072 /// Allocate implicit function VGPR arguments at the end of allocated user
2073 /// arguments.
2074 void SITargetLowering::allocateSpecialInputVGPRs(
2075   CCState &CCInfo, MachineFunction &MF,
2076   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2077   const unsigned Mask = 0x3ff;
2078   ArgDescriptor Arg;
2079 
2080   if (Info.hasWorkItemIDX()) {
2081     Arg = allocateVGPR32Input(CCInfo, Mask);
2082     Info.setWorkItemIDX(Arg);
2083   }
2084 
2085   if (Info.hasWorkItemIDY()) {
2086     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
2087     Info.setWorkItemIDY(Arg);
2088   }
2089 
2090   if (Info.hasWorkItemIDZ())
2091     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
2092 }
2093 
2094 /// Allocate implicit function VGPR arguments in fixed registers.
2095 void SITargetLowering::allocateSpecialInputVGPRsFixed(
2096   CCState &CCInfo, MachineFunction &MF,
2097   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2098   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
2099   if (!Reg)
2100     report_fatal_error("failed to allocated VGPR for implicit arguments");
2101 
2102   const unsigned Mask = 0x3ff;
2103   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2104   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
2105   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
2106 }
2107 
2108 void SITargetLowering::allocateSpecialInputSGPRs(
2109   CCState &CCInfo,
2110   MachineFunction &MF,
2111   const SIRegisterInfo &TRI,
2112   SIMachineFunctionInfo &Info) const {
2113   auto &ArgInfo = Info.getArgInfo();
2114 
2115   // TODO: Unify handling with private memory pointers.
2116   if (Info.hasDispatchPtr())
2117     allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
2118 
2119   if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5)
2120     allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
2121 
2122   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
2123   // constant offset from the kernarg segment.
2124   if (Info.hasImplicitArgPtr())
2125     allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
2126 
2127   if (Info.hasDispatchID())
2128     allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2129 
2130   // flat_scratch_init is not applicable for non-kernel functions.
2131 
2132   if (Info.hasWorkGroupIDX())
2133     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2134 
2135   if (Info.hasWorkGroupIDY())
2136     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2137 
2138   if (Info.hasWorkGroupIDZ())
2139     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2140 }
2141 
2142 // Allocate special inputs passed in user SGPRs.
2143 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2144                                             MachineFunction &MF,
2145                                             const SIRegisterInfo &TRI,
2146                                             SIMachineFunctionInfo &Info) const {
2147   if (Info.hasImplicitBufferPtr()) {
2148     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2149     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2150     CCInfo.AllocateReg(ImplicitBufferPtrReg);
2151   }
2152 
2153   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2154   if (Info.hasPrivateSegmentBuffer()) {
2155     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2156     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2157     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2158   }
2159 
2160   if (Info.hasDispatchPtr()) {
2161     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2162     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2163     CCInfo.AllocateReg(DispatchPtrReg);
2164   }
2165 
2166   if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) {
2167     Register QueuePtrReg = Info.addQueuePtr(TRI);
2168     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2169     CCInfo.AllocateReg(QueuePtrReg);
2170   }
2171 
2172   if (Info.hasKernargSegmentPtr()) {
2173     MachineRegisterInfo &MRI = MF.getRegInfo();
2174     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2175     CCInfo.AllocateReg(InputPtrReg);
2176 
2177     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2178     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2179   }
2180 
2181   if (Info.hasDispatchID()) {
2182     Register DispatchIDReg = Info.addDispatchID(TRI);
2183     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2184     CCInfo.AllocateReg(DispatchIDReg);
2185   }
2186 
2187   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2188     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2189     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2190     CCInfo.AllocateReg(FlatScratchInitReg);
2191   }
2192 
2193   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2194   // these from the dispatch pointer.
2195 }
2196 
2197 // Allocate special input registers that are initialized per-wave.
2198 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2199                                            MachineFunction &MF,
2200                                            SIMachineFunctionInfo &Info,
2201                                            CallingConv::ID CallConv,
2202                                            bool IsShader) const {
2203   if (Info.hasWorkGroupIDX()) {
2204     Register Reg = Info.addWorkGroupIDX();
2205     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2206     CCInfo.AllocateReg(Reg);
2207   }
2208 
2209   if (Info.hasWorkGroupIDY()) {
2210     Register Reg = Info.addWorkGroupIDY();
2211     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2212     CCInfo.AllocateReg(Reg);
2213   }
2214 
2215   if (Info.hasWorkGroupIDZ()) {
2216     Register Reg = Info.addWorkGroupIDZ();
2217     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2218     CCInfo.AllocateReg(Reg);
2219   }
2220 
2221   if (Info.hasWorkGroupInfo()) {
2222     Register Reg = Info.addWorkGroupInfo();
2223     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2224     CCInfo.AllocateReg(Reg);
2225   }
2226 
2227   if (Info.hasPrivateSegmentWaveByteOffset()) {
2228     // Scratch wave offset passed in system SGPR.
2229     unsigned PrivateSegmentWaveByteOffsetReg;
2230 
2231     if (IsShader) {
2232       PrivateSegmentWaveByteOffsetReg =
2233         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2234 
2235       // This is true if the scratch wave byte offset doesn't have a fixed
2236       // location.
2237       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2238         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2239         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2240       }
2241     } else
2242       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2243 
2244     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2245     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2246   }
2247 }
2248 
2249 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2250                                      MachineFunction &MF,
2251                                      const SIRegisterInfo &TRI,
2252                                      SIMachineFunctionInfo &Info) {
2253   // Now that we've figured out where the scratch register inputs are, see if
2254   // should reserve the arguments and use them directly.
2255   MachineFrameInfo &MFI = MF.getFrameInfo();
2256   bool HasStackObjects = MFI.hasStackObjects();
2257   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2258 
2259   // Record that we know we have non-spill stack objects so we don't need to
2260   // check all stack objects later.
2261   if (HasStackObjects)
2262     Info.setHasNonSpillStackObjects(true);
2263 
2264   // Everything live out of a block is spilled with fast regalloc, so it's
2265   // almost certain that spilling will be required.
2266   if (TM.getOptLevel() == CodeGenOpt::None)
2267     HasStackObjects = true;
2268 
2269   // For now assume stack access is needed in any callee functions, so we need
2270   // the scratch registers to pass in.
2271   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2272 
2273   if (!ST.enableFlatScratch()) {
2274     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2275       // If we have stack objects, we unquestionably need the private buffer
2276       // resource. For the Code Object V2 ABI, this will be the first 4 user
2277       // SGPR inputs. We can reserve those and use them directly.
2278 
2279       Register PrivateSegmentBufferReg =
2280           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2281       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2282     } else {
2283       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2284       // We tentatively reserve the last registers (skipping the last registers
2285       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2286       // we'll replace these with the ones immediately after those which were
2287       // really allocated. In the prologue copies will be inserted from the
2288       // argument to these reserved registers.
2289 
2290       // Without HSA, relocations are used for the scratch pointer and the
2291       // buffer resource setup is always inserted in the prologue. Scratch wave
2292       // offset is still in an input SGPR.
2293       Info.setScratchRSrcReg(ReservedBufferReg);
2294     }
2295   }
2296 
2297   MachineRegisterInfo &MRI = MF.getRegInfo();
2298 
2299   // For entry functions we have to set up the stack pointer if we use it,
2300   // whereas non-entry functions get this "for free". This means there is no
2301   // intrinsic advantage to using S32 over S34 in cases where we do not have
2302   // calls but do need a frame pointer (i.e. if we are requested to have one
2303   // because frame pointer elimination is disabled). To keep things simple we
2304   // only ever use S32 as the call ABI stack pointer, and so using it does not
2305   // imply we need a separate frame pointer.
2306   //
2307   // Try to use s32 as the SP, but move it if it would interfere with input
2308   // arguments. This won't work with calls though.
2309   //
2310   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2311   // registers.
2312   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2313     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2314   } else {
2315     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2316 
2317     if (MFI.hasCalls())
2318       report_fatal_error("call in graphics shader with too many input SGPRs");
2319 
2320     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2321       if (!MRI.isLiveIn(Reg)) {
2322         Info.setStackPtrOffsetReg(Reg);
2323         break;
2324       }
2325     }
2326 
2327     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2328       report_fatal_error("failed to find register for SP");
2329   }
2330 
2331   // hasFP should be accurate for entry functions even before the frame is
2332   // finalized, because it does not rely on the known stack size, only
2333   // properties like whether variable sized objects are present.
2334   if (ST.getFrameLowering()->hasFP(MF)) {
2335     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2336   }
2337 }
2338 
2339 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2340   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2341   return !Info->isEntryFunction();
2342 }
2343 
2344 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2345 
2346 }
2347 
2348 void SITargetLowering::insertCopiesSplitCSR(
2349   MachineBasicBlock *Entry,
2350   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2351   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2352 
2353   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2354   if (!IStart)
2355     return;
2356 
2357   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2358   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2359   MachineBasicBlock::iterator MBBI = Entry->begin();
2360   for (const MCPhysReg *I = IStart; *I; ++I) {
2361     const TargetRegisterClass *RC = nullptr;
2362     if (AMDGPU::SReg_64RegClass.contains(*I))
2363       RC = &AMDGPU::SGPR_64RegClass;
2364     else if (AMDGPU::SReg_32RegClass.contains(*I))
2365       RC = &AMDGPU::SGPR_32RegClass;
2366     else
2367       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2368 
2369     Register NewVR = MRI->createVirtualRegister(RC);
2370     // Create copy from CSR to a virtual register.
2371     Entry->addLiveIn(*I);
2372     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2373       .addReg(*I);
2374 
2375     // Insert the copy-back instructions right before the terminator.
2376     for (auto *Exit : Exits)
2377       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2378               TII->get(TargetOpcode::COPY), *I)
2379         .addReg(NewVR);
2380   }
2381 }
2382 
2383 SDValue SITargetLowering::LowerFormalArguments(
2384     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2385     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2386     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2387   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2388 
2389   MachineFunction &MF = DAG.getMachineFunction();
2390   const Function &Fn = MF.getFunction();
2391   FunctionType *FType = MF.getFunction().getFunctionType();
2392   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2393 
2394   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2395     DiagnosticInfoUnsupported NoGraphicsHSA(
2396         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2397     DAG.getContext()->diagnose(NoGraphicsHSA);
2398     return DAG.getEntryNode();
2399   }
2400 
2401   Info->allocateModuleLDSGlobal(Fn.getParent());
2402 
2403   SmallVector<ISD::InputArg, 16> Splits;
2404   SmallVector<CCValAssign, 16> ArgLocs;
2405   BitVector Skipped(Ins.size());
2406   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2407                  *DAG.getContext());
2408 
2409   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2410   bool IsKernel = AMDGPU::isKernel(CallConv);
2411   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2412 
2413   if (IsGraphics) {
2414     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2415            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2416            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2417            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2418            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2419            !Info->hasWorkItemIDZ());
2420   }
2421 
2422   if (CallConv == CallingConv::AMDGPU_PS) {
2423     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2424 
2425     // At least one interpolation mode must be enabled or else the GPU will
2426     // hang.
2427     //
2428     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2429     // set PSInputAddr, the user wants to enable some bits after the compilation
2430     // based on run-time states. Since we can't know what the final PSInputEna
2431     // will look like, so we shouldn't do anything here and the user should take
2432     // responsibility for the correct programming.
2433     //
2434     // Otherwise, the following restrictions apply:
2435     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2436     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2437     //   enabled too.
2438     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2439         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2440       CCInfo.AllocateReg(AMDGPU::VGPR0);
2441       CCInfo.AllocateReg(AMDGPU::VGPR1);
2442       Info->markPSInputAllocated(0);
2443       Info->markPSInputEnabled(0);
2444     }
2445     if (Subtarget->isAmdPalOS()) {
2446       // For isAmdPalOS, the user does not enable some bits after compilation
2447       // based on run-time states; the register values being generated here are
2448       // the final ones set in hardware. Therefore we need to apply the
2449       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2450       // a bit is set in PSInputAddr but not PSInputEnable is where the
2451       // frontend set up an input arg for a particular interpolation mode, but
2452       // nothing uses that input arg. Really we should have an earlier pass
2453       // that removes such an arg.)
2454       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2455       if ((PsInputBits & 0x7F) == 0 ||
2456           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2457         Info->markPSInputEnabled(
2458             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2459     }
2460   } else if (IsKernel) {
2461     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2462   } else {
2463     Splits.append(Ins.begin(), Ins.end());
2464   }
2465 
2466   if (IsEntryFunc) {
2467     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2468     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2469   } else if (!IsGraphics) {
2470     // For the fixed ABI, pass workitem IDs in the last argument register.
2471     allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2472   }
2473 
2474   if (IsKernel) {
2475     analyzeFormalArgumentsCompute(CCInfo, Ins);
2476   } else {
2477     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2478     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2479   }
2480 
2481   SmallVector<SDValue, 16> Chains;
2482 
2483   // FIXME: This is the minimum kernel argument alignment. We should improve
2484   // this to the maximum alignment of the arguments.
2485   //
2486   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2487   // kern arg offset.
2488   const Align KernelArgBaseAlign = Align(16);
2489 
2490   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2491     const ISD::InputArg &Arg = Ins[i];
2492     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2493       InVals.push_back(DAG.getUNDEF(Arg.VT));
2494       continue;
2495     }
2496 
2497     CCValAssign &VA = ArgLocs[ArgIdx++];
2498     MVT VT = VA.getLocVT();
2499 
2500     if (IsEntryFunc && VA.isMemLoc()) {
2501       VT = Ins[i].VT;
2502       EVT MemVT = VA.getLocVT();
2503 
2504       const uint64_t Offset = VA.getLocMemOffset();
2505       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2506 
2507       if (Arg.Flags.isByRef()) {
2508         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2509 
2510         const GCNTargetMachine &TM =
2511             static_cast<const GCNTargetMachine &>(getTargetMachine());
2512         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2513                                     Arg.Flags.getPointerAddrSpace())) {
2514           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2515                                      Arg.Flags.getPointerAddrSpace());
2516         }
2517 
2518         InVals.push_back(Ptr);
2519         continue;
2520       }
2521 
2522       SDValue Arg = lowerKernargMemParameter(
2523         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2524       Chains.push_back(Arg.getValue(1));
2525 
2526       auto *ParamTy =
2527         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2528       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2529           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2530                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2531         // On SI local pointers are just offsets into LDS, so they are always
2532         // less than 16-bits.  On CI and newer they could potentially be
2533         // real pointers, so we can't guarantee their size.
2534         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2535                           DAG.getValueType(MVT::i16));
2536       }
2537 
2538       InVals.push_back(Arg);
2539       continue;
2540     } else if (!IsEntryFunc && VA.isMemLoc()) {
2541       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2542       InVals.push_back(Val);
2543       if (!Arg.Flags.isByVal())
2544         Chains.push_back(Val.getValue(1));
2545       continue;
2546     }
2547 
2548     assert(VA.isRegLoc() && "Parameter must be in a register!");
2549 
2550     Register Reg = VA.getLocReg();
2551     const TargetRegisterClass *RC = nullptr;
2552     if (AMDGPU::VGPR_32RegClass.contains(Reg))
2553       RC = &AMDGPU::VGPR_32RegClass;
2554     else if (AMDGPU::SGPR_32RegClass.contains(Reg))
2555       RC = &AMDGPU::SGPR_32RegClass;
2556     else
2557       llvm_unreachable("Unexpected register class in LowerFormalArguments!");
2558     EVT ValVT = VA.getValVT();
2559 
2560     Reg = MF.addLiveIn(Reg, RC);
2561     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2562 
2563     if (Arg.Flags.isSRet()) {
2564       // The return object should be reasonably addressable.
2565 
2566       // FIXME: This helps when the return is a real sret. If it is a
2567       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2568       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2569       unsigned NumBits
2570         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2571       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2572         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2573     }
2574 
2575     // If this is an 8 or 16-bit value, it is really passed promoted
2576     // to 32 bits. Insert an assert[sz]ext to capture this, then
2577     // truncate to the right size.
2578     switch (VA.getLocInfo()) {
2579     case CCValAssign::Full:
2580       break;
2581     case CCValAssign::BCvt:
2582       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2583       break;
2584     case CCValAssign::SExt:
2585       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2586                         DAG.getValueType(ValVT));
2587       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2588       break;
2589     case CCValAssign::ZExt:
2590       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2591                         DAG.getValueType(ValVT));
2592       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2593       break;
2594     case CCValAssign::AExt:
2595       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2596       break;
2597     default:
2598       llvm_unreachable("Unknown loc info!");
2599     }
2600 
2601     InVals.push_back(Val);
2602   }
2603 
2604   // Start adding system SGPRs.
2605   if (IsEntryFunc) {
2606     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2607   } else {
2608     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2609     if (!IsGraphics)
2610       allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2611   }
2612 
2613   auto &ArgUsageInfo =
2614     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2615   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2616 
2617   unsigned StackArgSize = CCInfo.getNextStackOffset();
2618   Info->setBytesInStackArgArea(StackArgSize);
2619 
2620   return Chains.empty() ? Chain :
2621     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2622 }
2623 
2624 // TODO: If return values can't fit in registers, we should return as many as
2625 // possible in registers before passing on stack.
2626 bool SITargetLowering::CanLowerReturn(
2627   CallingConv::ID CallConv,
2628   MachineFunction &MF, bool IsVarArg,
2629   const SmallVectorImpl<ISD::OutputArg> &Outs,
2630   LLVMContext &Context) const {
2631   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2632   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2633   // for shaders. Vector types should be explicitly handled by CC.
2634   if (AMDGPU::isEntryFunctionCC(CallConv))
2635     return true;
2636 
2637   SmallVector<CCValAssign, 16> RVLocs;
2638   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2639   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2640 }
2641 
2642 SDValue
2643 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2644                               bool isVarArg,
2645                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2646                               const SmallVectorImpl<SDValue> &OutVals,
2647                               const SDLoc &DL, SelectionDAG &DAG) const {
2648   MachineFunction &MF = DAG.getMachineFunction();
2649   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2650 
2651   if (AMDGPU::isKernel(CallConv)) {
2652     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2653                                              OutVals, DL, DAG);
2654   }
2655 
2656   bool IsShader = AMDGPU::isShader(CallConv);
2657 
2658   Info->setIfReturnsVoid(Outs.empty());
2659   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2660 
2661   // CCValAssign - represent the assignment of the return value to a location.
2662   SmallVector<CCValAssign, 48> RVLocs;
2663   SmallVector<ISD::OutputArg, 48> Splits;
2664 
2665   // CCState - Info about the registers and stack slots.
2666   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2667                  *DAG.getContext());
2668 
2669   // Analyze outgoing return values.
2670   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2671 
2672   SDValue Flag;
2673   SmallVector<SDValue, 48> RetOps;
2674   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2675 
2676   // Copy the result values into the output registers.
2677   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2678        ++I, ++RealRVLocIdx) {
2679     CCValAssign &VA = RVLocs[I];
2680     assert(VA.isRegLoc() && "Can only return in registers!");
2681     // TODO: Partially return in registers if return values don't fit.
2682     SDValue Arg = OutVals[RealRVLocIdx];
2683 
2684     // Copied from other backends.
2685     switch (VA.getLocInfo()) {
2686     case CCValAssign::Full:
2687       break;
2688     case CCValAssign::BCvt:
2689       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2690       break;
2691     case CCValAssign::SExt:
2692       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2693       break;
2694     case CCValAssign::ZExt:
2695       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2696       break;
2697     case CCValAssign::AExt:
2698       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2699       break;
2700     default:
2701       llvm_unreachable("Unknown loc info!");
2702     }
2703 
2704     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2705     Flag = Chain.getValue(1);
2706     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2707   }
2708 
2709   // FIXME: Does sret work properly?
2710   if (!Info->isEntryFunction()) {
2711     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2712     const MCPhysReg *I =
2713       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2714     if (I) {
2715       for (; *I; ++I) {
2716         if (AMDGPU::SReg_64RegClass.contains(*I))
2717           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2718         else if (AMDGPU::SReg_32RegClass.contains(*I))
2719           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2720         else
2721           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2722       }
2723     }
2724   }
2725 
2726   // Update chain and glue.
2727   RetOps[0] = Chain;
2728   if (Flag.getNode())
2729     RetOps.push_back(Flag);
2730 
2731   unsigned Opc = AMDGPUISD::ENDPGM;
2732   if (!IsWaveEnd)
2733     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2734   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2735 }
2736 
2737 SDValue SITargetLowering::LowerCallResult(
2738     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2739     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2740     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2741     SDValue ThisVal) const {
2742   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2743 
2744   // Assign locations to each value returned by this call.
2745   SmallVector<CCValAssign, 16> RVLocs;
2746   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2747                  *DAG.getContext());
2748   CCInfo.AnalyzeCallResult(Ins, RetCC);
2749 
2750   // Copy all of the result registers out of their specified physreg.
2751   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2752     CCValAssign VA = RVLocs[i];
2753     SDValue Val;
2754 
2755     if (VA.isRegLoc()) {
2756       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2757       Chain = Val.getValue(1);
2758       InFlag = Val.getValue(2);
2759     } else if (VA.isMemLoc()) {
2760       report_fatal_error("TODO: return values in memory");
2761     } else
2762       llvm_unreachable("unknown argument location type");
2763 
2764     switch (VA.getLocInfo()) {
2765     case CCValAssign::Full:
2766       break;
2767     case CCValAssign::BCvt:
2768       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2769       break;
2770     case CCValAssign::ZExt:
2771       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2772                         DAG.getValueType(VA.getValVT()));
2773       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2774       break;
2775     case CCValAssign::SExt:
2776       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2777                         DAG.getValueType(VA.getValVT()));
2778       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2779       break;
2780     case CCValAssign::AExt:
2781       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2782       break;
2783     default:
2784       llvm_unreachable("Unknown loc info!");
2785     }
2786 
2787     InVals.push_back(Val);
2788   }
2789 
2790   return Chain;
2791 }
2792 
2793 // Add code to pass special inputs required depending on used features separate
2794 // from the explicit user arguments present in the IR.
2795 void SITargetLowering::passSpecialInputs(
2796     CallLoweringInfo &CLI,
2797     CCState &CCInfo,
2798     const SIMachineFunctionInfo &Info,
2799     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2800     SmallVectorImpl<SDValue> &MemOpChains,
2801     SDValue Chain) const {
2802   // If we don't have a call site, this was a call inserted by
2803   // legalization. These can never use special inputs.
2804   if (!CLI.CB)
2805     return;
2806 
2807   SelectionDAG &DAG = CLI.DAG;
2808   const SDLoc &DL = CLI.DL;
2809   const Function &F = DAG.getMachineFunction().getFunction();
2810 
2811   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2812   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2813 
2814   const AMDGPUFunctionArgInfo *CalleeArgInfo
2815     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2816   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2817     auto &ArgUsageInfo =
2818       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2819     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2820   }
2821 
2822   // TODO: Unify with private memory register handling. This is complicated by
2823   // the fact that at least in kernels, the input argument is not necessarily
2824   // in the same location as the input.
2825   static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
2826                              StringLiteral> ImplicitAttrs[] = {
2827     {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"},
2828     {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" },
2829     {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"},
2830     {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"},
2831     {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"},
2832     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"},
2833     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"}
2834   };
2835 
2836   for (auto Attr : ImplicitAttrs) {
2837     const ArgDescriptor *OutgoingArg;
2838     const TargetRegisterClass *ArgRC;
2839     LLT ArgTy;
2840 
2841     AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first;
2842 
2843     // If the callee does not use the attribute value, skip copying the value.
2844     if (CLI.CB->hasFnAttr(Attr.second))
2845       continue;
2846 
2847     std::tie(OutgoingArg, ArgRC, ArgTy) =
2848         CalleeArgInfo->getPreloadedValue(InputID);
2849     if (!OutgoingArg)
2850       continue;
2851 
2852     const ArgDescriptor *IncomingArg;
2853     const TargetRegisterClass *IncomingArgRC;
2854     LLT Ty;
2855     std::tie(IncomingArg, IncomingArgRC, Ty) =
2856         CallerArgInfo.getPreloadedValue(InputID);
2857     assert(IncomingArgRC == ArgRC);
2858 
2859     // All special arguments are ints for now.
2860     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2861     SDValue InputReg;
2862 
2863     if (IncomingArg) {
2864       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2865     } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
2866       // The implicit arg ptr is special because it doesn't have a corresponding
2867       // input for kernels, and is computed from the kernarg segment pointer.
2868       InputReg = getImplicitArgPtr(DAG, DL);
2869     } else {
2870       // We may have proven the input wasn't needed, although the ABI is
2871       // requiring it. We just need to allocate the register appropriately.
2872       InputReg = DAG.getUNDEF(ArgVT);
2873     }
2874 
2875     if (OutgoingArg->isRegister()) {
2876       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2877       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2878         report_fatal_error("failed to allocate implicit input argument");
2879     } else {
2880       unsigned SpecialArgOffset =
2881           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2882       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2883                                               SpecialArgOffset);
2884       MemOpChains.push_back(ArgStore);
2885     }
2886   }
2887 
2888   // Pack workitem IDs into a single register or pass it as is if already
2889   // packed.
2890   const ArgDescriptor *OutgoingArg;
2891   const TargetRegisterClass *ArgRC;
2892   LLT Ty;
2893 
2894   std::tie(OutgoingArg, ArgRC, Ty) =
2895       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2896   if (!OutgoingArg)
2897     std::tie(OutgoingArg, ArgRC, Ty) =
2898         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2899   if (!OutgoingArg)
2900     std::tie(OutgoingArg, ArgRC, Ty) =
2901         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2902   if (!OutgoingArg)
2903     return;
2904 
2905   const ArgDescriptor *IncomingArgX = std::get<0>(
2906       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2907   const ArgDescriptor *IncomingArgY = std::get<0>(
2908       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2909   const ArgDescriptor *IncomingArgZ = std::get<0>(
2910       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2911 
2912   SDValue InputReg;
2913   SDLoc SL;
2914 
2915   const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
2916   const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
2917   const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
2918 
2919   // If incoming ids are not packed we need to pack them.
2920   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
2921       NeedWorkItemIDX) {
2922     if (Subtarget->getMaxWorkitemID(F, 0) != 0) {
2923       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2924     } else {
2925       InputReg = DAG.getConstant(0, DL, MVT::i32);
2926     }
2927   }
2928 
2929   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
2930       NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) {
2931     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2932     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2933                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2934     InputReg = InputReg.getNode() ?
2935                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2936   }
2937 
2938   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
2939       NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) {
2940     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2941     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2942                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2943     InputReg = InputReg.getNode() ?
2944                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2945   }
2946 
2947   if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
2948     if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) {
2949       // We're in a situation where the outgoing function requires the workitem
2950       // ID, but the calling function does not have it (e.g a graphics function
2951       // calling a C calling convention function). This is illegal, but we need
2952       // to produce something.
2953       InputReg = DAG.getUNDEF(MVT::i32);
2954     } else {
2955       // Workitem ids are already packed, any of present incoming arguments
2956       // will carry all required fields.
2957       ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2958         IncomingArgX ? *IncomingArgX :
2959         IncomingArgY ? *IncomingArgY :
2960         *IncomingArgZ, ~0u);
2961       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2962     }
2963   }
2964 
2965   if (OutgoingArg->isRegister()) {
2966     if (InputReg)
2967       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2968 
2969     CCInfo.AllocateReg(OutgoingArg->getRegister());
2970   } else {
2971     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2972     if (InputReg) {
2973       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2974                                               SpecialArgOffset);
2975       MemOpChains.push_back(ArgStore);
2976     }
2977   }
2978 }
2979 
2980 static bool canGuaranteeTCO(CallingConv::ID CC) {
2981   return CC == CallingConv::Fast;
2982 }
2983 
2984 /// Return true if we might ever do TCO for calls with this calling convention.
2985 static bool mayTailCallThisCC(CallingConv::ID CC) {
2986   switch (CC) {
2987   case CallingConv::C:
2988   case CallingConv::AMDGPU_Gfx:
2989     return true;
2990   default:
2991     return canGuaranteeTCO(CC);
2992   }
2993 }
2994 
2995 bool SITargetLowering::isEligibleForTailCallOptimization(
2996     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2997     const SmallVectorImpl<ISD::OutputArg> &Outs,
2998     const SmallVectorImpl<SDValue> &OutVals,
2999     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3000   if (!mayTailCallThisCC(CalleeCC))
3001     return false;
3002 
3003   // For a divergent call target, we need to do a waterfall loop over the
3004   // possible callees which precludes us from using a simple jump.
3005   if (Callee->isDivergent())
3006     return false;
3007 
3008   MachineFunction &MF = DAG.getMachineFunction();
3009   const Function &CallerF = MF.getFunction();
3010   CallingConv::ID CallerCC = CallerF.getCallingConv();
3011   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3012   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3013 
3014   // Kernels aren't callable, and don't have a live in return address so it
3015   // doesn't make sense to do a tail call with entry functions.
3016   if (!CallerPreserved)
3017     return false;
3018 
3019   bool CCMatch = CallerCC == CalleeCC;
3020 
3021   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3022     if (canGuaranteeTCO(CalleeCC) && CCMatch)
3023       return true;
3024     return false;
3025   }
3026 
3027   // TODO: Can we handle var args?
3028   if (IsVarArg)
3029     return false;
3030 
3031   for (const Argument &Arg : CallerF.args()) {
3032     if (Arg.hasByValAttr())
3033       return false;
3034   }
3035 
3036   LLVMContext &Ctx = *DAG.getContext();
3037 
3038   // Check that the call results are passed in the same way.
3039   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
3040                                   CCAssignFnForCall(CalleeCC, IsVarArg),
3041                                   CCAssignFnForCall(CallerCC, IsVarArg)))
3042     return false;
3043 
3044   // The callee has to preserve all registers the caller needs to preserve.
3045   if (!CCMatch) {
3046     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3047     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3048       return false;
3049   }
3050 
3051   // Nothing more to check if the callee is taking no arguments.
3052   if (Outs.empty())
3053     return true;
3054 
3055   SmallVector<CCValAssign, 16> ArgLocs;
3056   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
3057 
3058   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
3059 
3060   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
3061   // If the stack arguments for this call do not fit into our own save area then
3062   // the call cannot be made tail.
3063   // TODO: Is this really necessary?
3064   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3065     return false;
3066 
3067   const MachineRegisterInfo &MRI = MF.getRegInfo();
3068   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
3069 }
3070 
3071 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3072   if (!CI->isTailCall())
3073     return false;
3074 
3075   const Function *ParentFn = CI->getParent()->getParent();
3076   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
3077     return false;
3078   return true;
3079 }
3080 
3081 // The wave scratch offset register is used as the global base pointer.
3082 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
3083                                     SmallVectorImpl<SDValue> &InVals) const {
3084   SelectionDAG &DAG = CLI.DAG;
3085   const SDLoc &DL = CLI.DL;
3086   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3087   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3088   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3089   SDValue Chain = CLI.Chain;
3090   SDValue Callee = CLI.Callee;
3091   bool &IsTailCall = CLI.IsTailCall;
3092   CallingConv::ID CallConv = CLI.CallConv;
3093   bool IsVarArg = CLI.IsVarArg;
3094   bool IsSibCall = false;
3095   bool IsThisReturn = false;
3096   MachineFunction &MF = DAG.getMachineFunction();
3097 
3098   if (Callee.isUndef() || isNullConstant(Callee)) {
3099     if (!CLI.IsTailCall) {
3100       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
3101         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
3102     }
3103 
3104     return Chain;
3105   }
3106 
3107   if (IsVarArg) {
3108     return lowerUnhandledCall(CLI, InVals,
3109                               "unsupported call to variadic function ");
3110   }
3111 
3112   if (!CLI.CB)
3113     report_fatal_error("unsupported libcall legalization");
3114 
3115   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
3116     return lowerUnhandledCall(CLI, InVals,
3117                               "unsupported required tail call to function ");
3118   }
3119 
3120   if (AMDGPU::isShader(CallConv)) {
3121     // Note the issue is with the CC of the called function, not of the call
3122     // itself.
3123     return lowerUnhandledCall(CLI, InVals,
3124                               "unsupported call to a shader function ");
3125   }
3126 
3127   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
3128       CallConv != CallingConv::AMDGPU_Gfx) {
3129     // Only allow calls with specific calling conventions.
3130     return lowerUnhandledCall(CLI, InVals,
3131                               "unsupported calling convention for call from "
3132                               "graphics shader of function ");
3133   }
3134 
3135   if (IsTailCall) {
3136     IsTailCall = isEligibleForTailCallOptimization(
3137       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3138     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
3139       report_fatal_error("failed to perform tail call elimination on a call "
3140                          "site marked musttail");
3141     }
3142 
3143     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3144 
3145     // A sibling call is one where we're under the usual C ABI and not planning
3146     // to change that but can still do a tail call:
3147     if (!TailCallOpt && IsTailCall)
3148       IsSibCall = true;
3149 
3150     if (IsTailCall)
3151       ++NumTailCalls;
3152   }
3153 
3154   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3155   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3156   SmallVector<SDValue, 8> MemOpChains;
3157 
3158   // Analyze operands of the call, assigning locations to each operand.
3159   SmallVector<CCValAssign, 16> ArgLocs;
3160   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3161   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3162 
3163   if (CallConv != CallingConv::AMDGPU_Gfx) {
3164     // With a fixed ABI, allocate fixed registers before user arguments.
3165     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3166   }
3167 
3168   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3169 
3170   // Get a count of how many bytes are to be pushed on the stack.
3171   unsigned NumBytes = CCInfo.getNextStackOffset();
3172 
3173   if (IsSibCall) {
3174     // Since we're not changing the ABI to make this a tail call, the memory
3175     // operands are already available in the caller's incoming argument space.
3176     NumBytes = 0;
3177   }
3178 
3179   // FPDiff is the byte offset of the call's argument area from the callee's.
3180   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3181   // by this amount for a tail call. In a sibling call it must be 0 because the
3182   // caller will deallocate the entire stack and the callee still expects its
3183   // arguments to begin at SP+0. Completely unused for non-tail calls.
3184   int32_t FPDiff = 0;
3185   MachineFrameInfo &MFI = MF.getFrameInfo();
3186 
3187   // Adjust the stack pointer for the new arguments...
3188   // These operations are automatically eliminated by the prolog/epilog pass
3189   if (!IsSibCall) {
3190     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3191 
3192     if (!Subtarget->enableFlatScratch()) {
3193       SmallVector<SDValue, 4> CopyFromChains;
3194 
3195       // In the HSA case, this should be an identity copy.
3196       SDValue ScratchRSrcReg
3197         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3198       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3199       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3200       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3201     }
3202   }
3203 
3204   MVT PtrVT = MVT::i32;
3205 
3206   // Walk the register/memloc assignments, inserting copies/loads.
3207   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3208     CCValAssign &VA = ArgLocs[i];
3209     SDValue Arg = OutVals[i];
3210 
3211     // Promote the value if needed.
3212     switch (VA.getLocInfo()) {
3213     case CCValAssign::Full:
3214       break;
3215     case CCValAssign::BCvt:
3216       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3217       break;
3218     case CCValAssign::ZExt:
3219       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3220       break;
3221     case CCValAssign::SExt:
3222       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3223       break;
3224     case CCValAssign::AExt:
3225       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3226       break;
3227     case CCValAssign::FPExt:
3228       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3229       break;
3230     default:
3231       llvm_unreachable("Unknown loc info!");
3232     }
3233 
3234     if (VA.isRegLoc()) {
3235       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3236     } else {
3237       assert(VA.isMemLoc());
3238 
3239       SDValue DstAddr;
3240       MachinePointerInfo DstInfo;
3241 
3242       unsigned LocMemOffset = VA.getLocMemOffset();
3243       int32_t Offset = LocMemOffset;
3244 
3245       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3246       MaybeAlign Alignment;
3247 
3248       if (IsTailCall) {
3249         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3250         unsigned OpSize = Flags.isByVal() ?
3251           Flags.getByValSize() : VA.getValVT().getStoreSize();
3252 
3253         // FIXME: We can have better than the minimum byval required alignment.
3254         Alignment =
3255             Flags.isByVal()
3256                 ? Flags.getNonZeroByValAlign()
3257                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3258 
3259         Offset = Offset + FPDiff;
3260         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3261 
3262         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3263         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3264 
3265         // Make sure any stack arguments overlapping with where we're storing
3266         // are loaded before this eventual operation. Otherwise they'll be
3267         // clobbered.
3268 
3269         // FIXME: Why is this really necessary? This seems to just result in a
3270         // lot of code to copy the stack and write them back to the same
3271         // locations, which are supposed to be immutable?
3272         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3273       } else {
3274         // Stores to the argument stack area are relative to the stack pointer.
3275         SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3276                                         MVT::i32);
3277         DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3278         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3279         Alignment =
3280             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3281       }
3282 
3283       if (Outs[i].Flags.isByVal()) {
3284         SDValue SizeNode =
3285             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3286         SDValue Cpy =
3287             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3288                           Outs[i].Flags.getNonZeroByValAlign(),
3289                           /*isVol = */ false, /*AlwaysInline = */ true,
3290                           /*isTailCall = */ false, DstInfo,
3291                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3292 
3293         MemOpChains.push_back(Cpy);
3294       } else {
3295         SDValue Store =
3296             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3297         MemOpChains.push_back(Store);
3298       }
3299     }
3300   }
3301 
3302   if (!MemOpChains.empty())
3303     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3304 
3305   // Build a sequence of copy-to-reg nodes chained together with token chain
3306   // and flag operands which copy the outgoing args into the appropriate regs.
3307   SDValue InFlag;
3308   for (auto &RegToPass : RegsToPass) {
3309     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3310                              RegToPass.second, InFlag);
3311     InFlag = Chain.getValue(1);
3312   }
3313 
3314 
3315   // We don't usually want to end the call-sequence here because we would tidy
3316   // the frame up *after* the call, however in the ABI-changing tail-call case
3317   // we've carefully laid out the parameters so that when sp is reset they'll be
3318   // in the correct location.
3319   if (IsTailCall && !IsSibCall) {
3320     Chain = DAG.getCALLSEQ_END(Chain,
3321                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3322                                DAG.getTargetConstant(0, DL, MVT::i32),
3323                                InFlag, DL);
3324     InFlag = Chain.getValue(1);
3325   }
3326 
3327   std::vector<SDValue> Ops;
3328   Ops.push_back(Chain);
3329   Ops.push_back(Callee);
3330   // Add a redundant copy of the callee global which will not be legalized, as
3331   // we need direct access to the callee later.
3332   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3333     const GlobalValue *GV = GSD->getGlobal();
3334     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3335   } else {
3336     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3337   }
3338 
3339   if (IsTailCall) {
3340     // Each tail call may have to adjust the stack by a different amount, so
3341     // this information must travel along with the operation for eventual
3342     // consumption by emitEpilogue.
3343     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3344   }
3345 
3346   // Add argument registers to the end of the list so that they are known live
3347   // into the call.
3348   for (auto &RegToPass : RegsToPass) {
3349     Ops.push_back(DAG.getRegister(RegToPass.first,
3350                                   RegToPass.second.getValueType()));
3351   }
3352 
3353   // Add a register mask operand representing the call-preserved registers.
3354 
3355   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3356   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3357   assert(Mask && "Missing call preserved mask for calling convention");
3358   Ops.push_back(DAG.getRegisterMask(Mask));
3359 
3360   if (InFlag.getNode())
3361     Ops.push_back(InFlag);
3362 
3363   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3364 
3365   // If we're doing a tall call, use a TC_RETURN here rather than an
3366   // actual call instruction.
3367   if (IsTailCall) {
3368     MFI.setHasTailCall();
3369     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3370   }
3371 
3372   // Returns a chain and a flag for retval copy to use.
3373   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3374   Chain = Call.getValue(0);
3375   InFlag = Call.getValue(1);
3376 
3377   uint64_t CalleePopBytes = NumBytes;
3378   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3379                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3380                              InFlag, DL);
3381   if (!Ins.empty())
3382     InFlag = Chain.getValue(1);
3383 
3384   // Handle result values, copying them out of physregs into vregs that we
3385   // return.
3386   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3387                          InVals, IsThisReturn,
3388                          IsThisReturn ? OutVals[0] : SDValue());
3389 }
3390 
3391 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3392 // except for applying the wave size scale to the increment amount.
3393 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3394     SDValue Op, SelectionDAG &DAG) const {
3395   const MachineFunction &MF = DAG.getMachineFunction();
3396   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3397 
3398   SDLoc dl(Op);
3399   EVT VT = Op.getValueType();
3400   SDValue Tmp1 = Op;
3401   SDValue Tmp2 = Op.getValue(1);
3402   SDValue Tmp3 = Op.getOperand(2);
3403   SDValue Chain = Tmp1.getOperand(0);
3404 
3405   Register SPReg = Info->getStackPtrOffsetReg();
3406 
3407   // Chain the dynamic stack allocation so that it doesn't modify the stack
3408   // pointer when other instructions are using the stack.
3409   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3410 
3411   SDValue Size  = Tmp2.getOperand(1);
3412   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3413   Chain = SP.getValue(1);
3414   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3415   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3416   const TargetFrameLowering *TFL = ST.getFrameLowering();
3417   unsigned Opc =
3418     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3419     ISD::ADD : ISD::SUB;
3420 
3421   SDValue ScaledSize = DAG.getNode(
3422       ISD::SHL, dl, VT, Size,
3423       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3424 
3425   Align StackAlign = TFL->getStackAlign();
3426   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3427   if (Alignment && *Alignment > StackAlign) {
3428     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3429                        DAG.getConstant(-(uint64_t)Alignment->value()
3430                                            << ST.getWavefrontSizeLog2(),
3431                                        dl, VT));
3432   }
3433 
3434   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3435   Tmp2 = DAG.getCALLSEQ_END(
3436       Chain, DAG.getIntPtrConstant(0, dl, true),
3437       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3438 
3439   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3440 }
3441 
3442 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3443                                                   SelectionDAG &DAG) const {
3444   // We only handle constant sizes here to allow non-entry block, static sized
3445   // allocas. A truly dynamic value is more difficult to support because we
3446   // don't know if the size value is uniform or not. If the size isn't uniform,
3447   // we would need to do a wave reduction to get the maximum size to know how
3448   // much to increment the uniform stack pointer.
3449   SDValue Size = Op.getOperand(1);
3450   if (isa<ConstantSDNode>(Size))
3451       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3452 
3453   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3454 }
3455 
3456 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3457                                              const MachineFunction &MF) const {
3458   Register Reg = StringSwitch<Register>(RegName)
3459     .Case("m0", AMDGPU::M0)
3460     .Case("exec", AMDGPU::EXEC)
3461     .Case("exec_lo", AMDGPU::EXEC_LO)
3462     .Case("exec_hi", AMDGPU::EXEC_HI)
3463     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3464     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3465     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3466     .Default(Register());
3467 
3468   if (Reg == AMDGPU::NoRegister) {
3469     report_fatal_error(Twine("invalid register name \""
3470                              + StringRef(RegName)  + "\"."));
3471 
3472   }
3473 
3474   if (!Subtarget->hasFlatScrRegister() &&
3475        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3476     report_fatal_error(Twine("invalid register \""
3477                              + StringRef(RegName)  + "\" for subtarget."));
3478   }
3479 
3480   switch (Reg) {
3481   case AMDGPU::M0:
3482   case AMDGPU::EXEC_LO:
3483   case AMDGPU::EXEC_HI:
3484   case AMDGPU::FLAT_SCR_LO:
3485   case AMDGPU::FLAT_SCR_HI:
3486     if (VT.getSizeInBits() == 32)
3487       return Reg;
3488     break;
3489   case AMDGPU::EXEC:
3490   case AMDGPU::FLAT_SCR:
3491     if (VT.getSizeInBits() == 64)
3492       return Reg;
3493     break;
3494   default:
3495     llvm_unreachable("missing register type checking");
3496   }
3497 
3498   report_fatal_error(Twine("invalid type for register \""
3499                            + StringRef(RegName) + "\"."));
3500 }
3501 
3502 // If kill is not the last instruction, split the block so kill is always a
3503 // proper terminator.
3504 MachineBasicBlock *
3505 SITargetLowering::splitKillBlock(MachineInstr &MI,
3506                                  MachineBasicBlock *BB) const {
3507   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3508   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3509   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3510   return SplitBB;
3511 }
3512 
3513 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3514 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3515 // be the first instruction in the remainder block.
3516 //
3517 /// \returns { LoopBody, Remainder }
3518 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3519 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3520   MachineFunction *MF = MBB.getParent();
3521   MachineBasicBlock::iterator I(&MI);
3522 
3523   // To insert the loop we need to split the block. Move everything after this
3524   // point to a new block, and insert a new empty block between the two.
3525   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3526   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3527   MachineFunction::iterator MBBI(MBB);
3528   ++MBBI;
3529 
3530   MF->insert(MBBI, LoopBB);
3531   MF->insert(MBBI, RemainderBB);
3532 
3533   LoopBB->addSuccessor(LoopBB);
3534   LoopBB->addSuccessor(RemainderBB);
3535 
3536   // Move the rest of the block into a new block.
3537   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3538 
3539   if (InstInLoop) {
3540     auto Next = std::next(I);
3541 
3542     // Move instruction to loop body.
3543     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3544 
3545     // Move the rest of the block.
3546     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3547   } else {
3548     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3549   }
3550 
3551   MBB.addSuccessor(LoopBB);
3552 
3553   return std::make_pair(LoopBB, RemainderBB);
3554 }
3555 
3556 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3557 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3558   MachineBasicBlock *MBB = MI.getParent();
3559   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3560   auto I = MI.getIterator();
3561   auto E = std::next(I);
3562 
3563   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3564     .addImm(0);
3565 
3566   MIBundleBuilder Bundler(*MBB, I, E);
3567   finalizeBundle(*MBB, Bundler.begin());
3568 }
3569 
3570 MachineBasicBlock *
3571 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3572                                          MachineBasicBlock *BB) const {
3573   const DebugLoc &DL = MI.getDebugLoc();
3574 
3575   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3576 
3577   MachineBasicBlock *LoopBB;
3578   MachineBasicBlock *RemainderBB;
3579   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3580 
3581   // Apparently kill flags are only valid if the def is in the same block?
3582   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3583     Src->setIsKill(false);
3584 
3585   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3586 
3587   MachineBasicBlock::iterator I = LoopBB->end();
3588 
3589   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3590     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3591 
3592   // Clear TRAP_STS.MEM_VIOL
3593   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3594     .addImm(0)
3595     .addImm(EncodedReg);
3596 
3597   bundleInstWithWaitcnt(MI);
3598 
3599   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3600 
3601   // Load and check TRAP_STS.MEM_VIOL
3602   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3603     .addImm(EncodedReg);
3604 
3605   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3606   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3607     .addReg(Reg, RegState::Kill)
3608     .addImm(0);
3609   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3610     .addMBB(LoopBB);
3611 
3612   return RemainderBB;
3613 }
3614 
3615 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3616 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3617 // will only do one iteration. In the worst case, this will loop 64 times.
3618 //
3619 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3620 static MachineBasicBlock::iterator
3621 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3622                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3623                        const DebugLoc &DL, const MachineOperand &Idx,
3624                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3625                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3626                        Register &SGPRIdxReg) {
3627 
3628   MachineFunction *MF = OrigBB.getParent();
3629   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3630   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3631   MachineBasicBlock::iterator I = LoopBB.begin();
3632 
3633   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3634   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3635   Register NewExec = MRI.createVirtualRegister(BoolRC);
3636   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3637   Register CondReg = MRI.createVirtualRegister(BoolRC);
3638 
3639   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3640     .addReg(InitReg)
3641     .addMBB(&OrigBB)
3642     .addReg(ResultReg)
3643     .addMBB(&LoopBB);
3644 
3645   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3646     .addReg(InitSaveExecReg)
3647     .addMBB(&OrigBB)
3648     .addReg(NewExec)
3649     .addMBB(&LoopBB);
3650 
3651   // Read the next variant <- also loop target.
3652   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3653       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3654 
3655   // Compare the just read M0 value to all possible Idx values.
3656   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3657       .addReg(CurrentIdxReg)
3658       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3659 
3660   // Update EXEC, save the original EXEC value to VCC.
3661   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3662                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3663           NewExec)
3664     .addReg(CondReg, RegState::Kill);
3665 
3666   MRI.setSimpleHint(NewExec, CondReg);
3667 
3668   if (UseGPRIdxMode) {
3669     if (Offset == 0) {
3670       SGPRIdxReg = CurrentIdxReg;
3671     } else {
3672       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3673       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3674           .addReg(CurrentIdxReg, RegState::Kill)
3675           .addImm(Offset);
3676     }
3677   } else {
3678     // Move index from VCC into M0
3679     if (Offset == 0) {
3680       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3681         .addReg(CurrentIdxReg, RegState::Kill);
3682     } else {
3683       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3684         .addReg(CurrentIdxReg, RegState::Kill)
3685         .addImm(Offset);
3686     }
3687   }
3688 
3689   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3690   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3691   MachineInstr *InsertPt =
3692     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3693                                                   : AMDGPU::S_XOR_B64_term), Exec)
3694       .addReg(Exec)
3695       .addReg(NewExec);
3696 
3697   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3698   // s_cbranch_scc0?
3699 
3700   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3701   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3702     .addMBB(&LoopBB);
3703 
3704   return InsertPt->getIterator();
3705 }
3706 
3707 // This has slightly sub-optimal regalloc when the source vector is killed by
3708 // the read. The register allocator does not understand that the kill is
3709 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3710 // subregister from it, using 1 more VGPR than necessary. This was saved when
3711 // this was expanded after register allocation.
3712 static MachineBasicBlock::iterator
3713 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3714                unsigned InitResultReg, unsigned PhiReg, int Offset,
3715                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3716   MachineFunction *MF = MBB.getParent();
3717   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3718   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3719   MachineRegisterInfo &MRI = MF->getRegInfo();
3720   const DebugLoc &DL = MI.getDebugLoc();
3721   MachineBasicBlock::iterator I(&MI);
3722 
3723   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3724   Register DstReg = MI.getOperand(0).getReg();
3725   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3726   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3727   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3728   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3729 
3730   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3731 
3732   // Save the EXEC mask
3733   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3734     .addReg(Exec);
3735 
3736   MachineBasicBlock *LoopBB;
3737   MachineBasicBlock *RemainderBB;
3738   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3739 
3740   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3741 
3742   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3743                                       InitResultReg, DstReg, PhiReg, TmpExec,
3744                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3745 
3746   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3747   MachineFunction::iterator MBBI(LoopBB);
3748   ++MBBI;
3749   MF->insert(MBBI, LandingPad);
3750   LoopBB->removeSuccessor(RemainderBB);
3751   LandingPad->addSuccessor(RemainderBB);
3752   LoopBB->addSuccessor(LandingPad);
3753   MachineBasicBlock::iterator First = LandingPad->begin();
3754   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3755     .addReg(SaveExec);
3756 
3757   return InsPt;
3758 }
3759 
3760 // Returns subreg index, offset
3761 static std::pair<unsigned, int>
3762 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3763                             const TargetRegisterClass *SuperRC,
3764                             unsigned VecReg,
3765                             int Offset) {
3766   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3767 
3768   // Skip out of bounds offsets, or else we would end up using an undefined
3769   // register.
3770   if (Offset >= NumElts || Offset < 0)
3771     return std::make_pair(AMDGPU::sub0, Offset);
3772 
3773   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3774 }
3775 
3776 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3777                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3778                                  int Offset) {
3779   MachineBasicBlock *MBB = MI.getParent();
3780   const DebugLoc &DL = MI.getDebugLoc();
3781   MachineBasicBlock::iterator I(&MI);
3782 
3783   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3784 
3785   assert(Idx->getReg() != AMDGPU::NoRegister);
3786 
3787   if (Offset == 0) {
3788     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3789   } else {
3790     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3791         .add(*Idx)
3792         .addImm(Offset);
3793   }
3794 }
3795 
3796 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3797                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3798                                    int Offset) {
3799   MachineBasicBlock *MBB = MI.getParent();
3800   const DebugLoc &DL = MI.getDebugLoc();
3801   MachineBasicBlock::iterator I(&MI);
3802 
3803   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3804 
3805   if (Offset == 0)
3806     return Idx->getReg();
3807 
3808   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3809   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3810       .add(*Idx)
3811       .addImm(Offset);
3812   return Tmp;
3813 }
3814 
3815 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3816                                           MachineBasicBlock &MBB,
3817                                           const GCNSubtarget &ST) {
3818   const SIInstrInfo *TII = ST.getInstrInfo();
3819   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3820   MachineFunction *MF = MBB.getParent();
3821   MachineRegisterInfo &MRI = MF->getRegInfo();
3822 
3823   Register Dst = MI.getOperand(0).getReg();
3824   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3825   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3826   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3827 
3828   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3829   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3830 
3831   unsigned SubReg;
3832   std::tie(SubReg, Offset)
3833     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3834 
3835   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3836 
3837   // Check for a SGPR index.
3838   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3839     MachineBasicBlock::iterator I(&MI);
3840     const DebugLoc &DL = MI.getDebugLoc();
3841 
3842     if (UseGPRIdxMode) {
3843       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3844       // to avoid interfering with other uses, so probably requires a new
3845       // optimization pass.
3846       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3847 
3848       const MCInstrDesc &GPRIDXDesc =
3849           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3850       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3851           .addReg(SrcReg)
3852           .addReg(Idx)
3853           .addImm(SubReg);
3854     } else {
3855       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3856 
3857       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3858         .addReg(SrcReg, 0, SubReg)
3859         .addReg(SrcReg, RegState::Implicit);
3860     }
3861 
3862     MI.eraseFromParent();
3863 
3864     return &MBB;
3865   }
3866 
3867   // Control flow needs to be inserted if indexing with a VGPR.
3868   const DebugLoc &DL = MI.getDebugLoc();
3869   MachineBasicBlock::iterator I(&MI);
3870 
3871   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3872   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3873 
3874   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3875 
3876   Register SGPRIdxReg;
3877   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3878                               UseGPRIdxMode, SGPRIdxReg);
3879 
3880   MachineBasicBlock *LoopBB = InsPt->getParent();
3881 
3882   if (UseGPRIdxMode) {
3883     const MCInstrDesc &GPRIDXDesc =
3884         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3885 
3886     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3887         .addReg(SrcReg)
3888         .addReg(SGPRIdxReg)
3889         .addImm(SubReg);
3890   } else {
3891     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3892       .addReg(SrcReg, 0, SubReg)
3893       .addReg(SrcReg, RegState::Implicit);
3894   }
3895 
3896   MI.eraseFromParent();
3897 
3898   return LoopBB;
3899 }
3900 
3901 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3902                                           MachineBasicBlock &MBB,
3903                                           const GCNSubtarget &ST) {
3904   const SIInstrInfo *TII = ST.getInstrInfo();
3905   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3906   MachineFunction *MF = MBB.getParent();
3907   MachineRegisterInfo &MRI = MF->getRegInfo();
3908 
3909   Register Dst = MI.getOperand(0).getReg();
3910   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3911   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3912   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3913   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3914   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3915   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3916 
3917   // This can be an immediate, but will be folded later.
3918   assert(Val->getReg());
3919 
3920   unsigned SubReg;
3921   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3922                                                          SrcVec->getReg(),
3923                                                          Offset);
3924   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3925 
3926   if (Idx->getReg() == AMDGPU::NoRegister) {
3927     MachineBasicBlock::iterator I(&MI);
3928     const DebugLoc &DL = MI.getDebugLoc();
3929 
3930     assert(Offset == 0);
3931 
3932     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3933         .add(*SrcVec)
3934         .add(*Val)
3935         .addImm(SubReg);
3936 
3937     MI.eraseFromParent();
3938     return &MBB;
3939   }
3940 
3941   // Check for a SGPR index.
3942   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3943     MachineBasicBlock::iterator I(&MI);
3944     const DebugLoc &DL = MI.getDebugLoc();
3945 
3946     if (UseGPRIdxMode) {
3947       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3948 
3949       const MCInstrDesc &GPRIDXDesc =
3950           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3951       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3952           .addReg(SrcVec->getReg())
3953           .add(*Val)
3954           .addReg(Idx)
3955           .addImm(SubReg);
3956     } else {
3957       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3958 
3959       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3960           TRI.getRegSizeInBits(*VecRC), 32, false);
3961       BuildMI(MBB, I, DL, MovRelDesc, Dst)
3962           .addReg(SrcVec->getReg())
3963           .add(*Val)
3964           .addImm(SubReg);
3965     }
3966     MI.eraseFromParent();
3967     return &MBB;
3968   }
3969 
3970   // Control flow needs to be inserted if indexing with a VGPR.
3971   if (Val->isReg())
3972     MRI.clearKillFlags(Val->getReg());
3973 
3974   const DebugLoc &DL = MI.getDebugLoc();
3975 
3976   Register PhiReg = MRI.createVirtualRegister(VecRC);
3977 
3978   Register SGPRIdxReg;
3979   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
3980                               UseGPRIdxMode, SGPRIdxReg);
3981   MachineBasicBlock *LoopBB = InsPt->getParent();
3982 
3983   if (UseGPRIdxMode) {
3984     const MCInstrDesc &GPRIDXDesc =
3985         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3986 
3987     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3988         .addReg(PhiReg)
3989         .add(*Val)
3990         .addReg(SGPRIdxReg)
3991         .addImm(AMDGPU::sub0);
3992   } else {
3993     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
3994         TRI.getRegSizeInBits(*VecRC), 32, false);
3995     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3996         .addReg(PhiReg)
3997         .add(*Val)
3998         .addImm(AMDGPU::sub0);
3999   }
4000 
4001   MI.eraseFromParent();
4002   return LoopBB;
4003 }
4004 
4005 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
4006   MachineInstr &MI, MachineBasicBlock *BB) const {
4007 
4008   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4009   MachineFunction *MF = BB->getParent();
4010   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
4011 
4012   switch (MI.getOpcode()) {
4013   case AMDGPU::S_UADDO_PSEUDO:
4014   case AMDGPU::S_USUBO_PSEUDO: {
4015     const DebugLoc &DL = MI.getDebugLoc();
4016     MachineOperand &Dest0 = MI.getOperand(0);
4017     MachineOperand &Dest1 = MI.getOperand(1);
4018     MachineOperand &Src0 = MI.getOperand(2);
4019     MachineOperand &Src1 = MI.getOperand(3);
4020 
4021     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
4022                        ? AMDGPU::S_ADD_I32
4023                        : AMDGPU::S_SUB_I32;
4024     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
4025 
4026     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
4027         .addImm(1)
4028         .addImm(0);
4029 
4030     MI.eraseFromParent();
4031     return BB;
4032   }
4033   case AMDGPU::S_ADD_U64_PSEUDO:
4034   case AMDGPU::S_SUB_U64_PSEUDO: {
4035     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4036     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4037     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4038     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
4039     const DebugLoc &DL = MI.getDebugLoc();
4040 
4041     MachineOperand &Dest = MI.getOperand(0);
4042     MachineOperand &Src0 = MI.getOperand(1);
4043     MachineOperand &Src1 = MI.getOperand(2);
4044 
4045     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4046     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4047 
4048     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
4049         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4050     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
4051         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4052 
4053     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
4054         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4055     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
4056         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4057 
4058     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
4059 
4060     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
4061     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
4062     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
4063     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
4064     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4065         .addReg(DestSub0)
4066         .addImm(AMDGPU::sub0)
4067         .addReg(DestSub1)
4068         .addImm(AMDGPU::sub1);
4069     MI.eraseFromParent();
4070     return BB;
4071   }
4072   case AMDGPU::V_ADD_U64_PSEUDO:
4073   case AMDGPU::V_SUB_U64_PSEUDO: {
4074     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4075     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4076     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4077     const DebugLoc &DL = MI.getDebugLoc();
4078 
4079     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
4080 
4081     MachineOperand &Dest = MI.getOperand(0);
4082     MachineOperand &Src0 = MI.getOperand(1);
4083     MachineOperand &Src1 = MI.getOperand(2);
4084 
4085     if (IsAdd && ST.hasLshlAddB64()) {
4086       auto Add = BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_LSHL_ADD_U64_e64),
4087                          Dest.getReg())
4088                      .add(Src0)
4089                      .addImm(0)
4090                      .add(Src1);
4091       TII->legalizeOperands(*Add);
4092       MI.eraseFromParent();
4093       return BB;
4094     }
4095 
4096     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4097 
4098     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4099     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4100 
4101     Register CarryReg = MRI.createVirtualRegister(CarryRC);
4102     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
4103 
4104     const TargetRegisterClass *Src0RC = Src0.isReg()
4105                                             ? MRI.getRegClass(Src0.getReg())
4106                                             : &AMDGPU::VReg_64RegClass;
4107     const TargetRegisterClass *Src1RC = Src1.isReg()
4108                                             ? MRI.getRegClass(Src1.getReg())
4109                                             : &AMDGPU::VReg_64RegClass;
4110 
4111     const TargetRegisterClass *Src0SubRC =
4112         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
4113     const TargetRegisterClass *Src1SubRC =
4114         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
4115 
4116     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
4117         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
4118     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
4119         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
4120 
4121     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
4122         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
4123     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
4124         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
4125 
4126     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
4127     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
4128                                .addReg(CarryReg, RegState::Define)
4129                                .add(SrcReg0Sub0)
4130                                .add(SrcReg1Sub0)
4131                                .addImm(0); // clamp bit
4132 
4133     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
4134     MachineInstr *HiHalf =
4135         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4136             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4137             .add(SrcReg0Sub1)
4138             .add(SrcReg1Sub1)
4139             .addReg(CarryReg, RegState::Kill)
4140             .addImm(0); // clamp bit
4141 
4142     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4143         .addReg(DestSub0)
4144         .addImm(AMDGPU::sub0)
4145         .addReg(DestSub1)
4146         .addImm(AMDGPU::sub1);
4147     TII->legalizeOperands(*LoHalf);
4148     TII->legalizeOperands(*HiHalf);
4149     MI.eraseFromParent();
4150     return BB;
4151   }
4152   case AMDGPU::S_ADD_CO_PSEUDO:
4153   case AMDGPU::S_SUB_CO_PSEUDO: {
4154     // This pseudo has a chance to be selected
4155     // only from uniform add/subcarry node. All the VGPR operands
4156     // therefore assumed to be splat vectors.
4157     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4158     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4159     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4160     MachineBasicBlock::iterator MII = MI;
4161     const DebugLoc &DL = MI.getDebugLoc();
4162     MachineOperand &Dest = MI.getOperand(0);
4163     MachineOperand &CarryDest = MI.getOperand(1);
4164     MachineOperand &Src0 = MI.getOperand(2);
4165     MachineOperand &Src1 = MI.getOperand(3);
4166     MachineOperand &Src2 = MI.getOperand(4);
4167     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4168                        ? AMDGPU::S_ADDC_U32
4169                        : AMDGPU::S_SUBB_U32;
4170     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4171       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4172       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4173           .addReg(Src0.getReg());
4174       Src0.setReg(RegOp0);
4175     }
4176     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4177       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4178       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4179           .addReg(Src1.getReg());
4180       Src1.setReg(RegOp1);
4181     }
4182     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4183     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4184       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4185           .addReg(Src2.getReg());
4186       Src2.setReg(RegOp2);
4187     }
4188 
4189     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4190     unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC);
4191     assert(WaveSize == 64 || WaveSize == 32);
4192 
4193     if (WaveSize == 64) {
4194       if (ST.hasScalarCompareEq64()) {
4195         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4196             .addReg(Src2.getReg())
4197             .addImm(0);
4198       } else {
4199         const TargetRegisterClass *SubRC =
4200             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4201         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4202             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4203         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4204             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4205         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4206 
4207         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4208             .add(Src2Sub0)
4209             .add(Src2Sub1);
4210 
4211         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4212             .addReg(Src2_32, RegState::Kill)
4213             .addImm(0);
4214       }
4215     } else {
4216       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4217           .addReg(Src2.getReg())
4218           .addImm(0);
4219     }
4220 
4221     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4222 
4223     unsigned SelOpc =
4224         (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
4225 
4226     BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg())
4227         .addImm(-1)
4228         .addImm(0);
4229 
4230     MI.eraseFromParent();
4231     return BB;
4232   }
4233   case AMDGPU::SI_INIT_M0: {
4234     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4235             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4236         .add(MI.getOperand(0));
4237     MI.eraseFromParent();
4238     return BB;
4239   }
4240   case AMDGPU::GET_GROUPSTATICSIZE: {
4241     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4242            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4243     DebugLoc DL = MI.getDebugLoc();
4244     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4245         .add(MI.getOperand(0))
4246         .addImm(MFI->getLDSSize());
4247     MI.eraseFromParent();
4248     return BB;
4249   }
4250   case AMDGPU::SI_INDIRECT_SRC_V1:
4251   case AMDGPU::SI_INDIRECT_SRC_V2:
4252   case AMDGPU::SI_INDIRECT_SRC_V4:
4253   case AMDGPU::SI_INDIRECT_SRC_V8:
4254   case AMDGPU::SI_INDIRECT_SRC_V16:
4255   case AMDGPU::SI_INDIRECT_SRC_V32:
4256     return emitIndirectSrc(MI, *BB, *getSubtarget());
4257   case AMDGPU::SI_INDIRECT_DST_V1:
4258   case AMDGPU::SI_INDIRECT_DST_V2:
4259   case AMDGPU::SI_INDIRECT_DST_V4:
4260   case AMDGPU::SI_INDIRECT_DST_V8:
4261   case AMDGPU::SI_INDIRECT_DST_V16:
4262   case AMDGPU::SI_INDIRECT_DST_V32:
4263     return emitIndirectDst(MI, *BB, *getSubtarget());
4264   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4265   case AMDGPU::SI_KILL_I1_PSEUDO:
4266     return splitKillBlock(MI, BB);
4267   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4268     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4269     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4270     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4271 
4272     Register Dst = MI.getOperand(0).getReg();
4273     Register Src0 = MI.getOperand(1).getReg();
4274     Register Src1 = MI.getOperand(2).getReg();
4275     const DebugLoc &DL = MI.getDebugLoc();
4276     Register SrcCond = MI.getOperand(3).getReg();
4277 
4278     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4279     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4280     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4281     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4282 
4283     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4284       .addReg(SrcCond);
4285     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4286       .addImm(0)
4287       .addReg(Src0, 0, AMDGPU::sub0)
4288       .addImm(0)
4289       .addReg(Src1, 0, AMDGPU::sub0)
4290       .addReg(SrcCondCopy);
4291     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4292       .addImm(0)
4293       .addReg(Src0, 0, AMDGPU::sub1)
4294       .addImm(0)
4295       .addReg(Src1, 0, AMDGPU::sub1)
4296       .addReg(SrcCondCopy);
4297 
4298     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4299       .addReg(DstLo)
4300       .addImm(AMDGPU::sub0)
4301       .addReg(DstHi)
4302       .addImm(AMDGPU::sub1);
4303     MI.eraseFromParent();
4304     return BB;
4305   }
4306   case AMDGPU::SI_BR_UNDEF: {
4307     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4308     const DebugLoc &DL = MI.getDebugLoc();
4309     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4310                            .add(MI.getOperand(0));
4311     Br->getOperand(1).setIsUndef(true); // read undef SCC
4312     MI.eraseFromParent();
4313     return BB;
4314   }
4315   case AMDGPU::ADJCALLSTACKUP:
4316   case AMDGPU::ADJCALLSTACKDOWN: {
4317     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4318     MachineInstrBuilder MIB(*MF, &MI);
4319     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4320        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4321     return BB;
4322   }
4323   case AMDGPU::SI_CALL_ISEL: {
4324     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4325     const DebugLoc &DL = MI.getDebugLoc();
4326 
4327     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4328 
4329     MachineInstrBuilder MIB;
4330     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4331 
4332     for (const MachineOperand &MO : MI.operands())
4333       MIB.add(MO);
4334 
4335     MIB.cloneMemRefs(MI);
4336     MI.eraseFromParent();
4337     return BB;
4338   }
4339   case AMDGPU::V_ADD_CO_U32_e32:
4340   case AMDGPU::V_SUB_CO_U32_e32:
4341   case AMDGPU::V_SUBREV_CO_U32_e32: {
4342     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4343     const DebugLoc &DL = MI.getDebugLoc();
4344     unsigned Opc = MI.getOpcode();
4345 
4346     bool NeedClampOperand = false;
4347     if (TII->pseudoToMCOpcode(Opc) == -1) {
4348       Opc = AMDGPU::getVOPe64(Opc);
4349       NeedClampOperand = true;
4350     }
4351 
4352     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4353     if (TII->isVOP3(*I)) {
4354       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4355       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4356       I.addReg(TRI->getVCC(), RegState::Define);
4357     }
4358     I.add(MI.getOperand(1))
4359      .add(MI.getOperand(2));
4360     if (NeedClampOperand)
4361       I.addImm(0); // clamp bit for e64 encoding
4362 
4363     TII->legalizeOperands(*I);
4364 
4365     MI.eraseFromParent();
4366     return BB;
4367   }
4368   case AMDGPU::V_ADDC_U32_e32:
4369   case AMDGPU::V_SUBB_U32_e32:
4370   case AMDGPU::V_SUBBREV_U32_e32:
4371     // These instructions have an implicit use of vcc which counts towards the
4372     // constant bus limit.
4373     TII->legalizeOperands(MI);
4374     return BB;
4375   case AMDGPU::DS_GWS_INIT:
4376   case AMDGPU::DS_GWS_SEMA_BR:
4377   case AMDGPU::DS_GWS_BARRIER:
4378     if (Subtarget->needsAlignedVGPRs()) {
4379       // Add implicit aligned super-reg to force alignment on the data operand.
4380       const DebugLoc &DL = MI.getDebugLoc();
4381       MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4382       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
4383       MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0);
4384       Register DataReg = Op->getReg();
4385       bool IsAGPR = TRI->isAGPR(MRI, DataReg);
4386       Register Undef = MRI.createVirtualRegister(
4387           IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass);
4388       BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef);
4389       Register NewVR =
4390           MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass
4391                                            : &AMDGPU::VReg_64_Align2RegClass);
4392       BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR)
4393           .addReg(DataReg, 0, Op->getSubReg())
4394           .addImm(AMDGPU::sub0)
4395           .addReg(Undef)
4396           .addImm(AMDGPU::sub1);
4397       Op->setReg(NewVR);
4398       Op->setSubReg(AMDGPU::sub0);
4399       MI.addOperand(MachineOperand::CreateReg(NewVR, false, true));
4400     }
4401     LLVM_FALLTHROUGH;
4402   case AMDGPU::DS_GWS_SEMA_V:
4403   case AMDGPU::DS_GWS_SEMA_P:
4404   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4405     // A s_waitcnt 0 is required to be the instruction immediately following.
4406     if (getSubtarget()->hasGWSAutoReplay()) {
4407       bundleInstWithWaitcnt(MI);
4408       return BB;
4409     }
4410 
4411     return emitGWSMemViolTestLoop(MI, BB);
4412   case AMDGPU::S_SETREG_B32: {
4413     // Try to optimize cases that only set the denormal mode or rounding mode.
4414     //
4415     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4416     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4417     // instead.
4418     //
4419     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4420     // allow you to have a no side effect instruction in the output of a
4421     // sideeffecting pattern.
4422     unsigned ID, Offset, Width;
4423     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4424     if (ID != AMDGPU::Hwreg::ID_MODE)
4425       return BB;
4426 
4427     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4428     const unsigned SetMask = WidthMask << Offset;
4429 
4430     if (getSubtarget()->hasDenormModeInst()) {
4431       unsigned SetDenormOp = 0;
4432       unsigned SetRoundOp = 0;
4433 
4434       // The dedicated instructions can only set the whole denorm or round mode
4435       // at once, not a subset of bits in either.
4436       if (SetMask ==
4437           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4438         // If this fully sets both the round and denorm mode, emit the two
4439         // dedicated instructions for these.
4440         SetRoundOp = AMDGPU::S_ROUND_MODE;
4441         SetDenormOp = AMDGPU::S_DENORM_MODE;
4442       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4443         SetRoundOp = AMDGPU::S_ROUND_MODE;
4444       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4445         SetDenormOp = AMDGPU::S_DENORM_MODE;
4446       }
4447 
4448       if (SetRoundOp || SetDenormOp) {
4449         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4450         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4451         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4452           unsigned ImmVal = Def->getOperand(1).getImm();
4453           if (SetRoundOp) {
4454             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4455                 .addImm(ImmVal & 0xf);
4456 
4457             // If we also have the denorm mode, get just the denorm mode bits.
4458             ImmVal >>= 4;
4459           }
4460 
4461           if (SetDenormOp) {
4462             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4463                 .addImm(ImmVal & 0xf);
4464           }
4465 
4466           MI.eraseFromParent();
4467           return BB;
4468         }
4469       }
4470     }
4471 
4472     // If only FP bits are touched, used the no side effects pseudo.
4473     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4474                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4475       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4476 
4477     return BB;
4478   }
4479   default:
4480     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4481   }
4482 }
4483 
4484 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4485   return isTypeLegal(VT.getScalarType());
4486 }
4487 
4488 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4489   // This currently forces unfolding various combinations of fsub into fma with
4490   // free fneg'd operands. As long as we have fast FMA (controlled by
4491   // isFMAFasterThanFMulAndFAdd), we should perform these.
4492 
4493   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4494   // most of these combines appear to be cycle neutral but save on instruction
4495   // count / code size.
4496   return true;
4497 }
4498 
4499 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; }
4500 
4501 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4502                                          EVT VT) const {
4503   if (!VT.isVector()) {
4504     return MVT::i1;
4505   }
4506   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4507 }
4508 
4509 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4510   // TODO: Should i16 be used always if legal? For now it would force VALU
4511   // shifts.
4512   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4513 }
4514 
4515 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4516   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4517              ? Ty.changeElementSize(16)
4518              : Ty.changeElementSize(32);
4519 }
4520 
4521 // Answering this is somewhat tricky and depends on the specific device which
4522 // have different rates for fma or all f64 operations.
4523 //
4524 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4525 // regardless of which device (although the number of cycles differs between
4526 // devices), so it is always profitable for f64.
4527 //
4528 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4529 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4530 // which we can always do even without fused FP ops since it returns the same
4531 // result as the separate operations and since it is always full
4532 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4533 // however does not support denormals, so we do report fma as faster if we have
4534 // a fast fma device and require denormals.
4535 //
4536 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4537                                                   EVT VT) const {
4538   VT = VT.getScalarType();
4539 
4540   switch (VT.getSimpleVT().SimpleTy) {
4541   case MVT::f32: {
4542     // If mad is not available this depends only on if f32 fma is full rate.
4543     if (!Subtarget->hasMadMacF32Insts())
4544       return Subtarget->hasFastFMAF32();
4545 
4546     // Otherwise f32 mad is always full rate and returns the same result as
4547     // the separate operations so should be preferred over fma.
4548     // However does not support denormals.
4549     if (hasFP32Denormals(MF))
4550       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4551 
4552     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4553     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4554   }
4555   case MVT::f64:
4556     return true;
4557   case MVT::f16:
4558     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4559   default:
4560     break;
4561   }
4562 
4563   return false;
4564 }
4565 
4566 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4567                                                   LLT Ty) const {
4568   switch (Ty.getScalarSizeInBits()) {
4569   case 16:
4570     return isFMAFasterThanFMulAndFAdd(MF, MVT::f16);
4571   case 32:
4572     return isFMAFasterThanFMulAndFAdd(MF, MVT::f32);
4573   case 64:
4574     return isFMAFasterThanFMulAndFAdd(MF, MVT::f64);
4575   default:
4576     break;
4577   }
4578 
4579   return false;
4580 }
4581 
4582 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const {
4583   if (!Ty.isScalar())
4584     return false;
4585 
4586   if (Ty.getScalarSizeInBits() == 16)
4587     return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF());
4588   if (Ty.getScalarSizeInBits() == 32)
4589     return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF());
4590 
4591   return false;
4592 }
4593 
4594 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4595                                    const SDNode *N) const {
4596   // TODO: Check future ftz flag
4597   // v_mad_f32/v_mac_f32 do not support denormals.
4598   EVT VT = N->getValueType(0);
4599   if (VT == MVT::f32)
4600     return Subtarget->hasMadMacF32Insts() &&
4601            !hasFP32Denormals(DAG.getMachineFunction());
4602   if (VT == MVT::f16) {
4603     return Subtarget->hasMadF16() &&
4604            !hasFP64FP16Denormals(DAG.getMachineFunction());
4605   }
4606 
4607   return false;
4608 }
4609 
4610 //===----------------------------------------------------------------------===//
4611 // Custom DAG Lowering Operations
4612 //===----------------------------------------------------------------------===//
4613 
4614 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4615 // wider vector type is legal.
4616 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4617                                              SelectionDAG &DAG) const {
4618   unsigned Opc = Op.getOpcode();
4619   EVT VT = Op.getValueType();
4620   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4621 
4622   SDValue Lo, Hi;
4623   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4624 
4625   SDLoc SL(Op);
4626   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4627                              Op->getFlags());
4628   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4629                              Op->getFlags());
4630 
4631   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4632 }
4633 
4634 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4635 // wider vector type is legal.
4636 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4637                                               SelectionDAG &DAG) const {
4638   unsigned Opc = Op.getOpcode();
4639   EVT VT = Op.getValueType();
4640   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4641          VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8f32 ||
4642          VT == MVT::v16f32 || VT == MVT::v32f32);
4643 
4644   SDValue Lo0, Hi0;
4645   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4646   SDValue Lo1, Hi1;
4647   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4648 
4649   SDLoc SL(Op);
4650 
4651   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4652                              Op->getFlags());
4653   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4654                              Op->getFlags());
4655 
4656   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4657 }
4658 
4659 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4660                                               SelectionDAG &DAG) const {
4661   unsigned Opc = Op.getOpcode();
4662   EVT VT = Op.getValueType();
4663   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 ||
4664          VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v8f32 ||
4665          VT == MVT::v16f32 || VT == MVT::v32f32);
4666 
4667   SDValue Lo0, Hi0;
4668   SDValue Op0 = Op.getOperand(0);
4669   std::tie(Lo0, Hi0) = Op0.getValueType().isVector()
4670                          ? DAG.SplitVectorOperand(Op.getNode(), 0)
4671                          : std::make_pair(Op0, Op0);
4672   SDValue Lo1, Hi1;
4673   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4674   SDValue Lo2, Hi2;
4675   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4676 
4677   SDLoc SL(Op);
4678   auto ResVT = DAG.GetSplitDestVTs(VT);
4679 
4680   SDValue OpLo = DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2,
4681                              Op->getFlags());
4682   SDValue OpHi = DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2,
4683                              Op->getFlags());
4684 
4685   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4686 }
4687 
4688 
4689 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4690   switch (Op.getOpcode()) {
4691   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4692   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4693   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4694   case ISD::LOAD: {
4695     SDValue Result = LowerLOAD(Op, DAG);
4696     assert((!Result.getNode() ||
4697             Result.getNode()->getNumValues() == 2) &&
4698            "Load should return a value and a chain");
4699     return Result;
4700   }
4701 
4702   case ISD::FSIN:
4703   case ISD::FCOS:
4704     return LowerTrig(Op, DAG);
4705   case ISD::SELECT: return LowerSELECT(Op, DAG);
4706   case ISD::FDIV: return LowerFDIV(Op, DAG);
4707   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4708   case ISD::STORE: return LowerSTORE(Op, DAG);
4709   case ISD::GlobalAddress: {
4710     MachineFunction &MF = DAG.getMachineFunction();
4711     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4712     return LowerGlobalAddress(MFI, Op, DAG);
4713   }
4714   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4715   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4716   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4717   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4718   case ISD::INSERT_SUBVECTOR:
4719     return lowerINSERT_SUBVECTOR(Op, DAG);
4720   case ISD::INSERT_VECTOR_ELT:
4721     return lowerINSERT_VECTOR_ELT(Op, DAG);
4722   case ISD::EXTRACT_VECTOR_ELT:
4723     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4724   case ISD::VECTOR_SHUFFLE:
4725     return lowerVECTOR_SHUFFLE(Op, DAG);
4726   case ISD::BUILD_VECTOR:
4727     return lowerBUILD_VECTOR(Op, DAG);
4728   case ISD::FP_ROUND:
4729     return lowerFP_ROUND(Op, DAG);
4730   case ISD::FPTRUNC_ROUND: {
4731     unsigned Opc;
4732     SDLoc DL(Op);
4733 
4734     if (Op.getOperand(0)->getValueType(0) != MVT::f32)
4735       return SDValue();
4736 
4737     // Get the rounding mode from the last operand
4738     int RoundMode = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4739     if (RoundMode == (int)RoundingMode::TowardPositive)
4740       Opc = AMDGPUISD::FPTRUNC_ROUND_UPWARD;
4741     else if (RoundMode == (int)RoundingMode::TowardNegative)
4742       Opc = AMDGPUISD::FPTRUNC_ROUND_DOWNWARD;
4743     else
4744       return SDValue();
4745 
4746     return DAG.getNode(Opc, DL, Op.getNode()->getVTList(), Op->getOperand(0));
4747   }
4748   case ISD::TRAP:
4749     return lowerTRAP(Op, DAG);
4750   case ISD::DEBUGTRAP:
4751     return lowerDEBUGTRAP(Op, DAG);
4752   case ISD::FABS:
4753   case ISD::FNEG:
4754   case ISD::FCANONICALIZE:
4755   case ISD::BSWAP:
4756     return splitUnaryVectorOp(Op, DAG);
4757   case ISD::FMINNUM:
4758   case ISD::FMAXNUM:
4759     return lowerFMINNUM_FMAXNUM(Op, DAG);
4760   case ISD::FMA:
4761     return splitTernaryVectorOp(Op, DAG);
4762   case ISD::FP_TO_SINT:
4763   case ISD::FP_TO_UINT:
4764     return LowerFP_TO_INT(Op, DAG);
4765   case ISD::SHL:
4766   case ISD::SRA:
4767   case ISD::SRL:
4768   case ISD::ADD:
4769   case ISD::SUB:
4770   case ISD::MUL:
4771   case ISD::SMIN:
4772   case ISD::SMAX:
4773   case ISD::UMIN:
4774   case ISD::UMAX:
4775   case ISD::FADD:
4776   case ISD::FMUL:
4777   case ISD::FMINNUM_IEEE:
4778   case ISD::FMAXNUM_IEEE:
4779   case ISD::UADDSAT:
4780   case ISD::USUBSAT:
4781   case ISD::SADDSAT:
4782   case ISD::SSUBSAT:
4783     return splitBinaryVectorOp(Op, DAG);
4784   case ISD::SMULO:
4785   case ISD::UMULO:
4786     return lowerXMULO(Op, DAG);
4787   case ISD::SMUL_LOHI:
4788   case ISD::UMUL_LOHI:
4789     return lowerXMUL_LOHI(Op, DAG);
4790   case ISD::DYNAMIC_STACKALLOC:
4791     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4792   }
4793   return SDValue();
4794 }
4795 
4796 // Used for D16: Casts the result of an instruction into the right vector,
4797 // packs values if loads return unpacked values.
4798 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4799                                        const SDLoc &DL,
4800                                        SelectionDAG &DAG, bool Unpacked) {
4801   if (!LoadVT.isVector())
4802     return Result;
4803 
4804   // Cast back to the original packed type or to a larger type that is a
4805   // multiple of 32 bit for D16. Widening the return type is a required for
4806   // legalization.
4807   EVT FittingLoadVT = LoadVT;
4808   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4809     FittingLoadVT =
4810         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4811                          LoadVT.getVectorNumElements() + 1);
4812   }
4813 
4814   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4815     // Truncate to v2i16/v4i16.
4816     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4817 
4818     // Workaround legalizer not scalarizing truncate after vector op
4819     // legalization but not creating intermediate vector trunc.
4820     SmallVector<SDValue, 4> Elts;
4821     DAG.ExtractVectorElements(Result, Elts);
4822     for (SDValue &Elt : Elts)
4823       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4824 
4825     // Pad illegal v1i16/v3fi6 to v4i16
4826     if ((LoadVT.getVectorNumElements() % 2) == 1)
4827       Elts.push_back(DAG.getUNDEF(MVT::i16));
4828 
4829     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4830 
4831     // Bitcast to original type (v2f16/v4f16).
4832     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4833   }
4834 
4835   // Cast back to the original packed type.
4836   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4837 }
4838 
4839 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4840                                               MemSDNode *M,
4841                                               SelectionDAG &DAG,
4842                                               ArrayRef<SDValue> Ops,
4843                                               bool IsIntrinsic) const {
4844   SDLoc DL(M);
4845 
4846   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4847   EVT LoadVT = M->getValueType(0);
4848 
4849   EVT EquivLoadVT = LoadVT;
4850   if (LoadVT.isVector()) {
4851     if (Unpacked) {
4852       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4853                                      LoadVT.getVectorNumElements());
4854     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4855       // Widen v3f16 to legal type
4856       EquivLoadVT =
4857           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4858                            LoadVT.getVectorNumElements() + 1);
4859     }
4860   }
4861 
4862   // Change from v4f16/v2f16 to EquivLoadVT.
4863   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4864 
4865   SDValue Load
4866     = DAG.getMemIntrinsicNode(
4867       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4868       VTList, Ops, M->getMemoryVT(),
4869       M->getMemOperand());
4870 
4871   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4872 
4873   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4874 }
4875 
4876 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4877                                              SelectionDAG &DAG,
4878                                              ArrayRef<SDValue> Ops) const {
4879   SDLoc DL(M);
4880   EVT LoadVT = M->getValueType(0);
4881   EVT EltType = LoadVT.getScalarType();
4882   EVT IntVT = LoadVT.changeTypeToInteger();
4883 
4884   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4885 
4886   unsigned Opc =
4887       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4888 
4889   if (IsD16) {
4890     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4891   }
4892 
4893   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4894   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4895     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4896 
4897   if (isTypeLegal(LoadVT)) {
4898     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4899                                M->getMemOperand(), DAG);
4900   }
4901 
4902   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4903   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4904   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4905                                         M->getMemOperand(), DAG);
4906   return DAG.getMergeValues(
4907       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4908       DL);
4909 }
4910 
4911 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4912                                   SDNode *N, SelectionDAG &DAG) {
4913   EVT VT = N->getValueType(0);
4914   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4915   unsigned CondCode = CD->getZExtValue();
4916   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4917     return DAG.getUNDEF(VT);
4918 
4919   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4920 
4921   SDValue LHS = N->getOperand(1);
4922   SDValue RHS = N->getOperand(2);
4923 
4924   SDLoc DL(N);
4925 
4926   EVT CmpVT = LHS.getValueType();
4927   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4928     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4929       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4930     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4931     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4932   }
4933 
4934   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4935 
4936   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4937   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4938 
4939   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4940                               DAG.getCondCode(CCOpcode));
4941   if (VT.bitsEq(CCVT))
4942     return SetCC;
4943   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4944 }
4945 
4946 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4947                                   SDNode *N, SelectionDAG &DAG) {
4948   EVT VT = N->getValueType(0);
4949   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4950 
4951   unsigned CondCode = CD->getZExtValue();
4952   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4953     return DAG.getUNDEF(VT);
4954 
4955   SDValue Src0 = N->getOperand(1);
4956   SDValue Src1 = N->getOperand(2);
4957   EVT CmpVT = Src0.getValueType();
4958   SDLoc SL(N);
4959 
4960   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4961     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4962     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4963   }
4964 
4965   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4966   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4967   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4968   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4969   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4970                               Src1, DAG.getCondCode(CCOpcode));
4971   if (VT.bitsEq(CCVT))
4972     return SetCC;
4973   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4974 }
4975 
4976 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4977                                     SelectionDAG &DAG) {
4978   EVT VT = N->getValueType(0);
4979   SDValue Src = N->getOperand(1);
4980   SDLoc SL(N);
4981 
4982   if (Src.getOpcode() == ISD::SETCC) {
4983     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4984     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4985                        Src.getOperand(1), Src.getOperand(2));
4986   }
4987   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4988     // (ballot 0) -> 0
4989     if (Arg->isZero())
4990       return DAG.getConstant(0, SL, VT);
4991 
4992     // (ballot 1) -> EXEC/EXEC_LO
4993     if (Arg->isOne()) {
4994       Register Exec;
4995       if (VT.getScalarSizeInBits() == 32)
4996         Exec = AMDGPU::EXEC_LO;
4997       else if (VT.getScalarSizeInBits() == 64)
4998         Exec = AMDGPU::EXEC;
4999       else
5000         return SDValue();
5001 
5002       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
5003     }
5004   }
5005 
5006   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
5007   // ISD::SETNE)
5008   return DAG.getNode(
5009       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
5010       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
5011 }
5012 
5013 void SITargetLowering::ReplaceNodeResults(SDNode *N,
5014                                           SmallVectorImpl<SDValue> &Results,
5015                                           SelectionDAG &DAG) const {
5016   switch (N->getOpcode()) {
5017   case ISD::INSERT_VECTOR_ELT: {
5018     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
5019       Results.push_back(Res);
5020     return;
5021   }
5022   case ISD::EXTRACT_VECTOR_ELT: {
5023     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
5024       Results.push_back(Res);
5025     return;
5026   }
5027   case ISD::INTRINSIC_WO_CHAIN: {
5028     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5029     switch (IID) {
5030     case Intrinsic::amdgcn_cvt_pkrtz: {
5031       SDValue Src0 = N->getOperand(1);
5032       SDValue Src1 = N->getOperand(2);
5033       SDLoc SL(N);
5034       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
5035                                 Src0, Src1);
5036       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
5037       return;
5038     }
5039     case Intrinsic::amdgcn_cvt_pknorm_i16:
5040     case Intrinsic::amdgcn_cvt_pknorm_u16:
5041     case Intrinsic::amdgcn_cvt_pk_i16:
5042     case Intrinsic::amdgcn_cvt_pk_u16: {
5043       SDValue Src0 = N->getOperand(1);
5044       SDValue Src1 = N->getOperand(2);
5045       SDLoc SL(N);
5046       unsigned Opcode;
5047 
5048       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
5049         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
5050       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
5051         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
5052       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
5053         Opcode = AMDGPUISD::CVT_PK_I16_I32;
5054       else
5055         Opcode = AMDGPUISD::CVT_PK_U16_U32;
5056 
5057       EVT VT = N->getValueType(0);
5058       if (isTypeLegal(VT))
5059         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
5060       else {
5061         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
5062         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
5063       }
5064       return;
5065     }
5066     }
5067     break;
5068   }
5069   case ISD::INTRINSIC_W_CHAIN: {
5070     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
5071       if (Res.getOpcode() == ISD::MERGE_VALUES) {
5072         // FIXME: Hacky
5073         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
5074           Results.push_back(Res.getOperand(I));
5075         }
5076       } else {
5077         Results.push_back(Res);
5078         Results.push_back(Res.getValue(1));
5079       }
5080       return;
5081     }
5082 
5083     break;
5084   }
5085   case ISD::SELECT: {
5086     SDLoc SL(N);
5087     EVT VT = N->getValueType(0);
5088     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
5089     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
5090     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
5091 
5092     EVT SelectVT = NewVT;
5093     if (NewVT.bitsLT(MVT::i32)) {
5094       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
5095       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
5096       SelectVT = MVT::i32;
5097     }
5098 
5099     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
5100                                     N->getOperand(0), LHS, RHS);
5101 
5102     if (NewVT != SelectVT)
5103       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
5104     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
5105     return;
5106   }
5107   case ISD::FNEG: {
5108     if (N->getValueType(0) != MVT::v2f16)
5109       break;
5110 
5111     SDLoc SL(N);
5112     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5113 
5114     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
5115                              BC,
5116                              DAG.getConstant(0x80008000, SL, MVT::i32));
5117     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5118     return;
5119   }
5120   case ISD::FABS: {
5121     if (N->getValueType(0) != MVT::v2f16)
5122       break;
5123 
5124     SDLoc SL(N);
5125     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5126 
5127     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
5128                              BC,
5129                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
5130     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5131     return;
5132   }
5133   default:
5134     break;
5135   }
5136 }
5137 
5138 /// Helper function for LowerBRCOND
5139 static SDNode *findUser(SDValue Value, unsigned Opcode) {
5140 
5141   SDNode *Parent = Value.getNode();
5142   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
5143        I != E; ++I) {
5144 
5145     if (I.getUse().get() != Value)
5146       continue;
5147 
5148     if (I->getOpcode() == Opcode)
5149       return *I;
5150   }
5151   return nullptr;
5152 }
5153 
5154 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
5155   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
5156     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
5157     case Intrinsic::amdgcn_if:
5158       return AMDGPUISD::IF;
5159     case Intrinsic::amdgcn_else:
5160       return AMDGPUISD::ELSE;
5161     case Intrinsic::amdgcn_loop:
5162       return AMDGPUISD::LOOP;
5163     case Intrinsic::amdgcn_end_cf:
5164       llvm_unreachable("should not occur");
5165     default:
5166       return 0;
5167     }
5168   }
5169 
5170   // break, if_break, else_break are all only used as inputs to loop, not
5171   // directly as branch conditions.
5172   return 0;
5173 }
5174 
5175 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
5176   const Triple &TT = getTargetMachine().getTargetTriple();
5177   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5178           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5179          AMDGPU::shouldEmitConstantsToTextSection(TT);
5180 }
5181 
5182 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
5183   // FIXME: Either avoid relying on address space here or change the default
5184   // address space for functions to avoid the explicit check.
5185   return (GV->getValueType()->isFunctionTy() ||
5186           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
5187          !shouldEmitFixup(GV) &&
5188          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
5189 }
5190 
5191 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
5192   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
5193 }
5194 
5195 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
5196   if (!GV->hasExternalLinkage())
5197     return true;
5198 
5199   const auto OS = getTargetMachine().getTargetTriple().getOS();
5200   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
5201 }
5202 
5203 /// This transforms the control flow intrinsics to get the branch destination as
5204 /// last parameter, also switches branch target with BR if the need arise
5205 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
5206                                       SelectionDAG &DAG) const {
5207   SDLoc DL(BRCOND);
5208 
5209   SDNode *Intr = BRCOND.getOperand(1).getNode();
5210   SDValue Target = BRCOND.getOperand(2);
5211   SDNode *BR = nullptr;
5212   SDNode *SetCC = nullptr;
5213 
5214   if (Intr->getOpcode() == ISD::SETCC) {
5215     // As long as we negate the condition everything is fine
5216     SetCC = Intr;
5217     Intr = SetCC->getOperand(0).getNode();
5218 
5219   } else {
5220     // Get the target from BR if we don't negate the condition
5221     BR = findUser(BRCOND, ISD::BR);
5222     assert(BR && "brcond missing unconditional branch user");
5223     Target = BR->getOperand(1);
5224   }
5225 
5226   unsigned CFNode = isCFIntrinsic(Intr);
5227   if (CFNode == 0) {
5228     // This is a uniform branch so we don't need to legalize.
5229     return BRCOND;
5230   }
5231 
5232   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5233                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5234 
5235   assert(!SetCC ||
5236         (SetCC->getConstantOperandVal(1) == 1 &&
5237          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5238                                                              ISD::SETNE));
5239 
5240   // operands of the new intrinsic call
5241   SmallVector<SDValue, 4> Ops;
5242   if (HaveChain)
5243     Ops.push_back(BRCOND.getOperand(0));
5244 
5245   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5246   Ops.push_back(Target);
5247 
5248   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5249 
5250   // build the new intrinsic call
5251   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5252 
5253   if (!HaveChain) {
5254     SDValue Ops[] =  {
5255       SDValue(Result, 0),
5256       BRCOND.getOperand(0)
5257     };
5258 
5259     Result = DAG.getMergeValues(Ops, DL).getNode();
5260   }
5261 
5262   if (BR) {
5263     // Give the branch instruction our target
5264     SDValue Ops[] = {
5265       BR->getOperand(0),
5266       BRCOND.getOperand(2)
5267     };
5268     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5269     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5270   }
5271 
5272   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5273 
5274   // Copy the intrinsic results to registers
5275   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5276     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5277     if (!CopyToReg)
5278       continue;
5279 
5280     Chain = DAG.getCopyToReg(
5281       Chain, DL,
5282       CopyToReg->getOperand(1),
5283       SDValue(Result, i - 1),
5284       SDValue());
5285 
5286     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5287   }
5288 
5289   // Remove the old intrinsic from the chain
5290   DAG.ReplaceAllUsesOfValueWith(
5291     SDValue(Intr, Intr->getNumValues() - 1),
5292     Intr->getOperand(0));
5293 
5294   return Chain;
5295 }
5296 
5297 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5298                                           SelectionDAG &DAG) const {
5299   MVT VT = Op.getSimpleValueType();
5300   SDLoc DL(Op);
5301   // Checking the depth
5302   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5303     return DAG.getConstant(0, DL, VT);
5304 
5305   MachineFunction &MF = DAG.getMachineFunction();
5306   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5307   // Check for kernel and shader functions
5308   if (Info->isEntryFunction())
5309     return DAG.getConstant(0, DL, VT);
5310 
5311   MachineFrameInfo &MFI = MF.getFrameInfo();
5312   // There is a call to @llvm.returnaddress in this function
5313   MFI.setReturnAddressIsTaken(true);
5314 
5315   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5316   // Get the return address reg and mark it as an implicit live-in
5317   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5318 
5319   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5320 }
5321 
5322 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5323                                             SDValue Op,
5324                                             const SDLoc &DL,
5325                                             EVT VT) const {
5326   return Op.getValueType().bitsLE(VT) ?
5327       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5328     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5329                 DAG.getTargetConstant(0, DL, MVT::i32));
5330 }
5331 
5332 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5333   assert(Op.getValueType() == MVT::f16 &&
5334          "Do not know how to custom lower FP_ROUND for non-f16 type");
5335 
5336   SDValue Src = Op.getOperand(0);
5337   EVT SrcVT = Src.getValueType();
5338   if (SrcVT != MVT::f64)
5339     return Op;
5340 
5341   SDLoc DL(Op);
5342 
5343   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5344   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5345   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5346 }
5347 
5348 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5349                                                SelectionDAG &DAG) const {
5350   EVT VT = Op.getValueType();
5351   const MachineFunction &MF = DAG.getMachineFunction();
5352   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5353   bool IsIEEEMode = Info->getMode().IEEE;
5354 
5355   // FIXME: Assert during selection that this is only selected for
5356   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5357   // mode functions, but this happens to be OK since it's only done in cases
5358   // where there is known no sNaN.
5359   if (IsIEEEMode)
5360     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5361 
5362   if (VT == MVT::v4f16 || VT == MVT::v8f16)
5363     return splitBinaryVectorOp(Op, DAG);
5364   return Op;
5365 }
5366 
5367 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5368   EVT VT = Op.getValueType();
5369   SDLoc SL(Op);
5370   SDValue LHS = Op.getOperand(0);
5371   SDValue RHS = Op.getOperand(1);
5372   bool isSigned = Op.getOpcode() == ISD::SMULO;
5373 
5374   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5375     const APInt &C = RHSC->getAPIntValue();
5376     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5377     if (C.isPowerOf2()) {
5378       // smulo(x, signed_min) is same as umulo(x, signed_min).
5379       bool UseArithShift = isSigned && !C.isMinSignedValue();
5380       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5381       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5382       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5383           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5384                       SL, VT, Result, ShiftAmt),
5385           LHS, ISD::SETNE);
5386       return DAG.getMergeValues({ Result, Overflow }, SL);
5387     }
5388   }
5389 
5390   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5391   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5392                             SL, VT, LHS, RHS);
5393 
5394   SDValue Sign = isSigned
5395     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5396                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5397     : DAG.getConstant(0, SL, VT);
5398   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5399 
5400   return DAG.getMergeValues({ Result, Overflow }, SL);
5401 }
5402 
5403 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const {
5404   if (Op->isDivergent()) {
5405     // Select to V_MAD_[IU]64_[IU]32.
5406     return Op;
5407   }
5408   if (Subtarget->hasSMulHi()) {
5409     // Expand to S_MUL_I32 + S_MUL_HI_[IU]32.
5410     return SDValue();
5411   }
5412   // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to
5413   // calculate the high part, so we might as well do the whole thing with
5414   // V_MAD_[IU]64_[IU]32.
5415   return Op;
5416 }
5417 
5418 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5419   if (!Subtarget->isTrapHandlerEnabled() ||
5420       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5421     return lowerTrapEndpgm(Op, DAG);
5422 
5423   if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) {
5424     switch (*HsaAbiVer) {
5425     case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
5426     case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
5427       return lowerTrapHsaQueuePtr(Op, DAG);
5428     case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
5429     case ELF::ELFABIVERSION_AMDGPU_HSA_V5:
5430       return Subtarget->supportsGetDoorbellID() ?
5431           lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG);
5432     }
5433   }
5434 
5435   llvm_unreachable("Unknown trap handler");
5436 }
5437 
5438 SDValue SITargetLowering::lowerTrapEndpgm(
5439     SDValue Op, SelectionDAG &DAG) const {
5440   SDLoc SL(Op);
5441   SDValue Chain = Op.getOperand(0);
5442   return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5443 }
5444 
5445 SDValue SITargetLowering::loadImplicitKernelArgument(SelectionDAG &DAG, MVT VT,
5446     const SDLoc &DL, Align Alignment, ImplicitParameter Param) const {
5447   MachineFunction &MF = DAG.getMachineFunction();
5448   uint64_t Offset = getImplicitParameterOffset(MF, Param);
5449   SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), Offset);
5450   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5451   return DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, PtrInfo, Alignment,
5452                      MachineMemOperand::MODereferenceable |
5453                          MachineMemOperand::MOInvariant);
5454 }
5455 
5456 SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5457     SDValue Op, SelectionDAG &DAG) const {
5458   SDLoc SL(Op);
5459   SDValue Chain = Op.getOperand(0);
5460 
5461   SDValue QueuePtr;
5462   // For code object version 5, QueuePtr is passed through implicit kernarg.
5463   if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) {
5464     QueuePtr =
5465         loadImplicitKernelArgument(DAG, MVT::i64, SL, Align(8), QUEUE_PTR);
5466   } else {
5467     MachineFunction &MF = DAG.getMachineFunction();
5468     SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5469     Register UserSGPR = Info->getQueuePtrUserSGPR();
5470 
5471     if (UserSGPR == AMDGPU::NoRegister) {
5472       // We probably are in a function incorrectly marked with
5473       // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the
5474       // trap, so just use a null pointer.
5475       QueuePtr = DAG.getConstant(0, SL, MVT::i64);
5476     } else {
5477       QueuePtr = CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, UserSGPR,
5478                                       MVT::i64);
5479     }
5480   }
5481 
5482   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5483   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5484                                    QueuePtr, SDValue());
5485 
5486   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5487   SDValue Ops[] = {
5488     ToReg,
5489     DAG.getTargetConstant(TrapID, SL, MVT::i16),
5490     SGPR01,
5491     ToReg.getValue(1)
5492   };
5493   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5494 }
5495 
5496 SDValue SITargetLowering::lowerTrapHsa(
5497     SDValue Op, SelectionDAG &DAG) const {
5498   SDLoc SL(Op);
5499   SDValue Chain = Op.getOperand(0);
5500 
5501   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5502   SDValue Ops[] = {
5503     Chain,
5504     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5505   };
5506   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5507 }
5508 
5509 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5510   SDLoc SL(Op);
5511   SDValue Chain = Op.getOperand(0);
5512   MachineFunction &MF = DAG.getMachineFunction();
5513 
5514   if (!Subtarget->isTrapHandlerEnabled() ||
5515       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5516     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5517                                      "debugtrap handler not supported",
5518                                      Op.getDebugLoc(),
5519                                      DS_Warning);
5520     LLVMContext &Ctx = MF.getFunction().getContext();
5521     Ctx.diagnose(NoTrap);
5522     return Chain;
5523   }
5524 
5525   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5526   SDValue Ops[] = {
5527     Chain,
5528     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5529   };
5530   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5531 }
5532 
5533 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5534                                              SelectionDAG &DAG) const {
5535   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5536   if (Subtarget->hasApertureRegs()) {
5537     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5538         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5539         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5540     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5541         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5542         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5543     unsigned Encoding =
5544         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5545         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5546         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5547 
5548     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5549     SDValue ApertureReg = SDValue(
5550         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5551     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5552     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5553   }
5554 
5555   // For code object version 5, private_base and shared_base are passed through
5556   // implicit kernargs.
5557   if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) {
5558     ImplicitParameter Param =
5559         (AS == AMDGPUAS::LOCAL_ADDRESS) ? SHARED_BASE : PRIVATE_BASE;
5560     return loadImplicitKernelArgument(DAG, MVT::i32, DL, Align(4), Param);
5561   }
5562 
5563   MachineFunction &MF = DAG.getMachineFunction();
5564   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5565   Register UserSGPR = Info->getQueuePtrUserSGPR();
5566   if (UserSGPR == AMDGPU::NoRegister) {
5567     // We probably are in a function incorrectly marked with
5568     // amdgpu-no-queue-ptr. This is undefined.
5569     return DAG.getUNDEF(MVT::i32);
5570   }
5571 
5572   SDValue QueuePtr = CreateLiveInRegister(
5573     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5574 
5575   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5576   // private_segment_aperture_base_hi.
5577   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5578 
5579   SDValue Ptr =
5580       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5581 
5582   // TODO: Use custom target PseudoSourceValue.
5583   // TODO: We should use the value from the IR intrinsic call, but it might not
5584   // be available and how do we get it?
5585   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5586   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5587                      commonAlignment(Align(64), StructOffset),
5588                      MachineMemOperand::MODereferenceable |
5589                          MachineMemOperand::MOInvariant);
5590 }
5591 
5592 /// Return true if the value is a known valid address, such that a null check is
5593 /// not necessary.
5594 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG,
5595                            const AMDGPUTargetMachine &TM, unsigned AddrSpace) {
5596   if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) ||
5597       isa<BasicBlockSDNode>(Val))
5598     return true;
5599 
5600   if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val))
5601     return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace);
5602 
5603   // TODO: Search through arithmetic, handle arguments and loads
5604   // marked nonnull.
5605   return false;
5606 }
5607 
5608 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5609                                              SelectionDAG &DAG) const {
5610   SDLoc SL(Op);
5611   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5612 
5613   SDValue Src = ASC->getOperand(0);
5614   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5615   unsigned SrcAS = ASC->getSrcAddressSpace();
5616 
5617   const AMDGPUTargetMachine &TM =
5618     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5619 
5620   // flat -> local/private
5621   if (SrcAS == AMDGPUAS::FLAT_ADDRESS) {
5622     unsigned DestAS = ASC->getDestAddressSpace();
5623 
5624     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5625         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5626       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5627 
5628       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5629         return Ptr;
5630 
5631       unsigned NullVal = TM.getNullPointerValue(DestAS);
5632       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5633       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5634 
5635       return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr,
5636                          SegmentNullPtr);
5637     }
5638   }
5639 
5640   // local/private -> flat
5641   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5642     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5643         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5644 
5645       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5646       SDValue CvtPtr =
5647           DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5648       CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr);
5649 
5650       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5651         return CvtPtr;
5652 
5653       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5654       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5655 
5656       SDValue NonNull
5657         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5658 
5659       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr,
5660                          FlatNullPtr);
5661     }
5662   }
5663 
5664   if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5665       Op.getValueType() == MVT::i64) {
5666     const SIMachineFunctionInfo *Info =
5667         DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>();
5668     SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32);
5669     SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi);
5670     return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
5671   }
5672 
5673   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5674       Src.getValueType() == MVT::i64)
5675     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5676 
5677   // global <-> flat are no-ops and never emitted.
5678 
5679   const MachineFunction &MF = DAG.getMachineFunction();
5680   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5681     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5682   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5683 
5684   return DAG.getUNDEF(ASC->getValueType(0));
5685 }
5686 
5687 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5688 // the small vector and inserting them into the big vector. That is better than
5689 // the default expansion of doing it via a stack slot. Even though the use of
5690 // the stack slot would be optimized away afterwards, the stack slot itself
5691 // remains.
5692 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5693                                                 SelectionDAG &DAG) const {
5694   SDValue Vec = Op.getOperand(0);
5695   SDValue Ins = Op.getOperand(1);
5696   SDValue Idx = Op.getOperand(2);
5697   EVT VecVT = Vec.getValueType();
5698   EVT InsVT = Ins.getValueType();
5699   EVT EltVT = VecVT.getVectorElementType();
5700   unsigned InsNumElts = InsVT.getVectorNumElements();
5701   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5702   SDLoc SL(Op);
5703 
5704   for (unsigned I = 0; I != InsNumElts; ++I) {
5705     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5706                               DAG.getConstant(I, SL, MVT::i32));
5707     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5708                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5709   }
5710   return Vec;
5711 }
5712 
5713 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5714                                                  SelectionDAG &DAG) const {
5715   SDValue Vec = Op.getOperand(0);
5716   SDValue InsVal = Op.getOperand(1);
5717   SDValue Idx = Op.getOperand(2);
5718   EVT VecVT = Vec.getValueType();
5719   EVT EltVT = VecVT.getVectorElementType();
5720   unsigned VecSize = VecVT.getSizeInBits();
5721   unsigned EltSize = EltVT.getSizeInBits();
5722 
5723 
5724   assert(VecSize <= 64);
5725 
5726   unsigned NumElts = VecVT.getVectorNumElements();
5727   SDLoc SL(Op);
5728   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5729 
5730   if (NumElts == 4 && EltSize == 16 && KIdx) {
5731     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5732 
5733     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5734                                  DAG.getConstant(0, SL, MVT::i32));
5735     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5736                                  DAG.getConstant(1, SL, MVT::i32));
5737 
5738     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5739     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5740 
5741     unsigned Idx = KIdx->getZExtValue();
5742     bool InsertLo = Idx < 2;
5743     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5744       InsertLo ? LoVec : HiVec,
5745       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5746       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5747 
5748     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5749 
5750     SDValue Concat = InsertLo ?
5751       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5752       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5753 
5754     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5755   }
5756 
5757   if (isa<ConstantSDNode>(Idx))
5758     return SDValue();
5759 
5760   MVT IntVT = MVT::getIntegerVT(VecSize);
5761 
5762   // Avoid stack access for dynamic indexing.
5763   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5764 
5765   // Create a congruent vector with the target value in each element so that
5766   // the required element can be masked and ORed into the target vector.
5767   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5768                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5769 
5770   assert(isPowerOf2_32(EltSize));
5771   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5772 
5773   // Convert vector index to bit-index.
5774   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5775 
5776   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5777   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5778                             DAG.getConstant(0xffff, SL, IntVT),
5779                             ScaledIdx);
5780 
5781   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5782   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5783                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5784 
5785   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5786   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5787 }
5788 
5789 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5790                                                   SelectionDAG &DAG) const {
5791   SDLoc SL(Op);
5792 
5793   EVT ResultVT = Op.getValueType();
5794   SDValue Vec = Op.getOperand(0);
5795   SDValue Idx = Op.getOperand(1);
5796   EVT VecVT = Vec.getValueType();
5797   unsigned VecSize = VecVT.getSizeInBits();
5798   EVT EltVT = VecVT.getVectorElementType();
5799 
5800   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5801 
5802   // Make sure we do any optimizations that will make it easier to fold
5803   // source modifiers before obscuring it with bit operations.
5804 
5805   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5806   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5807     return Combined;
5808 
5809   if (VecSize == 128) {
5810     SDValue Lo, Hi;
5811     EVT LoVT, HiVT;
5812     SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec);
5813     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5814     Lo =
5815         DAG.getBitcast(LoVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5816                                          V2, DAG.getConstant(0, SL, MVT::i32)));
5817     Hi =
5818         DAG.getBitcast(HiVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5819                                          V2, DAG.getConstant(1, SL, MVT::i32)));
5820     EVT IdxVT = Idx.getValueType();
5821     unsigned NElem = VecVT.getVectorNumElements();
5822     assert(isPowerOf2_32(NElem));
5823     SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT);
5824     SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask);
5825     SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT);
5826     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx);
5827   }
5828 
5829   assert(VecSize <= 64);
5830 
5831   unsigned EltSize = EltVT.getSizeInBits();
5832   assert(isPowerOf2_32(EltSize));
5833 
5834   MVT IntVT = MVT::getIntegerVT(VecSize);
5835   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5836 
5837   // Convert vector index to bit-index (* EltSize)
5838   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5839 
5840   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5841   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5842 
5843   if (ResultVT == MVT::f16) {
5844     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5845     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5846   }
5847 
5848   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5849 }
5850 
5851 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5852   assert(Elt % 2 == 0);
5853   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5854 }
5855 
5856 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5857                                               SelectionDAG &DAG) const {
5858   SDLoc SL(Op);
5859   EVT ResultVT = Op.getValueType();
5860   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5861 
5862   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5863   EVT EltVT = PackVT.getVectorElementType();
5864   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5865 
5866   // vector_shuffle <0,1,6,7> lhs, rhs
5867   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5868   //
5869   // vector_shuffle <6,7,2,3> lhs, rhs
5870   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5871   //
5872   // vector_shuffle <6,7,0,1> lhs, rhs
5873   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5874 
5875   // Avoid scalarizing when both halves are reading from consecutive elements.
5876   SmallVector<SDValue, 4> Pieces;
5877   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5878     if (elementPairIsContiguous(SVN->getMask(), I)) {
5879       const int Idx = SVN->getMaskElt(I);
5880       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5881       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5882       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5883                                     PackVT, SVN->getOperand(VecIdx),
5884                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5885       Pieces.push_back(SubVec);
5886     } else {
5887       const int Idx0 = SVN->getMaskElt(I);
5888       const int Idx1 = SVN->getMaskElt(I + 1);
5889       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5890       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5891       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5892       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5893 
5894       SDValue Vec0 = SVN->getOperand(VecIdx0);
5895       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5896                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5897 
5898       SDValue Vec1 = SVN->getOperand(VecIdx1);
5899       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5900                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5901       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5902     }
5903   }
5904 
5905   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5906 }
5907 
5908 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5909                                             SelectionDAG &DAG) const {
5910   SDLoc SL(Op);
5911   EVT VT = Op.getValueType();
5912 
5913   if (VT == MVT::v4i16 || VT == MVT::v4f16 ||
5914       VT == MVT::v8i16 || VT == MVT::v8f16) {
5915     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(),
5916                                   VT.getVectorNumElements() / 2);
5917     MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits());
5918 
5919     // Turn into pair of packed build_vectors.
5920     // TODO: Special case for constants that can be materialized with s_mov_b64.
5921     SmallVector<SDValue, 4> LoOps, HiOps;
5922     for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) {
5923       LoOps.push_back(Op.getOperand(I));
5924       HiOps.push_back(Op.getOperand(I + E));
5925     }
5926     SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps);
5927     SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps);
5928 
5929     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo);
5930     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi);
5931 
5932     SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL,
5933                                        { CastLo, CastHi });
5934     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5935   }
5936 
5937   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5938   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5939 
5940   SDValue Lo = Op.getOperand(0);
5941   SDValue Hi = Op.getOperand(1);
5942 
5943   // Avoid adding defined bits with the zero_extend.
5944   if (Hi.isUndef()) {
5945     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5946     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5947     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5948   }
5949 
5950   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5951   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5952 
5953   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5954                               DAG.getConstant(16, SL, MVT::i32));
5955   if (Lo.isUndef())
5956     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5957 
5958   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5959   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5960 
5961   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5962   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5963 }
5964 
5965 bool
5966 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5967   // We can fold offsets for anything that doesn't require a GOT relocation.
5968   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5969           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5970           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5971          !shouldEmitGOTReloc(GA->getGlobal());
5972 }
5973 
5974 static SDValue
5975 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5976                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5977                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5978   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5979   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5980   // lowered to the following code sequence:
5981   //
5982   // For constant address space:
5983   //   s_getpc_b64 s[0:1]
5984   //   s_add_u32 s0, s0, $symbol
5985   //   s_addc_u32 s1, s1, 0
5986   //
5987   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5988   //   a fixup or relocation is emitted to replace $symbol with a literal
5989   //   constant, which is a pc-relative offset from the encoding of the $symbol
5990   //   operand to the global variable.
5991   //
5992   // For global address space:
5993   //   s_getpc_b64 s[0:1]
5994   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5995   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5996   //
5997   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5998   //   fixups or relocations are emitted to replace $symbol@*@lo and
5999   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
6000   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
6001   //   operand to the global variable.
6002   //
6003   // What we want here is an offset from the value returned by s_getpc
6004   // (which is the address of the s_add_u32 instruction) to the global
6005   // variable, but since the encoding of $symbol starts 4 bytes after the start
6006   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
6007   // small. This requires us to add 4 to the global variable offset in order to
6008   // compute the correct address. Similarly for the s_addc_u32 instruction, the
6009   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
6010   // instruction.
6011   SDValue PtrLo =
6012       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
6013   SDValue PtrHi;
6014   if (GAFlags == SIInstrInfo::MO_NONE) {
6015     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
6016   } else {
6017     PtrHi =
6018         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
6019   }
6020   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
6021 }
6022 
6023 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
6024                                              SDValue Op,
6025                                              SelectionDAG &DAG) const {
6026   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
6027   SDLoc DL(GSD);
6028   EVT PtrVT = Op.getValueType();
6029 
6030   const GlobalValue *GV = GSD->getGlobal();
6031   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
6032        shouldUseLDSConstAddress(GV)) ||
6033       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
6034       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
6035     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
6036         GV->hasExternalLinkage()) {
6037       Type *Ty = GV->getValueType();
6038       // HIP uses an unsized array `extern __shared__ T s[]` or similar
6039       // zero-sized type in other languages to declare the dynamic shared
6040       // memory which size is not known at the compile time. They will be
6041       // allocated by the runtime and placed directly after the static
6042       // allocated ones. They all share the same offset.
6043       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
6044         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
6045         // Adjust alignment for that dynamic shared memory array.
6046         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
6047         return SDValue(
6048             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
6049       }
6050     }
6051     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
6052   }
6053 
6054   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
6055     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
6056                                             SIInstrInfo::MO_ABS32_LO);
6057     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
6058   }
6059 
6060   if (shouldEmitFixup(GV))
6061     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
6062   else if (shouldEmitPCReloc(GV))
6063     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
6064                                    SIInstrInfo::MO_REL32);
6065 
6066   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
6067                                             SIInstrInfo::MO_GOTPCREL32);
6068 
6069   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
6070   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
6071   const DataLayout &DataLayout = DAG.getDataLayout();
6072   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
6073   MachinePointerInfo PtrInfo
6074     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
6075 
6076   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
6077                      MachineMemOperand::MODereferenceable |
6078                          MachineMemOperand::MOInvariant);
6079 }
6080 
6081 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
6082                                    const SDLoc &DL, SDValue V) const {
6083   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
6084   // the destination register.
6085   //
6086   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
6087   // so we will end up with redundant moves to m0.
6088   //
6089   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
6090 
6091   // A Null SDValue creates a glue result.
6092   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
6093                                   V, Chain);
6094   return SDValue(M0, 0);
6095 }
6096 
6097 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
6098                                                  SDValue Op,
6099                                                  MVT VT,
6100                                                  unsigned Offset) const {
6101   SDLoc SL(Op);
6102   SDValue Param = lowerKernargMemParameter(
6103       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
6104   // The local size values will have the hi 16-bits as zero.
6105   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
6106                      DAG.getValueType(VT));
6107 }
6108 
6109 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6110                                         EVT VT) {
6111   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6112                                       "non-hsa intrinsic with hsa target",
6113                                       DL.getDebugLoc());
6114   DAG.getContext()->diagnose(BadIntrin);
6115   return DAG.getUNDEF(VT);
6116 }
6117 
6118 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6119                                          EVT VT) {
6120   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6121                                       "intrinsic not supported on subtarget",
6122                                       DL.getDebugLoc());
6123   DAG.getContext()->diagnose(BadIntrin);
6124   return DAG.getUNDEF(VT);
6125 }
6126 
6127 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
6128                                     ArrayRef<SDValue> Elts) {
6129   assert(!Elts.empty());
6130   MVT Type;
6131   unsigned NumElts = Elts.size();
6132 
6133   if (NumElts <= 8) {
6134     Type = MVT::getVectorVT(MVT::f32, NumElts);
6135   } else {
6136     assert(Elts.size() <= 16);
6137     Type = MVT::v16f32;
6138     NumElts = 16;
6139   }
6140 
6141   SmallVector<SDValue, 16> VecElts(NumElts);
6142   for (unsigned i = 0; i < Elts.size(); ++i) {
6143     SDValue Elt = Elts[i];
6144     if (Elt.getValueType() != MVT::f32)
6145       Elt = DAG.getBitcast(MVT::f32, Elt);
6146     VecElts[i] = Elt;
6147   }
6148   for (unsigned i = Elts.size(); i < NumElts; ++i)
6149     VecElts[i] = DAG.getUNDEF(MVT::f32);
6150 
6151   if (NumElts == 1)
6152     return VecElts[0];
6153   return DAG.getBuildVector(Type, DL, VecElts);
6154 }
6155 
6156 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
6157                               SDValue Src, int ExtraElts) {
6158   EVT SrcVT = Src.getValueType();
6159 
6160   SmallVector<SDValue, 8> Elts;
6161 
6162   if (SrcVT.isVector())
6163     DAG.ExtractVectorElements(Src, Elts);
6164   else
6165     Elts.push_back(Src);
6166 
6167   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
6168   while (ExtraElts--)
6169     Elts.push_back(Undef);
6170 
6171   return DAG.getBuildVector(CastVT, DL, Elts);
6172 }
6173 
6174 // Re-construct the required return value for a image load intrinsic.
6175 // This is more complicated due to the optional use TexFailCtrl which means the required
6176 // return type is an aggregate
6177 static SDValue constructRetValue(SelectionDAG &DAG,
6178                                  MachineSDNode *Result,
6179                                  ArrayRef<EVT> ResultTypes,
6180                                  bool IsTexFail, bool Unpacked, bool IsD16,
6181                                  int DMaskPop, int NumVDataDwords,
6182                                  const SDLoc &DL) {
6183   // Determine the required return type. This is the same regardless of IsTexFail flag
6184   EVT ReqRetVT = ResultTypes[0];
6185   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
6186   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6187     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
6188 
6189   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6190     DMaskPop : (DMaskPop + 1) / 2;
6191 
6192   MVT DataDwordVT = NumDataDwords == 1 ?
6193     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
6194 
6195   MVT MaskPopVT = MaskPopDwords == 1 ?
6196     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
6197 
6198   SDValue Data(Result, 0);
6199   SDValue TexFail;
6200 
6201   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
6202     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
6203     if (MaskPopVT.isVector()) {
6204       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
6205                          SDValue(Result, 0), ZeroIdx);
6206     } else {
6207       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
6208                          SDValue(Result, 0), ZeroIdx);
6209     }
6210   }
6211 
6212   if (DataDwordVT.isVector())
6213     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
6214                           NumDataDwords - MaskPopDwords);
6215 
6216   if (IsD16)
6217     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
6218 
6219   EVT LegalReqRetVT = ReqRetVT;
6220   if (!ReqRetVT.isVector()) {
6221     if (!Data.getValueType().isInteger())
6222       Data = DAG.getNode(ISD::BITCAST, DL,
6223                          Data.getValueType().changeTypeToInteger(), Data);
6224     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
6225   } else {
6226     // We need to widen the return vector to a legal type
6227     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
6228         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
6229       LegalReqRetVT =
6230           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
6231                            ReqRetVT.getVectorNumElements() + 1);
6232     }
6233   }
6234   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
6235 
6236   if (IsTexFail) {
6237     TexFail =
6238         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
6239                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
6240 
6241     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
6242   }
6243 
6244   if (Result->getNumValues() == 1)
6245     return Data;
6246 
6247   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
6248 }
6249 
6250 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
6251                          SDValue *LWE, bool &IsTexFail) {
6252   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
6253 
6254   uint64_t Value = TexFailCtrlConst->getZExtValue();
6255   if (Value) {
6256     IsTexFail = true;
6257   }
6258 
6259   SDLoc DL(TexFailCtrlConst);
6260   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
6261   Value &= ~(uint64_t)0x1;
6262   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
6263   Value &= ~(uint64_t)0x2;
6264 
6265   return Value == 0;
6266 }
6267 
6268 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
6269                                       MVT PackVectorVT,
6270                                       SmallVectorImpl<SDValue> &PackedAddrs,
6271                                       unsigned DimIdx, unsigned EndIdx,
6272                                       unsigned NumGradients) {
6273   SDLoc DL(Op);
6274   for (unsigned I = DimIdx; I < EndIdx; I++) {
6275     SDValue Addr = Op.getOperand(I);
6276 
6277     // Gradients are packed with undef for each coordinate.
6278     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
6279     // 1D: undef,dx/dh; undef,dx/dv
6280     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
6281     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
6282     if (((I + 1) >= EndIdx) ||
6283         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
6284                                          I == DimIdx + NumGradients - 1))) {
6285       if (Addr.getValueType() != MVT::i16)
6286         Addr = DAG.getBitcast(MVT::i16, Addr);
6287       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
6288     } else {
6289       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
6290       I++;
6291     }
6292     Addr = DAG.getBitcast(MVT::f32, Addr);
6293     PackedAddrs.push_back(Addr);
6294   }
6295 }
6296 
6297 SDValue SITargetLowering::lowerImage(SDValue Op,
6298                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
6299                                      SelectionDAG &DAG, bool WithChain) const {
6300   SDLoc DL(Op);
6301   MachineFunction &MF = DAG.getMachineFunction();
6302   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
6303   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
6304       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
6305   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
6306   unsigned IntrOpcode = Intr->BaseOpcode;
6307   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6308 
6309   SmallVector<EVT, 3> ResultTypes(Op->values());
6310   SmallVector<EVT, 3> OrigResultTypes(Op->values());
6311   bool IsD16 = false;
6312   bool IsG16 = false;
6313   bool IsA16 = false;
6314   SDValue VData;
6315   int NumVDataDwords;
6316   bool AdjustRetType = false;
6317 
6318   // Offset of intrinsic arguments
6319   const unsigned ArgOffset = WithChain ? 2 : 1;
6320 
6321   unsigned DMask;
6322   unsigned DMaskLanes = 0;
6323 
6324   if (BaseOpcode->Atomic) {
6325     VData = Op.getOperand(2);
6326 
6327     bool Is64Bit = VData.getValueType() == MVT::i64;
6328     if (BaseOpcode->AtomicX2) {
6329       SDValue VData2 = Op.getOperand(3);
6330       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6331                                  {VData, VData2});
6332       if (Is64Bit)
6333         VData = DAG.getBitcast(MVT::v4i32, VData);
6334 
6335       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6336       DMask = Is64Bit ? 0xf : 0x3;
6337       NumVDataDwords = Is64Bit ? 4 : 2;
6338     } else {
6339       DMask = Is64Bit ? 0x3 : 0x1;
6340       NumVDataDwords = Is64Bit ? 2 : 1;
6341     }
6342   } else {
6343     auto *DMaskConst =
6344         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6345     DMask = DMaskConst->getZExtValue();
6346     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6347 
6348     if (BaseOpcode->Store) {
6349       VData = Op.getOperand(2);
6350 
6351       MVT StoreVT = VData.getSimpleValueType();
6352       if (StoreVT.getScalarType() == MVT::f16) {
6353         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6354           return Op; // D16 is unsupported for this instruction
6355 
6356         IsD16 = true;
6357         VData = handleD16VData(VData, DAG, true);
6358       }
6359 
6360       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6361     } else {
6362       // Work out the num dwords based on the dmask popcount and underlying type
6363       // and whether packing is supported.
6364       MVT LoadVT = ResultTypes[0].getSimpleVT();
6365       if (LoadVT.getScalarType() == MVT::f16) {
6366         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6367           return Op; // D16 is unsupported for this instruction
6368 
6369         IsD16 = true;
6370       }
6371 
6372       // Confirm that the return type is large enough for the dmask specified
6373       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6374           (!LoadVT.isVector() && DMaskLanes > 1))
6375           return Op;
6376 
6377       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6378       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6379       // instructions.
6380       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6381           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6382         NumVDataDwords = (DMaskLanes + 1) / 2;
6383       else
6384         NumVDataDwords = DMaskLanes;
6385 
6386       AdjustRetType = true;
6387     }
6388   }
6389 
6390   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6391   SmallVector<SDValue, 4> VAddrs;
6392 
6393   // Check for 16 bit addresses or derivatives and pack if true.
6394   MVT VAddrVT =
6395       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6396   MVT VAddrScalarVT = VAddrVT.getScalarType();
6397   MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6398   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6399 
6400   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6401   VAddrScalarVT = VAddrVT.getScalarType();
6402   MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6403   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6404 
6405   // Push back extra arguments.
6406   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) {
6407     if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) {
6408       assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument");
6409       // Special handling of bias when A16 is on. Bias is of type half but
6410       // occupies full 32-bit.
6411       SDValue Bias = DAG.getBuildVector(
6412           MVT::v2f16, DL,
6413           {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)});
6414       VAddrs.push_back(Bias);
6415     } else {
6416       assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) &&
6417              "Bias needs to be converted to 16 bit in A16 mode");
6418       VAddrs.push_back(Op.getOperand(ArgOffset + I));
6419     }
6420   }
6421 
6422   if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
6423     // 16 bit gradients are supported, but are tied to the A16 control
6424     // so both gradients and addresses must be 16 bit
6425     LLVM_DEBUG(
6426         dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6427                   "require 16 bit args for both gradients and addresses");
6428     return Op;
6429   }
6430 
6431   if (IsA16) {
6432     if (!ST->hasA16()) {
6433       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6434                            "support 16 bit addresses\n");
6435       return Op;
6436     }
6437   }
6438 
6439   // We've dealt with incorrect input so we know that if IsA16, IsG16
6440   // are set then we have to compress/pack operands (either address,
6441   // gradient or both)
6442   // In the case where a16 and gradients are tied (no G16 support) then we
6443   // have already verified that both IsA16 and IsG16 are true
6444   if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
6445     // Activate g16
6446     const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6447         AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6448     IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6449   }
6450 
6451   // Add gradients (packed or unpacked)
6452   if (IsG16) {
6453     // Pack the gradients
6454     // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6455     packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
6456                               ArgOffset + Intr->GradientStart,
6457                               ArgOffset + Intr->CoordStart, Intr->NumGradients);
6458   } else {
6459     for (unsigned I = ArgOffset + Intr->GradientStart;
6460          I < ArgOffset + Intr->CoordStart; I++)
6461       VAddrs.push_back(Op.getOperand(I));
6462   }
6463 
6464   // Add addresses (packed or unpacked)
6465   if (IsA16) {
6466     packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
6467                               ArgOffset + Intr->CoordStart, VAddrEnd,
6468                               0 /* No gradients */);
6469   } else {
6470     // Add uncompressed address
6471     for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6472       VAddrs.push_back(Op.getOperand(I));
6473   }
6474 
6475   // If the register allocator cannot place the address registers contiguously
6476   // without introducing moves, then using the non-sequential address encoding
6477   // is always preferable, since it saves VALU instructions and is usually a
6478   // wash in terms of code size or even better.
6479   //
6480   // However, we currently have no way of hinting to the register allocator that
6481   // MIMG addresses should be placed contiguously when it is possible to do so,
6482   // so force non-NSA for the common 2-address case as a heuristic.
6483   //
6484   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6485   // allocation when possible.
6486   bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) &&
6487                 VAddrs.size() >= 3 &&
6488                 VAddrs.size() <= (unsigned)ST->getNSAMaxSize();
6489   SDValue VAddr;
6490   if (!UseNSA)
6491     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6492 
6493   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6494   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6495   SDValue Unorm;
6496   if (!BaseOpcode->Sampler) {
6497     Unorm = True;
6498   } else {
6499     auto UnormConst =
6500         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6501 
6502     Unorm = UnormConst->getZExtValue() ? True : False;
6503   }
6504 
6505   SDValue TFE;
6506   SDValue LWE;
6507   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6508   bool IsTexFail = false;
6509   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6510     return Op;
6511 
6512   if (IsTexFail) {
6513     if (!DMaskLanes) {
6514       // Expecting to get an error flag since TFC is on - and dmask is 0
6515       // Force dmask to be at least 1 otherwise the instruction will fail
6516       DMask = 0x1;
6517       DMaskLanes = 1;
6518       NumVDataDwords = 1;
6519     }
6520     NumVDataDwords += 1;
6521     AdjustRetType = true;
6522   }
6523 
6524   // Has something earlier tagged that the return type needs adjusting
6525   // This happens if the instruction is a load or has set TexFailCtrl flags
6526   if (AdjustRetType) {
6527     // NumVDataDwords reflects the true number of dwords required in the return type
6528     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6529       // This is a no-op load. This can be eliminated
6530       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6531       if (isa<MemSDNode>(Op))
6532         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6533       return Undef;
6534     }
6535 
6536     EVT NewVT = NumVDataDwords > 1 ?
6537                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6538                 : MVT::i32;
6539 
6540     ResultTypes[0] = NewVT;
6541     if (ResultTypes.size() == 3) {
6542       // Original result was aggregate type used for TexFailCtrl results
6543       // The actual instruction returns as a vector type which has now been
6544       // created. Remove the aggregate result.
6545       ResultTypes.erase(&ResultTypes[1]);
6546     }
6547   }
6548 
6549   unsigned CPol = cast<ConstantSDNode>(
6550       Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6551   if (BaseOpcode->Atomic)
6552     CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6553   if (CPol & ~AMDGPU::CPol::ALL)
6554     return Op;
6555 
6556   SmallVector<SDValue, 26> Ops;
6557   if (BaseOpcode->Store || BaseOpcode->Atomic)
6558     Ops.push_back(VData); // vdata
6559   if (UseNSA)
6560     append_range(Ops, VAddrs);
6561   else
6562     Ops.push_back(VAddr);
6563   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6564   if (BaseOpcode->Sampler)
6565     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6566   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6567   if (IsGFX10Plus)
6568     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6569   Ops.push_back(Unorm);
6570   Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6571   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6572                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6573   if (IsGFX10Plus)
6574     Ops.push_back(IsA16 ? True : False);
6575   if (!Subtarget->hasGFX90AInsts()) {
6576     Ops.push_back(TFE); //tfe
6577   } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6578     report_fatal_error("TFE is not supported on this GPU");
6579   }
6580   Ops.push_back(LWE); // lwe
6581   if (!IsGFX10Plus)
6582     Ops.push_back(DimInfo->DA ? True : False);
6583   if (BaseOpcode->HasD16)
6584     Ops.push_back(IsD16 ? True : False);
6585   if (isa<MemSDNode>(Op))
6586     Ops.push_back(Op.getOperand(0)); // chain
6587 
6588   int NumVAddrDwords =
6589       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6590   int Opcode = -1;
6591 
6592   if (IsGFX10Plus) {
6593     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6594                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6595                                           : AMDGPU::MIMGEncGfx10Default,
6596                                    NumVDataDwords, NumVAddrDwords);
6597   } else {
6598     if (Subtarget->hasGFX90AInsts()) {
6599       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6600                                      NumVDataDwords, NumVAddrDwords);
6601       if (Opcode == -1)
6602         report_fatal_error(
6603             "requested image instruction is not supported on this GPU");
6604     }
6605     if (Opcode == -1 &&
6606         Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6607       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6608                                      NumVDataDwords, NumVAddrDwords);
6609     if (Opcode == -1)
6610       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6611                                      NumVDataDwords, NumVAddrDwords);
6612   }
6613   assert(Opcode != -1);
6614 
6615   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6616   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6617     MachineMemOperand *MemRef = MemOp->getMemOperand();
6618     DAG.setNodeMemRefs(NewNode, {MemRef});
6619   }
6620 
6621   if (BaseOpcode->AtomicX2) {
6622     SmallVector<SDValue, 1> Elt;
6623     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6624     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6625   }
6626   if (BaseOpcode->Store)
6627     return SDValue(NewNode, 0);
6628   return constructRetValue(DAG, NewNode,
6629                            OrigResultTypes, IsTexFail,
6630                            Subtarget->hasUnpackedD16VMem(), IsD16,
6631                            DMaskLanes, NumVDataDwords, DL);
6632 }
6633 
6634 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6635                                        SDValue Offset, SDValue CachePolicy,
6636                                        SelectionDAG &DAG) const {
6637   MachineFunction &MF = DAG.getMachineFunction();
6638 
6639   const DataLayout &DataLayout = DAG.getDataLayout();
6640   Align Alignment =
6641       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6642 
6643   MachineMemOperand *MMO = MF.getMachineMemOperand(
6644       MachinePointerInfo(),
6645       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6646           MachineMemOperand::MOInvariant,
6647       VT.getStoreSize(), Alignment);
6648 
6649   if (!Offset->isDivergent()) {
6650     SDValue Ops[] = {
6651         Rsrc,
6652         Offset, // Offset
6653         CachePolicy
6654     };
6655 
6656     // Widen vec3 load to vec4.
6657     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6658       EVT WidenedVT =
6659           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6660       auto WidenedOp = DAG.getMemIntrinsicNode(
6661           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6662           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6663       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6664                                    DAG.getVectorIdxConstant(0, DL));
6665       return Subvector;
6666     }
6667 
6668     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6669                                    DAG.getVTList(VT), Ops, VT, MMO);
6670   }
6671 
6672   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6673   // assume that the buffer is unswizzled.
6674   SmallVector<SDValue, 4> Loads;
6675   unsigned NumLoads = 1;
6676   MVT LoadVT = VT.getSimpleVT();
6677   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6678   assert((LoadVT.getScalarType() == MVT::i32 ||
6679           LoadVT.getScalarType() == MVT::f32));
6680 
6681   if (NumElts == 8 || NumElts == 16) {
6682     NumLoads = NumElts / 4;
6683     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6684   }
6685 
6686   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6687   SDValue Ops[] = {
6688       DAG.getEntryNode(),                               // Chain
6689       Rsrc,                                             // rsrc
6690       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6691       {},                                               // voffset
6692       {},                                               // soffset
6693       {},                                               // offset
6694       CachePolicy,                                      // cachepolicy
6695       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6696   };
6697 
6698   // Use the alignment to ensure that the required offsets will fit into the
6699   // immediate offsets.
6700   setBufferOffsets(Offset, DAG, &Ops[3],
6701                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6702 
6703   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6704   for (unsigned i = 0; i < NumLoads; ++i) {
6705     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6706     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6707                                         LoadVT, MMO, DAG));
6708   }
6709 
6710   if (NumElts == 8 || NumElts == 16)
6711     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6712 
6713   return Loads[0];
6714 }
6715 
6716 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6717                                                   SelectionDAG &DAG) const {
6718   MachineFunction &MF = DAG.getMachineFunction();
6719   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6720 
6721   EVT VT = Op.getValueType();
6722   SDLoc DL(Op);
6723   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6724 
6725   // TODO: Should this propagate fast-math-flags?
6726 
6727   switch (IntrinsicID) {
6728   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6729     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6730       return emitNonHSAIntrinsicError(DAG, DL, VT);
6731     return getPreloadedValue(DAG, *MFI, VT,
6732                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6733   }
6734   case Intrinsic::amdgcn_dispatch_ptr:
6735   case Intrinsic::amdgcn_queue_ptr: {
6736     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6737       DiagnosticInfoUnsupported BadIntrin(
6738           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6739           DL.getDebugLoc());
6740       DAG.getContext()->diagnose(BadIntrin);
6741       return DAG.getUNDEF(VT);
6742     }
6743 
6744     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6745       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6746     return getPreloadedValue(DAG, *MFI, VT, RegID);
6747   }
6748   case Intrinsic::amdgcn_implicitarg_ptr: {
6749     if (MFI->isEntryFunction())
6750       return getImplicitArgPtr(DAG, DL);
6751     return getPreloadedValue(DAG, *MFI, VT,
6752                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6753   }
6754   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6755     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6756       // This only makes sense to call in a kernel, so just lower to null.
6757       return DAG.getConstant(0, DL, VT);
6758     }
6759 
6760     return getPreloadedValue(DAG, *MFI, VT,
6761                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6762   }
6763   case Intrinsic::amdgcn_dispatch_id: {
6764     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6765   }
6766   case Intrinsic::amdgcn_rcp:
6767     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6768   case Intrinsic::amdgcn_rsq:
6769     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6770   case Intrinsic::amdgcn_rsq_legacy:
6771     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6772       return emitRemovedIntrinsicError(DAG, DL, VT);
6773     return SDValue();
6774   case Intrinsic::amdgcn_rcp_legacy:
6775     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6776       return emitRemovedIntrinsicError(DAG, DL, VT);
6777     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6778   case Intrinsic::amdgcn_rsq_clamp: {
6779     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6780       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6781 
6782     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6783     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6784     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6785 
6786     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6787     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6788                               DAG.getConstantFP(Max, DL, VT));
6789     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6790                        DAG.getConstantFP(Min, DL, VT));
6791   }
6792   case Intrinsic::r600_read_ngroups_x:
6793     if (Subtarget->isAmdHsaOS())
6794       return emitNonHSAIntrinsicError(DAG, DL, VT);
6795 
6796     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6797                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6798                                     false);
6799   case Intrinsic::r600_read_ngroups_y:
6800     if (Subtarget->isAmdHsaOS())
6801       return emitNonHSAIntrinsicError(DAG, DL, VT);
6802 
6803     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6804                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6805                                     false);
6806   case Intrinsic::r600_read_ngroups_z:
6807     if (Subtarget->isAmdHsaOS())
6808       return emitNonHSAIntrinsicError(DAG, DL, VT);
6809 
6810     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6811                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6812                                     false);
6813   case Intrinsic::r600_read_global_size_x:
6814     if (Subtarget->isAmdHsaOS())
6815       return emitNonHSAIntrinsicError(DAG, DL, VT);
6816 
6817     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6818                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6819                                     Align(4), false);
6820   case Intrinsic::r600_read_global_size_y:
6821     if (Subtarget->isAmdHsaOS())
6822       return emitNonHSAIntrinsicError(DAG, DL, VT);
6823 
6824     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6825                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6826                                     Align(4), false);
6827   case Intrinsic::r600_read_global_size_z:
6828     if (Subtarget->isAmdHsaOS())
6829       return emitNonHSAIntrinsicError(DAG, DL, VT);
6830 
6831     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6832                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6833                                     Align(4), false);
6834   case Intrinsic::r600_read_local_size_x:
6835     if (Subtarget->isAmdHsaOS())
6836       return emitNonHSAIntrinsicError(DAG, DL, VT);
6837 
6838     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6839                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6840   case Intrinsic::r600_read_local_size_y:
6841     if (Subtarget->isAmdHsaOS())
6842       return emitNonHSAIntrinsicError(DAG, DL, VT);
6843 
6844     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6845                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6846   case Intrinsic::r600_read_local_size_z:
6847     if (Subtarget->isAmdHsaOS())
6848       return emitNonHSAIntrinsicError(DAG, DL, VT);
6849 
6850     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6851                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6852   case Intrinsic::amdgcn_workgroup_id_x:
6853     return getPreloadedValue(DAG, *MFI, VT,
6854                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6855   case Intrinsic::amdgcn_workgroup_id_y:
6856     return getPreloadedValue(DAG, *MFI, VT,
6857                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6858   case Intrinsic::amdgcn_workgroup_id_z:
6859     return getPreloadedValue(DAG, *MFI, VT,
6860                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6861   case Intrinsic::amdgcn_workitem_id_x:
6862     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 0) == 0)
6863       return DAG.getConstant(0, DL, MVT::i32);
6864 
6865     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6866                           SDLoc(DAG.getEntryNode()),
6867                           MFI->getArgInfo().WorkItemIDX);
6868   case Intrinsic::amdgcn_workitem_id_y:
6869     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 1) == 0)
6870       return DAG.getConstant(0, DL, MVT::i32);
6871 
6872     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6873                           SDLoc(DAG.getEntryNode()),
6874                           MFI->getArgInfo().WorkItemIDY);
6875   case Intrinsic::amdgcn_workitem_id_z:
6876     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 2) == 0)
6877       return DAG.getConstant(0, DL, MVT::i32);
6878 
6879     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6880                           SDLoc(DAG.getEntryNode()),
6881                           MFI->getArgInfo().WorkItemIDZ);
6882   case Intrinsic::amdgcn_wavefrontsize:
6883     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6884                            SDLoc(Op), MVT::i32);
6885   case Intrinsic::amdgcn_s_buffer_load: {
6886     unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6887     if (CPol & ~AMDGPU::CPol::ALL)
6888       return Op;
6889     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6890                         DAG);
6891   }
6892   case Intrinsic::amdgcn_fdiv_fast:
6893     return lowerFDIV_FAST(Op, DAG);
6894   case Intrinsic::amdgcn_sin:
6895     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6896 
6897   case Intrinsic::amdgcn_cos:
6898     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6899 
6900   case Intrinsic::amdgcn_mul_u24:
6901     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6902   case Intrinsic::amdgcn_mul_i24:
6903     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6904 
6905   case Intrinsic::amdgcn_log_clamp: {
6906     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6907       return SDValue();
6908 
6909     return emitRemovedIntrinsicError(DAG, DL, VT);
6910   }
6911   case Intrinsic::amdgcn_ldexp:
6912     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6913                        Op.getOperand(1), Op.getOperand(2));
6914 
6915   case Intrinsic::amdgcn_fract:
6916     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6917 
6918   case Intrinsic::amdgcn_class:
6919     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6920                        Op.getOperand(1), Op.getOperand(2));
6921   case Intrinsic::amdgcn_div_fmas:
6922     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6923                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6924                        Op.getOperand(4));
6925 
6926   case Intrinsic::amdgcn_div_fixup:
6927     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6928                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6929 
6930   case Intrinsic::amdgcn_div_scale: {
6931     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6932 
6933     // Translate to the operands expected by the machine instruction. The
6934     // first parameter must be the same as the first instruction.
6935     SDValue Numerator = Op.getOperand(1);
6936     SDValue Denominator = Op.getOperand(2);
6937 
6938     // Note this order is opposite of the machine instruction's operations,
6939     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6940     // intrinsic has the numerator as the first operand to match a normal
6941     // division operation.
6942 
6943     SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator;
6944 
6945     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6946                        Denominator, Numerator);
6947   }
6948   case Intrinsic::amdgcn_icmp: {
6949     // There is a Pat that handles this variant, so return it as-is.
6950     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6951         Op.getConstantOperandVal(2) == 0 &&
6952         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6953       return Op;
6954     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6955   }
6956   case Intrinsic::amdgcn_fcmp: {
6957     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6958   }
6959   case Intrinsic::amdgcn_ballot:
6960     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6961   case Intrinsic::amdgcn_fmed3:
6962     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6963                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6964   case Intrinsic::amdgcn_fdot2:
6965     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6966                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6967                        Op.getOperand(4));
6968   case Intrinsic::amdgcn_fmul_legacy:
6969     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6970                        Op.getOperand(1), Op.getOperand(2));
6971   case Intrinsic::amdgcn_sffbh:
6972     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6973   case Intrinsic::amdgcn_sbfe:
6974     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6975                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6976   case Intrinsic::amdgcn_ubfe:
6977     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6978                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6979   case Intrinsic::amdgcn_cvt_pkrtz:
6980   case Intrinsic::amdgcn_cvt_pknorm_i16:
6981   case Intrinsic::amdgcn_cvt_pknorm_u16:
6982   case Intrinsic::amdgcn_cvt_pk_i16:
6983   case Intrinsic::amdgcn_cvt_pk_u16: {
6984     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6985     EVT VT = Op.getValueType();
6986     unsigned Opcode;
6987 
6988     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6989       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6990     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6991       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6992     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6993       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6994     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6995       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6996     else
6997       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6998 
6999     if (isTypeLegal(VT))
7000       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
7001 
7002     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
7003                                Op.getOperand(1), Op.getOperand(2));
7004     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
7005   }
7006   case Intrinsic::amdgcn_fmad_ftz:
7007     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
7008                        Op.getOperand(2), Op.getOperand(3));
7009 
7010   case Intrinsic::amdgcn_if_break:
7011     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
7012                                       Op->getOperand(1), Op->getOperand(2)), 0);
7013 
7014   case Intrinsic::amdgcn_groupstaticsize: {
7015     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
7016     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
7017       return Op;
7018 
7019     const Module *M = MF.getFunction().getParent();
7020     const GlobalValue *GV =
7021         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
7022     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
7023                                             SIInstrInfo::MO_ABS32_LO);
7024     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
7025   }
7026   case Intrinsic::amdgcn_is_shared:
7027   case Intrinsic::amdgcn_is_private: {
7028     SDLoc SL(Op);
7029     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
7030       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
7031     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
7032     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
7033                                  Op.getOperand(1));
7034 
7035     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
7036                                 DAG.getConstant(1, SL, MVT::i32));
7037     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
7038   }
7039   case Intrinsic::amdgcn_perm:
7040     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
7041                        Op.getOperand(2), Op.getOperand(3));
7042   case Intrinsic::amdgcn_reloc_constant: {
7043     Module *M = const_cast<Module *>(MF.getFunction().getParent());
7044     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
7045     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
7046     auto RelocSymbol = cast<GlobalVariable>(
7047         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
7048     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
7049                                             SIInstrInfo::MO_ABS32_LO);
7050     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
7051   }
7052   default:
7053     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7054             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7055       return lowerImage(Op, ImageDimIntr, DAG, false);
7056 
7057     return Op;
7058   }
7059 }
7060 
7061 /// Update \p MMO based on the offset inputs to an intrinsic.
7062 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset,
7063                             SDValue SOffset, SDValue Offset,
7064                             SDValue VIndex = SDValue()) {
7065   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
7066       !isa<ConstantSDNode>(Offset)) {
7067     // The combined offset is not known to be constant, so we cannot represent
7068     // it in the MMO. Give up.
7069     MMO->setValue((Value *)nullptr);
7070     return;
7071   }
7072 
7073   if (VIndex && (!isa<ConstantSDNode>(VIndex) ||
7074                  !cast<ConstantSDNode>(VIndex)->isZero())) {
7075     // The strided index component of the address is not known to be zero, so we
7076     // cannot represent it in the MMO. Give up.
7077     MMO->setValue((Value *)nullptr);
7078     return;
7079   }
7080 
7081   MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() +
7082                  cast<ConstantSDNode>(SOffset)->getSExtValue() +
7083                  cast<ConstantSDNode>(Offset)->getSExtValue());
7084 }
7085 
7086 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
7087                                                      SelectionDAG &DAG,
7088                                                      unsigned NewOpcode) const {
7089   SDLoc DL(Op);
7090 
7091   SDValue VData = Op.getOperand(2);
7092   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7093   SDValue Ops[] = {
7094     Op.getOperand(0), // Chain
7095     VData,            // vdata
7096     Op.getOperand(3), // rsrc
7097     DAG.getConstant(0, DL, MVT::i32), // vindex
7098     Offsets.first,    // voffset
7099     Op.getOperand(5), // soffset
7100     Offsets.second,   // offset
7101     Op.getOperand(6), // cachepolicy
7102     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7103   };
7104 
7105   auto *M = cast<MemSDNode>(Op);
7106   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
7107 
7108   EVT MemVT = VData.getValueType();
7109   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7110                                  M->getMemOperand());
7111 }
7112 
7113 // Return a value to use for the idxen operand by examining the vindex operand.
7114 static unsigned getIdxEn(SDValue VIndex) {
7115   if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex))
7116     // No need to set idxen if vindex is known to be zero.
7117     return VIndexC->getZExtValue() != 0;
7118   return 1;
7119 }
7120 
7121 SDValue
7122 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
7123                                                 unsigned NewOpcode) const {
7124   SDLoc DL(Op);
7125 
7126   SDValue VData = Op.getOperand(2);
7127   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7128   SDValue Ops[] = {
7129     Op.getOperand(0), // Chain
7130     VData,            // vdata
7131     Op.getOperand(3), // rsrc
7132     Op.getOperand(4), // vindex
7133     Offsets.first,    // voffset
7134     Op.getOperand(6), // soffset
7135     Offsets.second,   // offset
7136     Op.getOperand(7), // cachepolicy
7137     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7138   };
7139 
7140   auto *M = cast<MemSDNode>(Op);
7141   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7142 
7143   EVT MemVT = VData.getValueType();
7144   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7145                                  M->getMemOperand());
7146 }
7147 
7148 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
7149                                                  SelectionDAG &DAG) const {
7150   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7151   SDLoc DL(Op);
7152 
7153   switch (IntrID) {
7154   case Intrinsic::amdgcn_ds_ordered_add:
7155   case Intrinsic::amdgcn_ds_ordered_swap: {
7156     MemSDNode *M = cast<MemSDNode>(Op);
7157     SDValue Chain = M->getOperand(0);
7158     SDValue M0 = M->getOperand(2);
7159     SDValue Value = M->getOperand(3);
7160     unsigned IndexOperand = M->getConstantOperandVal(7);
7161     unsigned WaveRelease = M->getConstantOperandVal(8);
7162     unsigned WaveDone = M->getConstantOperandVal(9);
7163 
7164     unsigned OrderedCountIndex = IndexOperand & 0x3f;
7165     IndexOperand &= ~0x3f;
7166     unsigned CountDw = 0;
7167 
7168     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
7169       CountDw = (IndexOperand >> 24) & 0xf;
7170       IndexOperand &= ~(0xf << 24);
7171 
7172       if (CountDw < 1 || CountDw > 4) {
7173         report_fatal_error(
7174             "ds_ordered_count: dword count must be between 1 and 4");
7175       }
7176     }
7177 
7178     if (IndexOperand)
7179       report_fatal_error("ds_ordered_count: bad index operand");
7180 
7181     if (WaveDone && !WaveRelease)
7182       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
7183 
7184     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
7185     unsigned ShaderType =
7186         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
7187     unsigned Offset0 = OrderedCountIndex << 2;
7188     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
7189                        (Instruction << 4);
7190 
7191     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
7192       Offset1 |= (CountDw - 1) << 6;
7193 
7194     unsigned Offset = Offset0 | (Offset1 << 8);
7195 
7196     SDValue Ops[] = {
7197       Chain,
7198       Value,
7199       DAG.getTargetConstant(Offset, DL, MVT::i16),
7200       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
7201     };
7202     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
7203                                    M->getVTList(), Ops, M->getMemoryVT(),
7204                                    M->getMemOperand());
7205   }
7206   case Intrinsic::amdgcn_ds_fadd: {
7207     MemSDNode *M = cast<MemSDNode>(Op);
7208     unsigned Opc;
7209     switch (IntrID) {
7210     case Intrinsic::amdgcn_ds_fadd:
7211       Opc = ISD::ATOMIC_LOAD_FADD;
7212       break;
7213     }
7214 
7215     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
7216                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
7217                          M->getMemOperand());
7218   }
7219   case Intrinsic::amdgcn_atomic_inc:
7220   case Intrinsic::amdgcn_atomic_dec:
7221   case Intrinsic::amdgcn_ds_fmin:
7222   case Intrinsic::amdgcn_ds_fmax: {
7223     MemSDNode *M = cast<MemSDNode>(Op);
7224     unsigned Opc;
7225     switch (IntrID) {
7226     case Intrinsic::amdgcn_atomic_inc:
7227       Opc = AMDGPUISD::ATOMIC_INC;
7228       break;
7229     case Intrinsic::amdgcn_atomic_dec:
7230       Opc = AMDGPUISD::ATOMIC_DEC;
7231       break;
7232     case Intrinsic::amdgcn_ds_fmin:
7233       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
7234       break;
7235     case Intrinsic::amdgcn_ds_fmax:
7236       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
7237       break;
7238     default:
7239       llvm_unreachable("Unknown intrinsic!");
7240     }
7241     SDValue Ops[] = {
7242       M->getOperand(0), // Chain
7243       M->getOperand(2), // Ptr
7244       M->getOperand(3)  // Value
7245     };
7246 
7247     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
7248                                    M->getMemoryVT(), M->getMemOperand());
7249   }
7250   case Intrinsic::amdgcn_buffer_load:
7251   case Intrinsic::amdgcn_buffer_load_format: {
7252     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
7253     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7254     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7255     SDValue Ops[] = {
7256       Op.getOperand(0), // Chain
7257       Op.getOperand(2), // rsrc
7258       Op.getOperand(3), // vindex
7259       SDValue(),        // voffset -- will be set by setBufferOffsets
7260       SDValue(),        // soffset -- will be set by setBufferOffsets
7261       SDValue(),        // offset -- will be set by setBufferOffsets
7262       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7263       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7264     };
7265     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
7266 
7267     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
7268         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
7269 
7270     EVT VT = Op.getValueType();
7271     EVT IntVT = VT.changeTypeToInteger();
7272     auto *M = cast<MemSDNode>(Op);
7273     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7274     EVT LoadVT = Op.getValueType();
7275 
7276     if (LoadVT.getScalarType() == MVT::f16)
7277       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
7278                                  M, DAG, Ops);
7279 
7280     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
7281     if (LoadVT.getScalarType() == MVT::i8 ||
7282         LoadVT.getScalarType() == MVT::i16)
7283       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
7284 
7285     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
7286                                M->getMemOperand(), DAG);
7287   }
7288   case Intrinsic::amdgcn_raw_buffer_load:
7289   case Intrinsic::amdgcn_raw_buffer_load_format: {
7290     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
7291 
7292     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7293     SDValue Ops[] = {
7294       Op.getOperand(0), // Chain
7295       Op.getOperand(2), // rsrc
7296       DAG.getConstant(0, DL, MVT::i32), // vindex
7297       Offsets.first,    // voffset
7298       Op.getOperand(4), // soffset
7299       Offsets.second,   // offset
7300       Op.getOperand(5), // cachepolicy, swizzled buffer
7301       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7302     };
7303 
7304     auto *M = cast<MemSDNode>(Op);
7305     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]);
7306     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
7307   }
7308   case Intrinsic::amdgcn_struct_buffer_load:
7309   case Intrinsic::amdgcn_struct_buffer_load_format: {
7310     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
7311 
7312     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7313     SDValue Ops[] = {
7314       Op.getOperand(0), // Chain
7315       Op.getOperand(2), // rsrc
7316       Op.getOperand(3), // vindex
7317       Offsets.first,    // voffset
7318       Op.getOperand(5), // soffset
7319       Offsets.second,   // offset
7320       Op.getOperand(6), // cachepolicy, swizzled buffer
7321       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7322     };
7323 
7324     auto *M = cast<MemSDNode>(Op);
7325     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7326     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7327   }
7328   case Intrinsic::amdgcn_tbuffer_load: {
7329     MemSDNode *M = cast<MemSDNode>(Op);
7330     EVT LoadVT = Op.getValueType();
7331 
7332     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7333     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7334     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7335     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7336     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7337     SDValue Ops[] = {
7338       Op.getOperand(0),  // Chain
7339       Op.getOperand(2),  // rsrc
7340       Op.getOperand(3),  // vindex
7341       Op.getOperand(4),  // voffset
7342       Op.getOperand(5),  // soffset
7343       Op.getOperand(6),  // offset
7344       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7345       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7346       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7347     };
7348 
7349     if (LoadVT.getScalarType() == MVT::f16)
7350       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7351                                  M, DAG, Ops);
7352     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7353                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7354                                DAG);
7355   }
7356   case Intrinsic::amdgcn_raw_tbuffer_load: {
7357     MemSDNode *M = cast<MemSDNode>(Op);
7358     EVT LoadVT = Op.getValueType();
7359     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7360 
7361     SDValue Ops[] = {
7362       Op.getOperand(0),  // Chain
7363       Op.getOperand(2),  // rsrc
7364       DAG.getConstant(0, DL, MVT::i32), // vindex
7365       Offsets.first,     // voffset
7366       Op.getOperand(4),  // soffset
7367       Offsets.second,    // offset
7368       Op.getOperand(5),  // format
7369       Op.getOperand(6),  // cachepolicy, swizzled buffer
7370       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7371     };
7372 
7373     if (LoadVT.getScalarType() == MVT::f16)
7374       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7375                                  M, DAG, Ops);
7376     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7377                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7378                                DAG);
7379   }
7380   case Intrinsic::amdgcn_struct_tbuffer_load: {
7381     MemSDNode *M = cast<MemSDNode>(Op);
7382     EVT LoadVT = Op.getValueType();
7383     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7384 
7385     SDValue Ops[] = {
7386       Op.getOperand(0),  // Chain
7387       Op.getOperand(2),  // rsrc
7388       Op.getOperand(3),  // vindex
7389       Offsets.first,     // voffset
7390       Op.getOperand(5),  // soffset
7391       Offsets.second,    // offset
7392       Op.getOperand(6),  // format
7393       Op.getOperand(7),  // cachepolicy, swizzled buffer
7394       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7395     };
7396 
7397     if (LoadVT.getScalarType() == MVT::f16)
7398       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7399                                  M, DAG, Ops);
7400     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7401                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7402                                DAG);
7403   }
7404   case Intrinsic::amdgcn_buffer_atomic_swap:
7405   case Intrinsic::amdgcn_buffer_atomic_add:
7406   case Intrinsic::amdgcn_buffer_atomic_sub:
7407   case Intrinsic::amdgcn_buffer_atomic_csub:
7408   case Intrinsic::amdgcn_buffer_atomic_smin:
7409   case Intrinsic::amdgcn_buffer_atomic_umin:
7410   case Intrinsic::amdgcn_buffer_atomic_smax:
7411   case Intrinsic::amdgcn_buffer_atomic_umax:
7412   case Intrinsic::amdgcn_buffer_atomic_and:
7413   case Intrinsic::amdgcn_buffer_atomic_or:
7414   case Intrinsic::amdgcn_buffer_atomic_xor:
7415   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7416     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7417     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7418     SDValue Ops[] = {
7419       Op.getOperand(0), // Chain
7420       Op.getOperand(2), // vdata
7421       Op.getOperand(3), // rsrc
7422       Op.getOperand(4), // vindex
7423       SDValue(),        // voffset -- will be set by setBufferOffsets
7424       SDValue(),        // soffset -- will be set by setBufferOffsets
7425       SDValue(),        // offset -- will be set by setBufferOffsets
7426       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7427       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7428     };
7429     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7430 
7431     EVT VT = Op.getValueType();
7432 
7433     auto *M = cast<MemSDNode>(Op);
7434     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7435     unsigned Opcode = 0;
7436 
7437     switch (IntrID) {
7438     case Intrinsic::amdgcn_buffer_atomic_swap:
7439       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7440       break;
7441     case Intrinsic::amdgcn_buffer_atomic_add:
7442       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7443       break;
7444     case Intrinsic::amdgcn_buffer_atomic_sub:
7445       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7446       break;
7447     case Intrinsic::amdgcn_buffer_atomic_csub:
7448       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7449       break;
7450     case Intrinsic::amdgcn_buffer_atomic_smin:
7451       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7452       break;
7453     case Intrinsic::amdgcn_buffer_atomic_umin:
7454       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7455       break;
7456     case Intrinsic::amdgcn_buffer_atomic_smax:
7457       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7458       break;
7459     case Intrinsic::amdgcn_buffer_atomic_umax:
7460       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7461       break;
7462     case Intrinsic::amdgcn_buffer_atomic_and:
7463       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7464       break;
7465     case Intrinsic::amdgcn_buffer_atomic_or:
7466       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7467       break;
7468     case Intrinsic::amdgcn_buffer_atomic_xor:
7469       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7470       break;
7471     case Intrinsic::amdgcn_buffer_atomic_fadd:
7472       if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7473         DiagnosticInfoUnsupported
7474           NoFpRet(DAG.getMachineFunction().getFunction(),
7475                   "return versions of fp atomics not supported",
7476                   DL.getDebugLoc(), DS_Error);
7477         DAG.getContext()->diagnose(NoFpRet);
7478         return SDValue();
7479       }
7480       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7481       break;
7482     default:
7483       llvm_unreachable("unhandled atomic opcode");
7484     }
7485 
7486     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7487                                    M->getMemOperand());
7488   }
7489   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7490     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7491   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7492     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7493   case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7494     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7495   case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7496     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7497   case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7498     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7499   case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7500     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7501   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7502     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7503   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7504     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7505   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7506     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7507   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7508     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7509   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7510     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7511   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7512     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7513   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7514     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7515   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7516     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7517   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7518     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7519   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7520     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7521   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7522     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7523   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7524     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7525   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7526     return lowerStructBufferAtomicIntrin(Op, DAG,
7527                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7528   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7529     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7530   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7531     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7532   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7533     return lowerStructBufferAtomicIntrin(Op, DAG,
7534                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7535   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7536     return lowerStructBufferAtomicIntrin(Op, DAG,
7537                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7538   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7539     return lowerStructBufferAtomicIntrin(Op, DAG,
7540                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7541   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7542     return lowerStructBufferAtomicIntrin(Op, DAG,
7543                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7544   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7545     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7546   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7547     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7548   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7549     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7550   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7551     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7552   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7553     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7554 
7555   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7556     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7557     unsigned IdxEn = getIdxEn(Op.getOperand(5));
7558     SDValue Ops[] = {
7559       Op.getOperand(0), // Chain
7560       Op.getOperand(2), // src
7561       Op.getOperand(3), // cmp
7562       Op.getOperand(4), // rsrc
7563       Op.getOperand(5), // vindex
7564       SDValue(),        // voffset -- will be set by setBufferOffsets
7565       SDValue(),        // soffset -- will be set by setBufferOffsets
7566       SDValue(),        // offset -- will be set by setBufferOffsets
7567       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7568       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7569     };
7570     setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7571 
7572     EVT VT = Op.getValueType();
7573     auto *M = cast<MemSDNode>(Op);
7574     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7575 
7576     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7577                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7578   }
7579   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7580     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7581     SDValue Ops[] = {
7582       Op.getOperand(0), // Chain
7583       Op.getOperand(2), // src
7584       Op.getOperand(3), // cmp
7585       Op.getOperand(4), // rsrc
7586       DAG.getConstant(0, DL, MVT::i32), // vindex
7587       Offsets.first,    // voffset
7588       Op.getOperand(6), // soffset
7589       Offsets.second,   // offset
7590       Op.getOperand(7), // cachepolicy
7591       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7592     };
7593     EVT VT = Op.getValueType();
7594     auto *M = cast<MemSDNode>(Op);
7595     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]);
7596 
7597     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7598                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7599   }
7600   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7601     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7602     SDValue Ops[] = {
7603       Op.getOperand(0), // Chain
7604       Op.getOperand(2), // src
7605       Op.getOperand(3), // cmp
7606       Op.getOperand(4), // rsrc
7607       Op.getOperand(5), // vindex
7608       Offsets.first,    // voffset
7609       Op.getOperand(7), // soffset
7610       Offsets.second,   // offset
7611       Op.getOperand(8), // cachepolicy
7612       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7613     };
7614     EVT VT = Op.getValueType();
7615     auto *M = cast<MemSDNode>(Op);
7616     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7617 
7618     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7619                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7620   }
7621   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7622     MemSDNode *M = cast<MemSDNode>(Op);
7623     SDValue NodePtr = M->getOperand(2);
7624     SDValue RayExtent = M->getOperand(3);
7625     SDValue RayOrigin = M->getOperand(4);
7626     SDValue RayDir = M->getOperand(5);
7627     SDValue RayInvDir = M->getOperand(6);
7628     SDValue TDescr = M->getOperand(7);
7629 
7630     assert(NodePtr.getValueType() == MVT::i32 ||
7631            NodePtr.getValueType() == MVT::i64);
7632     assert(RayDir.getValueType() == MVT::v3f16 ||
7633            RayDir.getValueType() == MVT::v3f32);
7634 
7635     if (!Subtarget->hasGFX10_AEncoding()) {
7636       emitRemovedIntrinsicError(DAG, DL, Op.getValueType());
7637       return SDValue();
7638     }
7639 
7640     const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7641     const bool Is64 = NodePtr.getValueType() == MVT::i64;
7642     const unsigned NumVDataDwords = 4;
7643     const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
7644     const bool UseNSA = Subtarget->hasNSAEncoding() &&
7645                         NumVAddrDwords <= Subtarget->getNSAMaxSize();
7646     const unsigned BaseOpcodes[2][2] = {
7647         {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
7648         {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
7649          AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
7650     int Opcode;
7651     if (UseNSA) {
7652       Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7653                                      AMDGPU::MIMGEncGfx10NSA, NumVDataDwords,
7654                                      NumVAddrDwords);
7655     } else {
7656       Opcode = AMDGPU::getMIMGOpcode(
7657           BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords,
7658           PowerOf2Ceil(NumVAddrDwords));
7659     }
7660     assert(Opcode != -1);
7661 
7662     SmallVector<SDValue, 16> Ops;
7663 
7664     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7665       SmallVector<SDValue, 3> Lanes;
7666       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7667       if (Lanes[0].getValueSizeInBits() == 32) {
7668         for (unsigned I = 0; I < 3; ++I)
7669           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7670       } else {
7671         if (IsAligned) {
7672           Ops.push_back(
7673             DAG.getBitcast(MVT::i32,
7674                            DAG.getBuildVector(MVT::v2f16, DL,
7675                                               { Lanes[0], Lanes[1] })));
7676           Ops.push_back(Lanes[2]);
7677         } else {
7678           SDValue Elt0 = Ops.pop_back_val();
7679           Ops.push_back(
7680             DAG.getBitcast(MVT::i32,
7681                            DAG.getBuildVector(MVT::v2f16, DL,
7682                                               { Elt0, Lanes[0] })));
7683           Ops.push_back(
7684             DAG.getBitcast(MVT::i32,
7685                            DAG.getBuildVector(MVT::v2f16, DL,
7686                                               { Lanes[1], Lanes[2] })));
7687         }
7688       }
7689     };
7690 
7691     if (Is64)
7692       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7693     else
7694       Ops.push_back(NodePtr);
7695 
7696     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7697     packLanes(RayOrigin, true);
7698     packLanes(RayDir, true);
7699     packLanes(RayInvDir, false);
7700 
7701     if (!UseNSA) {
7702       // Build a single vector containing all the operands so far prepared.
7703       if (NumVAddrDwords > 8) {
7704         SDValue Undef = DAG.getUNDEF(MVT::i32);
7705         Ops.append(16 - Ops.size(), Undef);
7706       }
7707       assert(Ops.size() == 8 || Ops.size() == 16);
7708       SDValue MergedOps = DAG.getBuildVector(
7709           Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops);
7710       Ops.clear();
7711       Ops.push_back(MergedOps);
7712     }
7713 
7714     Ops.push_back(TDescr);
7715     if (IsA16)
7716       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7717     Ops.push_back(M->getChain());
7718 
7719     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7720     MachineMemOperand *MemRef = M->getMemOperand();
7721     DAG.setNodeMemRefs(NewNode, {MemRef});
7722     return SDValue(NewNode, 0);
7723   }
7724   case Intrinsic::amdgcn_global_atomic_fadd:
7725     if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7726       DiagnosticInfoUnsupported
7727         NoFpRet(DAG.getMachineFunction().getFunction(),
7728                 "return versions of fp atomics not supported",
7729                 DL.getDebugLoc(), DS_Error);
7730       DAG.getContext()->diagnose(NoFpRet);
7731       return SDValue();
7732     }
7733     LLVM_FALLTHROUGH;
7734   case Intrinsic::amdgcn_global_atomic_fmin:
7735   case Intrinsic::amdgcn_global_atomic_fmax:
7736   case Intrinsic::amdgcn_flat_atomic_fadd:
7737   case Intrinsic::amdgcn_flat_atomic_fmin:
7738   case Intrinsic::amdgcn_flat_atomic_fmax: {
7739     MemSDNode *M = cast<MemSDNode>(Op);
7740     SDValue Ops[] = {
7741       M->getOperand(0), // Chain
7742       M->getOperand(2), // Ptr
7743       M->getOperand(3)  // Value
7744     };
7745     unsigned Opcode = 0;
7746     switch (IntrID) {
7747     case Intrinsic::amdgcn_global_atomic_fadd:
7748     case Intrinsic::amdgcn_flat_atomic_fadd: {
7749       EVT VT = Op.getOperand(3).getValueType();
7750       return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7751                            DAG.getVTList(VT, MVT::Other), Ops,
7752                            M->getMemOperand());
7753     }
7754     case Intrinsic::amdgcn_global_atomic_fmin:
7755     case Intrinsic::amdgcn_flat_atomic_fmin: {
7756       Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7757       break;
7758     }
7759     case Intrinsic::amdgcn_global_atomic_fmax:
7760     case Intrinsic::amdgcn_flat_atomic_fmax: {
7761       Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7762       break;
7763     }
7764     default:
7765       llvm_unreachable("unhandled atomic opcode");
7766     }
7767     return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7768                                    M->getVTList(), Ops, M->getMemoryVT(),
7769                                    M->getMemOperand());
7770   }
7771   default:
7772 
7773     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7774             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7775       return lowerImage(Op, ImageDimIntr, DAG, true);
7776 
7777     return SDValue();
7778   }
7779 }
7780 
7781 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7782 // dwordx4 if on SI.
7783 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7784                                               SDVTList VTList,
7785                                               ArrayRef<SDValue> Ops, EVT MemVT,
7786                                               MachineMemOperand *MMO,
7787                                               SelectionDAG &DAG) const {
7788   EVT VT = VTList.VTs[0];
7789   EVT WidenedVT = VT;
7790   EVT WidenedMemVT = MemVT;
7791   if (!Subtarget->hasDwordx3LoadStores() &&
7792       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7793     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7794                                  WidenedVT.getVectorElementType(), 4);
7795     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7796                                     WidenedMemVT.getVectorElementType(), 4);
7797     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7798   }
7799 
7800   assert(VTList.NumVTs == 2);
7801   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7802 
7803   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7804                                        WidenedMemVT, MMO);
7805   if (WidenedVT != VT) {
7806     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7807                                DAG.getVectorIdxConstant(0, DL));
7808     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7809   }
7810   return NewOp;
7811 }
7812 
7813 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7814                                          bool ImageStore) const {
7815   EVT StoreVT = VData.getValueType();
7816 
7817   // No change for f16 and legal vector D16 types.
7818   if (!StoreVT.isVector())
7819     return VData;
7820 
7821   SDLoc DL(VData);
7822   unsigned NumElements = StoreVT.getVectorNumElements();
7823 
7824   if (Subtarget->hasUnpackedD16VMem()) {
7825     // We need to unpack the packed data to store.
7826     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7827     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7828 
7829     EVT EquivStoreVT =
7830         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7831     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7832     return DAG.UnrollVectorOp(ZExt.getNode());
7833   }
7834 
7835   // The sq block of gfx8.1 does not estimate register use correctly for d16
7836   // image store instructions. The data operand is computed as if it were not a
7837   // d16 image instruction.
7838   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7839     // Bitcast to i16
7840     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7841     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7842 
7843     // Decompose into scalars
7844     SmallVector<SDValue, 4> Elts;
7845     DAG.ExtractVectorElements(IntVData, Elts);
7846 
7847     // Group pairs of i16 into v2i16 and bitcast to i32
7848     SmallVector<SDValue, 4> PackedElts;
7849     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7850       SDValue Pair =
7851           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7852       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7853       PackedElts.push_back(IntPair);
7854     }
7855     if ((NumElements % 2) == 1) {
7856       // Handle v3i16
7857       unsigned I = Elts.size() / 2;
7858       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7859                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7860       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7861       PackedElts.push_back(IntPair);
7862     }
7863 
7864     // Pad using UNDEF
7865     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7866 
7867     // Build final vector
7868     EVT VecVT =
7869         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7870     return DAG.getBuildVector(VecVT, DL, PackedElts);
7871   }
7872 
7873   if (NumElements == 3) {
7874     EVT IntStoreVT =
7875         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7876     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7877 
7878     EVT WidenedStoreVT = EVT::getVectorVT(
7879         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7880     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7881                                          WidenedStoreVT.getStoreSizeInBits());
7882     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7883     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7884   }
7885 
7886   assert(isTypeLegal(StoreVT));
7887   return VData;
7888 }
7889 
7890 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7891                                               SelectionDAG &DAG) const {
7892   SDLoc DL(Op);
7893   SDValue Chain = Op.getOperand(0);
7894   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7895   MachineFunction &MF = DAG.getMachineFunction();
7896 
7897   switch (IntrinsicID) {
7898   case Intrinsic::amdgcn_exp_compr: {
7899     SDValue Src0 = Op.getOperand(4);
7900     SDValue Src1 = Op.getOperand(5);
7901     // Hack around illegal type on SI by directly selecting it.
7902     if (isTypeLegal(Src0.getValueType()))
7903       return SDValue();
7904 
7905     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7906     SDValue Undef = DAG.getUNDEF(MVT::f32);
7907     const SDValue Ops[] = {
7908       Op.getOperand(2), // tgt
7909       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7910       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7911       Undef, // src2
7912       Undef, // src3
7913       Op.getOperand(7), // vm
7914       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7915       Op.getOperand(3), // en
7916       Op.getOperand(0) // Chain
7917     };
7918 
7919     unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7920     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7921   }
7922   case Intrinsic::amdgcn_s_barrier: {
7923     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7924       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7925       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7926       if (WGSize <= ST.getWavefrontSize())
7927         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7928                                           Op.getOperand(0)), 0);
7929     }
7930     return SDValue();
7931   };
7932   case Intrinsic::amdgcn_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     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7938     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7939     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7940     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7941     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7942     SDValue Ops[] = {
7943       Chain,
7944       VData,             // vdata
7945       Op.getOperand(3),  // rsrc
7946       Op.getOperand(4),  // vindex
7947       Op.getOperand(5),  // voffset
7948       Op.getOperand(6),  // soffset
7949       Op.getOperand(7),  // offset
7950       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7951       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7952       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7953     };
7954     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7955                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7956     MemSDNode *M = cast<MemSDNode>(Op);
7957     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7958                                    M->getMemoryVT(), M->getMemOperand());
7959   }
7960 
7961   case Intrinsic::amdgcn_struct_tbuffer_store: {
7962     SDValue VData = Op.getOperand(2);
7963     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7964     if (IsD16)
7965       VData = handleD16VData(VData, DAG);
7966     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7967     SDValue Ops[] = {
7968       Chain,
7969       VData,             // vdata
7970       Op.getOperand(3),  // rsrc
7971       Op.getOperand(4),  // vindex
7972       Offsets.first,     // voffset
7973       Op.getOperand(6),  // soffset
7974       Offsets.second,    // offset
7975       Op.getOperand(7),  // format
7976       Op.getOperand(8),  // cachepolicy, swizzled buffer
7977       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7978     };
7979     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7980                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7981     MemSDNode *M = cast<MemSDNode>(Op);
7982     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7983                                    M->getMemoryVT(), M->getMemOperand());
7984   }
7985 
7986   case Intrinsic::amdgcn_raw_tbuffer_store: {
7987     SDValue VData = Op.getOperand(2);
7988     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7989     if (IsD16)
7990       VData = handleD16VData(VData, DAG);
7991     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7992     SDValue Ops[] = {
7993       Chain,
7994       VData,             // vdata
7995       Op.getOperand(3),  // rsrc
7996       DAG.getConstant(0, DL, MVT::i32), // vindex
7997       Offsets.first,     // voffset
7998       Op.getOperand(5),  // soffset
7999       Offsets.second,    // offset
8000       Op.getOperand(6),  // format
8001       Op.getOperand(7),  // cachepolicy, swizzled buffer
8002       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8003     };
8004     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
8005                            AMDGPUISD::TBUFFER_STORE_FORMAT;
8006     MemSDNode *M = cast<MemSDNode>(Op);
8007     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8008                                    M->getMemoryVT(), M->getMemOperand());
8009   }
8010 
8011   case Intrinsic::amdgcn_buffer_store:
8012   case Intrinsic::amdgcn_buffer_store_format: {
8013     SDValue VData = Op.getOperand(2);
8014     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8015     if (IsD16)
8016       VData = handleD16VData(VData, DAG);
8017     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
8018     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
8019     unsigned IdxEn = getIdxEn(Op.getOperand(4));
8020     SDValue Ops[] = {
8021       Chain,
8022       VData,
8023       Op.getOperand(3), // rsrc
8024       Op.getOperand(4), // vindex
8025       SDValue(), // voffset -- will be set by setBufferOffsets
8026       SDValue(), // soffset -- will be set by setBufferOffsets
8027       SDValue(), // offset -- will be set by setBufferOffsets
8028       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
8029       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
8030     };
8031     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
8032 
8033     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
8034                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8035     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8036     MemSDNode *M = cast<MemSDNode>(Op);
8037     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8038 
8039     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8040     EVT VDataType = VData.getValueType().getScalarType();
8041     if (VDataType == MVT::i8 || VDataType == MVT::i16)
8042       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8043 
8044     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8045                                    M->getMemoryVT(), M->getMemOperand());
8046   }
8047 
8048   case Intrinsic::amdgcn_raw_buffer_store:
8049   case Intrinsic::amdgcn_raw_buffer_store_format: {
8050     const bool IsFormat =
8051         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
8052 
8053     SDValue VData = Op.getOperand(2);
8054     EVT VDataVT = VData.getValueType();
8055     EVT EltType = VDataVT.getScalarType();
8056     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8057     if (IsD16) {
8058       VData = handleD16VData(VData, DAG);
8059       VDataVT = VData.getValueType();
8060     }
8061 
8062     if (!isTypeLegal(VDataVT)) {
8063       VData =
8064           DAG.getNode(ISD::BITCAST, DL,
8065                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8066     }
8067 
8068     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
8069     SDValue Ops[] = {
8070       Chain,
8071       VData,
8072       Op.getOperand(3), // rsrc
8073       DAG.getConstant(0, DL, MVT::i32), // vindex
8074       Offsets.first,    // voffset
8075       Op.getOperand(5), // soffset
8076       Offsets.second,   // offset
8077       Op.getOperand(6), // cachepolicy, swizzled buffer
8078       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8079     };
8080     unsigned Opc =
8081         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
8082     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8083     MemSDNode *M = cast<MemSDNode>(Op);
8084     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
8085 
8086     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8087     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8088       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
8089 
8090     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8091                                    M->getMemoryVT(), M->getMemOperand());
8092   }
8093 
8094   case Intrinsic::amdgcn_struct_buffer_store:
8095   case Intrinsic::amdgcn_struct_buffer_store_format: {
8096     const bool IsFormat =
8097         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
8098 
8099     SDValue VData = Op.getOperand(2);
8100     EVT VDataVT = VData.getValueType();
8101     EVT EltType = VDataVT.getScalarType();
8102     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8103 
8104     if (IsD16) {
8105       VData = handleD16VData(VData, DAG);
8106       VDataVT = VData.getValueType();
8107     }
8108 
8109     if (!isTypeLegal(VDataVT)) {
8110       VData =
8111           DAG.getNode(ISD::BITCAST, DL,
8112                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8113     }
8114 
8115     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
8116     SDValue Ops[] = {
8117       Chain,
8118       VData,
8119       Op.getOperand(3), // rsrc
8120       Op.getOperand(4), // vindex
8121       Offsets.first,    // voffset
8122       Op.getOperand(6), // soffset
8123       Offsets.second,   // offset
8124       Op.getOperand(7), // cachepolicy, swizzled buffer
8125       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8126     };
8127     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
8128                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8129     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8130     MemSDNode *M = cast<MemSDNode>(Op);
8131     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8132 
8133     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8134     EVT VDataType = VData.getValueType().getScalarType();
8135     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8136       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8137 
8138     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8139                                    M->getMemoryVT(), M->getMemOperand());
8140   }
8141   case Intrinsic::amdgcn_end_cf:
8142     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
8143                                       Op->getOperand(2), Chain), 0);
8144 
8145   default: {
8146     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
8147             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
8148       return lowerImage(Op, ImageDimIntr, DAG, true);
8149 
8150     return Op;
8151   }
8152   }
8153 }
8154 
8155 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
8156 // offset (the offset that is included in bounds checking and swizzling, to be
8157 // split between the instruction's voffset and immoffset fields) and soffset
8158 // (the offset that is excluded from bounds checking and swizzling, to go in
8159 // the instruction's soffset field).  This function takes the first kind of
8160 // offset and figures out how to split it between voffset and immoffset.
8161 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
8162     SDValue Offset, SelectionDAG &DAG) const {
8163   SDLoc DL(Offset);
8164   const unsigned MaxImm = 4095;
8165   SDValue N0 = Offset;
8166   ConstantSDNode *C1 = nullptr;
8167 
8168   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
8169     N0 = SDValue();
8170   else if (DAG.isBaseWithConstantOffset(N0)) {
8171     C1 = cast<ConstantSDNode>(N0.getOperand(1));
8172     N0 = N0.getOperand(0);
8173   }
8174 
8175   if (C1) {
8176     unsigned ImmOffset = C1->getZExtValue();
8177     // If the immediate value is too big for the immoffset field, put the value
8178     // and -4096 into the immoffset field so that the value that is copied/added
8179     // for the voffset field is a multiple of 4096, and it stands more chance
8180     // of being CSEd with the copy/add for another similar load/store.
8181     // However, do not do that rounding down to a multiple of 4096 if that is a
8182     // negative number, as it appears to be illegal to have a negative offset
8183     // in the vgpr, even if adding the immediate offset makes it positive.
8184     unsigned Overflow = ImmOffset & ~MaxImm;
8185     ImmOffset -= Overflow;
8186     if ((int32_t)Overflow < 0) {
8187       Overflow += ImmOffset;
8188       ImmOffset = 0;
8189     }
8190     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
8191     if (Overflow) {
8192       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
8193       if (!N0)
8194         N0 = OverflowVal;
8195       else {
8196         SDValue Ops[] = { N0, OverflowVal };
8197         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
8198       }
8199     }
8200   }
8201   if (!N0)
8202     N0 = DAG.getConstant(0, DL, MVT::i32);
8203   if (!C1)
8204     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
8205   return {N0, SDValue(C1, 0)};
8206 }
8207 
8208 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
8209 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
8210 // pointed to by Offsets.
8211 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
8212                                         SelectionDAG &DAG, SDValue *Offsets,
8213                                         Align Alignment) const {
8214   SDLoc DL(CombinedOffset);
8215   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
8216     uint32_t Imm = C->getZExtValue();
8217     uint32_t SOffset, ImmOffset;
8218     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
8219                                  Alignment)) {
8220       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
8221       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8222       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8223       return;
8224     }
8225   }
8226   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
8227     SDValue N0 = CombinedOffset.getOperand(0);
8228     SDValue N1 = CombinedOffset.getOperand(1);
8229     uint32_t SOffset, ImmOffset;
8230     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
8231     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
8232                                                 Subtarget, Alignment)) {
8233       Offsets[0] = N0;
8234       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8235       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8236       return;
8237     }
8238   }
8239   Offsets[0] = CombinedOffset;
8240   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
8241   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
8242 }
8243 
8244 // Handle 8 bit and 16 bit buffer loads
8245 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
8246                                                      EVT LoadVT, SDLoc DL,
8247                                                      ArrayRef<SDValue> Ops,
8248                                                      MemSDNode *M) const {
8249   EVT IntVT = LoadVT.changeTypeToInteger();
8250   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
8251          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
8252 
8253   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
8254   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
8255                                                Ops, IntVT,
8256                                                M->getMemOperand());
8257   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
8258   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
8259 
8260   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
8261 }
8262 
8263 // Handle 8 bit and 16 bit buffer stores
8264 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
8265                                                       EVT VDataType, SDLoc DL,
8266                                                       SDValue Ops[],
8267                                                       MemSDNode *M) const {
8268   if (VDataType == MVT::f16)
8269     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
8270 
8271   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
8272   Ops[1] = BufferStoreExt;
8273   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
8274                                  AMDGPUISD::BUFFER_STORE_SHORT;
8275   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
8276   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
8277                                      M->getMemOperand());
8278 }
8279 
8280 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
8281                                  ISD::LoadExtType ExtType, SDValue Op,
8282                                  const SDLoc &SL, EVT VT) {
8283   if (VT.bitsLT(Op.getValueType()))
8284     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
8285 
8286   switch (ExtType) {
8287   case ISD::SEXTLOAD:
8288     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
8289   case ISD::ZEXTLOAD:
8290     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
8291   case ISD::EXTLOAD:
8292     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
8293   case ISD::NON_EXTLOAD:
8294     return Op;
8295   }
8296 
8297   llvm_unreachable("invalid ext type");
8298 }
8299 
8300 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
8301   SelectionDAG &DAG = DCI.DAG;
8302   if (Ld->getAlignment() < 4 || Ld->isDivergent())
8303     return SDValue();
8304 
8305   // FIXME: Constant loads should all be marked invariant.
8306   unsigned AS = Ld->getAddressSpace();
8307   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
8308       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
8309       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
8310     return SDValue();
8311 
8312   // Don't do this early, since it may interfere with adjacent load merging for
8313   // illegal types. We can avoid losing alignment information for exotic types
8314   // pre-legalize.
8315   EVT MemVT = Ld->getMemoryVT();
8316   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
8317       MemVT.getSizeInBits() >= 32)
8318     return SDValue();
8319 
8320   SDLoc SL(Ld);
8321 
8322   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
8323          "unexpected vector extload");
8324 
8325   // TODO: Drop only high part of range.
8326   SDValue Ptr = Ld->getBasePtr();
8327   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
8328                                 MVT::i32, SL, Ld->getChain(), Ptr,
8329                                 Ld->getOffset(),
8330                                 Ld->getPointerInfo(), MVT::i32,
8331                                 Ld->getAlignment(),
8332                                 Ld->getMemOperand()->getFlags(),
8333                                 Ld->getAAInfo(),
8334                                 nullptr); // Drop ranges
8335 
8336   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
8337   if (MemVT.isFloatingPoint()) {
8338     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
8339            "unexpected fp extload");
8340     TruncVT = MemVT.changeTypeToInteger();
8341   }
8342 
8343   SDValue Cvt = NewLoad;
8344   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
8345     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
8346                       DAG.getValueType(TruncVT));
8347   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
8348              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
8349     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
8350   } else {
8351     assert(Ld->getExtensionType() == ISD::EXTLOAD);
8352   }
8353 
8354   EVT VT = Ld->getValueType(0);
8355   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8356 
8357   DCI.AddToWorklist(Cvt.getNode());
8358 
8359   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
8360   // the appropriate extension from the 32-bit load.
8361   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
8362   DCI.AddToWorklist(Cvt.getNode());
8363 
8364   // Handle conversion back to floating point if necessary.
8365   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8366 
8367   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8368 }
8369 
8370 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8371   SDLoc DL(Op);
8372   LoadSDNode *Load = cast<LoadSDNode>(Op);
8373   ISD::LoadExtType ExtType = Load->getExtensionType();
8374   EVT MemVT = Load->getMemoryVT();
8375 
8376   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8377     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8378       return SDValue();
8379 
8380     // FIXME: Copied from PPC
8381     // First, load into 32 bits, then truncate to 1 bit.
8382 
8383     SDValue Chain = Load->getChain();
8384     SDValue BasePtr = Load->getBasePtr();
8385     MachineMemOperand *MMO = Load->getMemOperand();
8386 
8387     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8388 
8389     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8390                                    BasePtr, RealMemVT, MMO);
8391 
8392     if (!MemVT.isVector()) {
8393       SDValue Ops[] = {
8394         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8395         NewLD.getValue(1)
8396       };
8397 
8398       return DAG.getMergeValues(Ops, DL);
8399     }
8400 
8401     SmallVector<SDValue, 3> Elts;
8402     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8403       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8404                                 DAG.getConstant(I, DL, MVT::i32));
8405 
8406       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8407     }
8408 
8409     SDValue Ops[] = {
8410       DAG.getBuildVector(MemVT, DL, Elts),
8411       NewLD.getValue(1)
8412     };
8413 
8414     return DAG.getMergeValues(Ops, DL);
8415   }
8416 
8417   if (!MemVT.isVector())
8418     return SDValue();
8419 
8420   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8421          "Custom lowering for non-i32 vectors hasn't been implemented.");
8422 
8423   unsigned Alignment = Load->getAlignment();
8424   unsigned AS = Load->getAddressSpace();
8425   if (Subtarget->hasLDSMisalignedBug() &&
8426       AS == AMDGPUAS::FLAT_ADDRESS &&
8427       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8428     return SplitVectorLoad(Op, DAG);
8429   }
8430 
8431   MachineFunction &MF = DAG.getMachineFunction();
8432   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8433   // If there is a possibility that flat instruction access scratch memory
8434   // then we need to use the same legalization rules we use for private.
8435   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8436       !Subtarget->hasMultiDwordFlatScratchAddressing())
8437     AS = MFI->hasFlatScratchInit() ?
8438          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8439 
8440   unsigned NumElements = MemVT.getVectorNumElements();
8441 
8442   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8443       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8444     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8445       if (MemVT.isPow2VectorType())
8446         return SDValue();
8447       return WidenOrSplitVectorLoad(Op, DAG);
8448     }
8449     // Non-uniform loads will be selected to MUBUF instructions, so they
8450     // have the same legalization requirements as global and private
8451     // loads.
8452     //
8453   }
8454 
8455   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8456       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8457       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8458     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8459         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8460         Alignment >= 4 && NumElements < 32) {
8461       if (MemVT.isPow2VectorType())
8462         return SDValue();
8463       return WidenOrSplitVectorLoad(Op, DAG);
8464     }
8465     // Non-uniform loads will be selected to MUBUF instructions, so they
8466     // have the same legalization requirements as global and private
8467     // loads.
8468     //
8469   }
8470   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8471       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8472       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8473       AS == AMDGPUAS::FLAT_ADDRESS) {
8474     if (NumElements > 4)
8475       return SplitVectorLoad(Op, DAG);
8476     // v3 loads not supported on SI.
8477     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8478       return WidenOrSplitVectorLoad(Op, DAG);
8479 
8480     // v3 and v4 loads are supported for private and global memory.
8481     return SDValue();
8482   }
8483   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8484     // Depending on the setting of the private_element_size field in the
8485     // resource descriptor, we can only make private accesses up to a certain
8486     // size.
8487     switch (Subtarget->getMaxPrivateElementSize()) {
8488     case 4: {
8489       SDValue Ops[2];
8490       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8491       return DAG.getMergeValues(Ops, DL);
8492     }
8493     case 8:
8494       if (NumElements > 2)
8495         return SplitVectorLoad(Op, DAG);
8496       return SDValue();
8497     case 16:
8498       // Same as global/flat
8499       if (NumElements > 4)
8500         return SplitVectorLoad(Op, DAG);
8501       // v3 loads not supported on SI.
8502       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8503         return WidenOrSplitVectorLoad(Op, DAG);
8504 
8505       return SDValue();
8506     default:
8507       llvm_unreachable("unsupported private_element_size");
8508     }
8509   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8510     // Use ds_read_b128 or ds_read_b96 when possible.
8511     if (Subtarget->hasDS96AndDS128() &&
8512         ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) ||
8513          MemVT.getStoreSize() == 12) &&
8514         allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8515                                            Load->getAlign()))
8516       return SDValue();
8517 
8518     if (NumElements > 2)
8519       return SplitVectorLoad(Op, DAG);
8520 
8521     // SI has a hardware bug in the LDS / GDS bounds checking: if the base
8522     // address is negative, then the instruction is incorrectly treated as
8523     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8524     // loads here to avoid emitting ds_read2_b32. We may re-combine the
8525     // load later in the SILoadStoreOptimizer.
8526     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
8527         NumElements == 2 && MemVT.getStoreSize() == 8 &&
8528         Load->getAlignment() < 8) {
8529       return SplitVectorLoad(Op, DAG);
8530     }
8531   }
8532 
8533   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8534                                       MemVT, *Load->getMemOperand())) {
8535     SDValue Ops[2];
8536     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8537     return DAG.getMergeValues(Ops, DL);
8538   }
8539 
8540   return SDValue();
8541 }
8542 
8543 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8544   EVT VT = Op.getValueType();
8545   if (VT.getSizeInBits() == 128)
8546     return splitTernaryVectorOp(Op, DAG);
8547 
8548   assert(VT.getSizeInBits() == 64);
8549 
8550   SDLoc DL(Op);
8551   SDValue Cond = Op.getOperand(0);
8552 
8553   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8554   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8555 
8556   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8557   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8558 
8559   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8560   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8561 
8562   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8563 
8564   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8565   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8566 
8567   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8568 
8569   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8570   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8571 }
8572 
8573 // Catch division cases where we can use shortcuts with rcp and rsq
8574 // instructions.
8575 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8576                                               SelectionDAG &DAG) const {
8577   SDLoc SL(Op);
8578   SDValue LHS = Op.getOperand(0);
8579   SDValue RHS = Op.getOperand(1);
8580   EVT VT = Op.getValueType();
8581   const SDNodeFlags Flags = Op->getFlags();
8582 
8583   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8584 
8585   // Without !fpmath accuracy information, we can't do more because we don't
8586   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8587   if (!AllowInaccurateRcp)
8588     return SDValue();
8589 
8590   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8591     if (CLHS->isExactlyValue(1.0)) {
8592       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8593       // the CI documentation has a worst case error of 1 ulp.
8594       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8595       // use it as long as we aren't trying to use denormals.
8596       //
8597       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8598 
8599       // 1.0 / sqrt(x) -> rsq(x)
8600 
8601       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8602       // error seems really high at 2^29 ULP.
8603       if (RHS.getOpcode() == ISD::FSQRT)
8604         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8605 
8606       // 1.0 / x -> rcp(x)
8607       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8608     }
8609 
8610     // Same as for 1.0, but expand the sign out of the constant.
8611     if (CLHS->isExactlyValue(-1.0)) {
8612       // -1.0 / x -> rcp (fneg x)
8613       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8614       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8615     }
8616   }
8617 
8618   // Turn into multiply by the reciprocal.
8619   // x / y -> x * (1.0 / y)
8620   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8621   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8622 }
8623 
8624 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8625                                                 SelectionDAG &DAG) const {
8626   SDLoc SL(Op);
8627   SDValue X = Op.getOperand(0);
8628   SDValue Y = Op.getOperand(1);
8629   EVT VT = Op.getValueType();
8630   const SDNodeFlags Flags = Op->getFlags();
8631 
8632   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8633                             DAG.getTarget().Options.UnsafeFPMath;
8634   if (!AllowInaccurateDiv)
8635     return SDValue();
8636 
8637   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8638   SDValue One = DAG.getConstantFP(1.0, SL, VT);
8639 
8640   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8641   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8642 
8643   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8644   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8645   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8646   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8647   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8648   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8649 }
8650 
8651 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8652                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8653                           SDNodeFlags Flags) {
8654   if (GlueChain->getNumValues() <= 1) {
8655     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8656   }
8657 
8658   assert(GlueChain->getNumValues() == 3);
8659 
8660   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8661   switch (Opcode) {
8662   default: llvm_unreachable("no chain equivalent for opcode");
8663   case ISD::FMUL:
8664     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8665     break;
8666   }
8667 
8668   return DAG.getNode(Opcode, SL, VTList,
8669                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8670                      Flags);
8671 }
8672 
8673 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8674                            EVT VT, SDValue A, SDValue B, SDValue C,
8675                            SDValue GlueChain, SDNodeFlags Flags) {
8676   if (GlueChain->getNumValues() <= 1) {
8677     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8678   }
8679 
8680   assert(GlueChain->getNumValues() == 3);
8681 
8682   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8683   switch (Opcode) {
8684   default: llvm_unreachable("no chain equivalent for opcode");
8685   case ISD::FMA:
8686     Opcode = AMDGPUISD::FMA_W_CHAIN;
8687     break;
8688   }
8689 
8690   return DAG.getNode(Opcode, SL, VTList,
8691                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8692                      Flags);
8693 }
8694 
8695 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8696   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8697     return FastLowered;
8698 
8699   SDLoc SL(Op);
8700   SDValue Src0 = Op.getOperand(0);
8701   SDValue Src1 = Op.getOperand(1);
8702 
8703   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8704   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8705 
8706   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8707   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8708 
8709   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8710   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8711 
8712   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8713 }
8714 
8715 // Faster 2.5 ULP division that does not support denormals.
8716 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8717   SDLoc SL(Op);
8718   SDValue LHS = Op.getOperand(1);
8719   SDValue RHS = Op.getOperand(2);
8720 
8721   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8722 
8723   const APFloat K0Val(BitsToFloat(0x6f800000));
8724   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8725 
8726   const APFloat K1Val(BitsToFloat(0x2f800000));
8727   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8728 
8729   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8730 
8731   EVT SetCCVT =
8732     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8733 
8734   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8735 
8736   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8737 
8738   // TODO: Should this propagate fast-math-flags?
8739   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8740 
8741   // rcp does not support denormals.
8742   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8743 
8744   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8745 
8746   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8747 }
8748 
8749 // Returns immediate value for setting the F32 denorm mode when using the
8750 // S_DENORM_MODE instruction.
8751 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8752                                     const SDLoc &SL, const GCNSubtarget *ST) {
8753   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8754   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8755                                 ? FP_DENORM_FLUSH_NONE
8756                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8757 
8758   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8759   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8760 }
8761 
8762 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8763   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8764     return FastLowered;
8765 
8766   // The selection matcher assumes anything with a chain selecting to a
8767   // mayRaiseFPException machine instruction. Since we're introducing a chain
8768   // here, we need to explicitly report nofpexcept for the regular fdiv
8769   // lowering.
8770   SDNodeFlags Flags = Op->getFlags();
8771   Flags.setNoFPExcept(true);
8772 
8773   SDLoc SL(Op);
8774   SDValue LHS = Op.getOperand(0);
8775   SDValue RHS = Op.getOperand(1);
8776 
8777   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8778 
8779   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8780 
8781   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8782                                           {RHS, RHS, LHS}, Flags);
8783   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8784                                         {LHS, RHS, LHS}, Flags);
8785 
8786   // Denominator is scaled to not be denormal, so using rcp is ok.
8787   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8788                                   DenominatorScaled, Flags);
8789   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8790                                      DenominatorScaled, Flags);
8791 
8792   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8793                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8794                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8795   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8796 
8797   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8798 
8799   if (!HasFP32Denormals) {
8800     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8801     // lowering. The chain dependence is insufficient, and we need glue. We do
8802     // not need the glue variants in a strictfp function.
8803 
8804     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8805 
8806     SDNode *EnableDenorm;
8807     if (Subtarget->hasDenormModeInst()) {
8808       const SDValue EnableDenormValue =
8809           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8810 
8811       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8812                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8813     } else {
8814       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8815                                                         SL, MVT::i32);
8816       EnableDenorm =
8817           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8818                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8819     }
8820 
8821     SDValue Ops[3] = {
8822       NegDivScale0,
8823       SDValue(EnableDenorm, 0),
8824       SDValue(EnableDenorm, 1)
8825     };
8826 
8827     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8828   }
8829 
8830   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8831                              ApproxRcp, One, NegDivScale0, Flags);
8832 
8833   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8834                              ApproxRcp, Fma0, Flags);
8835 
8836   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8837                            Fma1, Fma1, Flags);
8838 
8839   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8840                              NumeratorScaled, Mul, Flags);
8841 
8842   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8843                              Fma2, Fma1, Mul, Fma2, Flags);
8844 
8845   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8846                              NumeratorScaled, Fma3, Flags);
8847 
8848   if (!HasFP32Denormals) {
8849     SDNode *DisableDenorm;
8850     if (Subtarget->hasDenormModeInst()) {
8851       const SDValue DisableDenormValue =
8852           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8853 
8854       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8855                                   Fma4.getValue(1), DisableDenormValue,
8856                                   Fma4.getValue(2)).getNode();
8857     } else {
8858       const SDValue DisableDenormValue =
8859           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8860 
8861       DisableDenorm = DAG.getMachineNode(
8862           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8863           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8864     }
8865 
8866     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8867                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8868     DAG.setRoot(OutputChain);
8869   }
8870 
8871   SDValue Scale = NumeratorScaled.getValue(1);
8872   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8873                              {Fma4, Fma1, Fma3, Scale}, Flags);
8874 
8875   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8876 }
8877 
8878 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8879   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
8880     return FastLowered;
8881 
8882   SDLoc SL(Op);
8883   SDValue X = Op.getOperand(0);
8884   SDValue Y = Op.getOperand(1);
8885 
8886   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8887 
8888   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8889 
8890   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8891 
8892   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8893 
8894   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8895 
8896   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8897 
8898   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8899 
8900   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8901 
8902   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8903 
8904   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8905   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8906 
8907   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8908                              NegDivScale0, Mul, DivScale1);
8909 
8910   SDValue Scale;
8911 
8912   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8913     // Workaround a hardware bug on SI where the condition output from div_scale
8914     // is not usable.
8915 
8916     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8917 
8918     // Figure out if the scale to use for div_fmas.
8919     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8920     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8921     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8922     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8923 
8924     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8925     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8926 
8927     SDValue Scale0Hi
8928       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8929     SDValue Scale1Hi
8930       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8931 
8932     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8933     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8934     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8935   } else {
8936     Scale = DivScale1.getValue(1);
8937   }
8938 
8939   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8940                              Fma4, Fma3, Mul, Scale);
8941 
8942   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8943 }
8944 
8945 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8946   EVT VT = Op.getValueType();
8947 
8948   if (VT == MVT::f32)
8949     return LowerFDIV32(Op, DAG);
8950 
8951   if (VT == MVT::f64)
8952     return LowerFDIV64(Op, DAG);
8953 
8954   if (VT == MVT::f16)
8955     return LowerFDIV16(Op, DAG);
8956 
8957   llvm_unreachable("Unexpected type for fdiv");
8958 }
8959 
8960 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8961   SDLoc DL(Op);
8962   StoreSDNode *Store = cast<StoreSDNode>(Op);
8963   EVT VT = Store->getMemoryVT();
8964 
8965   if (VT == MVT::i1) {
8966     return DAG.getTruncStore(Store->getChain(), DL,
8967        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8968        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8969   }
8970 
8971   assert(VT.isVector() &&
8972          Store->getValue().getValueType().getScalarType() == MVT::i32);
8973 
8974   unsigned AS = Store->getAddressSpace();
8975   if (Subtarget->hasLDSMisalignedBug() &&
8976       AS == AMDGPUAS::FLAT_ADDRESS &&
8977       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8978     return SplitVectorStore(Op, DAG);
8979   }
8980 
8981   MachineFunction &MF = DAG.getMachineFunction();
8982   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8983   // If there is a possibility that flat instruction access scratch memory
8984   // then we need to use the same legalization rules we use for private.
8985   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8986       !Subtarget->hasMultiDwordFlatScratchAddressing())
8987     AS = MFI->hasFlatScratchInit() ?
8988          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8989 
8990   unsigned NumElements = VT.getVectorNumElements();
8991   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8992       AS == AMDGPUAS::FLAT_ADDRESS) {
8993     if (NumElements > 4)
8994       return SplitVectorStore(Op, DAG);
8995     // v3 stores not supported on SI.
8996     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8997       return SplitVectorStore(Op, DAG);
8998 
8999     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
9000                                         VT, *Store->getMemOperand()))
9001       return expandUnalignedStore(Store, DAG);
9002 
9003     return SDValue();
9004   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
9005     switch (Subtarget->getMaxPrivateElementSize()) {
9006     case 4:
9007       return scalarizeVectorStore(Store, DAG);
9008     case 8:
9009       if (NumElements > 2)
9010         return SplitVectorStore(Op, DAG);
9011       return SDValue();
9012     case 16:
9013       if (NumElements > 4 ||
9014           (NumElements == 3 && !Subtarget->enableFlatScratch()))
9015         return SplitVectorStore(Op, DAG);
9016       return SDValue();
9017     default:
9018       llvm_unreachable("unsupported private_element_size");
9019     }
9020   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
9021     // Use ds_write_b128 or ds_write_b96 when possible.
9022     if (Subtarget->hasDS96AndDS128() &&
9023         ((Subtarget->useDS128() && VT.getStoreSize() == 16) ||
9024          (VT.getStoreSize() == 12)) &&
9025         allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
9026                                            Store->getAlign()))
9027       return SDValue();
9028 
9029     if (NumElements > 2)
9030       return SplitVectorStore(Op, DAG);
9031 
9032     // SI has a hardware bug in the LDS / GDS bounds checking: if the base
9033     // address is negative, then the instruction is incorrectly treated as
9034     // out-of-bounds even if base + offsets is in bounds. Split vectorized
9035     // stores here to avoid emitting ds_write2_b32. We may re-combine the
9036     // store later in the SILoadStoreOptimizer.
9037     if (!Subtarget->hasUsableDSOffset() &&
9038         NumElements == 2 && VT.getStoreSize() == 8 &&
9039         Store->getAlignment() < 8) {
9040       return SplitVectorStore(Op, DAG);
9041     }
9042 
9043     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
9044                                         VT, *Store->getMemOperand())) {
9045       if (VT.isVector())
9046         return SplitVectorStore(Op, DAG);
9047       return expandUnalignedStore(Store, DAG);
9048     }
9049 
9050     return SDValue();
9051   } else {
9052     llvm_unreachable("unhandled address space");
9053   }
9054 }
9055 
9056 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
9057   SDLoc DL(Op);
9058   EVT VT = Op.getValueType();
9059   SDValue Arg = Op.getOperand(0);
9060   SDValue TrigVal;
9061 
9062   // Propagate fast-math flags so that the multiply we introduce can be folded
9063   // if Arg is already the result of a multiply by constant.
9064   auto Flags = Op->getFlags();
9065 
9066   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
9067 
9068   if (Subtarget->hasTrigReducedRange()) {
9069     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9070     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
9071   } else {
9072     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9073   }
9074 
9075   switch (Op.getOpcode()) {
9076   case ISD::FCOS:
9077     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
9078   case ISD::FSIN:
9079     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
9080   default:
9081     llvm_unreachable("Wrong trig opcode");
9082   }
9083 }
9084 
9085 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9086   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
9087   assert(AtomicNode->isCompareAndSwap());
9088   unsigned AS = AtomicNode->getAddressSpace();
9089 
9090   // No custom lowering required for local address space
9091   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
9092     return Op;
9093 
9094   // Non-local address space requires custom lowering for atomic compare
9095   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
9096   SDLoc DL(Op);
9097   SDValue ChainIn = Op.getOperand(0);
9098   SDValue Addr = Op.getOperand(1);
9099   SDValue Old = Op.getOperand(2);
9100   SDValue New = Op.getOperand(3);
9101   EVT VT = Op.getValueType();
9102   MVT SimpleVT = VT.getSimpleVT();
9103   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
9104 
9105   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
9106   SDValue Ops[] = { ChainIn, Addr, NewOld };
9107 
9108   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
9109                                  Ops, VT, AtomicNode->getMemOperand());
9110 }
9111 
9112 //===----------------------------------------------------------------------===//
9113 // Custom DAG optimizations
9114 //===----------------------------------------------------------------------===//
9115 
9116 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
9117                                                      DAGCombinerInfo &DCI) const {
9118   EVT VT = N->getValueType(0);
9119   EVT ScalarVT = VT.getScalarType();
9120   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
9121     return SDValue();
9122 
9123   SelectionDAG &DAG = DCI.DAG;
9124   SDLoc DL(N);
9125 
9126   SDValue Src = N->getOperand(0);
9127   EVT SrcVT = Src.getValueType();
9128 
9129   // TODO: We could try to match extracting the higher bytes, which would be
9130   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
9131   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
9132   // about in practice.
9133   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
9134     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
9135       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
9136       DCI.AddToWorklist(Cvt.getNode());
9137 
9138       // For the f16 case, fold to a cast to f32 and then cast back to f16.
9139       if (ScalarVT != MVT::f32) {
9140         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
9141                           DAG.getTargetConstant(0, DL, MVT::i32));
9142       }
9143       return Cvt;
9144     }
9145   }
9146 
9147   return SDValue();
9148 }
9149 
9150 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
9151 
9152 // This is a variant of
9153 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
9154 //
9155 // The normal DAG combiner will do this, but only if the add has one use since
9156 // that would increase the number of instructions.
9157 //
9158 // This prevents us from seeing a constant offset that can be folded into a
9159 // memory instruction's addressing mode. If we know the resulting add offset of
9160 // a pointer can be folded into an addressing offset, we can replace the pointer
9161 // operand with the add of new constant offset. This eliminates one of the uses,
9162 // and may allow the remaining use to also be simplified.
9163 //
9164 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
9165                                                unsigned AddrSpace,
9166                                                EVT MemVT,
9167                                                DAGCombinerInfo &DCI) const {
9168   SDValue N0 = N->getOperand(0);
9169   SDValue N1 = N->getOperand(1);
9170 
9171   // We only do this to handle cases where it's profitable when there are
9172   // multiple uses of the add, so defer to the standard combine.
9173   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
9174       N0->hasOneUse())
9175     return SDValue();
9176 
9177   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
9178   if (!CN1)
9179     return SDValue();
9180 
9181   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9182   if (!CAdd)
9183     return SDValue();
9184 
9185   // If the resulting offset is too large, we can't fold it into the addressing
9186   // mode offset.
9187   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
9188   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
9189 
9190   AddrMode AM;
9191   AM.HasBaseReg = true;
9192   AM.BaseOffs = Offset.getSExtValue();
9193   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
9194     return SDValue();
9195 
9196   SelectionDAG &DAG = DCI.DAG;
9197   SDLoc SL(N);
9198   EVT VT = N->getValueType(0);
9199 
9200   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
9201   SDValue COffset = DAG.getConstant(Offset, SL, VT);
9202 
9203   SDNodeFlags Flags;
9204   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
9205                           (N0.getOpcode() == ISD::OR ||
9206                            N0->getFlags().hasNoUnsignedWrap()));
9207 
9208   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
9209 }
9210 
9211 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
9212 /// by the chain and intrinsic ID. Theoretically we would also need to check the
9213 /// specific intrinsic, but they all place the pointer operand first.
9214 static unsigned getBasePtrIndex(const MemSDNode *N) {
9215   switch (N->getOpcode()) {
9216   case ISD::STORE:
9217   case ISD::INTRINSIC_W_CHAIN:
9218   case ISD::INTRINSIC_VOID:
9219     return 2;
9220   default:
9221     return 1;
9222   }
9223 }
9224 
9225 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
9226                                                   DAGCombinerInfo &DCI) const {
9227   SelectionDAG &DAG = DCI.DAG;
9228   SDLoc SL(N);
9229 
9230   unsigned PtrIdx = getBasePtrIndex(N);
9231   SDValue Ptr = N->getOperand(PtrIdx);
9232 
9233   // TODO: We could also do this for multiplies.
9234   if (Ptr.getOpcode() == ISD::SHL) {
9235     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
9236                                           N->getMemoryVT(), DCI);
9237     if (NewPtr) {
9238       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
9239 
9240       NewOps[PtrIdx] = NewPtr;
9241       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
9242     }
9243   }
9244 
9245   return SDValue();
9246 }
9247 
9248 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
9249   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
9250          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
9251          (Opc == ISD::XOR && Val == 0);
9252 }
9253 
9254 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
9255 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
9256 // integer combine opportunities since most 64-bit operations are decomposed
9257 // this way.  TODO: We won't want this for SALU especially if it is an inline
9258 // immediate.
9259 SDValue SITargetLowering::splitBinaryBitConstantOp(
9260   DAGCombinerInfo &DCI,
9261   const SDLoc &SL,
9262   unsigned Opc, SDValue LHS,
9263   const ConstantSDNode *CRHS) const {
9264   uint64_t Val = CRHS->getZExtValue();
9265   uint32_t ValLo = Lo_32(Val);
9266   uint32_t ValHi = Hi_32(Val);
9267   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9268 
9269     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
9270          bitOpWithConstantIsReducible(Opc, ValHi)) ||
9271         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
9272     // If we need to materialize a 64-bit immediate, it will be split up later
9273     // anyway. Avoid creating the harder to understand 64-bit immediate
9274     // materialization.
9275     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
9276   }
9277 
9278   return SDValue();
9279 }
9280 
9281 // Returns true if argument is a boolean value which is not serialized into
9282 // memory or argument and does not require v_cndmask_b32 to be deserialized.
9283 static bool isBoolSGPR(SDValue V) {
9284   if (V.getValueType() != MVT::i1)
9285     return false;
9286   switch (V.getOpcode()) {
9287   default:
9288     break;
9289   case ISD::SETCC:
9290   case AMDGPUISD::FP_CLASS:
9291     return true;
9292   case ISD::AND:
9293   case ISD::OR:
9294   case ISD::XOR:
9295     return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
9296   }
9297   return false;
9298 }
9299 
9300 // If a constant has all zeroes or all ones within each byte return it.
9301 // Otherwise return 0.
9302 static uint32_t getConstantPermuteMask(uint32_t C) {
9303   // 0xff for any zero byte in the mask
9304   uint32_t ZeroByteMask = 0;
9305   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
9306   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
9307   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
9308   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
9309   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
9310   if ((NonZeroByteMask & C) != NonZeroByteMask)
9311     return 0; // Partial bytes selected.
9312   return C;
9313 }
9314 
9315 // Check if a node selects whole bytes from its operand 0 starting at a byte
9316 // boundary while masking the rest. Returns select mask as in the v_perm_b32
9317 // or -1 if not succeeded.
9318 // Note byte select encoding:
9319 // value 0-3 selects corresponding source byte;
9320 // value 0xc selects zero;
9321 // value 0xff selects 0xff.
9322 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
9323   assert(V.getValueSizeInBits() == 32);
9324 
9325   if (V.getNumOperands() != 2)
9326     return ~0;
9327 
9328   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
9329   if (!N1)
9330     return ~0;
9331 
9332   uint32_t C = N1->getZExtValue();
9333 
9334   switch (V.getOpcode()) {
9335   default:
9336     break;
9337   case ISD::AND:
9338     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9339       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
9340     }
9341     break;
9342 
9343   case ISD::OR:
9344     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9345       return (0x03020100 & ~ConstMask) | ConstMask;
9346     }
9347     break;
9348 
9349   case ISD::SHL:
9350     if (C % 8)
9351       return ~0;
9352 
9353     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
9354 
9355   case ISD::SRL:
9356     if (C % 8)
9357       return ~0;
9358 
9359     return uint32_t(0x0c0c0c0c03020100ull >> C);
9360   }
9361 
9362   return ~0;
9363 }
9364 
9365 SDValue SITargetLowering::performAndCombine(SDNode *N,
9366                                             DAGCombinerInfo &DCI) const {
9367   if (DCI.isBeforeLegalize())
9368     return SDValue();
9369 
9370   SelectionDAG &DAG = DCI.DAG;
9371   EVT VT = N->getValueType(0);
9372   SDValue LHS = N->getOperand(0);
9373   SDValue RHS = N->getOperand(1);
9374 
9375 
9376   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9377   if (VT == MVT::i64 && CRHS) {
9378     if (SDValue Split
9379         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9380       return Split;
9381   }
9382 
9383   if (CRHS && VT == MVT::i32) {
9384     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9385     // nb = number of trailing zeroes in mask
9386     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9387     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9388     uint64_t Mask = CRHS->getZExtValue();
9389     unsigned Bits = countPopulation(Mask);
9390     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9391         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9392       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9393         unsigned Shift = CShift->getZExtValue();
9394         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9395         unsigned Offset = NB + Shift;
9396         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9397           SDLoc SL(N);
9398           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9399                                     LHS->getOperand(0),
9400                                     DAG.getConstant(Offset, SL, MVT::i32),
9401                                     DAG.getConstant(Bits, SL, MVT::i32));
9402           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9403           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9404                                     DAG.getValueType(NarrowVT));
9405           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9406                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9407           return Shl;
9408         }
9409       }
9410     }
9411 
9412     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9413     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9414         isa<ConstantSDNode>(LHS.getOperand(2))) {
9415       uint32_t Sel = getConstantPermuteMask(Mask);
9416       if (!Sel)
9417         return SDValue();
9418 
9419       // Select 0xc for all zero bytes
9420       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9421       SDLoc DL(N);
9422       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9423                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9424     }
9425   }
9426 
9427   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9428   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9429   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9430     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9431     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9432 
9433     SDValue X = LHS.getOperand(0);
9434     SDValue Y = RHS.getOperand(0);
9435     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9436       return SDValue();
9437 
9438     if (LCC == ISD::SETO) {
9439       if (X != LHS.getOperand(1))
9440         return SDValue();
9441 
9442       if (RCC == ISD::SETUNE) {
9443         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9444         if (!C1 || !C1->isInfinity() || C1->isNegative())
9445           return SDValue();
9446 
9447         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9448                               SIInstrFlags::N_SUBNORMAL |
9449                               SIInstrFlags::N_ZERO |
9450                               SIInstrFlags::P_ZERO |
9451                               SIInstrFlags::P_SUBNORMAL |
9452                               SIInstrFlags::P_NORMAL;
9453 
9454         static_assert(((~(SIInstrFlags::S_NAN |
9455                           SIInstrFlags::Q_NAN |
9456                           SIInstrFlags::N_INFINITY |
9457                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9458                       "mask not equal");
9459 
9460         SDLoc DL(N);
9461         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9462                            X, DAG.getConstant(Mask, DL, MVT::i32));
9463       }
9464     }
9465   }
9466 
9467   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9468     std::swap(LHS, RHS);
9469 
9470   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9471       RHS.hasOneUse()) {
9472     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9473     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9474     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9475     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9476     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9477         (RHS.getOperand(0) == LHS.getOperand(0) &&
9478          LHS.getOperand(0) == LHS.getOperand(1))) {
9479       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9480       unsigned NewMask = LCC == ISD::SETO ?
9481         Mask->getZExtValue() & ~OrdMask :
9482         Mask->getZExtValue() & OrdMask;
9483 
9484       SDLoc DL(N);
9485       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9486                          DAG.getConstant(NewMask, DL, MVT::i32));
9487     }
9488   }
9489 
9490   if (VT == MVT::i32 &&
9491       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9492     // and x, (sext cc from i1) => select cc, x, 0
9493     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9494       std::swap(LHS, RHS);
9495     if (isBoolSGPR(RHS.getOperand(0)))
9496       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9497                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9498   }
9499 
9500   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9501   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9502   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9503       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9504     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9505     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9506     if (LHSMask != ~0u && RHSMask != ~0u) {
9507       // Canonicalize the expression in an attempt to have fewer unique masks
9508       // and therefore fewer registers used to hold the masks.
9509       if (LHSMask > RHSMask) {
9510         std::swap(LHSMask, RHSMask);
9511         std::swap(LHS, RHS);
9512       }
9513 
9514       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9515       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9516       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9517       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9518 
9519       // Check of we need to combine values from two sources within a byte.
9520       if (!(LHSUsedLanes & RHSUsedLanes) &&
9521           // If we select high and lower word keep it for SDWA.
9522           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9523           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9524         // Each byte in each mask is either selector mask 0-3, or has higher
9525         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9526         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9527         // mask which is not 0xff wins. By anding both masks we have a correct
9528         // result except that 0x0c shall be corrected to give 0x0c only.
9529         uint32_t Mask = LHSMask & RHSMask;
9530         for (unsigned I = 0; I < 32; I += 8) {
9531           uint32_t ByteSel = 0xff << I;
9532           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9533             Mask &= (0x0c << I) & 0xffffffff;
9534         }
9535 
9536         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9537         // or 0x0c.
9538         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9539         SDLoc DL(N);
9540 
9541         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9542                            LHS.getOperand(0), RHS.getOperand(0),
9543                            DAG.getConstant(Sel, DL, MVT::i32));
9544       }
9545     }
9546   }
9547 
9548   return SDValue();
9549 }
9550 
9551 SDValue SITargetLowering::performOrCombine(SDNode *N,
9552                                            DAGCombinerInfo &DCI) const {
9553   SelectionDAG &DAG = DCI.DAG;
9554   SDValue LHS = N->getOperand(0);
9555   SDValue RHS = N->getOperand(1);
9556 
9557   EVT VT = N->getValueType(0);
9558   if (VT == MVT::i1) {
9559     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9560     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9561         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9562       SDValue Src = LHS.getOperand(0);
9563       if (Src != RHS.getOperand(0))
9564         return SDValue();
9565 
9566       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9567       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9568       if (!CLHS || !CRHS)
9569         return SDValue();
9570 
9571       // Only 10 bits are used.
9572       static const uint32_t MaxMask = 0x3ff;
9573 
9574       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9575       SDLoc DL(N);
9576       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9577                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9578     }
9579 
9580     return SDValue();
9581   }
9582 
9583   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9584   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9585       LHS.getOpcode() == AMDGPUISD::PERM &&
9586       isa<ConstantSDNode>(LHS.getOperand(2))) {
9587     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9588     if (!Sel)
9589       return SDValue();
9590 
9591     Sel |= LHS.getConstantOperandVal(2);
9592     SDLoc DL(N);
9593     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9594                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9595   }
9596 
9597   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9598   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9599   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9600       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9601     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9602     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9603     if (LHSMask != ~0u && RHSMask != ~0u) {
9604       // Canonicalize the expression in an attempt to have fewer unique masks
9605       // and therefore fewer registers used to hold the masks.
9606       if (LHSMask > RHSMask) {
9607         std::swap(LHSMask, RHSMask);
9608         std::swap(LHS, RHS);
9609       }
9610 
9611       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9612       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9613       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9614       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9615 
9616       // Check of we need to combine values from two sources within a byte.
9617       if (!(LHSUsedLanes & RHSUsedLanes) &&
9618           // If we select high and lower word keep it for SDWA.
9619           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9620           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9621         // Kill zero bytes selected by other mask. Zero value is 0xc.
9622         LHSMask &= ~RHSUsedLanes;
9623         RHSMask &= ~LHSUsedLanes;
9624         // Add 4 to each active LHS lane
9625         LHSMask |= LHSUsedLanes & 0x04040404;
9626         // Combine masks
9627         uint32_t Sel = LHSMask | RHSMask;
9628         SDLoc DL(N);
9629 
9630         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9631                            LHS.getOperand(0), RHS.getOperand(0),
9632                            DAG.getConstant(Sel, DL, MVT::i32));
9633       }
9634     }
9635   }
9636 
9637   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9638     return SDValue();
9639 
9640   // TODO: This could be a generic combine with a predicate for extracting the
9641   // high half of an integer being free.
9642 
9643   // (or i64:x, (zero_extend i32:y)) ->
9644   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9645   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9646       RHS.getOpcode() != ISD::ZERO_EXTEND)
9647     std::swap(LHS, RHS);
9648 
9649   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9650     SDValue ExtSrc = RHS.getOperand(0);
9651     EVT SrcVT = ExtSrc.getValueType();
9652     if (SrcVT == MVT::i32) {
9653       SDLoc SL(N);
9654       SDValue LowLHS, HiBits;
9655       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9656       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9657 
9658       DCI.AddToWorklist(LowOr.getNode());
9659       DCI.AddToWorklist(HiBits.getNode());
9660 
9661       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9662                                 LowOr, HiBits);
9663       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9664     }
9665   }
9666 
9667   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9668   if (CRHS) {
9669     if (SDValue Split
9670           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR,
9671                                      N->getOperand(0), CRHS))
9672       return Split;
9673   }
9674 
9675   return SDValue();
9676 }
9677 
9678 SDValue SITargetLowering::performXorCombine(SDNode *N,
9679                                             DAGCombinerInfo &DCI) const {
9680   if (SDValue RV = reassociateScalarOps(N, DCI.DAG))
9681     return RV;
9682 
9683   EVT VT = N->getValueType(0);
9684   if (VT != MVT::i64)
9685     return SDValue();
9686 
9687   SDValue LHS = N->getOperand(0);
9688   SDValue RHS = N->getOperand(1);
9689 
9690   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9691   if (CRHS) {
9692     if (SDValue Split
9693           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9694       return Split;
9695   }
9696 
9697   return SDValue();
9698 }
9699 
9700 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9701                                                    DAGCombinerInfo &DCI) const {
9702   if (!Subtarget->has16BitInsts() ||
9703       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9704     return SDValue();
9705 
9706   EVT VT = N->getValueType(0);
9707   if (VT != MVT::i32)
9708     return SDValue();
9709 
9710   SDValue Src = N->getOperand(0);
9711   if (Src.getValueType() != MVT::i16)
9712     return SDValue();
9713 
9714   return SDValue();
9715 }
9716 
9717 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9718                                                         DAGCombinerInfo &DCI)
9719                                                         const {
9720   SDValue Src = N->getOperand(0);
9721   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9722 
9723   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9724       VTSign->getVT() == MVT::i8) ||
9725       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9726       VTSign->getVT() == MVT::i16)) &&
9727       Src.hasOneUse()) {
9728     auto *M = cast<MemSDNode>(Src);
9729     SDValue Ops[] = {
9730       Src.getOperand(0), // Chain
9731       Src.getOperand(1), // rsrc
9732       Src.getOperand(2), // vindex
9733       Src.getOperand(3), // voffset
9734       Src.getOperand(4), // soffset
9735       Src.getOperand(5), // offset
9736       Src.getOperand(6),
9737       Src.getOperand(7)
9738     };
9739     // replace with BUFFER_LOAD_BYTE/SHORT
9740     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9741                                          Src.getOperand(0).getValueType());
9742     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9743                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9744     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9745                                                           ResList,
9746                                                           Ops, M->getMemoryVT(),
9747                                                           M->getMemOperand());
9748     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9749                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9750   }
9751   return SDValue();
9752 }
9753 
9754 SDValue SITargetLowering::performClassCombine(SDNode *N,
9755                                               DAGCombinerInfo &DCI) const {
9756   SelectionDAG &DAG = DCI.DAG;
9757   SDValue Mask = N->getOperand(1);
9758 
9759   // fp_class x, 0 -> false
9760   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9761     if (CMask->isZero())
9762       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9763   }
9764 
9765   if (N->getOperand(0).isUndef())
9766     return DAG.getUNDEF(MVT::i1);
9767 
9768   return SDValue();
9769 }
9770 
9771 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9772                                             DAGCombinerInfo &DCI) const {
9773   EVT VT = N->getValueType(0);
9774   SDValue N0 = N->getOperand(0);
9775 
9776   if (N0.isUndef())
9777     return N0;
9778 
9779   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9780                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9781     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9782                            N->getFlags());
9783   }
9784 
9785   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9786     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9787                            N0.getOperand(0), N->getFlags());
9788   }
9789 
9790   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9791 }
9792 
9793 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9794                                        unsigned MaxDepth) const {
9795   unsigned Opcode = Op.getOpcode();
9796   if (Opcode == ISD::FCANONICALIZE)
9797     return true;
9798 
9799   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9800     auto F = CFP->getValueAPF();
9801     if (F.isNaN() && F.isSignaling())
9802       return false;
9803     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9804   }
9805 
9806   // If source is a result of another standard FP operation it is already in
9807   // canonical form.
9808   if (MaxDepth == 0)
9809     return false;
9810 
9811   switch (Opcode) {
9812   // These will flush denorms if required.
9813   case ISD::FADD:
9814   case ISD::FSUB:
9815   case ISD::FMUL:
9816   case ISD::FCEIL:
9817   case ISD::FFLOOR:
9818   case ISD::FMA:
9819   case ISD::FMAD:
9820   case ISD::FSQRT:
9821   case ISD::FDIV:
9822   case ISD::FREM:
9823   case ISD::FP_ROUND:
9824   case ISD::FP_EXTEND:
9825   case AMDGPUISD::FMUL_LEGACY:
9826   case AMDGPUISD::FMAD_FTZ:
9827   case AMDGPUISD::RCP:
9828   case AMDGPUISD::RSQ:
9829   case AMDGPUISD::RSQ_CLAMP:
9830   case AMDGPUISD::RCP_LEGACY:
9831   case AMDGPUISD::RCP_IFLAG:
9832   case AMDGPUISD::DIV_SCALE:
9833   case AMDGPUISD::DIV_FMAS:
9834   case AMDGPUISD::DIV_FIXUP:
9835   case AMDGPUISD::FRACT:
9836   case AMDGPUISD::LDEXP:
9837   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9838   case AMDGPUISD::CVT_F32_UBYTE0:
9839   case AMDGPUISD::CVT_F32_UBYTE1:
9840   case AMDGPUISD::CVT_F32_UBYTE2:
9841   case AMDGPUISD::CVT_F32_UBYTE3:
9842     return true;
9843 
9844   // It can/will be lowered or combined as a bit operation.
9845   // Need to check their input recursively to handle.
9846   case ISD::FNEG:
9847   case ISD::FABS:
9848   case ISD::FCOPYSIGN:
9849     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9850 
9851   case ISD::FSIN:
9852   case ISD::FCOS:
9853   case ISD::FSINCOS:
9854     return Op.getValueType().getScalarType() != MVT::f16;
9855 
9856   case ISD::FMINNUM:
9857   case ISD::FMAXNUM:
9858   case ISD::FMINNUM_IEEE:
9859   case ISD::FMAXNUM_IEEE:
9860   case AMDGPUISD::CLAMP:
9861   case AMDGPUISD::FMED3:
9862   case AMDGPUISD::FMAX3:
9863   case AMDGPUISD::FMIN3: {
9864     // FIXME: Shouldn't treat the generic operations different based these.
9865     // However, we aren't really required to flush the result from
9866     // minnum/maxnum..
9867 
9868     // snans will be quieted, so we only need to worry about denormals.
9869     if (Subtarget->supportsMinMaxDenormModes() ||
9870         denormalsEnabledForType(DAG, Op.getValueType()))
9871       return true;
9872 
9873     // Flushing may be required.
9874     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9875     // targets need to check their input recursively.
9876 
9877     // FIXME: Does this apply with clamp? It's implemented with max.
9878     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9879       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9880         return false;
9881     }
9882 
9883     return true;
9884   }
9885   case ISD::SELECT: {
9886     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9887            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9888   }
9889   case ISD::BUILD_VECTOR: {
9890     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9891       SDValue SrcOp = Op.getOperand(i);
9892       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9893         return false;
9894     }
9895 
9896     return true;
9897   }
9898   case ISD::EXTRACT_VECTOR_ELT:
9899   case ISD::EXTRACT_SUBVECTOR: {
9900     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9901   }
9902   case ISD::INSERT_VECTOR_ELT: {
9903     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9904            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9905   }
9906   case ISD::UNDEF:
9907     // Could be anything.
9908     return false;
9909 
9910   case ISD::BITCAST:
9911     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9912   case ISD::TRUNCATE: {
9913     // Hack round the mess we make when legalizing extract_vector_elt
9914     if (Op.getValueType() == MVT::i16) {
9915       SDValue TruncSrc = Op.getOperand(0);
9916       if (TruncSrc.getValueType() == MVT::i32 &&
9917           TruncSrc.getOpcode() == ISD::BITCAST &&
9918           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9919         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9920       }
9921     }
9922     return false;
9923   }
9924   case ISD::INTRINSIC_WO_CHAIN: {
9925     unsigned IntrinsicID
9926       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9927     // TODO: Handle more intrinsics
9928     switch (IntrinsicID) {
9929     case Intrinsic::amdgcn_cvt_pkrtz:
9930     case Intrinsic::amdgcn_cubeid:
9931     case Intrinsic::amdgcn_frexp_mant:
9932     case Intrinsic::amdgcn_fdot2:
9933     case Intrinsic::amdgcn_rcp:
9934     case Intrinsic::amdgcn_rsq:
9935     case Intrinsic::amdgcn_rsq_clamp:
9936     case Intrinsic::amdgcn_rcp_legacy:
9937     case Intrinsic::amdgcn_rsq_legacy:
9938     case Intrinsic::amdgcn_trig_preop:
9939       return true;
9940     default:
9941       break;
9942     }
9943 
9944     LLVM_FALLTHROUGH;
9945   }
9946   default:
9947     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9948            DAG.isKnownNeverSNaN(Op);
9949   }
9950 
9951   llvm_unreachable("invalid operation");
9952 }
9953 
9954 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
9955                                        unsigned MaxDepth) const {
9956   MachineRegisterInfo &MRI = MF.getRegInfo();
9957   MachineInstr *MI = MRI.getVRegDef(Reg);
9958   unsigned Opcode = MI->getOpcode();
9959 
9960   if (Opcode == AMDGPU::G_FCANONICALIZE)
9961     return true;
9962 
9963   Optional<FPValueAndVReg> FCR;
9964   // Constant splat (can be padded with undef) or scalar constant.
9965   if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) {
9966     if (FCR->Value.isSignaling())
9967       return false;
9968     return !FCR->Value.isDenormal() ||
9969            denormalsEnabledForType(MRI.getType(FCR->VReg), MF);
9970   }
9971 
9972   if (MaxDepth == 0)
9973     return false;
9974 
9975   switch (Opcode) {
9976   case AMDGPU::G_FMINNUM_IEEE:
9977   case AMDGPU::G_FMAXNUM_IEEE: {
9978     if (Subtarget->supportsMinMaxDenormModes() ||
9979         denormalsEnabledForType(MRI.getType(Reg), MF))
9980       return true;
9981     for (const MachineOperand &MO : llvm::drop_begin(MI->operands()))
9982       if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1))
9983         return false;
9984     return true;
9985   }
9986   default:
9987     return denormalsEnabledForType(MRI.getType(Reg), MF) &&
9988            isKnownNeverSNaN(Reg, MRI);
9989   }
9990 
9991   llvm_unreachable("invalid operation");
9992 }
9993 
9994 // Constant fold canonicalize.
9995 SDValue SITargetLowering::getCanonicalConstantFP(
9996   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9997   // Flush denormals to 0 if not enabled.
9998   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9999     return DAG.getConstantFP(0.0, SL, VT);
10000 
10001   if (C.isNaN()) {
10002     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
10003     if (C.isSignaling()) {
10004       // Quiet a signaling NaN.
10005       // FIXME: Is this supposed to preserve payload bits?
10006       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
10007     }
10008 
10009     // Make sure it is the canonical NaN bitpattern.
10010     //
10011     // TODO: Can we use -1 as the canonical NaN value since it's an inline
10012     // immediate?
10013     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
10014       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
10015   }
10016 
10017   // Already canonical.
10018   return DAG.getConstantFP(C, SL, VT);
10019 }
10020 
10021 static bool vectorEltWillFoldAway(SDValue Op) {
10022   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
10023 }
10024 
10025 SDValue SITargetLowering::performFCanonicalizeCombine(
10026   SDNode *N,
10027   DAGCombinerInfo &DCI) const {
10028   SelectionDAG &DAG = DCI.DAG;
10029   SDValue N0 = N->getOperand(0);
10030   EVT VT = N->getValueType(0);
10031 
10032   // fcanonicalize undef -> qnan
10033   if (N0.isUndef()) {
10034     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
10035     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
10036   }
10037 
10038   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
10039     EVT VT = N->getValueType(0);
10040     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
10041   }
10042 
10043   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
10044   //                                                   (fcanonicalize k)
10045   //
10046   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
10047 
10048   // TODO: This could be better with wider vectors that will be split to v2f16,
10049   // and to consider uses since there aren't that many packed operations.
10050   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
10051       isTypeLegal(MVT::v2f16)) {
10052     SDLoc SL(N);
10053     SDValue NewElts[2];
10054     SDValue Lo = N0.getOperand(0);
10055     SDValue Hi = N0.getOperand(1);
10056     EVT EltVT = Lo.getValueType();
10057 
10058     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
10059       for (unsigned I = 0; I != 2; ++I) {
10060         SDValue Op = N0.getOperand(I);
10061         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
10062           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
10063                                               CFP->getValueAPF());
10064         } else if (Op.isUndef()) {
10065           // Handled below based on what the other operand is.
10066           NewElts[I] = Op;
10067         } else {
10068           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
10069         }
10070       }
10071 
10072       // If one half is undef, and one is constant, prefer a splat vector rather
10073       // than the normal qNaN. If it's a register, prefer 0.0 since that's
10074       // cheaper to use and may be free with a packed operation.
10075       if (NewElts[0].isUndef()) {
10076         if (isa<ConstantFPSDNode>(NewElts[1]))
10077           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
10078             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
10079       }
10080 
10081       if (NewElts[1].isUndef()) {
10082         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
10083           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
10084       }
10085 
10086       return DAG.getBuildVector(VT, SL, NewElts);
10087     }
10088   }
10089 
10090   unsigned SrcOpc = N0.getOpcode();
10091 
10092   // If it's free to do so, push canonicalizes further up the source, which may
10093   // find a canonical source.
10094   //
10095   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
10096   // sNaNs.
10097   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
10098     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10099     if (CRHS && N0.hasOneUse()) {
10100       SDLoc SL(N);
10101       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
10102                                    N0.getOperand(0));
10103       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
10104       DCI.AddToWorklist(Canon0.getNode());
10105 
10106       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
10107     }
10108   }
10109 
10110   return isCanonicalized(DAG, N0) ? N0 : SDValue();
10111 }
10112 
10113 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
10114   switch (Opc) {
10115   case ISD::FMAXNUM:
10116   case ISD::FMAXNUM_IEEE:
10117     return AMDGPUISD::FMAX3;
10118   case ISD::SMAX:
10119     return AMDGPUISD::SMAX3;
10120   case ISD::UMAX:
10121     return AMDGPUISD::UMAX3;
10122   case ISD::FMINNUM:
10123   case ISD::FMINNUM_IEEE:
10124     return AMDGPUISD::FMIN3;
10125   case ISD::SMIN:
10126     return AMDGPUISD::SMIN3;
10127   case ISD::UMIN:
10128     return AMDGPUISD::UMIN3;
10129   default:
10130     llvm_unreachable("Not a min/max opcode");
10131   }
10132 }
10133 
10134 SDValue SITargetLowering::performIntMed3ImmCombine(
10135   SelectionDAG &DAG, const SDLoc &SL,
10136   SDValue Op0, SDValue Op1, bool Signed) const {
10137   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
10138   if (!K1)
10139     return SDValue();
10140 
10141   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
10142   if (!K0)
10143     return SDValue();
10144 
10145   if (Signed) {
10146     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
10147       return SDValue();
10148   } else {
10149     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
10150       return SDValue();
10151   }
10152 
10153   EVT VT = K0->getValueType(0);
10154   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
10155   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
10156     return DAG.getNode(Med3Opc, SL, VT,
10157                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
10158   }
10159 
10160   // If there isn't a 16-bit med3 operation, convert to 32-bit.
10161   if (VT == MVT::i16) {
10162     MVT NVT = MVT::i32;
10163     unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
10164 
10165     SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
10166     SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
10167     SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
10168 
10169     SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
10170     return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
10171   }
10172 
10173   return SDValue();
10174 }
10175 
10176 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
10177   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
10178     return C;
10179 
10180   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
10181     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
10182       return C;
10183   }
10184 
10185   return nullptr;
10186 }
10187 
10188 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
10189                                                   const SDLoc &SL,
10190                                                   SDValue Op0,
10191                                                   SDValue Op1) const {
10192   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
10193   if (!K1)
10194     return SDValue();
10195 
10196   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
10197   if (!K0)
10198     return SDValue();
10199 
10200   // Ordered >= (although NaN inputs should have folded away by now).
10201   if (K0->getValueAPF() > K1->getValueAPF())
10202     return SDValue();
10203 
10204   const MachineFunction &MF = DAG.getMachineFunction();
10205   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10206 
10207   // TODO: Check IEEE bit enabled?
10208   EVT VT = Op0.getValueType();
10209   if (Info->getMode().DX10Clamp) {
10210     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
10211     // hardware fmed3 behavior converting to a min.
10212     // FIXME: Should this be allowing -0.0?
10213     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
10214       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
10215   }
10216 
10217   // med3 for f16 is only available on gfx9+, and not available for v2f16.
10218   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
10219     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
10220     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
10221     // then give the other result, which is different from med3 with a NaN
10222     // input.
10223     SDValue Var = Op0.getOperand(0);
10224     if (!DAG.isKnownNeverSNaN(Var))
10225       return SDValue();
10226 
10227     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10228 
10229     if ((!K0->hasOneUse() ||
10230          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
10231         (!K1->hasOneUse() ||
10232          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
10233       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
10234                          Var, SDValue(K0, 0), SDValue(K1, 0));
10235     }
10236   }
10237 
10238   return SDValue();
10239 }
10240 
10241 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
10242                                                DAGCombinerInfo &DCI) const {
10243   SelectionDAG &DAG = DCI.DAG;
10244 
10245   EVT VT = N->getValueType(0);
10246   unsigned Opc = N->getOpcode();
10247   SDValue Op0 = N->getOperand(0);
10248   SDValue Op1 = N->getOperand(1);
10249 
10250   // Only do this if the inner op has one use since this will just increases
10251   // register pressure for no benefit.
10252 
10253   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
10254       !VT.isVector() &&
10255       (VT == MVT::i32 || VT == MVT::f32 ||
10256        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
10257     // max(max(a, b), c) -> max3(a, b, c)
10258     // min(min(a, b), c) -> min3(a, b, c)
10259     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
10260       SDLoc DL(N);
10261       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10262                          DL,
10263                          N->getValueType(0),
10264                          Op0.getOperand(0),
10265                          Op0.getOperand(1),
10266                          Op1);
10267     }
10268 
10269     // Try commuted.
10270     // max(a, max(b, c)) -> max3(a, b, c)
10271     // min(a, min(b, c)) -> min3(a, b, c)
10272     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
10273       SDLoc DL(N);
10274       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10275                          DL,
10276                          N->getValueType(0),
10277                          Op0,
10278                          Op1.getOperand(0),
10279                          Op1.getOperand(1));
10280     }
10281   }
10282 
10283   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
10284   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
10285     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
10286       return Med3;
10287   }
10288 
10289   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
10290     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
10291       return Med3;
10292   }
10293 
10294   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
10295   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
10296        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
10297        (Opc == AMDGPUISD::FMIN_LEGACY &&
10298         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
10299       (VT == MVT::f32 || VT == MVT::f64 ||
10300        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
10301        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
10302       Op0.hasOneUse()) {
10303     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
10304       return Res;
10305   }
10306 
10307   return SDValue();
10308 }
10309 
10310 static bool isClampZeroToOne(SDValue A, SDValue B) {
10311   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
10312     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
10313       // FIXME: Should this be allowing -0.0?
10314       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
10315              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
10316     }
10317   }
10318 
10319   return false;
10320 }
10321 
10322 // FIXME: Should only worry about snans for version with chain.
10323 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
10324                                               DAGCombinerInfo &DCI) const {
10325   EVT VT = N->getValueType(0);
10326   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
10327   // NaNs. With a NaN input, the order of the operands may change the result.
10328 
10329   SelectionDAG &DAG = DCI.DAG;
10330   SDLoc SL(N);
10331 
10332   SDValue Src0 = N->getOperand(0);
10333   SDValue Src1 = N->getOperand(1);
10334   SDValue Src2 = N->getOperand(2);
10335 
10336   if (isClampZeroToOne(Src0, Src1)) {
10337     // const_a, const_b, x -> clamp is safe in all cases including signaling
10338     // nans.
10339     // FIXME: Should this be allowing -0.0?
10340     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
10341   }
10342 
10343   const MachineFunction &MF = DAG.getMachineFunction();
10344   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10345 
10346   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
10347   // handling no dx10-clamp?
10348   if (Info->getMode().DX10Clamp) {
10349     // If NaNs is clamped to 0, we are free to reorder the inputs.
10350 
10351     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10352       std::swap(Src0, Src1);
10353 
10354     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10355       std::swap(Src1, Src2);
10356 
10357     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10358       std::swap(Src0, Src1);
10359 
10360     if (isClampZeroToOne(Src1, Src2))
10361       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10362   }
10363 
10364   return SDValue();
10365 }
10366 
10367 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10368                                                  DAGCombinerInfo &DCI) const {
10369   SDValue Src0 = N->getOperand(0);
10370   SDValue Src1 = N->getOperand(1);
10371   if (Src0.isUndef() && Src1.isUndef())
10372     return DCI.DAG.getUNDEF(N->getValueType(0));
10373   return SDValue();
10374 }
10375 
10376 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10377 // expanded into a set of cmp/select instructions.
10378 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10379                                                 unsigned NumElem,
10380                                                 bool IsDivergentIdx) {
10381   if (UseDivergentRegisterIndexing)
10382     return false;
10383 
10384   unsigned VecSize = EltSize * NumElem;
10385 
10386   // Sub-dword vectors of size 2 dword or less have better implementation.
10387   if (VecSize <= 64 && EltSize < 32)
10388     return false;
10389 
10390   // Always expand the rest of sub-dword instructions, otherwise it will be
10391   // lowered via memory.
10392   if (EltSize < 32)
10393     return true;
10394 
10395   // Always do this if var-idx is divergent, otherwise it will become a loop.
10396   if (IsDivergentIdx)
10397     return true;
10398 
10399   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10400   unsigned NumInsts = NumElem /* Number of compares */ +
10401                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10402   return NumInsts <= 16;
10403 }
10404 
10405 static bool shouldExpandVectorDynExt(SDNode *N) {
10406   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10407   if (isa<ConstantSDNode>(Idx))
10408     return false;
10409 
10410   SDValue Vec = N->getOperand(0);
10411   EVT VecVT = Vec.getValueType();
10412   EVT EltVT = VecVT.getVectorElementType();
10413   unsigned EltSize = EltVT.getSizeInBits();
10414   unsigned NumElem = VecVT.getVectorNumElements();
10415 
10416   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
10417                                                     Idx->isDivergent());
10418 }
10419 
10420 SDValue SITargetLowering::performExtractVectorEltCombine(
10421   SDNode *N, DAGCombinerInfo &DCI) const {
10422   SDValue Vec = N->getOperand(0);
10423   SelectionDAG &DAG = DCI.DAG;
10424 
10425   EVT VecVT = Vec.getValueType();
10426   EVT EltVT = VecVT.getVectorElementType();
10427 
10428   if ((Vec.getOpcode() == ISD::FNEG ||
10429        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10430     SDLoc SL(N);
10431     EVT EltVT = N->getValueType(0);
10432     SDValue Idx = N->getOperand(1);
10433     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10434                               Vec.getOperand(0), Idx);
10435     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10436   }
10437 
10438   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10439   //    =>
10440   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10441   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10442   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10443   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10444     SDLoc SL(N);
10445     EVT EltVT = N->getValueType(0);
10446     SDValue Idx = N->getOperand(1);
10447     unsigned Opc = Vec.getOpcode();
10448 
10449     switch(Opc) {
10450     default:
10451       break;
10452       // TODO: Support other binary operations.
10453     case ISD::FADD:
10454     case ISD::FSUB:
10455     case ISD::FMUL:
10456     case ISD::ADD:
10457     case ISD::UMIN:
10458     case ISD::UMAX:
10459     case ISD::SMIN:
10460     case ISD::SMAX:
10461     case ISD::FMAXNUM:
10462     case ISD::FMINNUM:
10463     case ISD::FMAXNUM_IEEE:
10464     case ISD::FMINNUM_IEEE: {
10465       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10466                                  Vec.getOperand(0), Idx);
10467       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10468                                  Vec.getOperand(1), Idx);
10469 
10470       DCI.AddToWorklist(Elt0.getNode());
10471       DCI.AddToWorklist(Elt1.getNode());
10472       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10473     }
10474     }
10475   }
10476 
10477   unsigned VecSize = VecVT.getSizeInBits();
10478   unsigned EltSize = EltVT.getSizeInBits();
10479 
10480   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10481   if (::shouldExpandVectorDynExt(N)) {
10482     SDLoc SL(N);
10483     SDValue Idx = N->getOperand(1);
10484     SDValue V;
10485     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10486       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10487       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10488       if (I == 0)
10489         V = Elt;
10490       else
10491         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10492     }
10493     return V;
10494   }
10495 
10496   if (!DCI.isBeforeLegalize())
10497     return SDValue();
10498 
10499   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10500   // elements. This exposes more load reduction opportunities by replacing
10501   // multiple small extract_vector_elements with a single 32-bit extract.
10502   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10503   if (isa<MemSDNode>(Vec) &&
10504       EltSize <= 16 &&
10505       EltVT.isByteSized() &&
10506       VecSize > 32 &&
10507       VecSize % 32 == 0 &&
10508       Idx) {
10509     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10510 
10511     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10512     unsigned EltIdx = BitIndex / 32;
10513     unsigned LeftoverBitIdx = BitIndex % 32;
10514     SDLoc SL(N);
10515 
10516     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10517     DCI.AddToWorklist(Cast.getNode());
10518 
10519     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10520                               DAG.getConstant(EltIdx, SL, MVT::i32));
10521     DCI.AddToWorklist(Elt.getNode());
10522     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10523                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10524     DCI.AddToWorklist(Srl.getNode());
10525 
10526     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10527     DCI.AddToWorklist(Trunc.getNode());
10528     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10529   }
10530 
10531   return SDValue();
10532 }
10533 
10534 SDValue
10535 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10536                                                 DAGCombinerInfo &DCI) const {
10537   SDValue Vec = N->getOperand(0);
10538   SDValue Idx = N->getOperand(2);
10539   EVT VecVT = Vec.getValueType();
10540   EVT EltVT = VecVT.getVectorElementType();
10541 
10542   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10543   // => BUILD_VECTOR n x select (e, const-idx)
10544   if (!::shouldExpandVectorDynExt(N))
10545     return SDValue();
10546 
10547   SelectionDAG &DAG = DCI.DAG;
10548   SDLoc SL(N);
10549   SDValue Ins = N->getOperand(1);
10550   EVT IdxVT = Idx.getValueType();
10551 
10552   SmallVector<SDValue, 16> Ops;
10553   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10554     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10555     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10556     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10557     Ops.push_back(V);
10558   }
10559 
10560   return DAG.getBuildVector(VecVT, SL, Ops);
10561 }
10562 
10563 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10564                                           const SDNode *N0,
10565                                           const SDNode *N1) const {
10566   EVT VT = N0->getValueType(0);
10567 
10568   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10569   // support denormals ever.
10570   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10571        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10572         getSubtarget()->hasMadF16())) &&
10573        isOperationLegal(ISD::FMAD, VT))
10574     return ISD::FMAD;
10575 
10576   const TargetOptions &Options = DAG.getTarget().Options;
10577   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10578        (N0->getFlags().hasAllowContract() &&
10579         N1->getFlags().hasAllowContract())) &&
10580       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10581     return ISD::FMA;
10582   }
10583 
10584   return 0;
10585 }
10586 
10587 // For a reassociatable opcode perform:
10588 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10589 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10590                                                SelectionDAG &DAG) const {
10591   EVT VT = N->getValueType(0);
10592   if (VT != MVT::i32 && VT != MVT::i64)
10593     return SDValue();
10594 
10595   if (DAG.isBaseWithConstantOffset(SDValue(N, 0)))
10596     return SDValue();
10597 
10598   unsigned Opc = N->getOpcode();
10599   SDValue Op0 = N->getOperand(0);
10600   SDValue Op1 = N->getOperand(1);
10601 
10602   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10603     return SDValue();
10604 
10605   if (Op0->isDivergent())
10606     std::swap(Op0, Op1);
10607 
10608   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10609     return SDValue();
10610 
10611   SDValue Op2 = Op1.getOperand(1);
10612   Op1 = Op1.getOperand(0);
10613   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10614     return SDValue();
10615 
10616   if (Op1->isDivergent())
10617     std::swap(Op1, Op2);
10618 
10619   SDLoc SL(N);
10620   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10621   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10622 }
10623 
10624 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10625                            EVT VT,
10626                            SDValue N0, SDValue N1, SDValue N2,
10627                            bool Signed) {
10628   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10629   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10630   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10631   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10632 }
10633 
10634 SDValue SITargetLowering::performAddCombine(SDNode *N,
10635                                             DAGCombinerInfo &DCI) const {
10636   SelectionDAG &DAG = DCI.DAG;
10637   EVT VT = N->getValueType(0);
10638   SDLoc SL(N);
10639   SDValue LHS = N->getOperand(0);
10640   SDValue RHS = N->getOperand(1);
10641 
10642   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10643       && Subtarget->hasMad64_32() &&
10644       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10645       VT.getScalarSizeInBits() <= 64) {
10646     if (LHS.getOpcode() != ISD::MUL)
10647       std::swap(LHS, RHS);
10648 
10649     SDValue MulLHS = LHS.getOperand(0);
10650     SDValue MulRHS = LHS.getOperand(1);
10651     SDValue AddRHS = RHS;
10652 
10653     // TODO: Maybe restrict if SGPR inputs.
10654     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10655         numBitsUnsigned(MulRHS, DAG) <= 32) {
10656       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10657       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10658       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10659       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10660     }
10661 
10662     if (numBitsSigned(MulLHS, DAG) <= 32 && numBitsSigned(MulRHS, DAG) <= 32) {
10663       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10664       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10665       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10666       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10667     }
10668 
10669     return SDValue();
10670   }
10671 
10672   if (SDValue V = reassociateScalarOps(N, DAG)) {
10673     return V;
10674   }
10675 
10676   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10677     return SDValue();
10678 
10679   // add x, zext (setcc) => addcarry x, 0, setcc
10680   // add x, sext (setcc) => subcarry x, 0, setcc
10681   unsigned Opc = LHS.getOpcode();
10682   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10683       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10684     std::swap(RHS, LHS);
10685 
10686   Opc = RHS.getOpcode();
10687   switch (Opc) {
10688   default: break;
10689   case ISD::ZERO_EXTEND:
10690   case ISD::SIGN_EXTEND:
10691   case ISD::ANY_EXTEND: {
10692     auto Cond = RHS.getOperand(0);
10693     // If this won't be a real VOPC output, we would still need to insert an
10694     // extra instruction anyway.
10695     if (!isBoolSGPR(Cond))
10696       break;
10697     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10698     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10699     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10700     return DAG.getNode(Opc, SL, VTList, Args);
10701   }
10702   case ISD::ADDCARRY: {
10703     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10704     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10705     if (!C || C->getZExtValue() != 0) break;
10706     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10707     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10708   }
10709   }
10710   return SDValue();
10711 }
10712 
10713 SDValue SITargetLowering::performSubCombine(SDNode *N,
10714                                             DAGCombinerInfo &DCI) const {
10715   SelectionDAG &DAG = DCI.DAG;
10716   EVT VT = N->getValueType(0);
10717 
10718   if (VT != MVT::i32)
10719     return SDValue();
10720 
10721   SDLoc SL(N);
10722   SDValue LHS = N->getOperand(0);
10723   SDValue RHS = N->getOperand(1);
10724 
10725   // sub x, zext (setcc) => subcarry x, 0, setcc
10726   // sub x, sext (setcc) => addcarry x, 0, setcc
10727   unsigned Opc = RHS.getOpcode();
10728   switch (Opc) {
10729   default: break;
10730   case ISD::ZERO_EXTEND:
10731   case ISD::SIGN_EXTEND:
10732   case ISD::ANY_EXTEND: {
10733     auto Cond = RHS.getOperand(0);
10734     // If this won't be a real VOPC output, we would still need to insert an
10735     // extra instruction anyway.
10736     if (!isBoolSGPR(Cond))
10737       break;
10738     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10739     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10740     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10741     return DAG.getNode(Opc, SL, VTList, Args);
10742   }
10743   }
10744 
10745   if (LHS.getOpcode() == ISD::SUBCARRY) {
10746     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10747     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10748     if (!C || !C->isZero())
10749       return SDValue();
10750     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10751     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10752   }
10753   return SDValue();
10754 }
10755 
10756 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10757   DAGCombinerInfo &DCI) const {
10758 
10759   if (N->getValueType(0) != MVT::i32)
10760     return SDValue();
10761 
10762   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10763   if (!C || C->getZExtValue() != 0)
10764     return SDValue();
10765 
10766   SelectionDAG &DAG = DCI.DAG;
10767   SDValue LHS = N->getOperand(0);
10768 
10769   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10770   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10771   unsigned LHSOpc = LHS.getOpcode();
10772   unsigned Opc = N->getOpcode();
10773   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10774       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10775     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10776     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10777   }
10778   return SDValue();
10779 }
10780 
10781 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10782                                              DAGCombinerInfo &DCI) const {
10783   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10784     return SDValue();
10785 
10786   SelectionDAG &DAG = DCI.DAG;
10787   EVT VT = N->getValueType(0);
10788 
10789   SDLoc SL(N);
10790   SDValue LHS = N->getOperand(0);
10791   SDValue RHS = N->getOperand(1);
10792 
10793   // These should really be instruction patterns, but writing patterns with
10794   // source modifiers is a pain.
10795 
10796   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10797   if (LHS.getOpcode() == ISD::FADD) {
10798     SDValue A = LHS.getOperand(0);
10799     if (A == LHS.getOperand(1)) {
10800       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10801       if (FusedOp != 0) {
10802         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10803         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10804       }
10805     }
10806   }
10807 
10808   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10809   if (RHS.getOpcode() == ISD::FADD) {
10810     SDValue A = RHS.getOperand(0);
10811     if (A == RHS.getOperand(1)) {
10812       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10813       if (FusedOp != 0) {
10814         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10815         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10816       }
10817     }
10818   }
10819 
10820   return SDValue();
10821 }
10822 
10823 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10824                                              DAGCombinerInfo &DCI) const {
10825   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10826     return SDValue();
10827 
10828   SelectionDAG &DAG = DCI.DAG;
10829   SDLoc SL(N);
10830   EVT VT = N->getValueType(0);
10831   assert(!VT.isVector());
10832 
10833   // Try to get the fneg to fold into the source modifier. This undoes generic
10834   // DAG combines and folds them into the mad.
10835   //
10836   // Only do this if we are not trying to support denormals. v_mad_f32 does
10837   // not support denormals ever.
10838   SDValue LHS = N->getOperand(0);
10839   SDValue RHS = N->getOperand(1);
10840   if (LHS.getOpcode() == ISD::FADD) {
10841     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10842     SDValue A = LHS.getOperand(0);
10843     if (A == LHS.getOperand(1)) {
10844       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10845       if (FusedOp != 0){
10846         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10847         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10848 
10849         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10850       }
10851     }
10852   }
10853 
10854   if (RHS.getOpcode() == ISD::FADD) {
10855     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10856 
10857     SDValue A = RHS.getOperand(0);
10858     if (A == RHS.getOperand(1)) {
10859       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10860       if (FusedOp != 0){
10861         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10862         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10863       }
10864     }
10865   }
10866 
10867   return SDValue();
10868 }
10869 
10870 SDValue SITargetLowering::performFMACombine(SDNode *N,
10871                                             DAGCombinerInfo &DCI) const {
10872   SelectionDAG &DAG = DCI.DAG;
10873   EVT VT = N->getValueType(0);
10874   SDLoc SL(N);
10875 
10876   if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
10877     return SDValue();
10878 
10879   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10880   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10881   SDValue Op1 = N->getOperand(0);
10882   SDValue Op2 = N->getOperand(1);
10883   SDValue FMA = N->getOperand(2);
10884 
10885   if (FMA.getOpcode() != ISD::FMA ||
10886       Op1.getOpcode() != ISD::FP_EXTEND ||
10887       Op2.getOpcode() != ISD::FP_EXTEND)
10888     return SDValue();
10889 
10890   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10891   // regardless of the denorm mode setting. Therefore,
10892   // unsafe-fp-math/fp-contract is sufficient to allow generating fdot2.
10893   const TargetOptions &Options = DAG.getTarget().Options;
10894   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10895       (N->getFlags().hasAllowContract() &&
10896        FMA->getFlags().hasAllowContract())) {
10897     Op1 = Op1.getOperand(0);
10898     Op2 = Op2.getOperand(0);
10899     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10900         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10901       return SDValue();
10902 
10903     SDValue Vec1 = Op1.getOperand(0);
10904     SDValue Idx1 = Op1.getOperand(1);
10905     SDValue Vec2 = Op2.getOperand(0);
10906 
10907     SDValue FMAOp1 = FMA.getOperand(0);
10908     SDValue FMAOp2 = FMA.getOperand(1);
10909     SDValue FMAAcc = FMA.getOperand(2);
10910 
10911     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10912         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10913       return SDValue();
10914 
10915     FMAOp1 = FMAOp1.getOperand(0);
10916     FMAOp2 = FMAOp2.getOperand(0);
10917     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10918         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10919       return SDValue();
10920 
10921     SDValue Vec3 = FMAOp1.getOperand(0);
10922     SDValue Vec4 = FMAOp2.getOperand(0);
10923     SDValue Idx2 = FMAOp1.getOperand(1);
10924 
10925     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10926         // Idx1 and Idx2 cannot be the same.
10927         Idx1 == Idx2)
10928       return SDValue();
10929 
10930     if (Vec1 == Vec2 || Vec3 == Vec4)
10931       return SDValue();
10932 
10933     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10934       return SDValue();
10935 
10936     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10937         (Vec1 == Vec4 && Vec2 == Vec3)) {
10938       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10939                          DAG.getTargetConstant(0, SL, MVT::i1));
10940     }
10941   }
10942   return SDValue();
10943 }
10944 
10945 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10946                                               DAGCombinerInfo &DCI) const {
10947   SelectionDAG &DAG = DCI.DAG;
10948   SDLoc SL(N);
10949 
10950   SDValue LHS = N->getOperand(0);
10951   SDValue RHS = N->getOperand(1);
10952   EVT VT = LHS.getValueType();
10953   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10954 
10955   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10956   if (!CRHS) {
10957     CRHS = dyn_cast<ConstantSDNode>(LHS);
10958     if (CRHS) {
10959       std::swap(LHS, RHS);
10960       CC = getSetCCSwappedOperands(CC);
10961     }
10962   }
10963 
10964   if (CRHS) {
10965     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10966         isBoolSGPR(LHS.getOperand(0))) {
10967       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10968       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10969       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10970       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10971       if ((CRHS->isAllOnes() &&
10972            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10973           (CRHS->isZero() &&
10974            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10975         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10976                            DAG.getConstant(-1, SL, MVT::i1));
10977       if ((CRHS->isAllOnes() &&
10978            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10979           (CRHS->isZero() &&
10980            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10981         return LHS.getOperand(0);
10982     }
10983 
10984     const APInt &CRHSVal = CRHS->getAPIntValue();
10985     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10986         LHS.getOpcode() == ISD::SELECT &&
10987         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10988         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10989         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10990         isBoolSGPR(LHS.getOperand(0))) {
10991       // Given CT != FT:
10992       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10993       // setcc (select cc, CT, CF), CF, ne => cc
10994       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10995       // setcc (select cc, CT, CF), CT, eq => cc
10996       const APInt &CT = LHS.getConstantOperandAPInt(1);
10997       const APInt &CF = LHS.getConstantOperandAPInt(2);
10998 
10999       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
11000           (CT == CRHSVal && CC == ISD::SETNE))
11001         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
11002                            DAG.getConstant(-1, SL, MVT::i1));
11003       if ((CF == CRHSVal && CC == ISD::SETNE) ||
11004           (CT == CRHSVal && CC == ISD::SETEQ))
11005         return LHS.getOperand(0);
11006     }
11007   }
11008 
11009   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
11010                                            VT != MVT::f16))
11011     return SDValue();
11012 
11013   // Match isinf/isfinite pattern
11014   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
11015   // (fcmp one (fabs x), inf) -> (fp_class x,
11016   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
11017   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
11018     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
11019     if (!CRHS)
11020       return SDValue();
11021 
11022     const APFloat &APF = CRHS->getValueAPF();
11023     if (APF.isInfinity() && !APF.isNegative()) {
11024       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
11025                                  SIInstrFlags::N_INFINITY;
11026       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
11027                                     SIInstrFlags::P_ZERO |
11028                                     SIInstrFlags::N_NORMAL |
11029                                     SIInstrFlags::P_NORMAL |
11030                                     SIInstrFlags::N_SUBNORMAL |
11031                                     SIInstrFlags::P_SUBNORMAL;
11032       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
11033       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
11034                          DAG.getConstant(Mask, SL, MVT::i32));
11035     }
11036   }
11037 
11038   return SDValue();
11039 }
11040 
11041 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
11042                                                      DAGCombinerInfo &DCI) const {
11043   SelectionDAG &DAG = DCI.DAG;
11044   SDLoc SL(N);
11045   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
11046 
11047   SDValue Src = N->getOperand(0);
11048   SDValue Shift = N->getOperand(0);
11049 
11050   // TODO: Extend type shouldn't matter (assuming legal types).
11051   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
11052     Shift = Shift.getOperand(0);
11053 
11054   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
11055     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
11056     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
11057     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
11058     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
11059     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
11060     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
11061       SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0),
11062                                  SDLoc(Shift.getOperand(0)), MVT::i32);
11063 
11064       unsigned ShiftOffset = 8 * Offset;
11065       if (Shift.getOpcode() == ISD::SHL)
11066         ShiftOffset -= C->getZExtValue();
11067       else
11068         ShiftOffset += C->getZExtValue();
11069 
11070       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
11071         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
11072                            MVT::f32, Shifted);
11073       }
11074     }
11075   }
11076 
11077   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11078   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
11079   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
11080     // We simplified Src. If this node is not dead, visit it again so it is
11081     // folded properly.
11082     if (N->getOpcode() != ISD::DELETED_NODE)
11083       DCI.AddToWorklist(N);
11084     return SDValue(N, 0);
11085   }
11086 
11087   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
11088   if (SDValue DemandedSrc =
11089           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
11090     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
11091 
11092   return SDValue();
11093 }
11094 
11095 SDValue SITargetLowering::performClampCombine(SDNode *N,
11096                                               DAGCombinerInfo &DCI) const {
11097   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
11098   if (!CSrc)
11099     return SDValue();
11100 
11101   const MachineFunction &MF = DCI.DAG.getMachineFunction();
11102   const APFloat &F = CSrc->getValueAPF();
11103   APFloat Zero = APFloat::getZero(F.getSemantics());
11104   if (F < Zero ||
11105       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
11106     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
11107   }
11108 
11109   APFloat One(F.getSemantics(), "1.0");
11110   if (F > One)
11111     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
11112 
11113   return SDValue(CSrc, 0);
11114 }
11115 
11116 
11117 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
11118                                             DAGCombinerInfo &DCI) const {
11119   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
11120     return SDValue();
11121   switch (N->getOpcode()) {
11122   case ISD::ADD:
11123     return performAddCombine(N, DCI);
11124   case ISD::SUB:
11125     return performSubCombine(N, DCI);
11126   case ISD::ADDCARRY:
11127   case ISD::SUBCARRY:
11128     return performAddCarrySubCarryCombine(N, DCI);
11129   case ISD::FADD:
11130     return performFAddCombine(N, DCI);
11131   case ISD::FSUB:
11132     return performFSubCombine(N, DCI);
11133   case ISD::SETCC:
11134     return performSetCCCombine(N, DCI);
11135   case ISD::FMAXNUM:
11136   case ISD::FMINNUM:
11137   case ISD::FMAXNUM_IEEE:
11138   case ISD::FMINNUM_IEEE:
11139   case ISD::SMAX:
11140   case ISD::SMIN:
11141   case ISD::UMAX:
11142   case ISD::UMIN:
11143   case AMDGPUISD::FMIN_LEGACY:
11144   case AMDGPUISD::FMAX_LEGACY:
11145     return performMinMaxCombine(N, DCI);
11146   case ISD::FMA:
11147     return performFMACombine(N, DCI);
11148   case ISD::AND:
11149     return performAndCombine(N, DCI);
11150   case ISD::OR:
11151     return performOrCombine(N, DCI);
11152   case ISD::XOR:
11153     return performXorCombine(N, DCI);
11154   case ISD::ZERO_EXTEND:
11155     return performZeroExtendCombine(N, DCI);
11156   case ISD::SIGN_EXTEND_INREG:
11157     return performSignExtendInRegCombine(N , DCI);
11158   case AMDGPUISD::FP_CLASS:
11159     return performClassCombine(N, DCI);
11160   case ISD::FCANONICALIZE:
11161     return performFCanonicalizeCombine(N, DCI);
11162   case AMDGPUISD::RCP:
11163     return performRcpCombine(N, DCI);
11164   case AMDGPUISD::FRACT:
11165   case AMDGPUISD::RSQ:
11166   case AMDGPUISD::RCP_LEGACY:
11167   case AMDGPUISD::RCP_IFLAG:
11168   case AMDGPUISD::RSQ_CLAMP:
11169   case AMDGPUISD::LDEXP: {
11170     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
11171     SDValue Src = N->getOperand(0);
11172     if (Src.isUndef())
11173       return Src;
11174     break;
11175   }
11176   case ISD::SINT_TO_FP:
11177   case ISD::UINT_TO_FP:
11178     return performUCharToFloatCombine(N, DCI);
11179   case AMDGPUISD::CVT_F32_UBYTE0:
11180   case AMDGPUISD::CVT_F32_UBYTE1:
11181   case AMDGPUISD::CVT_F32_UBYTE2:
11182   case AMDGPUISD::CVT_F32_UBYTE3:
11183     return performCvtF32UByteNCombine(N, DCI);
11184   case AMDGPUISD::FMED3:
11185     return performFMed3Combine(N, DCI);
11186   case AMDGPUISD::CVT_PKRTZ_F16_F32:
11187     return performCvtPkRTZCombine(N, DCI);
11188   case AMDGPUISD::CLAMP:
11189     return performClampCombine(N, DCI);
11190   case ISD::SCALAR_TO_VECTOR: {
11191     SelectionDAG &DAG = DCI.DAG;
11192     EVT VT = N->getValueType(0);
11193 
11194     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
11195     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
11196       SDLoc SL(N);
11197       SDValue Src = N->getOperand(0);
11198       EVT EltVT = Src.getValueType();
11199       if (EltVT == MVT::f16)
11200         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
11201 
11202       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
11203       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
11204     }
11205 
11206     break;
11207   }
11208   case ISD::EXTRACT_VECTOR_ELT:
11209     return performExtractVectorEltCombine(N, DCI);
11210   case ISD::INSERT_VECTOR_ELT:
11211     return performInsertVectorEltCombine(N, DCI);
11212   case ISD::LOAD: {
11213     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
11214       return Widended;
11215     LLVM_FALLTHROUGH;
11216   }
11217   default: {
11218     if (!DCI.isBeforeLegalize()) {
11219       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
11220         return performMemSDNodeCombine(MemNode, DCI);
11221     }
11222 
11223     break;
11224   }
11225   }
11226 
11227   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
11228 }
11229 
11230 /// Helper function for adjustWritemask
11231 static unsigned SubIdx2Lane(unsigned Idx) {
11232   switch (Idx) {
11233   default: return ~0u;
11234   case AMDGPU::sub0: return 0;
11235   case AMDGPU::sub1: return 1;
11236   case AMDGPU::sub2: return 2;
11237   case AMDGPU::sub3: return 3;
11238   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
11239   }
11240 }
11241 
11242 /// Adjust the writemask of MIMG instructions
11243 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
11244                                           SelectionDAG &DAG) const {
11245   unsigned Opcode = Node->getMachineOpcode();
11246 
11247   // Subtract 1 because the vdata output is not a MachineSDNode operand.
11248   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
11249   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
11250     return Node; // not implemented for D16
11251 
11252   SDNode *Users[5] = { nullptr };
11253   unsigned Lane = 0;
11254   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
11255   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
11256   unsigned NewDmask = 0;
11257   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
11258   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
11259   bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
11260                   Node->getConstantOperandVal(LWEIdx))
11261                      ? true
11262                      : false;
11263   unsigned TFCLane = 0;
11264   bool HasChain = Node->getNumValues() > 1;
11265 
11266   if (OldDmask == 0) {
11267     // These are folded out, but on the chance it happens don't assert.
11268     return Node;
11269   }
11270 
11271   unsigned OldBitsSet = countPopulation(OldDmask);
11272   // Work out which is the TFE/LWE lane if that is enabled.
11273   if (UsesTFC) {
11274     TFCLane = OldBitsSet;
11275   }
11276 
11277   // Try to figure out the used register components
11278   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
11279        I != E; ++I) {
11280 
11281     // Don't look at users of the chain.
11282     if (I.getUse().getResNo() != 0)
11283       continue;
11284 
11285     // Abort if we can't understand the usage
11286     if (!I->isMachineOpcode() ||
11287         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
11288       return Node;
11289 
11290     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
11291     // Note that subregs are packed, i.e. Lane==0 is the first bit set
11292     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
11293     // set, etc.
11294     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
11295     if (Lane == ~0u)
11296       return Node;
11297 
11298     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
11299     if (UsesTFC && Lane == TFCLane) {
11300       Users[Lane] = *I;
11301     } else {
11302       // Set which texture component corresponds to the lane.
11303       unsigned Comp;
11304       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
11305         Comp = countTrailingZeros(Dmask);
11306         Dmask &= ~(1 << Comp);
11307       }
11308 
11309       // Abort if we have more than one user per component.
11310       if (Users[Lane])
11311         return Node;
11312 
11313       Users[Lane] = *I;
11314       NewDmask |= 1 << Comp;
11315     }
11316   }
11317 
11318   // Don't allow 0 dmask, as hardware assumes one channel enabled.
11319   bool NoChannels = !NewDmask;
11320   if (NoChannels) {
11321     if (!UsesTFC) {
11322       // No uses of the result and not using TFC. Then do nothing.
11323       return Node;
11324     }
11325     // If the original dmask has one channel - then nothing to do
11326     if (OldBitsSet == 1)
11327       return Node;
11328     // Use an arbitrary dmask - required for the instruction to work
11329     NewDmask = 1;
11330   }
11331   // Abort if there's no change
11332   if (NewDmask == OldDmask)
11333     return Node;
11334 
11335   unsigned BitsSet = countPopulation(NewDmask);
11336 
11337   // Check for TFE or LWE - increase the number of channels by one to account
11338   // for the extra return value
11339   // This will need adjustment for D16 if this is also included in
11340   // adjustWriteMask (this function) but at present D16 are excluded.
11341   unsigned NewChannels = BitsSet + UsesTFC;
11342 
11343   int NewOpcode =
11344       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
11345   assert(NewOpcode != -1 &&
11346          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
11347          "failed to find equivalent MIMG op");
11348 
11349   // Adjust the writemask in the node
11350   SmallVector<SDValue, 12> Ops;
11351   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
11352   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
11353   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11354 
11355   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11356 
11357   MVT ResultVT = NewChannels == 1 ?
11358     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11359                            NewChannels == 5 ? 8 : NewChannels);
11360   SDVTList NewVTList = HasChain ?
11361     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11362 
11363 
11364   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11365                                               NewVTList, Ops);
11366 
11367   if (HasChain) {
11368     // Update chain.
11369     DAG.setNodeMemRefs(NewNode, Node->memoperands());
11370     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11371   }
11372 
11373   if (NewChannels == 1) {
11374     assert(Node->hasNUsesOfValue(1, 0));
11375     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11376                                       SDLoc(Node), Users[Lane]->getValueType(0),
11377                                       SDValue(NewNode, 0));
11378     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11379     return nullptr;
11380   }
11381 
11382   // Update the users of the node with the new indices
11383   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11384     SDNode *User = Users[i];
11385     if (!User) {
11386       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11387       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11388       if (i || !NoChannels)
11389         continue;
11390     } else {
11391       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11392       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11393     }
11394 
11395     switch (Idx) {
11396     default: break;
11397     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11398     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11399     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11400     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11401     }
11402   }
11403 
11404   DAG.RemoveDeadNode(Node);
11405   return nullptr;
11406 }
11407 
11408 static bool isFrameIndexOp(SDValue Op) {
11409   if (Op.getOpcode() == ISD::AssertZext)
11410     Op = Op.getOperand(0);
11411 
11412   return isa<FrameIndexSDNode>(Op);
11413 }
11414 
11415 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11416 /// with frame index operands.
11417 /// LLVM assumes that inputs are to these instructions are registers.
11418 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11419                                                         SelectionDAG &DAG) const {
11420   if (Node->getOpcode() == ISD::CopyToReg) {
11421     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11422     SDValue SrcVal = Node->getOperand(2);
11423 
11424     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11425     // to try understanding copies to physical registers.
11426     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11427       SDLoc SL(Node);
11428       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11429       SDValue VReg = DAG.getRegister(
11430         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11431 
11432       SDNode *Glued = Node->getGluedNode();
11433       SDValue ToVReg
11434         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11435                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11436       SDValue ToResultReg
11437         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11438                            VReg, ToVReg.getValue(1));
11439       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11440       DAG.RemoveDeadNode(Node);
11441       return ToResultReg.getNode();
11442     }
11443   }
11444 
11445   SmallVector<SDValue, 8> Ops;
11446   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11447     if (!isFrameIndexOp(Node->getOperand(i))) {
11448       Ops.push_back(Node->getOperand(i));
11449       continue;
11450     }
11451 
11452     SDLoc DL(Node);
11453     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11454                                      Node->getOperand(i).getValueType(),
11455                                      Node->getOperand(i)), 0));
11456   }
11457 
11458   return DAG.UpdateNodeOperands(Node, Ops);
11459 }
11460 
11461 /// Fold the instructions after selecting them.
11462 /// Returns null if users were already updated.
11463 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11464                                           SelectionDAG &DAG) const {
11465   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11466   unsigned Opcode = Node->getMachineOpcode();
11467 
11468   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11469       !TII->isGather4(Opcode) &&
11470       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11471     return adjustWritemask(Node, DAG);
11472   }
11473 
11474   if (Opcode == AMDGPU::INSERT_SUBREG ||
11475       Opcode == AMDGPU::REG_SEQUENCE) {
11476     legalizeTargetIndependentNode(Node, DAG);
11477     return Node;
11478   }
11479 
11480   switch (Opcode) {
11481   case AMDGPU::V_DIV_SCALE_F32_e64:
11482   case AMDGPU::V_DIV_SCALE_F64_e64: {
11483     // Satisfy the operand register constraint when one of the inputs is
11484     // undefined. Ordinarily each undef value will have its own implicit_def of
11485     // a vreg, so force these to use a single register.
11486     SDValue Src0 = Node->getOperand(1);
11487     SDValue Src1 = Node->getOperand(3);
11488     SDValue Src2 = Node->getOperand(5);
11489 
11490     if ((Src0.isMachineOpcode() &&
11491          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11492         (Src0 == Src1 || Src0 == Src2))
11493       break;
11494 
11495     MVT VT = Src0.getValueType().getSimpleVT();
11496     const TargetRegisterClass *RC =
11497         getRegClassFor(VT, Src0.getNode()->isDivergent());
11498 
11499     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11500     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11501 
11502     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11503                                       UndefReg, Src0, SDValue());
11504 
11505     // src0 must be the same register as src1 or src2, even if the value is
11506     // undefined, so make sure we don't violate this constraint.
11507     if (Src0.isMachineOpcode() &&
11508         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11509       if (Src1.isMachineOpcode() &&
11510           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11511         Src0 = Src1;
11512       else if (Src2.isMachineOpcode() &&
11513                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11514         Src0 = Src2;
11515       else {
11516         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11517         Src0 = UndefReg;
11518         Src1 = UndefReg;
11519       }
11520     } else
11521       break;
11522 
11523     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11524     Ops[1] = Src0;
11525     Ops[3] = Src1;
11526     Ops[5] = Src2;
11527     Ops.push_back(ImpDef.getValue(1));
11528     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11529   }
11530   default:
11531     break;
11532   }
11533 
11534   return Node;
11535 }
11536 
11537 // Any MIMG instructions that use tfe or lwe require an initialization of the
11538 // result register that will be written in the case of a memory access failure.
11539 // The required code is also added to tie this init code to the result of the
11540 // img instruction.
11541 void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
11542   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11543   const SIRegisterInfo &TRI = TII->getRegisterInfo();
11544   MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11545   MachineBasicBlock &MBB = *MI.getParent();
11546 
11547   MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
11548   MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
11549   MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
11550 
11551   if (!TFE && !LWE) // intersect_ray
11552     return;
11553 
11554   unsigned TFEVal = TFE ? TFE->getImm() : 0;
11555   unsigned LWEVal = LWE->getImm();
11556   unsigned D16Val = D16 ? D16->getImm() : 0;
11557 
11558   if (!TFEVal && !LWEVal)
11559     return;
11560 
11561   // At least one of TFE or LWE are non-zero
11562   // We have to insert a suitable initialization of the result value and
11563   // tie this to the dest of the image instruction.
11564 
11565   const DebugLoc &DL = MI.getDebugLoc();
11566 
11567   int DstIdx =
11568       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
11569 
11570   // Calculate which dword we have to initialize to 0.
11571   MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
11572 
11573   // check that dmask operand is found.
11574   assert(MO_Dmask && "Expected dmask operand in instruction");
11575 
11576   unsigned dmask = MO_Dmask->getImm();
11577   // Determine the number of active lanes taking into account the
11578   // Gather4 special case
11579   unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask);
11580 
11581   bool Packed = !Subtarget->hasUnpackedD16VMem();
11582 
11583   unsigned InitIdx =
11584       D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
11585 
11586   // Abandon attempt if the dst size isn't large enough
11587   // - this is in fact an error but this is picked up elsewhere and
11588   // reported correctly.
11589   uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
11590   if (DstSize < InitIdx)
11591     return;
11592 
11593   // Create a register for the initialization value.
11594   Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11595   unsigned NewDst = 0; // Final initialized value will be in here
11596 
11597   // If PRTStrictNull feature is enabled (the default) then initialize
11598   // all the result registers to 0, otherwise just the error indication
11599   // register (VGPRn+1)
11600   unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
11601   unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
11602 
11603   BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
11604   for (; SizeLeft; SizeLeft--, CurrIdx++) {
11605     NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11606     // Initialize dword
11607     Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
11608     BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
11609       .addImm(0);
11610     // Insert into the super-reg
11611     BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
11612       .addReg(PrevDst)
11613       .addReg(SubReg)
11614       .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
11615 
11616     PrevDst = NewDst;
11617   }
11618 
11619   // Add as an implicit operand
11620   MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
11621 
11622   // Tie the just added implicit operand to the dst
11623   MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
11624 }
11625 
11626 /// Assign the register class depending on the number of
11627 /// bits set in the writemask
11628 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11629                                                      SDNode *Node) const {
11630   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11631 
11632   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11633 
11634   if (TII->isVOP3(MI.getOpcode())) {
11635     // Make sure constant bus requirements are respected.
11636     TII->legalizeOperandsVOP3(MRI, MI);
11637 
11638     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11639     // This saves a chain-copy of registers and better balance register
11640     // use between vgpr and agpr as agpr tuples tend to be big.
11641     if (MI.getDesc().OpInfo) {
11642       unsigned Opc = MI.getOpcode();
11643       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11644       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11645                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11646         if (I == -1)
11647           break;
11648         MachineOperand &Op = MI.getOperand(I);
11649         if (!Op.isReg() || !Op.getReg().isVirtual())
11650           continue;
11651         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11652         if (!TRI->hasAGPRs(RC))
11653           continue;
11654         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11655         if (!Src || !Src->isCopy() ||
11656             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11657           continue;
11658         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11659         // All uses of agpr64 and agpr32 can also accept vgpr except for
11660         // v_accvgpr_read, but we do not produce agpr reads during selection,
11661         // so no use checks are needed.
11662         MRI.setRegClass(Op.getReg(), NewRC);
11663       }
11664 
11665       // Resolve the rest of AV operands to AGPRs.
11666       if (auto *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2)) {
11667         if (Src2->isReg() && Src2->getReg().isVirtual()) {
11668           auto *RC = TRI->getRegClassForReg(MRI, Src2->getReg());
11669           if (TRI->isVectorSuperClass(RC)) {
11670             auto *NewRC = TRI->getEquivalentAGPRClass(RC);
11671             MRI.setRegClass(Src2->getReg(), NewRC);
11672             if (Src2->isTied())
11673               MRI.setRegClass(MI.getOperand(0).getReg(), NewRC);
11674           }
11675         }
11676       }
11677     }
11678 
11679     return;
11680   }
11681 
11682   // Replace unused atomics with the no return version.
11683   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11684   if (NoRetAtomicOp != -1) {
11685     if (!Node->hasAnyUseOfValue(0)) {
11686       int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
11687                                                AMDGPU::OpName::cpol);
11688       if (CPolIdx != -1) {
11689         MachineOperand &CPol = MI.getOperand(CPolIdx);
11690         CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC);
11691       }
11692       MI.removeOperand(0);
11693       MI.setDesc(TII->get(NoRetAtomicOp));
11694       return;
11695     }
11696 
11697     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11698     // instruction, because the return type of these instructions is a vec2 of
11699     // the memory type, so it can be tied to the input operand.
11700     // This means these instructions always have a use, so we need to add a
11701     // special case to check if the atomic has only one extract_subreg use,
11702     // which itself has no uses.
11703     if ((Node->hasNUsesOfValue(1, 0) &&
11704          Node->use_begin()->isMachineOpcode() &&
11705          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11706          !Node->use_begin()->hasAnyUseOfValue(0))) {
11707       Register Def = MI.getOperand(0).getReg();
11708 
11709       // Change this into a noret atomic.
11710       MI.setDesc(TII->get(NoRetAtomicOp));
11711       MI.removeOperand(0);
11712 
11713       // If we only remove the def operand from the atomic instruction, the
11714       // extract_subreg will be left with a use of a vreg without a def.
11715       // So we need to insert an implicit_def to avoid machine verifier
11716       // errors.
11717       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11718               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11719     }
11720     return;
11721   }
11722 
11723   if (TII->isMIMG(MI) && !MI.mayStore())
11724     AddIMGInit(MI);
11725 }
11726 
11727 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11728                               uint64_t Val) {
11729   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11730   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11731 }
11732 
11733 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11734                                                 const SDLoc &DL,
11735                                                 SDValue Ptr) const {
11736   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11737 
11738   // Build the half of the subregister with the constants before building the
11739   // full 128-bit register. If we are building multiple resource descriptors,
11740   // this will allow CSEing of the 2-component register.
11741   const SDValue Ops0[] = {
11742     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11743     buildSMovImm32(DAG, DL, 0),
11744     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11745     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11746     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11747   };
11748 
11749   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11750                                                 MVT::v2i32, Ops0), 0);
11751 
11752   // Combine the constants and the pointer.
11753   const SDValue Ops1[] = {
11754     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11755     Ptr,
11756     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11757     SubRegHi,
11758     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11759   };
11760 
11761   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11762 }
11763 
11764 /// Return a resource descriptor with the 'Add TID' bit enabled
11765 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11766 ///        of the resource descriptor) to create an offset, which is added to
11767 ///        the resource pointer.
11768 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11769                                            SDValue Ptr, uint32_t RsrcDword1,
11770                                            uint64_t RsrcDword2And3) const {
11771   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11772   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11773   if (RsrcDword1) {
11774     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11775                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11776                     0);
11777   }
11778 
11779   SDValue DataLo = buildSMovImm32(DAG, DL,
11780                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11781   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11782 
11783   const SDValue Ops[] = {
11784     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11785     PtrLo,
11786     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11787     PtrHi,
11788     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11789     DataLo,
11790     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11791     DataHi,
11792     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11793   };
11794 
11795   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11796 }
11797 
11798 //===----------------------------------------------------------------------===//
11799 //                         SI Inline Assembly Support
11800 //===----------------------------------------------------------------------===//
11801 
11802 std::pair<unsigned, const TargetRegisterClass *>
11803 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
11804                                                StringRef Constraint,
11805                                                MVT VT) const {
11806   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
11807 
11808   const TargetRegisterClass *RC = nullptr;
11809   if (Constraint.size() == 1) {
11810     const unsigned BitWidth = VT.getSizeInBits();
11811     switch (Constraint[0]) {
11812     default:
11813       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11814     case 's':
11815     case 'r':
11816       switch (BitWidth) {
11817       case 16:
11818         RC = &AMDGPU::SReg_32RegClass;
11819         break;
11820       case 64:
11821         RC = &AMDGPU::SGPR_64RegClass;
11822         break;
11823       default:
11824         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11825         if (!RC)
11826           return std::make_pair(0U, nullptr);
11827         break;
11828       }
11829       break;
11830     case 'v':
11831       switch (BitWidth) {
11832       case 16:
11833         RC = &AMDGPU::VGPR_32RegClass;
11834         break;
11835       default:
11836         RC = TRI->getVGPRClassForBitWidth(BitWidth);
11837         if (!RC)
11838           return std::make_pair(0U, nullptr);
11839         break;
11840       }
11841       break;
11842     case 'a':
11843       if (!Subtarget->hasMAIInsts())
11844         break;
11845       switch (BitWidth) {
11846       case 16:
11847         RC = &AMDGPU::AGPR_32RegClass;
11848         break;
11849       default:
11850         RC = TRI->getAGPRClassForBitWidth(BitWidth);
11851         if (!RC)
11852           return std::make_pair(0U, nullptr);
11853         break;
11854       }
11855       break;
11856     }
11857     // We actually support i128, i16 and f16 as inline parameters
11858     // even if they are not reported as legal
11859     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11860                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11861       return std::make_pair(0U, RC);
11862   }
11863 
11864   if (Constraint.startswith("{") && Constraint.endswith("}")) {
11865     StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
11866     if (RegName.consume_front("v")) {
11867       RC = &AMDGPU::VGPR_32RegClass;
11868     } else if (RegName.consume_front("s")) {
11869       RC = &AMDGPU::SGPR_32RegClass;
11870     } else if (RegName.consume_front("a")) {
11871       RC = &AMDGPU::AGPR_32RegClass;
11872     }
11873 
11874     if (RC) {
11875       uint32_t Idx;
11876       if (RegName.consume_front("[")) {
11877         uint32_t End;
11878         bool Failed = RegName.consumeInteger(10, Idx);
11879         Failed |= !RegName.consume_front(":");
11880         Failed |= RegName.consumeInteger(10, End);
11881         Failed |= !RegName.consume_back("]");
11882         if (!Failed) {
11883           uint32_t Width = (End - Idx + 1) * 32;
11884           MCRegister Reg = RC->getRegister(Idx);
11885           if (SIRegisterInfo::isVGPRClass(RC))
11886             RC = TRI->getVGPRClassForBitWidth(Width);
11887           else if (SIRegisterInfo::isSGPRClass(RC))
11888             RC = TRI->getSGPRClassForBitWidth(Width);
11889           else if (SIRegisterInfo::isAGPRClass(RC))
11890             RC = TRI->getAGPRClassForBitWidth(Width);
11891           if (RC) {
11892             Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC);
11893             return std::make_pair(Reg, RC);
11894           }
11895         }
11896       } else {
11897         bool Failed = RegName.getAsInteger(10, Idx);
11898         if (!Failed && Idx < RC->getNumRegs())
11899           return std::make_pair(RC->getRegister(Idx), RC);
11900       }
11901     }
11902   }
11903 
11904   auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11905   if (Ret.first)
11906     Ret.second = TRI->getPhysRegClass(Ret.first);
11907 
11908   return Ret;
11909 }
11910 
11911 static bool isImmConstraint(StringRef Constraint) {
11912   if (Constraint.size() == 1) {
11913     switch (Constraint[0]) {
11914     default: break;
11915     case 'I':
11916     case 'J':
11917     case 'A':
11918     case 'B':
11919     case 'C':
11920       return true;
11921     }
11922   } else if (Constraint == "DA" ||
11923              Constraint == "DB") {
11924     return true;
11925   }
11926   return false;
11927 }
11928 
11929 SITargetLowering::ConstraintType
11930 SITargetLowering::getConstraintType(StringRef Constraint) const {
11931   if (Constraint.size() == 1) {
11932     switch (Constraint[0]) {
11933     default: break;
11934     case 's':
11935     case 'v':
11936     case 'a':
11937       return C_RegisterClass;
11938     }
11939   }
11940   if (isImmConstraint(Constraint)) {
11941     return C_Other;
11942   }
11943   return TargetLowering::getConstraintType(Constraint);
11944 }
11945 
11946 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11947   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11948     Val = Val & maskTrailingOnes<uint64_t>(Size);
11949   }
11950   return Val;
11951 }
11952 
11953 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11954                                                     std::string &Constraint,
11955                                                     std::vector<SDValue> &Ops,
11956                                                     SelectionDAG &DAG) const {
11957   if (isImmConstraint(Constraint)) {
11958     uint64_t Val;
11959     if (getAsmOperandConstVal(Op, Val) &&
11960         checkAsmConstraintVal(Op, Constraint, Val)) {
11961       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11962       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11963     }
11964   } else {
11965     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11966   }
11967 }
11968 
11969 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11970   unsigned Size = Op.getScalarValueSizeInBits();
11971   if (Size > 64)
11972     return false;
11973 
11974   if (Size == 16 && !Subtarget->has16BitInsts())
11975     return false;
11976 
11977   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11978     Val = C->getSExtValue();
11979     return true;
11980   }
11981   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11982     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11983     return true;
11984   }
11985   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11986     if (Size != 16 || Op.getNumOperands() != 2)
11987       return false;
11988     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11989       return false;
11990     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11991       Val = C->getSExtValue();
11992       return true;
11993     }
11994     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11995       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11996       return true;
11997     }
11998   }
11999 
12000   return false;
12001 }
12002 
12003 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
12004                                              const std::string &Constraint,
12005                                              uint64_t Val) const {
12006   if (Constraint.size() == 1) {
12007     switch (Constraint[0]) {
12008     case 'I':
12009       return AMDGPU::isInlinableIntLiteral(Val);
12010     case 'J':
12011       return isInt<16>(Val);
12012     case 'A':
12013       return checkAsmConstraintValA(Op, Val);
12014     case 'B':
12015       return isInt<32>(Val);
12016     case 'C':
12017       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
12018              AMDGPU::isInlinableIntLiteral(Val);
12019     default:
12020       break;
12021     }
12022   } else if (Constraint.size() == 2) {
12023     if (Constraint == "DA") {
12024       int64_t HiBits = static_cast<int32_t>(Val >> 32);
12025       int64_t LoBits = static_cast<int32_t>(Val);
12026       return checkAsmConstraintValA(Op, HiBits, 32) &&
12027              checkAsmConstraintValA(Op, LoBits, 32);
12028     }
12029     if (Constraint == "DB") {
12030       return true;
12031     }
12032   }
12033   llvm_unreachable("Invalid asm constraint");
12034 }
12035 
12036 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
12037                                               uint64_t Val,
12038                                               unsigned MaxSize) const {
12039   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
12040   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
12041   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
12042       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
12043       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
12044     return true;
12045   }
12046   return false;
12047 }
12048 
12049 static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
12050   switch (UnalignedClassID) {
12051   case AMDGPU::VReg_64RegClassID:
12052     return AMDGPU::VReg_64_Align2RegClassID;
12053   case AMDGPU::VReg_96RegClassID:
12054     return AMDGPU::VReg_96_Align2RegClassID;
12055   case AMDGPU::VReg_128RegClassID:
12056     return AMDGPU::VReg_128_Align2RegClassID;
12057   case AMDGPU::VReg_160RegClassID:
12058     return AMDGPU::VReg_160_Align2RegClassID;
12059   case AMDGPU::VReg_192RegClassID:
12060     return AMDGPU::VReg_192_Align2RegClassID;
12061   case AMDGPU::VReg_224RegClassID:
12062     return AMDGPU::VReg_224_Align2RegClassID;
12063   case AMDGPU::VReg_256RegClassID:
12064     return AMDGPU::VReg_256_Align2RegClassID;
12065   case AMDGPU::VReg_512RegClassID:
12066     return AMDGPU::VReg_512_Align2RegClassID;
12067   case AMDGPU::VReg_1024RegClassID:
12068     return AMDGPU::VReg_1024_Align2RegClassID;
12069   case AMDGPU::AReg_64RegClassID:
12070     return AMDGPU::AReg_64_Align2RegClassID;
12071   case AMDGPU::AReg_96RegClassID:
12072     return AMDGPU::AReg_96_Align2RegClassID;
12073   case AMDGPU::AReg_128RegClassID:
12074     return AMDGPU::AReg_128_Align2RegClassID;
12075   case AMDGPU::AReg_160RegClassID:
12076     return AMDGPU::AReg_160_Align2RegClassID;
12077   case AMDGPU::AReg_192RegClassID:
12078     return AMDGPU::AReg_192_Align2RegClassID;
12079   case AMDGPU::AReg_256RegClassID:
12080     return AMDGPU::AReg_256_Align2RegClassID;
12081   case AMDGPU::AReg_512RegClassID:
12082     return AMDGPU::AReg_512_Align2RegClassID;
12083   case AMDGPU::AReg_1024RegClassID:
12084     return AMDGPU::AReg_1024_Align2RegClassID;
12085   default:
12086     return -1;
12087   }
12088 }
12089 
12090 // Figure out which registers should be reserved for stack access. Only after
12091 // the function is legalized do we know all of the non-spill stack objects or if
12092 // calls are present.
12093 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
12094   MachineRegisterInfo &MRI = MF.getRegInfo();
12095   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12096   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
12097   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12098   const SIInstrInfo *TII = ST.getInstrInfo();
12099 
12100   if (Info->isEntryFunction()) {
12101     // Callable functions have fixed registers used for stack access.
12102     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
12103   }
12104 
12105   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
12106                              Info->getStackPtrOffsetReg()));
12107   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
12108     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
12109 
12110   // We need to worry about replacing the default register with itself in case
12111   // of MIR testcases missing the MFI.
12112   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
12113     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
12114 
12115   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
12116     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
12117 
12118   Info->limitOccupancy(MF);
12119 
12120   if (ST.isWave32() && !MF.empty()) {
12121     for (auto &MBB : MF) {
12122       for (auto &MI : MBB) {
12123         TII->fixImplicitOperands(MI);
12124       }
12125     }
12126   }
12127 
12128   // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
12129   // classes if required. Ideally the register class constraints would differ
12130   // per-subtarget, but there's no easy way to achieve that right now. This is
12131   // not a problem for VGPRs because the correctly aligned VGPR class is implied
12132   // from using them as the register class for legal types.
12133   if (ST.needsAlignedVGPRs()) {
12134     for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
12135       const Register Reg = Register::index2VirtReg(I);
12136       const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
12137       if (!RC)
12138         continue;
12139       int NewClassID = getAlignedAGPRClassID(RC->getID());
12140       if (NewClassID != -1)
12141         MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
12142     }
12143   }
12144 
12145   TargetLoweringBase::finalizeLowering(MF);
12146 }
12147 
12148 void SITargetLowering::computeKnownBitsForFrameIndex(
12149   const int FI, KnownBits &Known, const MachineFunction &MF) const {
12150   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
12151 
12152   // Set the high bits to zero based on the maximum allowed scratch size per
12153   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
12154   // calculation won't overflow, so assume the sign bit is never set.
12155   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
12156 }
12157 
12158 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
12159                                    KnownBits &Known, unsigned Dim) {
12160   unsigned MaxValue =
12161       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
12162   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
12163 }
12164 
12165 void SITargetLowering::computeKnownBitsForTargetInstr(
12166     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
12167     const MachineRegisterInfo &MRI, unsigned Depth) const {
12168   const MachineInstr *MI = MRI.getVRegDef(R);
12169   switch (MI->getOpcode()) {
12170   case AMDGPU::G_INTRINSIC: {
12171     switch (MI->getIntrinsicID()) {
12172     case Intrinsic::amdgcn_workitem_id_x:
12173       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
12174       break;
12175     case Intrinsic::amdgcn_workitem_id_y:
12176       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
12177       break;
12178     case Intrinsic::amdgcn_workitem_id_z:
12179       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
12180       break;
12181     case Intrinsic::amdgcn_mbcnt_lo:
12182     case Intrinsic::amdgcn_mbcnt_hi: {
12183       // These return at most the wavefront size - 1.
12184       unsigned Size = MRI.getType(R).getSizeInBits();
12185       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
12186       break;
12187     }
12188     case Intrinsic::amdgcn_groupstaticsize: {
12189       // We can report everything over the maximum size as 0. We can't report
12190       // based on the actual size because we don't know if it's accurate or not
12191       // at any given point.
12192       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
12193       break;
12194     }
12195     }
12196     break;
12197   }
12198   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
12199     Known.Zero.setHighBits(24);
12200     break;
12201   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
12202     Known.Zero.setHighBits(16);
12203     break;
12204   }
12205 }
12206 
12207 Align SITargetLowering::computeKnownAlignForTargetInstr(
12208   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
12209   unsigned Depth) const {
12210   const MachineInstr *MI = MRI.getVRegDef(R);
12211   switch (MI->getOpcode()) {
12212   case AMDGPU::G_INTRINSIC:
12213   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
12214     // FIXME: Can this move to generic code? What about the case where the call
12215     // site specifies a lower alignment?
12216     Intrinsic::ID IID = MI->getIntrinsicID();
12217     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
12218     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
12219     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
12220       return *RetAlign;
12221     return Align(1);
12222   }
12223   default:
12224     return Align(1);
12225   }
12226 }
12227 
12228 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12229   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
12230   const Align CacheLineAlign = Align(64);
12231 
12232   // Pre-GFX10 target did not benefit from loop alignment
12233   if (!ML || DisableLoopAlignment ||
12234       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
12235       getSubtarget()->hasInstFwdPrefetchBug())
12236     return PrefAlign;
12237 
12238   // On GFX10 I$ is 4 x 64 bytes cache lines.
12239   // By default prefetcher keeps one cache line behind and reads two ahead.
12240   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
12241   // behind and one ahead.
12242   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
12243   // If loop fits 64 bytes it always spans no more than two cache lines and
12244   // does not need an alignment.
12245   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
12246   // Else if loop is less or equal 192 bytes we need two lines behind.
12247 
12248   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12249   const MachineBasicBlock *Header = ML->getHeader();
12250   if (Header->getAlignment() != PrefAlign)
12251     return Header->getAlignment(); // Already processed.
12252 
12253   unsigned LoopSize = 0;
12254   for (const MachineBasicBlock *MBB : ML->blocks()) {
12255     // If inner loop block is aligned assume in average half of the alignment
12256     // size to be added as nops.
12257     if (MBB != Header)
12258       LoopSize += MBB->getAlignment().value() / 2;
12259 
12260     for (const MachineInstr &MI : *MBB) {
12261       LoopSize += TII->getInstSizeInBytes(MI);
12262       if (LoopSize > 192)
12263         return PrefAlign;
12264     }
12265   }
12266 
12267   if (LoopSize <= 64)
12268     return PrefAlign;
12269 
12270   if (LoopSize <= 128)
12271     return CacheLineAlign;
12272 
12273   // If any of parent loops is surrounded by prefetch instructions do not
12274   // insert new for inner loop, which would reset parent's settings.
12275   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
12276     if (MachineBasicBlock *Exit = P->getExitBlock()) {
12277       auto I = Exit->getFirstNonDebugInstr();
12278       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
12279         return CacheLineAlign;
12280     }
12281   }
12282 
12283   MachineBasicBlock *Pre = ML->getLoopPreheader();
12284   MachineBasicBlock *Exit = ML->getExitBlock();
12285 
12286   if (Pre && Exit) {
12287     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
12288             TII->get(AMDGPU::S_INST_PREFETCH))
12289       .addImm(1); // prefetch 2 lines behind PC
12290 
12291     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
12292             TII->get(AMDGPU::S_INST_PREFETCH))
12293       .addImm(2); // prefetch 1 line behind PC
12294   }
12295 
12296   return CacheLineAlign;
12297 }
12298 
12299 LLVM_ATTRIBUTE_UNUSED
12300 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
12301   assert(N->getOpcode() == ISD::CopyFromReg);
12302   do {
12303     // Follow the chain until we find an INLINEASM node.
12304     N = N->getOperand(0).getNode();
12305     if (N->getOpcode() == ISD::INLINEASM ||
12306         N->getOpcode() == ISD::INLINEASM_BR)
12307       return true;
12308   } while (N->getOpcode() == ISD::CopyFromReg);
12309   return false;
12310 }
12311 
12312 bool SITargetLowering::isSDNodeSourceOfDivergence(
12313     const SDNode *N, FunctionLoweringInfo *FLI,
12314     LegacyDivergenceAnalysis *KDA) const {
12315   switch (N->getOpcode()) {
12316   case ISD::CopyFromReg: {
12317     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
12318     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
12319     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12320     Register Reg = R->getReg();
12321 
12322     // FIXME: Why does this need to consider isLiveIn?
12323     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
12324       return !TRI->isSGPRReg(MRI, Reg);
12325 
12326     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
12327       return KDA->isDivergent(V);
12328 
12329     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
12330     return !TRI->isSGPRReg(MRI, Reg);
12331   }
12332   case ISD::LOAD: {
12333     const LoadSDNode *L = cast<LoadSDNode>(N);
12334     unsigned AS = L->getAddressSpace();
12335     // A flat load may access private memory.
12336     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
12337   }
12338   case ISD::CALLSEQ_END:
12339     return true;
12340   case ISD::INTRINSIC_WO_CHAIN:
12341     return AMDGPU::isIntrinsicSourceOfDivergence(
12342         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
12343   case ISD::INTRINSIC_W_CHAIN:
12344     return AMDGPU::isIntrinsicSourceOfDivergence(
12345         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
12346   case AMDGPUISD::ATOMIC_CMP_SWAP:
12347   case AMDGPUISD::ATOMIC_INC:
12348   case AMDGPUISD::ATOMIC_DEC:
12349   case AMDGPUISD::ATOMIC_LOAD_FMIN:
12350   case AMDGPUISD::ATOMIC_LOAD_FMAX:
12351   case AMDGPUISD::BUFFER_ATOMIC_SWAP:
12352   case AMDGPUISD::BUFFER_ATOMIC_ADD:
12353   case AMDGPUISD::BUFFER_ATOMIC_SUB:
12354   case AMDGPUISD::BUFFER_ATOMIC_SMIN:
12355   case AMDGPUISD::BUFFER_ATOMIC_UMIN:
12356   case AMDGPUISD::BUFFER_ATOMIC_SMAX:
12357   case AMDGPUISD::BUFFER_ATOMIC_UMAX:
12358   case AMDGPUISD::BUFFER_ATOMIC_AND:
12359   case AMDGPUISD::BUFFER_ATOMIC_OR:
12360   case AMDGPUISD::BUFFER_ATOMIC_XOR:
12361   case AMDGPUISD::BUFFER_ATOMIC_INC:
12362   case AMDGPUISD::BUFFER_ATOMIC_DEC:
12363   case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
12364   case AMDGPUISD::BUFFER_ATOMIC_CSUB:
12365   case AMDGPUISD::BUFFER_ATOMIC_FADD:
12366   case AMDGPUISD::BUFFER_ATOMIC_FMIN:
12367   case AMDGPUISD::BUFFER_ATOMIC_FMAX:
12368     // Target-specific read-modify-write atomics are sources of divergence.
12369     return true;
12370   default:
12371     if (auto *A = dyn_cast<AtomicSDNode>(N)) {
12372       // Generic read-modify-write atomics are sources of divergence.
12373       return A->readMem() && A->writeMem();
12374     }
12375     return false;
12376   }
12377 }
12378 
12379 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
12380                                                EVT VT) const {
12381   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
12382   case MVT::f32:
12383     return hasFP32Denormals(DAG.getMachineFunction());
12384   case MVT::f64:
12385   case MVT::f16:
12386     return hasFP64FP16Denormals(DAG.getMachineFunction());
12387   default:
12388     return false;
12389   }
12390 }
12391 
12392 bool SITargetLowering::denormalsEnabledForType(LLT Ty,
12393                                                MachineFunction &MF) const {
12394   switch (Ty.getScalarSizeInBits()) {
12395   case 32:
12396     return hasFP32Denormals(MF);
12397   case 64:
12398   case 16:
12399     return hasFP64FP16Denormals(MF);
12400   default:
12401     return false;
12402   }
12403 }
12404 
12405 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
12406                                                     const SelectionDAG &DAG,
12407                                                     bool SNaN,
12408                                                     unsigned Depth) const {
12409   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
12410     const MachineFunction &MF = DAG.getMachineFunction();
12411     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12412 
12413     if (Info->getMode().DX10Clamp)
12414       return true; // Clamped to 0.
12415     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
12416   }
12417 
12418   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
12419                                                             SNaN, Depth);
12420 }
12421 
12422 // Global FP atomic instructions have a hardcoded FP mode and do not support
12423 // FP32 denormals, and only support v2f16 denormals.
12424 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
12425   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
12426   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
12427   if (&Flt == &APFloat::IEEEsingle())
12428     return DenormMode == DenormalMode::getPreserveSign();
12429   return DenormMode == DenormalMode::getIEEE();
12430 }
12431 
12432 TargetLowering::AtomicExpansionKind
12433 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
12434 
12435   auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) {
12436     OptimizationRemarkEmitter ORE(RMW->getFunction());
12437     LLVMContext &Ctx = RMW->getFunction()->getContext();
12438     SmallVector<StringRef> SSNs;
12439     Ctx.getSyncScopeNames(SSNs);
12440     auto MemScope = SSNs[RMW->getSyncScopeID()].empty()
12441                         ? "system"
12442                         : SSNs[RMW->getSyncScopeID()];
12443     ORE.emit([&]() {
12444       return OptimizationRemark(DEBUG_TYPE, "Passed", RMW)
12445              << "Hardware instruction generated for atomic "
12446              << RMW->getOperationName(RMW->getOperation())
12447              << " operation at memory scope " << MemScope
12448              << " due to an unsafe request.";
12449     });
12450     return Kind;
12451   };
12452 
12453   switch (RMW->getOperation()) {
12454   case AtomicRMWInst::FAdd: {
12455     Type *Ty = RMW->getType();
12456 
12457     // We don't have a way to support 16-bit atomics now, so just leave them
12458     // as-is.
12459     if (Ty->isHalfTy())
12460       return AtomicExpansionKind::None;
12461 
12462     if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
12463       return AtomicExpansionKind::CmpXChg;
12464 
12465     unsigned AS = RMW->getPointerAddressSpace();
12466 
12467     if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) &&
12468          Subtarget->hasAtomicFaddInsts()) {
12469       if (Subtarget->hasGFX940Insts())
12470         return AtomicExpansionKind::None;
12471 
12472       // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
12473       // floating point atomic instructions. May generate more efficient code,
12474       // but may not respect rounding and denormal modes, and may give incorrect
12475       // results for certain memory destinations.
12476       if (RMW->getFunction()
12477               ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12478               .getValueAsString() != "true")
12479         return AtomicExpansionKind::CmpXChg;
12480 
12481       if (Subtarget->hasGFX90AInsts()) {
12482         if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS)
12483           return AtomicExpansionKind::CmpXChg;
12484 
12485         auto SSID = RMW->getSyncScopeID();
12486         if (SSID == SyncScope::System ||
12487             SSID == RMW->getContext().getOrInsertSyncScopeID("one-as"))
12488           return AtomicExpansionKind::CmpXChg;
12489 
12490         return ReportUnsafeHWInst(AtomicExpansionKind::None);
12491       }
12492 
12493       if (AS == AMDGPUAS::FLAT_ADDRESS)
12494         return AtomicExpansionKind::CmpXChg;
12495 
12496       return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12497                               : AtomicExpansionKind::CmpXChg;
12498     }
12499 
12500     // DS FP atomics do respect the denormal mode, but the rounding mode is
12501     // fixed to round-to-nearest-even.
12502     // The only exception is DS_ADD_F64 which never flushes regardless of mode.
12503     if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) {
12504       if (!Ty->isDoubleTy())
12505         return AtomicExpansionKind::None;
12506 
12507       if (fpModeMatchesGlobalFPAtomicMode(RMW))
12508         return AtomicExpansionKind::None;
12509 
12510       return RMW->getFunction()
12511                          ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12512                          .getValueAsString() == "true"
12513                  ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12514                  : AtomicExpansionKind::CmpXChg;
12515     }
12516 
12517     return AtomicExpansionKind::CmpXChg;
12518   }
12519   default:
12520     break;
12521   }
12522 
12523   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
12524 }
12525 
12526 const TargetRegisterClass *
12527 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
12528   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
12529   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12530   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
12531     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
12532                                                : &AMDGPU::SReg_32RegClass;
12533   if (!TRI->isSGPRClass(RC) && !isDivergent)
12534     return TRI->getEquivalentSGPRClass(RC);
12535   else if (TRI->isSGPRClass(RC) && isDivergent)
12536     return TRI->getEquivalentVGPRClass(RC);
12537 
12538   return RC;
12539 }
12540 
12541 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
12542 // uniform values (as produced by the mask results of control flow intrinsics)
12543 // used outside of divergent blocks. The phi users need to also be treated as
12544 // always uniform.
12545 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
12546                       unsigned WaveSize) {
12547   // FIXME: We assume we never cast the mask results of a control flow
12548   // intrinsic.
12549   // Early exit if the type won't be consistent as a compile time hack.
12550   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
12551   if (!IT || IT->getBitWidth() != WaveSize)
12552     return false;
12553 
12554   if (!isa<Instruction>(V))
12555     return false;
12556   if (!Visited.insert(V).second)
12557     return false;
12558   bool Result = false;
12559   for (auto U : V->users()) {
12560     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
12561       if (V == U->getOperand(1)) {
12562         switch (Intrinsic->getIntrinsicID()) {
12563         default:
12564           Result = false;
12565           break;
12566         case Intrinsic::amdgcn_if_break:
12567         case Intrinsic::amdgcn_if:
12568         case Intrinsic::amdgcn_else:
12569           Result = true;
12570           break;
12571         }
12572       }
12573       if (V == U->getOperand(0)) {
12574         switch (Intrinsic->getIntrinsicID()) {
12575         default:
12576           Result = false;
12577           break;
12578         case Intrinsic::amdgcn_end_cf:
12579         case Intrinsic::amdgcn_loop:
12580           Result = true;
12581           break;
12582         }
12583       }
12584     } else {
12585       Result = hasCFUser(U, Visited, WaveSize);
12586     }
12587     if (Result)
12588       break;
12589   }
12590   return Result;
12591 }
12592 
12593 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
12594                                                const Value *V) const {
12595   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
12596     if (CI->isInlineAsm()) {
12597       // FIXME: This cannot give a correct answer. This should only trigger in
12598       // the case where inline asm returns mixed SGPR and VGPR results, used
12599       // outside the defining block. We don't have a specific result to
12600       // consider, so this assumes if any value is SGPR, the overall register
12601       // also needs to be SGPR.
12602       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
12603       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
12604           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
12605       for (auto &TC : TargetConstraints) {
12606         if (TC.Type == InlineAsm::isOutput) {
12607           ComputeConstraintToUse(TC, SDValue());
12608           const TargetRegisterClass *RC = getRegForInlineAsmConstraint(
12609               SIRI, TC.ConstraintCode, TC.ConstraintVT).second;
12610           if (RC && SIRI->isSGPRClass(RC))
12611             return true;
12612         }
12613       }
12614     }
12615   }
12616   SmallPtrSet<const Value *, 16> Visited;
12617   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
12618 }
12619 
12620 std::pair<InstructionCost, MVT>
12621 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
12622                                           Type *Ty) const {
12623   std::pair<InstructionCost, MVT> Cost =
12624       TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
12625   auto Size = DL.getTypeSizeInBits(Ty);
12626   // Maximum load or store can handle 8 dwords for scalar and 4 for
12627   // vector ALU. Let's assume anything above 8 dwords is expensive
12628   // even if legal.
12629   if (Size <= 256)
12630     return Cost;
12631 
12632   Cost.first += (Size + 255) / 256;
12633   return Cost;
12634 }
12635 
12636 bool SITargetLowering::hasMemSDNodeUser(SDNode *N) const {
12637   SDNode::use_iterator I = N->use_begin(), E = N->use_end();
12638   for (; I != E; ++I) {
12639     if (MemSDNode *M = dyn_cast<MemSDNode>(*I)) {
12640       if (getBasePtrIndex(M) == I.getOperandNo())
12641         return true;
12642     }
12643   }
12644   return false;
12645 }
12646 
12647 bool SITargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0,
12648                                            SDValue N1) const {
12649   if (!N0.hasOneUse())
12650     return false;
12651   // Take care of the opportunity to keep N0 uniform
12652   if (N0->isDivergent() || !N1->isDivergent())
12653     return true;
12654   // Check if we have a good chance to form the memory access pattern with the
12655   // base and offset
12656   return (DAG.isBaseWithConstantOffset(N0) &&
12657           hasMemSDNodeUser(*N0->use_begin()));
12658 }
12659 
12660 MachineMemOperand::Flags
12661 SITargetLowering::getTargetMMOFlags(const Instruction &I) const {
12662   // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load.
12663   if (I.getMetadata("amdgpu.noclobber"))
12664     return MONoClobber;
12665   return MachineMemOperand::MONone;
12666 }
12667