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                        ISD::ADDCARRY,
893                        ISD::SUB,
894                        ISD::SUBCARRY,
895                        ISD::FADD,
896                        ISD::FSUB,
897                        ISD::FMINNUM,
898                        ISD::FMAXNUM,
899                        ISD::FMINNUM_IEEE,
900                        ISD::FMAXNUM_IEEE,
901                        ISD::FMA,
902                        ISD::SMIN,
903                        ISD::SMAX,
904                        ISD::UMIN,
905                        ISD::UMAX,
906                        ISD::SETCC,
907                        ISD::AND,
908                        ISD::OR,
909                        ISD::XOR,
910                        ISD::SINT_TO_FP,
911                        ISD::UINT_TO_FP,
912                        ISD::FCANONICALIZE,
913                        ISD::SCALAR_TO_VECTOR,
914                        ISD::ZERO_EXTEND,
915                        ISD::SIGN_EXTEND_INREG,
916                        ISD::EXTRACT_VECTOR_ELT,
917                        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                        ISD::STORE,
923                        ISD::ATOMIC_LOAD,
924                        ISD::ATOMIC_STORE,
925                        ISD::ATOMIC_CMP_SWAP,
926                        ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
927                        ISD::ATOMIC_SWAP,
928                        ISD::ATOMIC_LOAD_ADD,
929                        ISD::ATOMIC_LOAD_SUB,
930                        ISD::ATOMIC_LOAD_AND,
931                        ISD::ATOMIC_LOAD_OR,
932                        ISD::ATOMIC_LOAD_XOR,
933                        ISD::ATOMIC_LOAD_NAND,
934                        ISD::ATOMIC_LOAD_MIN,
935                        ISD::ATOMIC_LOAD_MAX,
936                        ISD::ATOMIC_LOAD_UMIN,
937                        ISD::ATOMIC_LOAD_UMAX,
938                        ISD::ATOMIC_LOAD_FADD,
939                        ISD::INTRINSIC_VOID,
940                        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() && Alignment < Align(4))
1522       return false;
1523 
1524     Align RequiredAlignment(PowerOf2Ceil(Size/8)); // Natural alignment.
1525     if (Subtarget->hasLDSMisalignedBug() && Size > 32 &&
1526         Alignment < RequiredAlignment)
1527       return false;
1528 
1529     // Either, the alignment requirements are "enabled", or there is an
1530     // unaligned LDS access related hardware bug though alignment requirements
1531     // are "disabled". In either case, we need to check for proper alignment
1532     // requirements.
1533     //
1534     switch (Size) {
1535     case 64:
1536       // SI has a hardware bug in the LDS / GDS bounds checking: if the base
1537       // address is negative, then the instruction is incorrectly treated as
1538       // out-of-bounds even if base + offsets is in bounds. Split vectorized
1539       // loads here to avoid emitting ds_read2_b32. We may re-combine the
1540       // load later in the SILoadStoreOptimizer.
1541       if (!Subtarget->hasUsableDSOffset() && Alignment < Align(8))
1542         return false;
1543 
1544       // 8 byte accessing via ds_read/write_b64 require 8-byte alignment, but we
1545       // can do a 4 byte aligned, 8 byte access in a single operation using
1546       // ds_read2/write2_b32 with adjacent offsets.
1547       RequiredAlignment = Align(4);
1548 
1549       if (Subtarget->hasUnalignedDSAccessEnabled()) {
1550         // We will either select ds_read_b64/ds_write_b64 or ds_read2_b32/
1551         // ds_write2_b32 depending on the alignment. In either case with either
1552         // alignment there is no faster way of doing this.
1553         if (IsFast)
1554           *IsFast = true;
1555         return true;
1556       }
1557 
1558       break;
1559     case 96:
1560       if (!Subtarget->hasDS96AndDS128())
1561         return false;
1562 
1563       // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
1564       // gfx8 and older.
1565 
1566       if (Subtarget->hasUnalignedDSAccessEnabled()) {
1567         // Naturally aligned access is fastest. However, also report it is Fast
1568         // if memory is aligned less than DWORD. A narrow load or store will be
1569         // be equally slow as a single ds_read_b96/ds_write_b96, but there will
1570         // be more of them, so overall we will pay less penalty issuing a single
1571         // instruction.
1572         if (IsFast)
1573           *IsFast = Alignment >= RequiredAlignment || Alignment < Align(4);
1574         return true;
1575       }
1576 
1577       break;
1578     case 128:
1579       if (!Subtarget->hasDS96AndDS128() || !Subtarget->useDS128())
1580         return false;
1581 
1582       // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
1583       // gfx8 and older, but  we can do a 8 byte aligned, 16 byte access in a
1584       // single operation using ds_read2/write2_b64.
1585       RequiredAlignment = Align(8);
1586 
1587       if (Subtarget->hasUnalignedDSAccessEnabled()) {
1588         // Naturally aligned access is fastest. However, also report it is Fast
1589         // if memory is aligned less than DWORD. A narrow load or store will be
1590         // be equally slow as a single ds_read_b128/ds_write_b128, but there
1591         // will be more of them, so overall we will pay less penalty issuing a
1592         // single instruction.
1593         if (IsFast)
1594           *IsFast = Alignment >= RequiredAlignment || Alignment < Align(4);
1595         return true;
1596       }
1597 
1598       break;
1599     default:
1600       if (Size > 32)
1601         return false;
1602 
1603       break;
1604     }
1605 
1606     if (IsFast)
1607       *IsFast = Alignment >= RequiredAlignment;
1608 
1609     return Alignment >= RequiredAlignment ||
1610            Subtarget->hasUnalignedDSAccessEnabled();
1611   }
1612 
1613   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1614     bool AlignedBy4 = Alignment >= Align(4);
1615     if (IsFast)
1616       *IsFast = AlignedBy4;
1617 
1618     return AlignedBy4 ||
1619            Subtarget->enableFlatScratch() ||
1620            Subtarget->hasUnalignedScratchAccess();
1621   }
1622 
1623   // FIXME: We have to be conservative here and assume that flat operations
1624   // will access scratch.  If we had access to the IR function, then we
1625   // could determine if any private memory was used in the function.
1626   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1627       !Subtarget->hasUnalignedScratchAccess()) {
1628     bool AlignedBy4 = Alignment >= Align(4);
1629     if (IsFast)
1630       *IsFast = AlignedBy4;
1631 
1632     return AlignedBy4;
1633   }
1634 
1635   if (Subtarget->hasUnalignedBufferAccessEnabled()) {
1636     // If we have a uniform constant load, it still requires using a slow
1637     // buffer instruction if unaligned.
1638     if (IsFast) {
1639       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1640       // 2-byte alignment is worse than 1 unless doing a 2-byte access.
1641       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1642                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1643         Alignment >= Align(4) : Alignment != Align(2);
1644     }
1645 
1646     return true;
1647   }
1648 
1649   // Smaller than dword value must be aligned.
1650   if (Size < 32)
1651     return false;
1652 
1653   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1654   // byte-address are ignored, thus forcing Dword alignment.
1655   // This applies to private, global, and constant memory.
1656   if (IsFast)
1657     *IsFast = true;
1658 
1659   return Size >= 32 && Alignment >= Align(4);
1660 }
1661 
1662 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1663     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1664     bool *IsFast) const {
1665   bool Allow = allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1666                                                   Alignment, Flags, IsFast);
1667 
1668   if (Allow && IsFast && Subtarget->hasUnalignedDSAccessEnabled() &&
1669       (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1670        AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1671     // Lie it is fast if +unaligned-access-mode is passed so that DS accesses
1672     // get vectorized. We could use ds_read2_b*/ds_write2_b* instructions on a
1673     // misaligned data which is faster than a pair of ds_read_b*/ds_write_b*
1674     // which would be equally misaligned.
1675     // This is only used by the common passes, selection always calls the
1676     // allowsMisalignedMemoryAccessesImpl version.
1677     *IsFast = true;
1678   }
1679 
1680   return Allow;
1681 }
1682 
1683 EVT SITargetLowering::getOptimalMemOpType(
1684     const MemOp &Op, const AttributeList &FuncAttributes) const {
1685   // FIXME: Should account for address space here.
1686 
1687   // The default fallback uses the private pointer size as a guess for a type to
1688   // use. Make sure we switch these to 64-bit accesses.
1689 
1690   if (Op.size() >= 16 &&
1691       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1692     return MVT::v4i32;
1693 
1694   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1695     return MVT::v2i32;
1696 
1697   // Use the default.
1698   return MVT::Other;
1699 }
1700 
1701 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1702   const MemSDNode *MemNode = cast<MemSDNode>(N);
1703   return MemNode->getMemOperand()->getFlags() & MONoClobber;
1704 }
1705 
1706 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1707   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1708          AS == AMDGPUAS::PRIVATE_ADDRESS;
1709 }
1710 
1711 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1712                                            unsigned DestAS) const {
1713   // Flat -> private/local is a simple truncate.
1714   // Flat -> global is no-op
1715   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1716     return true;
1717 
1718   const GCNTargetMachine &TM =
1719       static_cast<const GCNTargetMachine &>(getTargetMachine());
1720   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1721 }
1722 
1723 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1724   const MemSDNode *MemNode = cast<MemSDNode>(N);
1725 
1726   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1727 }
1728 
1729 TargetLoweringBase::LegalizeTypeAction
1730 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1731   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1732       VT.getScalarType().bitsLE(MVT::i16))
1733     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1734   return TargetLoweringBase::getPreferredVectorAction(VT);
1735 }
1736 
1737 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1738                                                          Type *Ty) const {
1739   // FIXME: Could be smarter if called for vector constants.
1740   return true;
1741 }
1742 
1743 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1744   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1745     switch (Op) {
1746     case ISD::LOAD:
1747     case ISD::STORE:
1748 
1749     // These operations are done with 32-bit instructions anyway.
1750     case ISD::AND:
1751     case ISD::OR:
1752     case ISD::XOR:
1753     case ISD::SELECT:
1754       // TODO: Extensions?
1755       return true;
1756     default:
1757       return false;
1758     }
1759   }
1760 
1761   // SimplifySetCC uses this function to determine whether or not it should
1762   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1763   if (VT == MVT::i1 && Op == ISD::SETCC)
1764     return false;
1765 
1766   return TargetLowering::isTypeDesirableForOp(Op, VT);
1767 }
1768 
1769 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1770                                                    const SDLoc &SL,
1771                                                    SDValue Chain,
1772                                                    uint64_t Offset) const {
1773   const DataLayout &DL = DAG.getDataLayout();
1774   MachineFunction &MF = DAG.getMachineFunction();
1775   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1776 
1777   const ArgDescriptor *InputPtrReg;
1778   const TargetRegisterClass *RC;
1779   LLT ArgTy;
1780   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1781 
1782   std::tie(InputPtrReg, RC, ArgTy) =
1783       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1784 
1785   // We may not have the kernarg segment argument if we have no kernel
1786   // arguments.
1787   if (!InputPtrReg)
1788     return DAG.getConstant(0, SL, PtrVT);
1789 
1790   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1791   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1792     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1793 
1794   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1795 }
1796 
1797 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1798                                             const SDLoc &SL) const {
1799   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1800                                                FIRST_IMPLICIT);
1801   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1802 }
1803 
1804 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1805                                          const SDLoc &SL, SDValue Val,
1806                                          bool Signed,
1807                                          const ISD::InputArg *Arg) const {
1808   // First, if it is a widened vector, narrow it.
1809   if (VT.isVector() &&
1810       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1811     EVT NarrowedVT =
1812         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1813                          VT.getVectorNumElements());
1814     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1815                       DAG.getConstant(0, SL, MVT::i32));
1816   }
1817 
1818   // Then convert the vector elements or scalar value.
1819   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1820       VT.bitsLT(MemVT)) {
1821     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1822     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1823   }
1824 
1825   if (MemVT.isFloatingPoint())
1826     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1827   else if (Signed)
1828     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1829   else
1830     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1831 
1832   return Val;
1833 }
1834 
1835 SDValue SITargetLowering::lowerKernargMemParameter(
1836     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1837     uint64_t Offset, Align Alignment, bool Signed,
1838     const ISD::InputArg *Arg) const {
1839   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1840 
1841   // Try to avoid using an extload by loading earlier than the argument address,
1842   // and extracting the relevant bits. The load should hopefully be merged with
1843   // the previous argument.
1844   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1845     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1846     int64_t AlignDownOffset = alignDown(Offset, 4);
1847     int64_t OffsetDiff = Offset - AlignDownOffset;
1848 
1849     EVT IntVT = MemVT.changeTypeToInteger();
1850 
1851     // TODO: If we passed in the base kernel offset we could have a better
1852     // alignment than 4, but we don't really need it.
1853     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1854     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1855                                MachineMemOperand::MODereferenceable |
1856                                    MachineMemOperand::MOInvariant);
1857 
1858     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1859     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1860 
1861     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1862     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1863     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1864 
1865 
1866     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1867   }
1868 
1869   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1870   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1871                              MachineMemOperand::MODereferenceable |
1872                                  MachineMemOperand::MOInvariant);
1873 
1874   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1875   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1876 }
1877 
1878 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1879                                               const SDLoc &SL, SDValue Chain,
1880                                               const ISD::InputArg &Arg) const {
1881   MachineFunction &MF = DAG.getMachineFunction();
1882   MachineFrameInfo &MFI = MF.getFrameInfo();
1883 
1884   if (Arg.Flags.isByVal()) {
1885     unsigned Size = Arg.Flags.getByValSize();
1886     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1887     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1888   }
1889 
1890   unsigned ArgOffset = VA.getLocMemOffset();
1891   unsigned ArgSize = VA.getValVT().getStoreSize();
1892 
1893   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1894 
1895   // Create load nodes to retrieve arguments from the stack.
1896   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1897   SDValue ArgValue;
1898 
1899   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1900   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1901   MVT MemVT = VA.getValVT();
1902 
1903   switch (VA.getLocInfo()) {
1904   default:
1905     break;
1906   case CCValAssign::BCvt:
1907     MemVT = VA.getLocVT();
1908     break;
1909   case CCValAssign::SExt:
1910     ExtType = ISD::SEXTLOAD;
1911     break;
1912   case CCValAssign::ZExt:
1913     ExtType = ISD::ZEXTLOAD;
1914     break;
1915   case CCValAssign::AExt:
1916     ExtType = ISD::EXTLOAD;
1917     break;
1918   }
1919 
1920   ArgValue = DAG.getExtLoad(
1921     ExtType, SL, VA.getLocVT(), Chain, FIN,
1922     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1923     MemVT);
1924   return ArgValue;
1925 }
1926 
1927 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1928   const SIMachineFunctionInfo &MFI,
1929   EVT VT,
1930   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1931   const ArgDescriptor *Reg;
1932   const TargetRegisterClass *RC;
1933   LLT Ty;
1934 
1935   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1936   if (!Reg) {
1937     if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) {
1938       // It's possible for a kernarg intrinsic call to appear in a kernel with
1939       // no allocated segment, in which case we do not add the user sgpr
1940       // argument, so just return null.
1941       return DAG.getConstant(0, SDLoc(), VT);
1942     }
1943 
1944     // It's undefined behavior if a function marked with the amdgpu-no-*
1945     // attributes uses the corresponding intrinsic.
1946     return DAG.getUNDEF(VT);
1947   }
1948 
1949   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1950 }
1951 
1952 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1953                                CallingConv::ID CallConv,
1954                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1955                                FunctionType *FType,
1956                                SIMachineFunctionInfo *Info) {
1957   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1958     const ISD::InputArg *Arg = &Ins[I];
1959 
1960     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1961            "vector type argument should have been split");
1962 
1963     // First check if it's a PS input addr.
1964     if (CallConv == CallingConv::AMDGPU_PS &&
1965         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1966       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1967 
1968       // Inconveniently only the first part of the split is marked as isSplit,
1969       // so skip to the end. We only want to increment PSInputNum once for the
1970       // entire split argument.
1971       if (Arg->Flags.isSplit()) {
1972         while (!Arg->Flags.isSplitEnd()) {
1973           assert((!Arg->VT.isVector() ||
1974                   Arg->VT.getScalarSizeInBits() == 16) &&
1975                  "unexpected vector split in ps argument type");
1976           if (!SkipArg)
1977             Splits.push_back(*Arg);
1978           Arg = &Ins[++I];
1979         }
1980       }
1981 
1982       if (SkipArg) {
1983         // We can safely skip PS inputs.
1984         Skipped.set(Arg->getOrigArgIndex());
1985         ++PSInputNum;
1986         continue;
1987       }
1988 
1989       Info->markPSInputAllocated(PSInputNum);
1990       if (Arg->Used)
1991         Info->markPSInputEnabled(PSInputNum);
1992 
1993       ++PSInputNum;
1994     }
1995 
1996     Splits.push_back(*Arg);
1997   }
1998 }
1999 
2000 // Allocate special inputs passed in VGPRs.
2001 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
2002                                                       MachineFunction &MF,
2003                                                       const SIRegisterInfo &TRI,
2004                                                       SIMachineFunctionInfo &Info) const {
2005   const LLT S32 = LLT::scalar(32);
2006   MachineRegisterInfo &MRI = MF.getRegInfo();
2007 
2008   if (Info.hasWorkItemIDX()) {
2009     Register Reg = AMDGPU::VGPR0;
2010     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
2011 
2012     CCInfo.AllocateReg(Reg);
2013     unsigned Mask = (Subtarget->hasPackedTID() &&
2014                      Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
2015     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2016   }
2017 
2018   if (Info.hasWorkItemIDY()) {
2019     assert(Info.hasWorkItemIDX());
2020     if (Subtarget->hasPackedTID()) {
2021       Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
2022                                                         0x3ff << 10));
2023     } else {
2024       unsigned Reg = AMDGPU::VGPR1;
2025       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
2026 
2027       CCInfo.AllocateReg(Reg);
2028       Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
2029     }
2030   }
2031 
2032   if (Info.hasWorkItemIDZ()) {
2033     assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
2034     if (Subtarget->hasPackedTID()) {
2035       Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
2036                                                         0x3ff << 20));
2037     } else {
2038       unsigned Reg = AMDGPU::VGPR2;
2039       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
2040 
2041       CCInfo.AllocateReg(Reg);
2042       Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
2043     }
2044   }
2045 }
2046 
2047 // Try to allocate a VGPR at the end of the argument list, or if no argument
2048 // VGPRs are left allocating a stack slot.
2049 // If \p Mask is is given it indicates bitfield position in the register.
2050 // If \p Arg is given use it with new ]p Mask instead of allocating new.
2051 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
2052                                          ArgDescriptor Arg = ArgDescriptor()) {
2053   if (Arg.isSet())
2054     return ArgDescriptor::createArg(Arg, Mask);
2055 
2056   ArrayRef<MCPhysReg> ArgVGPRs
2057     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
2058   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
2059   if (RegIdx == ArgVGPRs.size()) {
2060     // Spill to stack required.
2061     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
2062 
2063     return ArgDescriptor::createStack(Offset, Mask);
2064   }
2065 
2066   unsigned Reg = ArgVGPRs[RegIdx];
2067   Reg = CCInfo.AllocateReg(Reg);
2068   assert(Reg != AMDGPU::NoRegister);
2069 
2070   MachineFunction &MF = CCInfo.getMachineFunction();
2071   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
2072   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
2073   return ArgDescriptor::createRegister(Reg, Mask);
2074 }
2075 
2076 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
2077                                              const TargetRegisterClass *RC,
2078                                              unsigned NumArgRegs) {
2079   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
2080   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
2081   if (RegIdx == ArgSGPRs.size())
2082     report_fatal_error("ran out of SGPRs for arguments");
2083 
2084   unsigned Reg = ArgSGPRs[RegIdx];
2085   Reg = CCInfo.AllocateReg(Reg);
2086   assert(Reg != AMDGPU::NoRegister);
2087 
2088   MachineFunction &MF = CCInfo.getMachineFunction();
2089   MF.addLiveIn(Reg, RC);
2090   return ArgDescriptor::createRegister(Reg);
2091 }
2092 
2093 // If this has a fixed position, we still should allocate the register in the
2094 // CCInfo state. Technically we could get away with this for values passed
2095 // outside of the normal argument range.
2096 static void allocateFixedSGPRInputImpl(CCState &CCInfo,
2097                                        const TargetRegisterClass *RC,
2098                                        MCRegister Reg) {
2099   Reg = CCInfo.AllocateReg(Reg);
2100   assert(Reg != AMDGPU::NoRegister);
2101   MachineFunction &MF = CCInfo.getMachineFunction();
2102   MF.addLiveIn(Reg, RC);
2103 }
2104 
2105 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
2106   if (Arg) {
2107     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
2108                                Arg.getRegister());
2109   } else
2110     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
2111 }
2112 
2113 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
2114   if (Arg) {
2115     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
2116                                Arg.getRegister());
2117   } else
2118     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
2119 }
2120 
2121 /// Allocate implicit function VGPR arguments at the end of allocated user
2122 /// arguments.
2123 void SITargetLowering::allocateSpecialInputVGPRs(
2124   CCState &CCInfo, MachineFunction &MF,
2125   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2126   const unsigned Mask = 0x3ff;
2127   ArgDescriptor Arg;
2128 
2129   if (Info.hasWorkItemIDX()) {
2130     Arg = allocateVGPR32Input(CCInfo, Mask);
2131     Info.setWorkItemIDX(Arg);
2132   }
2133 
2134   if (Info.hasWorkItemIDY()) {
2135     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
2136     Info.setWorkItemIDY(Arg);
2137   }
2138 
2139   if (Info.hasWorkItemIDZ())
2140     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
2141 }
2142 
2143 /// Allocate implicit function VGPR arguments in fixed registers.
2144 void SITargetLowering::allocateSpecialInputVGPRsFixed(
2145   CCState &CCInfo, MachineFunction &MF,
2146   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2147   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
2148   if (!Reg)
2149     report_fatal_error("failed to allocated VGPR for implicit arguments");
2150 
2151   const unsigned Mask = 0x3ff;
2152   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2153   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
2154   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
2155 }
2156 
2157 void SITargetLowering::allocateSpecialInputSGPRs(
2158   CCState &CCInfo,
2159   MachineFunction &MF,
2160   const SIRegisterInfo &TRI,
2161   SIMachineFunctionInfo &Info) const {
2162   auto &ArgInfo = Info.getArgInfo();
2163 
2164   // TODO: Unify handling with private memory pointers.
2165   if (Info.hasDispatchPtr())
2166     allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
2167 
2168   if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5)
2169     allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
2170 
2171   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
2172   // constant offset from the kernarg segment.
2173   if (Info.hasImplicitArgPtr())
2174     allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
2175 
2176   if (Info.hasDispatchID())
2177     allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2178 
2179   // flat_scratch_init is not applicable for non-kernel functions.
2180 
2181   if (Info.hasWorkGroupIDX())
2182     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2183 
2184   if (Info.hasWorkGroupIDY())
2185     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2186 
2187   if (Info.hasWorkGroupIDZ())
2188     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2189 }
2190 
2191 // Allocate special inputs passed in user SGPRs.
2192 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2193                                             MachineFunction &MF,
2194                                             const SIRegisterInfo &TRI,
2195                                             SIMachineFunctionInfo &Info) const {
2196   if (Info.hasImplicitBufferPtr()) {
2197     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2198     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2199     CCInfo.AllocateReg(ImplicitBufferPtrReg);
2200   }
2201 
2202   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2203   if (Info.hasPrivateSegmentBuffer()) {
2204     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2205     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2206     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2207   }
2208 
2209   if (Info.hasDispatchPtr()) {
2210     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2211     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2212     CCInfo.AllocateReg(DispatchPtrReg);
2213   }
2214 
2215   if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) {
2216     Register QueuePtrReg = Info.addQueuePtr(TRI);
2217     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2218     CCInfo.AllocateReg(QueuePtrReg);
2219   }
2220 
2221   if (Info.hasKernargSegmentPtr()) {
2222     MachineRegisterInfo &MRI = MF.getRegInfo();
2223     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2224     CCInfo.AllocateReg(InputPtrReg);
2225 
2226     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2227     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2228   }
2229 
2230   if (Info.hasDispatchID()) {
2231     Register DispatchIDReg = Info.addDispatchID(TRI);
2232     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2233     CCInfo.AllocateReg(DispatchIDReg);
2234   }
2235 
2236   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2237     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2238     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2239     CCInfo.AllocateReg(FlatScratchInitReg);
2240   }
2241 
2242   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2243   // these from the dispatch pointer.
2244 }
2245 
2246 // Allocate special input registers that are initialized per-wave.
2247 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2248                                            MachineFunction &MF,
2249                                            SIMachineFunctionInfo &Info,
2250                                            CallingConv::ID CallConv,
2251                                            bool IsShader) const {
2252   if (Info.hasWorkGroupIDX()) {
2253     Register Reg = Info.addWorkGroupIDX();
2254     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2255     CCInfo.AllocateReg(Reg);
2256   }
2257 
2258   if (Info.hasWorkGroupIDY()) {
2259     Register Reg = Info.addWorkGroupIDY();
2260     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2261     CCInfo.AllocateReg(Reg);
2262   }
2263 
2264   if (Info.hasWorkGroupIDZ()) {
2265     Register Reg = Info.addWorkGroupIDZ();
2266     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2267     CCInfo.AllocateReg(Reg);
2268   }
2269 
2270   if (Info.hasWorkGroupInfo()) {
2271     Register Reg = Info.addWorkGroupInfo();
2272     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2273     CCInfo.AllocateReg(Reg);
2274   }
2275 
2276   if (Info.hasPrivateSegmentWaveByteOffset()) {
2277     // Scratch wave offset passed in system SGPR.
2278     unsigned PrivateSegmentWaveByteOffsetReg;
2279 
2280     if (IsShader) {
2281       PrivateSegmentWaveByteOffsetReg =
2282         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2283 
2284       // This is true if the scratch wave byte offset doesn't have a fixed
2285       // location.
2286       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2287         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2288         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2289       }
2290     } else
2291       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2292 
2293     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2294     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2295   }
2296 }
2297 
2298 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2299                                      MachineFunction &MF,
2300                                      const SIRegisterInfo &TRI,
2301                                      SIMachineFunctionInfo &Info) {
2302   // Now that we've figured out where the scratch register inputs are, see if
2303   // should reserve the arguments and use them directly.
2304   MachineFrameInfo &MFI = MF.getFrameInfo();
2305   bool HasStackObjects = MFI.hasStackObjects();
2306   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2307 
2308   // Record that we know we have non-spill stack objects so we don't need to
2309   // check all stack objects later.
2310   if (HasStackObjects)
2311     Info.setHasNonSpillStackObjects(true);
2312 
2313   // Everything live out of a block is spilled with fast regalloc, so it's
2314   // almost certain that spilling will be required.
2315   if (TM.getOptLevel() == CodeGenOpt::None)
2316     HasStackObjects = true;
2317 
2318   // For now assume stack access is needed in any callee functions, so we need
2319   // the scratch registers to pass in.
2320   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2321 
2322   if (!ST.enableFlatScratch()) {
2323     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2324       // If we have stack objects, we unquestionably need the private buffer
2325       // resource. For the Code Object V2 ABI, this will be the first 4 user
2326       // SGPR inputs. We can reserve those and use them directly.
2327 
2328       Register PrivateSegmentBufferReg =
2329           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2330       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2331     } else {
2332       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2333       // We tentatively reserve the last registers (skipping the last registers
2334       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2335       // we'll replace these with the ones immediately after those which were
2336       // really allocated. In the prologue copies will be inserted from the
2337       // argument to these reserved registers.
2338 
2339       // Without HSA, relocations are used for the scratch pointer and the
2340       // buffer resource setup is always inserted in the prologue. Scratch wave
2341       // offset is still in an input SGPR.
2342       Info.setScratchRSrcReg(ReservedBufferReg);
2343     }
2344   }
2345 
2346   MachineRegisterInfo &MRI = MF.getRegInfo();
2347 
2348   // For entry functions we have to set up the stack pointer if we use it,
2349   // whereas non-entry functions get this "for free". This means there is no
2350   // intrinsic advantage to using S32 over S34 in cases where we do not have
2351   // calls but do need a frame pointer (i.e. if we are requested to have one
2352   // because frame pointer elimination is disabled). To keep things simple we
2353   // only ever use S32 as the call ABI stack pointer, and so using it does not
2354   // imply we need a separate frame pointer.
2355   //
2356   // Try to use s32 as the SP, but move it if it would interfere with input
2357   // arguments. This won't work with calls though.
2358   //
2359   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2360   // registers.
2361   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2362     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2363   } else {
2364     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2365 
2366     if (MFI.hasCalls())
2367       report_fatal_error("call in graphics shader with too many input SGPRs");
2368 
2369     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2370       if (!MRI.isLiveIn(Reg)) {
2371         Info.setStackPtrOffsetReg(Reg);
2372         break;
2373       }
2374     }
2375 
2376     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2377       report_fatal_error("failed to find register for SP");
2378   }
2379 
2380   // hasFP should be accurate for entry functions even before the frame is
2381   // finalized, because it does not rely on the known stack size, only
2382   // properties like whether variable sized objects are present.
2383   if (ST.getFrameLowering()->hasFP(MF)) {
2384     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2385   }
2386 }
2387 
2388 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2389   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2390   return !Info->isEntryFunction();
2391 }
2392 
2393 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2394 
2395 }
2396 
2397 void SITargetLowering::insertCopiesSplitCSR(
2398   MachineBasicBlock *Entry,
2399   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2400   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2401 
2402   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2403   if (!IStart)
2404     return;
2405 
2406   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2407   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2408   MachineBasicBlock::iterator MBBI = Entry->begin();
2409   for (const MCPhysReg *I = IStart; *I; ++I) {
2410     const TargetRegisterClass *RC = nullptr;
2411     if (AMDGPU::SReg_64RegClass.contains(*I))
2412       RC = &AMDGPU::SGPR_64RegClass;
2413     else if (AMDGPU::SReg_32RegClass.contains(*I))
2414       RC = &AMDGPU::SGPR_32RegClass;
2415     else
2416       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2417 
2418     Register NewVR = MRI->createVirtualRegister(RC);
2419     // Create copy from CSR to a virtual register.
2420     Entry->addLiveIn(*I);
2421     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2422       .addReg(*I);
2423 
2424     // Insert the copy-back instructions right before the terminator.
2425     for (auto *Exit : Exits)
2426       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2427               TII->get(TargetOpcode::COPY), *I)
2428         .addReg(NewVR);
2429   }
2430 }
2431 
2432 SDValue SITargetLowering::LowerFormalArguments(
2433     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2434     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2435     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2436   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2437 
2438   MachineFunction &MF = DAG.getMachineFunction();
2439   const Function &Fn = MF.getFunction();
2440   FunctionType *FType = MF.getFunction().getFunctionType();
2441   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2442 
2443   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2444     DiagnosticInfoUnsupported NoGraphicsHSA(
2445         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2446     DAG.getContext()->diagnose(NoGraphicsHSA);
2447     return DAG.getEntryNode();
2448   }
2449 
2450   Info->allocateModuleLDSGlobal(Fn.getParent());
2451 
2452   SmallVector<ISD::InputArg, 16> Splits;
2453   SmallVector<CCValAssign, 16> ArgLocs;
2454   BitVector Skipped(Ins.size());
2455   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2456                  *DAG.getContext());
2457 
2458   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2459   bool IsKernel = AMDGPU::isKernel(CallConv);
2460   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2461 
2462   if (IsGraphics) {
2463     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2464            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2465            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2466            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2467            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2468            !Info->hasWorkItemIDZ());
2469   }
2470 
2471   if (CallConv == CallingConv::AMDGPU_PS) {
2472     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2473 
2474     // At least one interpolation mode must be enabled or else the GPU will
2475     // hang.
2476     //
2477     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2478     // set PSInputAddr, the user wants to enable some bits after the compilation
2479     // based on run-time states. Since we can't know what the final PSInputEna
2480     // will look like, so we shouldn't do anything here and the user should take
2481     // responsibility for the correct programming.
2482     //
2483     // Otherwise, the following restrictions apply:
2484     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2485     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2486     //   enabled too.
2487     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2488         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2489       CCInfo.AllocateReg(AMDGPU::VGPR0);
2490       CCInfo.AllocateReg(AMDGPU::VGPR1);
2491       Info->markPSInputAllocated(0);
2492       Info->markPSInputEnabled(0);
2493     }
2494     if (Subtarget->isAmdPalOS()) {
2495       // For isAmdPalOS, the user does not enable some bits after compilation
2496       // based on run-time states; the register values being generated here are
2497       // the final ones set in hardware. Therefore we need to apply the
2498       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2499       // a bit is set in PSInputAddr but not PSInputEnable is where the
2500       // frontend set up an input arg for a particular interpolation mode, but
2501       // nothing uses that input arg. Really we should have an earlier pass
2502       // that removes such an arg.)
2503       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2504       if ((PsInputBits & 0x7F) == 0 ||
2505           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2506         Info->markPSInputEnabled(
2507             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2508     }
2509   } else if (IsKernel) {
2510     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2511   } else {
2512     Splits.append(Ins.begin(), Ins.end());
2513   }
2514 
2515   if (IsEntryFunc) {
2516     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2517     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2518   } else if (!IsGraphics) {
2519     // For the fixed ABI, pass workitem IDs in the last argument register.
2520     allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2521   }
2522 
2523   if (IsKernel) {
2524     analyzeFormalArgumentsCompute(CCInfo, Ins);
2525   } else {
2526     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2527     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2528   }
2529 
2530   SmallVector<SDValue, 16> Chains;
2531 
2532   // FIXME: This is the minimum kernel argument alignment. We should improve
2533   // this to the maximum alignment of the arguments.
2534   //
2535   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2536   // kern arg offset.
2537   const Align KernelArgBaseAlign = Align(16);
2538 
2539   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2540     const ISD::InputArg &Arg = Ins[i];
2541     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2542       InVals.push_back(DAG.getUNDEF(Arg.VT));
2543       continue;
2544     }
2545 
2546     CCValAssign &VA = ArgLocs[ArgIdx++];
2547     MVT VT = VA.getLocVT();
2548 
2549     if (IsEntryFunc && VA.isMemLoc()) {
2550       VT = Ins[i].VT;
2551       EVT MemVT = VA.getLocVT();
2552 
2553       const uint64_t Offset = VA.getLocMemOffset();
2554       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2555 
2556       if (Arg.Flags.isByRef()) {
2557         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2558 
2559         const GCNTargetMachine &TM =
2560             static_cast<const GCNTargetMachine &>(getTargetMachine());
2561         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2562                                     Arg.Flags.getPointerAddrSpace())) {
2563           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2564                                      Arg.Flags.getPointerAddrSpace());
2565         }
2566 
2567         InVals.push_back(Ptr);
2568         continue;
2569       }
2570 
2571       SDValue Arg = lowerKernargMemParameter(
2572         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2573       Chains.push_back(Arg.getValue(1));
2574 
2575       auto *ParamTy =
2576         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2577       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2578           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2579                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2580         // On SI local pointers are just offsets into LDS, so they are always
2581         // less than 16-bits.  On CI and newer they could potentially be
2582         // real pointers, so we can't guarantee their size.
2583         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2584                           DAG.getValueType(MVT::i16));
2585       }
2586 
2587       InVals.push_back(Arg);
2588       continue;
2589     } else if (!IsEntryFunc && VA.isMemLoc()) {
2590       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2591       InVals.push_back(Val);
2592       if (!Arg.Flags.isByVal())
2593         Chains.push_back(Val.getValue(1));
2594       continue;
2595     }
2596 
2597     assert(VA.isRegLoc() && "Parameter must be in a register!");
2598 
2599     Register Reg = VA.getLocReg();
2600     const TargetRegisterClass *RC = nullptr;
2601     if (AMDGPU::VGPR_32RegClass.contains(Reg))
2602       RC = &AMDGPU::VGPR_32RegClass;
2603     else if (AMDGPU::SGPR_32RegClass.contains(Reg))
2604       RC = &AMDGPU::SGPR_32RegClass;
2605     else
2606       llvm_unreachable("Unexpected register class in LowerFormalArguments!");
2607     EVT ValVT = VA.getValVT();
2608 
2609     Reg = MF.addLiveIn(Reg, RC);
2610     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2611 
2612     if (Arg.Flags.isSRet()) {
2613       // The return object should be reasonably addressable.
2614 
2615       // FIXME: This helps when the return is a real sret. If it is a
2616       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2617       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2618       unsigned NumBits
2619         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2620       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2621         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2622     }
2623 
2624     // If this is an 8 or 16-bit value, it is really passed promoted
2625     // to 32 bits. Insert an assert[sz]ext to capture this, then
2626     // truncate to the right size.
2627     switch (VA.getLocInfo()) {
2628     case CCValAssign::Full:
2629       break;
2630     case CCValAssign::BCvt:
2631       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2632       break;
2633     case CCValAssign::SExt:
2634       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2635                         DAG.getValueType(ValVT));
2636       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2637       break;
2638     case CCValAssign::ZExt:
2639       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2640                         DAG.getValueType(ValVT));
2641       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2642       break;
2643     case CCValAssign::AExt:
2644       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2645       break;
2646     default:
2647       llvm_unreachable("Unknown loc info!");
2648     }
2649 
2650     InVals.push_back(Val);
2651   }
2652 
2653   // Start adding system SGPRs.
2654   if (IsEntryFunc) {
2655     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2656   } else {
2657     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2658     if (!IsGraphics)
2659       allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2660   }
2661 
2662   auto &ArgUsageInfo =
2663     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2664   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2665 
2666   unsigned StackArgSize = CCInfo.getNextStackOffset();
2667   Info->setBytesInStackArgArea(StackArgSize);
2668 
2669   return Chains.empty() ? Chain :
2670     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2671 }
2672 
2673 // TODO: If return values can't fit in registers, we should return as many as
2674 // possible in registers before passing on stack.
2675 bool SITargetLowering::CanLowerReturn(
2676   CallingConv::ID CallConv,
2677   MachineFunction &MF, bool IsVarArg,
2678   const SmallVectorImpl<ISD::OutputArg> &Outs,
2679   LLVMContext &Context) const {
2680   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2681   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2682   // for shaders. Vector types should be explicitly handled by CC.
2683   if (AMDGPU::isEntryFunctionCC(CallConv))
2684     return true;
2685 
2686   SmallVector<CCValAssign, 16> RVLocs;
2687   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2688   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2689 }
2690 
2691 SDValue
2692 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2693                               bool isVarArg,
2694                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2695                               const SmallVectorImpl<SDValue> &OutVals,
2696                               const SDLoc &DL, SelectionDAG &DAG) const {
2697   MachineFunction &MF = DAG.getMachineFunction();
2698   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2699 
2700   if (AMDGPU::isKernel(CallConv)) {
2701     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2702                                              OutVals, DL, DAG);
2703   }
2704 
2705   bool IsShader = AMDGPU::isShader(CallConv);
2706 
2707   Info->setIfReturnsVoid(Outs.empty());
2708   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2709 
2710   // CCValAssign - represent the assignment of the return value to a location.
2711   SmallVector<CCValAssign, 48> RVLocs;
2712   SmallVector<ISD::OutputArg, 48> Splits;
2713 
2714   // CCState - Info about the registers and stack slots.
2715   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2716                  *DAG.getContext());
2717 
2718   // Analyze outgoing return values.
2719   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2720 
2721   SDValue Flag;
2722   SmallVector<SDValue, 48> RetOps;
2723   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2724 
2725   // Copy the result values into the output registers.
2726   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2727        ++I, ++RealRVLocIdx) {
2728     CCValAssign &VA = RVLocs[I];
2729     assert(VA.isRegLoc() && "Can only return in registers!");
2730     // TODO: Partially return in registers if return values don't fit.
2731     SDValue Arg = OutVals[RealRVLocIdx];
2732 
2733     // Copied from other backends.
2734     switch (VA.getLocInfo()) {
2735     case CCValAssign::Full:
2736       break;
2737     case CCValAssign::BCvt:
2738       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2739       break;
2740     case CCValAssign::SExt:
2741       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2742       break;
2743     case CCValAssign::ZExt:
2744       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2745       break;
2746     case CCValAssign::AExt:
2747       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2748       break;
2749     default:
2750       llvm_unreachable("Unknown loc info!");
2751     }
2752 
2753     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2754     Flag = Chain.getValue(1);
2755     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2756   }
2757 
2758   // FIXME: Does sret work properly?
2759   if (!Info->isEntryFunction()) {
2760     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2761     const MCPhysReg *I =
2762       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2763     if (I) {
2764       for (; *I; ++I) {
2765         if (AMDGPU::SReg_64RegClass.contains(*I))
2766           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2767         else if (AMDGPU::SReg_32RegClass.contains(*I))
2768           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2769         else
2770           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2771       }
2772     }
2773   }
2774 
2775   // Update chain and glue.
2776   RetOps[0] = Chain;
2777   if (Flag.getNode())
2778     RetOps.push_back(Flag);
2779 
2780   unsigned Opc = AMDGPUISD::ENDPGM;
2781   if (!IsWaveEnd)
2782     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2783   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2784 }
2785 
2786 SDValue SITargetLowering::LowerCallResult(
2787     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2788     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2789     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2790     SDValue ThisVal) const {
2791   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2792 
2793   // Assign locations to each value returned by this call.
2794   SmallVector<CCValAssign, 16> RVLocs;
2795   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2796                  *DAG.getContext());
2797   CCInfo.AnalyzeCallResult(Ins, RetCC);
2798 
2799   // Copy all of the result registers out of their specified physreg.
2800   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2801     CCValAssign VA = RVLocs[i];
2802     SDValue Val;
2803 
2804     if (VA.isRegLoc()) {
2805       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2806       Chain = Val.getValue(1);
2807       InFlag = Val.getValue(2);
2808     } else if (VA.isMemLoc()) {
2809       report_fatal_error("TODO: return values in memory");
2810     } else
2811       llvm_unreachable("unknown argument location type");
2812 
2813     switch (VA.getLocInfo()) {
2814     case CCValAssign::Full:
2815       break;
2816     case CCValAssign::BCvt:
2817       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2818       break;
2819     case CCValAssign::ZExt:
2820       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2821                         DAG.getValueType(VA.getValVT()));
2822       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2823       break;
2824     case CCValAssign::SExt:
2825       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2826                         DAG.getValueType(VA.getValVT()));
2827       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2828       break;
2829     case CCValAssign::AExt:
2830       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2831       break;
2832     default:
2833       llvm_unreachable("Unknown loc info!");
2834     }
2835 
2836     InVals.push_back(Val);
2837   }
2838 
2839   return Chain;
2840 }
2841 
2842 // Add code to pass special inputs required depending on used features separate
2843 // from the explicit user arguments present in the IR.
2844 void SITargetLowering::passSpecialInputs(
2845     CallLoweringInfo &CLI,
2846     CCState &CCInfo,
2847     const SIMachineFunctionInfo &Info,
2848     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2849     SmallVectorImpl<SDValue> &MemOpChains,
2850     SDValue Chain) const {
2851   // If we don't have a call site, this was a call inserted by
2852   // legalization. These can never use special inputs.
2853   if (!CLI.CB)
2854     return;
2855 
2856   SelectionDAG &DAG = CLI.DAG;
2857   const SDLoc &DL = CLI.DL;
2858   const Function &F = DAG.getMachineFunction().getFunction();
2859 
2860   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2861   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2862 
2863   const AMDGPUFunctionArgInfo *CalleeArgInfo
2864     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2865   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2866     auto &ArgUsageInfo =
2867       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2868     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2869   }
2870 
2871   // TODO: Unify with private memory register handling. This is complicated by
2872   // the fact that at least in kernels, the input argument is not necessarily
2873   // in the same location as the input.
2874   static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
2875                              StringLiteral> ImplicitAttrs[] = {
2876     {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"},
2877     {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" },
2878     {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"},
2879     {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"},
2880     {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"},
2881     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"},
2882     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"}
2883   };
2884 
2885   for (auto Attr : ImplicitAttrs) {
2886     const ArgDescriptor *OutgoingArg;
2887     const TargetRegisterClass *ArgRC;
2888     LLT ArgTy;
2889 
2890     AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first;
2891 
2892     // If the callee does not use the attribute value, skip copying the value.
2893     if (CLI.CB->hasFnAttr(Attr.second))
2894       continue;
2895 
2896     std::tie(OutgoingArg, ArgRC, ArgTy) =
2897         CalleeArgInfo->getPreloadedValue(InputID);
2898     if (!OutgoingArg)
2899       continue;
2900 
2901     const ArgDescriptor *IncomingArg;
2902     const TargetRegisterClass *IncomingArgRC;
2903     LLT Ty;
2904     std::tie(IncomingArg, IncomingArgRC, Ty) =
2905         CallerArgInfo.getPreloadedValue(InputID);
2906     assert(IncomingArgRC == ArgRC);
2907 
2908     // All special arguments are ints for now.
2909     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2910     SDValue InputReg;
2911 
2912     if (IncomingArg) {
2913       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2914     } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
2915       // The implicit arg ptr is special because it doesn't have a corresponding
2916       // input for kernels, and is computed from the kernarg segment pointer.
2917       InputReg = getImplicitArgPtr(DAG, DL);
2918     } else {
2919       // We may have proven the input wasn't needed, although the ABI is
2920       // requiring it. We just need to allocate the register appropriately.
2921       InputReg = DAG.getUNDEF(ArgVT);
2922     }
2923 
2924     if (OutgoingArg->isRegister()) {
2925       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2926       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2927         report_fatal_error("failed to allocate implicit input argument");
2928     } else {
2929       unsigned SpecialArgOffset =
2930           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2931       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2932                                               SpecialArgOffset);
2933       MemOpChains.push_back(ArgStore);
2934     }
2935   }
2936 
2937   // Pack workitem IDs into a single register or pass it as is if already
2938   // packed.
2939   const ArgDescriptor *OutgoingArg;
2940   const TargetRegisterClass *ArgRC;
2941   LLT Ty;
2942 
2943   std::tie(OutgoingArg, ArgRC, Ty) =
2944       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2945   if (!OutgoingArg)
2946     std::tie(OutgoingArg, ArgRC, Ty) =
2947         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2948   if (!OutgoingArg)
2949     std::tie(OutgoingArg, ArgRC, Ty) =
2950         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2951   if (!OutgoingArg)
2952     return;
2953 
2954   const ArgDescriptor *IncomingArgX = std::get<0>(
2955       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2956   const ArgDescriptor *IncomingArgY = std::get<0>(
2957       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2958   const ArgDescriptor *IncomingArgZ = std::get<0>(
2959       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2960 
2961   SDValue InputReg;
2962   SDLoc SL;
2963 
2964   const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
2965   const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
2966   const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
2967 
2968   // If incoming ids are not packed we need to pack them.
2969   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
2970       NeedWorkItemIDX) {
2971     if (Subtarget->getMaxWorkitemID(F, 0) != 0) {
2972       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2973     } else {
2974       InputReg = DAG.getConstant(0, DL, MVT::i32);
2975     }
2976   }
2977 
2978   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
2979       NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) {
2980     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2981     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2982                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2983     InputReg = InputReg.getNode() ?
2984                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2985   }
2986 
2987   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
2988       NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) {
2989     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2990     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2991                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2992     InputReg = InputReg.getNode() ?
2993                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2994   }
2995 
2996   if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
2997     if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) {
2998       // We're in a situation where the outgoing function requires the workitem
2999       // ID, but the calling function does not have it (e.g a graphics function
3000       // calling a C calling convention function). This is illegal, but we need
3001       // to produce something.
3002       InputReg = DAG.getUNDEF(MVT::i32);
3003     } else {
3004       // Workitem ids are already packed, any of present incoming arguments
3005       // will carry all required fields.
3006       ArgDescriptor IncomingArg = ArgDescriptor::createArg(
3007         IncomingArgX ? *IncomingArgX :
3008         IncomingArgY ? *IncomingArgY :
3009         *IncomingArgZ, ~0u);
3010       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
3011     }
3012   }
3013 
3014   if (OutgoingArg->isRegister()) {
3015     if (InputReg)
3016       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
3017 
3018     CCInfo.AllocateReg(OutgoingArg->getRegister());
3019   } else {
3020     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
3021     if (InputReg) {
3022       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
3023                                               SpecialArgOffset);
3024       MemOpChains.push_back(ArgStore);
3025     }
3026   }
3027 }
3028 
3029 static bool canGuaranteeTCO(CallingConv::ID CC) {
3030   return CC == CallingConv::Fast;
3031 }
3032 
3033 /// Return true if we might ever do TCO for calls with this calling convention.
3034 static bool mayTailCallThisCC(CallingConv::ID CC) {
3035   switch (CC) {
3036   case CallingConv::C:
3037   case CallingConv::AMDGPU_Gfx:
3038     return true;
3039   default:
3040     return canGuaranteeTCO(CC);
3041   }
3042 }
3043 
3044 bool SITargetLowering::isEligibleForTailCallOptimization(
3045     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
3046     const SmallVectorImpl<ISD::OutputArg> &Outs,
3047     const SmallVectorImpl<SDValue> &OutVals,
3048     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3049   if (!mayTailCallThisCC(CalleeCC))
3050     return false;
3051 
3052   // For a divergent call target, we need to do a waterfall loop over the
3053   // possible callees which precludes us from using a simple jump.
3054   if (Callee->isDivergent())
3055     return false;
3056 
3057   MachineFunction &MF = DAG.getMachineFunction();
3058   const Function &CallerF = MF.getFunction();
3059   CallingConv::ID CallerCC = CallerF.getCallingConv();
3060   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3061   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3062 
3063   // Kernels aren't callable, and don't have a live in return address so it
3064   // doesn't make sense to do a tail call with entry functions.
3065   if (!CallerPreserved)
3066     return false;
3067 
3068   bool CCMatch = CallerCC == CalleeCC;
3069 
3070   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3071     if (canGuaranteeTCO(CalleeCC) && CCMatch)
3072       return true;
3073     return false;
3074   }
3075 
3076   // TODO: Can we handle var args?
3077   if (IsVarArg)
3078     return false;
3079 
3080   for (const Argument &Arg : CallerF.args()) {
3081     if (Arg.hasByValAttr())
3082       return false;
3083   }
3084 
3085   LLVMContext &Ctx = *DAG.getContext();
3086 
3087   // Check that the call results are passed in the same way.
3088   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
3089                                   CCAssignFnForCall(CalleeCC, IsVarArg),
3090                                   CCAssignFnForCall(CallerCC, IsVarArg)))
3091     return false;
3092 
3093   // The callee has to preserve all registers the caller needs to preserve.
3094   if (!CCMatch) {
3095     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3096     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3097       return false;
3098   }
3099 
3100   // Nothing more to check if the callee is taking no arguments.
3101   if (Outs.empty())
3102     return true;
3103 
3104   SmallVector<CCValAssign, 16> ArgLocs;
3105   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
3106 
3107   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
3108 
3109   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
3110   // If the stack arguments for this call do not fit into our own save area then
3111   // the call cannot be made tail.
3112   // TODO: Is this really necessary?
3113   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3114     return false;
3115 
3116   const MachineRegisterInfo &MRI = MF.getRegInfo();
3117   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
3118 }
3119 
3120 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3121   if (!CI->isTailCall())
3122     return false;
3123 
3124   const Function *ParentFn = CI->getParent()->getParent();
3125   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
3126     return false;
3127   return true;
3128 }
3129 
3130 // The wave scratch offset register is used as the global base pointer.
3131 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
3132                                     SmallVectorImpl<SDValue> &InVals) const {
3133   SelectionDAG &DAG = CLI.DAG;
3134   const SDLoc &DL = CLI.DL;
3135   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3136   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3137   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3138   SDValue Chain = CLI.Chain;
3139   SDValue Callee = CLI.Callee;
3140   bool &IsTailCall = CLI.IsTailCall;
3141   CallingConv::ID CallConv = CLI.CallConv;
3142   bool IsVarArg = CLI.IsVarArg;
3143   bool IsSibCall = false;
3144   bool IsThisReturn = false;
3145   MachineFunction &MF = DAG.getMachineFunction();
3146 
3147   if (Callee.isUndef() || isNullConstant(Callee)) {
3148     if (!CLI.IsTailCall) {
3149       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
3150         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
3151     }
3152 
3153     return Chain;
3154   }
3155 
3156   if (IsVarArg) {
3157     return lowerUnhandledCall(CLI, InVals,
3158                               "unsupported call to variadic function ");
3159   }
3160 
3161   if (!CLI.CB)
3162     report_fatal_error("unsupported libcall legalization");
3163 
3164   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
3165     return lowerUnhandledCall(CLI, InVals,
3166                               "unsupported required tail call to function ");
3167   }
3168 
3169   if (AMDGPU::isShader(CallConv)) {
3170     // Note the issue is with the CC of the called function, not of the call
3171     // itself.
3172     return lowerUnhandledCall(CLI, InVals,
3173                               "unsupported call to a shader function ");
3174   }
3175 
3176   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
3177       CallConv != CallingConv::AMDGPU_Gfx) {
3178     // Only allow calls with specific calling conventions.
3179     return lowerUnhandledCall(CLI, InVals,
3180                               "unsupported calling convention for call from "
3181                               "graphics shader of function ");
3182   }
3183 
3184   if (IsTailCall) {
3185     IsTailCall = isEligibleForTailCallOptimization(
3186       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3187     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
3188       report_fatal_error("failed to perform tail call elimination on a call "
3189                          "site marked musttail");
3190     }
3191 
3192     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3193 
3194     // A sibling call is one where we're under the usual C ABI and not planning
3195     // to change that but can still do a tail call:
3196     if (!TailCallOpt && IsTailCall)
3197       IsSibCall = true;
3198 
3199     if (IsTailCall)
3200       ++NumTailCalls;
3201   }
3202 
3203   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3204   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3205   SmallVector<SDValue, 8> MemOpChains;
3206 
3207   // Analyze operands of the call, assigning locations to each operand.
3208   SmallVector<CCValAssign, 16> ArgLocs;
3209   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3210   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3211 
3212   if (CallConv != CallingConv::AMDGPU_Gfx) {
3213     // With a fixed ABI, allocate fixed registers before user arguments.
3214     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3215   }
3216 
3217   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3218 
3219   // Get a count of how many bytes are to be pushed on the stack.
3220   unsigned NumBytes = CCInfo.getNextStackOffset();
3221 
3222   if (IsSibCall) {
3223     // Since we're not changing the ABI to make this a tail call, the memory
3224     // operands are already available in the caller's incoming argument space.
3225     NumBytes = 0;
3226   }
3227 
3228   // FPDiff is the byte offset of the call's argument area from the callee's.
3229   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3230   // by this amount for a tail call. In a sibling call it must be 0 because the
3231   // caller will deallocate the entire stack and the callee still expects its
3232   // arguments to begin at SP+0. Completely unused for non-tail calls.
3233   int32_t FPDiff = 0;
3234   MachineFrameInfo &MFI = MF.getFrameInfo();
3235 
3236   // Adjust the stack pointer for the new arguments...
3237   // These operations are automatically eliminated by the prolog/epilog pass
3238   if (!IsSibCall) {
3239     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3240 
3241     if (!Subtarget->enableFlatScratch()) {
3242       SmallVector<SDValue, 4> CopyFromChains;
3243 
3244       // In the HSA case, this should be an identity copy.
3245       SDValue ScratchRSrcReg
3246         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3247       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3248       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3249       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3250     }
3251   }
3252 
3253   MVT PtrVT = MVT::i32;
3254 
3255   // Walk the register/memloc assignments, inserting copies/loads.
3256   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3257     CCValAssign &VA = ArgLocs[i];
3258     SDValue Arg = OutVals[i];
3259 
3260     // Promote the value if needed.
3261     switch (VA.getLocInfo()) {
3262     case CCValAssign::Full:
3263       break;
3264     case CCValAssign::BCvt:
3265       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3266       break;
3267     case CCValAssign::ZExt:
3268       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3269       break;
3270     case CCValAssign::SExt:
3271       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3272       break;
3273     case CCValAssign::AExt:
3274       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3275       break;
3276     case CCValAssign::FPExt:
3277       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3278       break;
3279     default:
3280       llvm_unreachable("Unknown loc info!");
3281     }
3282 
3283     if (VA.isRegLoc()) {
3284       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3285     } else {
3286       assert(VA.isMemLoc());
3287 
3288       SDValue DstAddr;
3289       MachinePointerInfo DstInfo;
3290 
3291       unsigned LocMemOffset = VA.getLocMemOffset();
3292       int32_t Offset = LocMemOffset;
3293 
3294       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3295       MaybeAlign Alignment;
3296 
3297       if (IsTailCall) {
3298         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3299         unsigned OpSize = Flags.isByVal() ?
3300           Flags.getByValSize() : VA.getValVT().getStoreSize();
3301 
3302         // FIXME: We can have better than the minimum byval required alignment.
3303         Alignment =
3304             Flags.isByVal()
3305                 ? Flags.getNonZeroByValAlign()
3306                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3307 
3308         Offset = Offset + FPDiff;
3309         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3310 
3311         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3312         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3313 
3314         // Make sure any stack arguments overlapping with where we're storing
3315         // are loaded before this eventual operation. Otherwise they'll be
3316         // clobbered.
3317 
3318         // FIXME: Why is this really necessary? This seems to just result in a
3319         // lot of code to copy the stack and write them back to the same
3320         // locations, which are supposed to be immutable?
3321         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3322       } else {
3323         // Stores to the argument stack area are relative to the stack pointer.
3324         SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3325                                         MVT::i32);
3326         DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3327         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3328         Alignment =
3329             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3330       }
3331 
3332       if (Outs[i].Flags.isByVal()) {
3333         SDValue SizeNode =
3334             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3335         SDValue Cpy =
3336             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3337                           Outs[i].Flags.getNonZeroByValAlign(),
3338                           /*isVol = */ false, /*AlwaysInline = */ true,
3339                           /*isTailCall = */ false, DstInfo,
3340                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3341 
3342         MemOpChains.push_back(Cpy);
3343       } else {
3344         SDValue Store =
3345             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3346         MemOpChains.push_back(Store);
3347       }
3348     }
3349   }
3350 
3351   if (!MemOpChains.empty())
3352     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3353 
3354   // Build a sequence of copy-to-reg nodes chained together with token chain
3355   // and flag operands which copy the outgoing args into the appropriate regs.
3356   SDValue InFlag;
3357   for (auto &RegToPass : RegsToPass) {
3358     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3359                              RegToPass.second, InFlag);
3360     InFlag = Chain.getValue(1);
3361   }
3362 
3363 
3364   // We don't usually want to end the call-sequence here because we would tidy
3365   // the frame up *after* the call, however in the ABI-changing tail-call case
3366   // we've carefully laid out the parameters so that when sp is reset they'll be
3367   // in the correct location.
3368   if (IsTailCall && !IsSibCall) {
3369     Chain = DAG.getCALLSEQ_END(Chain,
3370                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3371                                DAG.getTargetConstant(0, DL, MVT::i32),
3372                                InFlag, DL);
3373     InFlag = Chain.getValue(1);
3374   }
3375 
3376   std::vector<SDValue> Ops;
3377   Ops.push_back(Chain);
3378   Ops.push_back(Callee);
3379   // Add a redundant copy of the callee global which will not be legalized, as
3380   // we need direct access to the callee later.
3381   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3382     const GlobalValue *GV = GSD->getGlobal();
3383     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3384   } else {
3385     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3386   }
3387 
3388   if (IsTailCall) {
3389     // Each tail call may have to adjust the stack by a different amount, so
3390     // this information must travel along with the operation for eventual
3391     // consumption by emitEpilogue.
3392     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3393   }
3394 
3395   // Add argument registers to the end of the list so that they are known live
3396   // into the call.
3397   for (auto &RegToPass : RegsToPass) {
3398     Ops.push_back(DAG.getRegister(RegToPass.first,
3399                                   RegToPass.second.getValueType()));
3400   }
3401 
3402   // Add a register mask operand representing the call-preserved registers.
3403 
3404   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3405   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3406   assert(Mask && "Missing call preserved mask for calling convention");
3407   Ops.push_back(DAG.getRegisterMask(Mask));
3408 
3409   if (InFlag.getNode())
3410     Ops.push_back(InFlag);
3411 
3412   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3413 
3414   // If we're doing a tall call, use a TC_RETURN here rather than an
3415   // actual call instruction.
3416   if (IsTailCall) {
3417     MFI.setHasTailCall();
3418     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3419   }
3420 
3421   // Returns a chain and a flag for retval copy to use.
3422   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3423   Chain = Call.getValue(0);
3424   InFlag = Call.getValue(1);
3425 
3426   uint64_t CalleePopBytes = NumBytes;
3427   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3428                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3429                              InFlag, DL);
3430   if (!Ins.empty())
3431     InFlag = Chain.getValue(1);
3432 
3433   // Handle result values, copying them out of physregs into vregs that we
3434   // return.
3435   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3436                          InVals, IsThisReturn,
3437                          IsThisReturn ? OutVals[0] : SDValue());
3438 }
3439 
3440 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3441 // except for applying the wave size scale to the increment amount.
3442 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3443     SDValue Op, SelectionDAG &DAG) const {
3444   const MachineFunction &MF = DAG.getMachineFunction();
3445   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3446 
3447   SDLoc dl(Op);
3448   EVT VT = Op.getValueType();
3449   SDValue Tmp1 = Op;
3450   SDValue Tmp2 = Op.getValue(1);
3451   SDValue Tmp3 = Op.getOperand(2);
3452   SDValue Chain = Tmp1.getOperand(0);
3453 
3454   Register SPReg = Info->getStackPtrOffsetReg();
3455 
3456   // Chain the dynamic stack allocation so that it doesn't modify the stack
3457   // pointer when other instructions are using the stack.
3458   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3459 
3460   SDValue Size  = Tmp2.getOperand(1);
3461   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3462   Chain = SP.getValue(1);
3463   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3464   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3465   const TargetFrameLowering *TFL = ST.getFrameLowering();
3466   unsigned Opc =
3467     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3468     ISD::ADD : ISD::SUB;
3469 
3470   SDValue ScaledSize = DAG.getNode(
3471       ISD::SHL, dl, VT, Size,
3472       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3473 
3474   Align StackAlign = TFL->getStackAlign();
3475   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3476   if (Alignment && *Alignment > StackAlign) {
3477     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3478                        DAG.getConstant(-(uint64_t)Alignment->value()
3479                                            << ST.getWavefrontSizeLog2(),
3480                                        dl, VT));
3481   }
3482 
3483   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3484   Tmp2 = DAG.getCALLSEQ_END(
3485       Chain, DAG.getIntPtrConstant(0, dl, true),
3486       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3487 
3488   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3489 }
3490 
3491 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3492                                                   SelectionDAG &DAG) const {
3493   // We only handle constant sizes here to allow non-entry block, static sized
3494   // allocas. A truly dynamic value is more difficult to support because we
3495   // don't know if the size value is uniform or not. If the size isn't uniform,
3496   // we would need to do a wave reduction to get the maximum size to know how
3497   // much to increment the uniform stack pointer.
3498   SDValue Size = Op.getOperand(1);
3499   if (isa<ConstantSDNode>(Size))
3500       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3501 
3502   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3503 }
3504 
3505 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3506                                              const MachineFunction &MF) const {
3507   Register Reg = StringSwitch<Register>(RegName)
3508     .Case("m0", AMDGPU::M0)
3509     .Case("exec", AMDGPU::EXEC)
3510     .Case("exec_lo", AMDGPU::EXEC_LO)
3511     .Case("exec_hi", AMDGPU::EXEC_HI)
3512     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3513     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3514     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3515     .Default(Register());
3516 
3517   if (Reg == AMDGPU::NoRegister) {
3518     report_fatal_error(Twine("invalid register name \""
3519                              + StringRef(RegName)  + "\"."));
3520 
3521   }
3522 
3523   if (!Subtarget->hasFlatScrRegister() &&
3524        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3525     report_fatal_error(Twine("invalid register \""
3526                              + StringRef(RegName)  + "\" for subtarget."));
3527   }
3528 
3529   switch (Reg) {
3530   case AMDGPU::M0:
3531   case AMDGPU::EXEC_LO:
3532   case AMDGPU::EXEC_HI:
3533   case AMDGPU::FLAT_SCR_LO:
3534   case AMDGPU::FLAT_SCR_HI:
3535     if (VT.getSizeInBits() == 32)
3536       return Reg;
3537     break;
3538   case AMDGPU::EXEC:
3539   case AMDGPU::FLAT_SCR:
3540     if (VT.getSizeInBits() == 64)
3541       return Reg;
3542     break;
3543   default:
3544     llvm_unreachable("missing register type checking");
3545   }
3546 
3547   report_fatal_error(Twine("invalid type for register \""
3548                            + StringRef(RegName) + "\"."));
3549 }
3550 
3551 // If kill is not the last instruction, split the block so kill is always a
3552 // proper terminator.
3553 MachineBasicBlock *
3554 SITargetLowering::splitKillBlock(MachineInstr &MI,
3555                                  MachineBasicBlock *BB) const {
3556   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3557   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3558   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3559   return SplitBB;
3560 }
3561 
3562 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3563 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3564 // be the first instruction in the remainder block.
3565 //
3566 /// \returns { LoopBody, Remainder }
3567 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3568 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3569   MachineFunction *MF = MBB.getParent();
3570   MachineBasicBlock::iterator I(&MI);
3571 
3572   // To insert the loop we need to split the block. Move everything after this
3573   // point to a new block, and insert a new empty block between the two.
3574   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3575   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3576   MachineFunction::iterator MBBI(MBB);
3577   ++MBBI;
3578 
3579   MF->insert(MBBI, LoopBB);
3580   MF->insert(MBBI, RemainderBB);
3581 
3582   LoopBB->addSuccessor(LoopBB);
3583   LoopBB->addSuccessor(RemainderBB);
3584 
3585   // Move the rest of the block into a new block.
3586   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3587 
3588   if (InstInLoop) {
3589     auto Next = std::next(I);
3590 
3591     // Move instruction to loop body.
3592     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3593 
3594     // Move the rest of the block.
3595     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3596   } else {
3597     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3598   }
3599 
3600   MBB.addSuccessor(LoopBB);
3601 
3602   return std::make_pair(LoopBB, RemainderBB);
3603 }
3604 
3605 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3606 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3607   MachineBasicBlock *MBB = MI.getParent();
3608   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3609   auto I = MI.getIterator();
3610   auto E = std::next(I);
3611 
3612   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3613     .addImm(0);
3614 
3615   MIBundleBuilder Bundler(*MBB, I, E);
3616   finalizeBundle(*MBB, Bundler.begin());
3617 }
3618 
3619 MachineBasicBlock *
3620 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3621                                          MachineBasicBlock *BB) const {
3622   const DebugLoc &DL = MI.getDebugLoc();
3623 
3624   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3625 
3626   MachineBasicBlock *LoopBB;
3627   MachineBasicBlock *RemainderBB;
3628   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3629 
3630   // Apparently kill flags are only valid if the def is in the same block?
3631   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3632     Src->setIsKill(false);
3633 
3634   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3635 
3636   MachineBasicBlock::iterator I = LoopBB->end();
3637 
3638   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3639     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3640 
3641   // Clear TRAP_STS.MEM_VIOL
3642   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3643     .addImm(0)
3644     .addImm(EncodedReg);
3645 
3646   bundleInstWithWaitcnt(MI);
3647 
3648   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3649 
3650   // Load and check TRAP_STS.MEM_VIOL
3651   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3652     .addImm(EncodedReg);
3653 
3654   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3655   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3656     .addReg(Reg, RegState::Kill)
3657     .addImm(0);
3658   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3659     .addMBB(LoopBB);
3660 
3661   return RemainderBB;
3662 }
3663 
3664 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3665 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3666 // will only do one iteration. In the worst case, this will loop 64 times.
3667 //
3668 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3669 static MachineBasicBlock::iterator
3670 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3671                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3672                        const DebugLoc &DL, const MachineOperand &Idx,
3673                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3674                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3675                        Register &SGPRIdxReg) {
3676 
3677   MachineFunction *MF = OrigBB.getParent();
3678   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3679   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3680   MachineBasicBlock::iterator I = LoopBB.begin();
3681 
3682   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3683   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3684   Register NewExec = MRI.createVirtualRegister(BoolRC);
3685   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3686   Register CondReg = MRI.createVirtualRegister(BoolRC);
3687 
3688   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3689     .addReg(InitReg)
3690     .addMBB(&OrigBB)
3691     .addReg(ResultReg)
3692     .addMBB(&LoopBB);
3693 
3694   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3695     .addReg(InitSaveExecReg)
3696     .addMBB(&OrigBB)
3697     .addReg(NewExec)
3698     .addMBB(&LoopBB);
3699 
3700   // Read the next variant <- also loop target.
3701   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3702       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3703 
3704   // Compare the just read M0 value to all possible Idx values.
3705   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3706       .addReg(CurrentIdxReg)
3707       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3708 
3709   // Update EXEC, save the original EXEC value to VCC.
3710   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3711                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3712           NewExec)
3713     .addReg(CondReg, RegState::Kill);
3714 
3715   MRI.setSimpleHint(NewExec, CondReg);
3716 
3717   if (UseGPRIdxMode) {
3718     if (Offset == 0) {
3719       SGPRIdxReg = CurrentIdxReg;
3720     } else {
3721       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3722       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3723           .addReg(CurrentIdxReg, RegState::Kill)
3724           .addImm(Offset);
3725     }
3726   } else {
3727     // Move index from VCC into M0
3728     if (Offset == 0) {
3729       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3730         .addReg(CurrentIdxReg, RegState::Kill);
3731     } else {
3732       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3733         .addReg(CurrentIdxReg, RegState::Kill)
3734         .addImm(Offset);
3735     }
3736   }
3737 
3738   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3739   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3740   MachineInstr *InsertPt =
3741     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3742                                                   : AMDGPU::S_XOR_B64_term), Exec)
3743       .addReg(Exec)
3744       .addReg(NewExec);
3745 
3746   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3747   // s_cbranch_scc0?
3748 
3749   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3750   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3751     .addMBB(&LoopBB);
3752 
3753   return InsertPt->getIterator();
3754 }
3755 
3756 // This has slightly sub-optimal regalloc when the source vector is killed by
3757 // the read. The register allocator does not understand that the kill is
3758 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3759 // subregister from it, using 1 more VGPR than necessary. This was saved when
3760 // this was expanded after register allocation.
3761 static MachineBasicBlock::iterator
3762 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3763                unsigned InitResultReg, unsigned PhiReg, int Offset,
3764                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3765   MachineFunction *MF = MBB.getParent();
3766   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3767   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3768   MachineRegisterInfo &MRI = MF->getRegInfo();
3769   const DebugLoc &DL = MI.getDebugLoc();
3770   MachineBasicBlock::iterator I(&MI);
3771 
3772   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3773   Register DstReg = MI.getOperand(0).getReg();
3774   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3775   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3776   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3777   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3778 
3779   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3780 
3781   // Save the EXEC mask
3782   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3783     .addReg(Exec);
3784 
3785   MachineBasicBlock *LoopBB;
3786   MachineBasicBlock *RemainderBB;
3787   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3788 
3789   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3790 
3791   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3792                                       InitResultReg, DstReg, PhiReg, TmpExec,
3793                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3794 
3795   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3796   MachineFunction::iterator MBBI(LoopBB);
3797   ++MBBI;
3798   MF->insert(MBBI, LandingPad);
3799   LoopBB->removeSuccessor(RemainderBB);
3800   LandingPad->addSuccessor(RemainderBB);
3801   LoopBB->addSuccessor(LandingPad);
3802   MachineBasicBlock::iterator First = LandingPad->begin();
3803   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3804     .addReg(SaveExec);
3805 
3806   return InsPt;
3807 }
3808 
3809 // Returns subreg index, offset
3810 static std::pair<unsigned, int>
3811 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3812                             const TargetRegisterClass *SuperRC,
3813                             unsigned VecReg,
3814                             int Offset) {
3815   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3816 
3817   // Skip out of bounds offsets, or else we would end up using an undefined
3818   // register.
3819   if (Offset >= NumElts || Offset < 0)
3820     return std::make_pair(AMDGPU::sub0, Offset);
3821 
3822   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3823 }
3824 
3825 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3826                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3827                                  int Offset) {
3828   MachineBasicBlock *MBB = MI.getParent();
3829   const DebugLoc &DL = MI.getDebugLoc();
3830   MachineBasicBlock::iterator I(&MI);
3831 
3832   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3833 
3834   assert(Idx->getReg() != AMDGPU::NoRegister);
3835 
3836   if (Offset == 0) {
3837     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3838   } else {
3839     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3840         .add(*Idx)
3841         .addImm(Offset);
3842   }
3843 }
3844 
3845 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3846                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3847                                    int Offset) {
3848   MachineBasicBlock *MBB = MI.getParent();
3849   const DebugLoc &DL = MI.getDebugLoc();
3850   MachineBasicBlock::iterator I(&MI);
3851 
3852   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3853 
3854   if (Offset == 0)
3855     return Idx->getReg();
3856 
3857   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3858   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3859       .add(*Idx)
3860       .addImm(Offset);
3861   return Tmp;
3862 }
3863 
3864 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3865                                           MachineBasicBlock &MBB,
3866                                           const GCNSubtarget &ST) {
3867   const SIInstrInfo *TII = ST.getInstrInfo();
3868   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3869   MachineFunction *MF = MBB.getParent();
3870   MachineRegisterInfo &MRI = MF->getRegInfo();
3871 
3872   Register Dst = MI.getOperand(0).getReg();
3873   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3874   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3875   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3876 
3877   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3878   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3879 
3880   unsigned SubReg;
3881   std::tie(SubReg, Offset)
3882     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3883 
3884   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3885 
3886   // Check for a SGPR index.
3887   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3888     MachineBasicBlock::iterator I(&MI);
3889     const DebugLoc &DL = MI.getDebugLoc();
3890 
3891     if (UseGPRIdxMode) {
3892       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3893       // to avoid interfering with other uses, so probably requires a new
3894       // optimization pass.
3895       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3896 
3897       const MCInstrDesc &GPRIDXDesc =
3898           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3899       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3900           .addReg(SrcReg)
3901           .addReg(Idx)
3902           .addImm(SubReg);
3903     } else {
3904       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3905 
3906       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3907         .addReg(SrcReg, 0, SubReg)
3908         .addReg(SrcReg, RegState::Implicit);
3909     }
3910 
3911     MI.eraseFromParent();
3912 
3913     return &MBB;
3914   }
3915 
3916   // Control flow needs to be inserted if indexing with a VGPR.
3917   const DebugLoc &DL = MI.getDebugLoc();
3918   MachineBasicBlock::iterator I(&MI);
3919 
3920   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3921   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3922 
3923   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3924 
3925   Register SGPRIdxReg;
3926   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3927                               UseGPRIdxMode, SGPRIdxReg);
3928 
3929   MachineBasicBlock *LoopBB = InsPt->getParent();
3930 
3931   if (UseGPRIdxMode) {
3932     const MCInstrDesc &GPRIDXDesc =
3933         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3934 
3935     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3936         .addReg(SrcReg)
3937         .addReg(SGPRIdxReg)
3938         .addImm(SubReg);
3939   } else {
3940     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3941       .addReg(SrcReg, 0, SubReg)
3942       .addReg(SrcReg, RegState::Implicit);
3943   }
3944 
3945   MI.eraseFromParent();
3946 
3947   return LoopBB;
3948 }
3949 
3950 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3951                                           MachineBasicBlock &MBB,
3952                                           const GCNSubtarget &ST) {
3953   const SIInstrInfo *TII = ST.getInstrInfo();
3954   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3955   MachineFunction *MF = MBB.getParent();
3956   MachineRegisterInfo &MRI = MF->getRegInfo();
3957 
3958   Register Dst = MI.getOperand(0).getReg();
3959   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3960   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3961   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3962   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3963   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3964   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3965 
3966   // This can be an immediate, but will be folded later.
3967   assert(Val->getReg());
3968 
3969   unsigned SubReg;
3970   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3971                                                          SrcVec->getReg(),
3972                                                          Offset);
3973   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3974 
3975   if (Idx->getReg() == AMDGPU::NoRegister) {
3976     MachineBasicBlock::iterator I(&MI);
3977     const DebugLoc &DL = MI.getDebugLoc();
3978 
3979     assert(Offset == 0);
3980 
3981     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3982         .add(*SrcVec)
3983         .add(*Val)
3984         .addImm(SubReg);
3985 
3986     MI.eraseFromParent();
3987     return &MBB;
3988   }
3989 
3990   // Check for a SGPR index.
3991   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3992     MachineBasicBlock::iterator I(&MI);
3993     const DebugLoc &DL = MI.getDebugLoc();
3994 
3995     if (UseGPRIdxMode) {
3996       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3997 
3998       const MCInstrDesc &GPRIDXDesc =
3999           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
4000       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
4001           .addReg(SrcVec->getReg())
4002           .add(*Val)
4003           .addReg(Idx)
4004           .addImm(SubReg);
4005     } else {
4006       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
4007 
4008       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
4009           TRI.getRegSizeInBits(*VecRC), 32, false);
4010       BuildMI(MBB, I, DL, MovRelDesc, Dst)
4011           .addReg(SrcVec->getReg())
4012           .add(*Val)
4013           .addImm(SubReg);
4014     }
4015     MI.eraseFromParent();
4016     return &MBB;
4017   }
4018 
4019   // Control flow needs to be inserted if indexing with a VGPR.
4020   if (Val->isReg())
4021     MRI.clearKillFlags(Val->getReg());
4022 
4023   const DebugLoc &DL = MI.getDebugLoc();
4024 
4025   Register PhiReg = MRI.createVirtualRegister(VecRC);
4026 
4027   Register SGPRIdxReg;
4028   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
4029                               UseGPRIdxMode, SGPRIdxReg);
4030   MachineBasicBlock *LoopBB = InsPt->getParent();
4031 
4032   if (UseGPRIdxMode) {
4033     const MCInstrDesc &GPRIDXDesc =
4034         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
4035 
4036     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
4037         .addReg(PhiReg)
4038         .add(*Val)
4039         .addReg(SGPRIdxReg)
4040         .addImm(AMDGPU::sub0);
4041   } else {
4042     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
4043         TRI.getRegSizeInBits(*VecRC), 32, false);
4044     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
4045         .addReg(PhiReg)
4046         .add(*Val)
4047         .addImm(AMDGPU::sub0);
4048   }
4049 
4050   MI.eraseFromParent();
4051   return LoopBB;
4052 }
4053 
4054 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
4055   MachineInstr &MI, MachineBasicBlock *BB) const {
4056 
4057   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4058   MachineFunction *MF = BB->getParent();
4059   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
4060 
4061   switch (MI.getOpcode()) {
4062   case AMDGPU::S_UADDO_PSEUDO:
4063   case AMDGPU::S_USUBO_PSEUDO: {
4064     const DebugLoc &DL = MI.getDebugLoc();
4065     MachineOperand &Dest0 = MI.getOperand(0);
4066     MachineOperand &Dest1 = MI.getOperand(1);
4067     MachineOperand &Src0 = MI.getOperand(2);
4068     MachineOperand &Src1 = MI.getOperand(3);
4069 
4070     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
4071                        ? AMDGPU::S_ADD_I32
4072                        : AMDGPU::S_SUB_I32;
4073     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
4074 
4075     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
4076         .addImm(1)
4077         .addImm(0);
4078 
4079     MI.eraseFromParent();
4080     return BB;
4081   }
4082   case AMDGPU::S_ADD_U64_PSEUDO:
4083   case AMDGPU::S_SUB_U64_PSEUDO: {
4084     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4085     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4086     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4087     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
4088     const DebugLoc &DL = MI.getDebugLoc();
4089 
4090     MachineOperand &Dest = MI.getOperand(0);
4091     MachineOperand &Src0 = MI.getOperand(1);
4092     MachineOperand &Src1 = MI.getOperand(2);
4093 
4094     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4095     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4096 
4097     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
4098         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4099     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
4100         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4101 
4102     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
4103         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4104     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
4105         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4106 
4107     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
4108 
4109     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
4110     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
4111     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
4112     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
4113     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4114         .addReg(DestSub0)
4115         .addImm(AMDGPU::sub0)
4116         .addReg(DestSub1)
4117         .addImm(AMDGPU::sub1);
4118     MI.eraseFromParent();
4119     return BB;
4120   }
4121   case AMDGPU::V_ADD_U64_PSEUDO:
4122   case AMDGPU::V_SUB_U64_PSEUDO: {
4123     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4124     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4125     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4126     const DebugLoc &DL = MI.getDebugLoc();
4127 
4128     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
4129 
4130     MachineOperand &Dest = MI.getOperand(0);
4131     MachineOperand &Src0 = MI.getOperand(1);
4132     MachineOperand &Src1 = MI.getOperand(2);
4133 
4134     if (IsAdd && ST.hasLshlAddB64()) {
4135       auto Add = BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_LSHL_ADD_U64_e64),
4136                          Dest.getReg())
4137                      .add(Src0)
4138                      .addImm(0)
4139                      .add(Src1);
4140       TII->legalizeOperands(*Add);
4141       MI.eraseFromParent();
4142       return BB;
4143     }
4144 
4145     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4146 
4147     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4148     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4149 
4150     Register CarryReg = MRI.createVirtualRegister(CarryRC);
4151     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
4152 
4153     const TargetRegisterClass *Src0RC = Src0.isReg()
4154                                             ? MRI.getRegClass(Src0.getReg())
4155                                             : &AMDGPU::VReg_64RegClass;
4156     const TargetRegisterClass *Src1RC = Src1.isReg()
4157                                             ? MRI.getRegClass(Src1.getReg())
4158                                             : &AMDGPU::VReg_64RegClass;
4159 
4160     const TargetRegisterClass *Src0SubRC =
4161         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
4162     const TargetRegisterClass *Src1SubRC =
4163         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
4164 
4165     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
4166         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
4167     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
4168         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
4169 
4170     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
4171         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
4172     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
4173         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
4174 
4175     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
4176     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
4177                                .addReg(CarryReg, RegState::Define)
4178                                .add(SrcReg0Sub0)
4179                                .add(SrcReg1Sub0)
4180                                .addImm(0); // clamp bit
4181 
4182     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
4183     MachineInstr *HiHalf =
4184         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4185             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4186             .add(SrcReg0Sub1)
4187             .add(SrcReg1Sub1)
4188             .addReg(CarryReg, RegState::Kill)
4189             .addImm(0); // clamp bit
4190 
4191     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4192         .addReg(DestSub0)
4193         .addImm(AMDGPU::sub0)
4194         .addReg(DestSub1)
4195         .addImm(AMDGPU::sub1);
4196     TII->legalizeOperands(*LoHalf);
4197     TII->legalizeOperands(*HiHalf);
4198     MI.eraseFromParent();
4199     return BB;
4200   }
4201   case AMDGPU::S_ADD_CO_PSEUDO:
4202   case AMDGPU::S_SUB_CO_PSEUDO: {
4203     // This pseudo has a chance to be selected
4204     // only from uniform add/subcarry node. All the VGPR operands
4205     // therefore assumed to be splat vectors.
4206     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4207     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4208     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4209     MachineBasicBlock::iterator MII = MI;
4210     const DebugLoc &DL = MI.getDebugLoc();
4211     MachineOperand &Dest = MI.getOperand(0);
4212     MachineOperand &CarryDest = MI.getOperand(1);
4213     MachineOperand &Src0 = MI.getOperand(2);
4214     MachineOperand &Src1 = MI.getOperand(3);
4215     MachineOperand &Src2 = MI.getOperand(4);
4216     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4217                        ? AMDGPU::S_ADDC_U32
4218                        : AMDGPU::S_SUBB_U32;
4219     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4220       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4221       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4222           .addReg(Src0.getReg());
4223       Src0.setReg(RegOp0);
4224     }
4225     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4226       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4227       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4228           .addReg(Src1.getReg());
4229       Src1.setReg(RegOp1);
4230     }
4231     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4232     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4233       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4234           .addReg(Src2.getReg());
4235       Src2.setReg(RegOp2);
4236     }
4237 
4238     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4239     unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC);
4240     assert(WaveSize == 64 || WaveSize == 32);
4241 
4242     if (WaveSize == 64) {
4243       if (ST.hasScalarCompareEq64()) {
4244         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4245             .addReg(Src2.getReg())
4246             .addImm(0);
4247       } else {
4248         const TargetRegisterClass *SubRC =
4249             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4250         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4251             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4252         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4253             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4254         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4255 
4256         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4257             .add(Src2Sub0)
4258             .add(Src2Sub1);
4259 
4260         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4261             .addReg(Src2_32, RegState::Kill)
4262             .addImm(0);
4263       }
4264     } else {
4265       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4266           .addReg(Src2.getReg())
4267           .addImm(0);
4268     }
4269 
4270     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4271 
4272     unsigned SelOpc =
4273         (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
4274 
4275     BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg())
4276         .addImm(-1)
4277         .addImm(0);
4278 
4279     MI.eraseFromParent();
4280     return BB;
4281   }
4282   case AMDGPU::SI_INIT_M0: {
4283     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4284             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4285         .add(MI.getOperand(0));
4286     MI.eraseFromParent();
4287     return BB;
4288   }
4289   case AMDGPU::GET_GROUPSTATICSIZE: {
4290     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4291            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4292     DebugLoc DL = MI.getDebugLoc();
4293     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4294         .add(MI.getOperand(0))
4295         .addImm(MFI->getLDSSize());
4296     MI.eraseFromParent();
4297     return BB;
4298   }
4299   case AMDGPU::SI_INDIRECT_SRC_V1:
4300   case AMDGPU::SI_INDIRECT_SRC_V2:
4301   case AMDGPU::SI_INDIRECT_SRC_V4:
4302   case AMDGPU::SI_INDIRECT_SRC_V8:
4303   case AMDGPU::SI_INDIRECT_SRC_V16:
4304   case AMDGPU::SI_INDIRECT_SRC_V32:
4305     return emitIndirectSrc(MI, *BB, *getSubtarget());
4306   case AMDGPU::SI_INDIRECT_DST_V1:
4307   case AMDGPU::SI_INDIRECT_DST_V2:
4308   case AMDGPU::SI_INDIRECT_DST_V4:
4309   case AMDGPU::SI_INDIRECT_DST_V8:
4310   case AMDGPU::SI_INDIRECT_DST_V16:
4311   case AMDGPU::SI_INDIRECT_DST_V32:
4312     return emitIndirectDst(MI, *BB, *getSubtarget());
4313   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4314   case AMDGPU::SI_KILL_I1_PSEUDO:
4315     return splitKillBlock(MI, BB);
4316   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4317     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4318     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4319     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4320 
4321     Register Dst = MI.getOperand(0).getReg();
4322     Register Src0 = MI.getOperand(1).getReg();
4323     Register Src1 = MI.getOperand(2).getReg();
4324     const DebugLoc &DL = MI.getDebugLoc();
4325     Register SrcCond = MI.getOperand(3).getReg();
4326 
4327     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4328     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4329     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4330     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4331 
4332     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4333       .addReg(SrcCond);
4334     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4335       .addImm(0)
4336       .addReg(Src0, 0, AMDGPU::sub0)
4337       .addImm(0)
4338       .addReg(Src1, 0, AMDGPU::sub0)
4339       .addReg(SrcCondCopy);
4340     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4341       .addImm(0)
4342       .addReg(Src0, 0, AMDGPU::sub1)
4343       .addImm(0)
4344       .addReg(Src1, 0, AMDGPU::sub1)
4345       .addReg(SrcCondCopy);
4346 
4347     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4348       .addReg(DstLo)
4349       .addImm(AMDGPU::sub0)
4350       .addReg(DstHi)
4351       .addImm(AMDGPU::sub1);
4352     MI.eraseFromParent();
4353     return BB;
4354   }
4355   case AMDGPU::SI_BR_UNDEF: {
4356     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4357     const DebugLoc &DL = MI.getDebugLoc();
4358     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4359                            .add(MI.getOperand(0));
4360     Br->getOperand(1).setIsUndef(true); // read undef SCC
4361     MI.eraseFromParent();
4362     return BB;
4363   }
4364   case AMDGPU::ADJCALLSTACKUP:
4365   case AMDGPU::ADJCALLSTACKDOWN: {
4366     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4367     MachineInstrBuilder MIB(*MF, &MI);
4368     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4369        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4370     return BB;
4371   }
4372   case AMDGPU::SI_CALL_ISEL: {
4373     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4374     const DebugLoc &DL = MI.getDebugLoc();
4375 
4376     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4377 
4378     MachineInstrBuilder MIB;
4379     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4380 
4381     for (const MachineOperand &MO : MI.operands())
4382       MIB.add(MO);
4383 
4384     MIB.cloneMemRefs(MI);
4385     MI.eraseFromParent();
4386     return BB;
4387   }
4388   case AMDGPU::V_ADD_CO_U32_e32:
4389   case AMDGPU::V_SUB_CO_U32_e32:
4390   case AMDGPU::V_SUBREV_CO_U32_e32: {
4391     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4392     const DebugLoc &DL = MI.getDebugLoc();
4393     unsigned Opc = MI.getOpcode();
4394 
4395     bool NeedClampOperand = false;
4396     if (TII->pseudoToMCOpcode(Opc) == -1) {
4397       Opc = AMDGPU::getVOPe64(Opc);
4398       NeedClampOperand = true;
4399     }
4400 
4401     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4402     if (TII->isVOP3(*I)) {
4403       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4404       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4405       I.addReg(TRI->getVCC(), RegState::Define);
4406     }
4407     I.add(MI.getOperand(1))
4408      .add(MI.getOperand(2));
4409     if (NeedClampOperand)
4410       I.addImm(0); // clamp bit for e64 encoding
4411 
4412     TII->legalizeOperands(*I);
4413 
4414     MI.eraseFromParent();
4415     return BB;
4416   }
4417   case AMDGPU::V_ADDC_U32_e32:
4418   case AMDGPU::V_SUBB_U32_e32:
4419   case AMDGPU::V_SUBBREV_U32_e32:
4420     // These instructions have an implicit use of vcc which counts towards the
4421     // constant bus limit.
4422     TII->legalizeOperands(MI);
4423     return BB;
4424   case AMDGPU::DS_GWS_INIT:
4425   case AMDGPU::DS_GWS_SEMA_BR:
4426   case AMDGPU::DS_GWS_BARRIER:
4427     if (Subtarget->needsAlignedVGPRs()) {
4428       // Add implicit aligned super-reg to force alignment on the data operand.
4429       const DebugLoc &DL = MI.getDebugLoc();
4430       MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4431       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
4432       MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0);
4433       Register DataReg = Op->getReg();
4434       bool IsAGPR = TRI->isAGPR(MRI, DataReg);
4435       Register Undef = MRI.createVirtualRegister(
4436           IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass);
4437       BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef);
4438       Register NewVR =
4439           MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass
4440                                            : &AMDGPU::VReg_64_Align2RegClass);
4441       BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR)
4442           .addReg(DataReg, 0, Op->getSubReg())
4443           .addImm(AMDGPU::sub0)
4444           .addReg(Undef)
4445           .addImm(AMDGPU::sub1);
4446       Op->setReg(NewVR);
4447       Op->setSubReg(AMDGPU::sub0);
4448       MI.addOperand(MachineOperand::CreateReg(NewVR, false, true));
4449     }
4450     LLVM_FALLTHROUGH;
4451   case AMDGPU::DS_GWS_SEMA_V:
4452   case AMDGPU::DS_GWS_SEMA_P:
4453   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4454     // A s_waitcnt 0 is required to be the instruction immediately following.
4455     if (getSubtarget()->hasGWSAutoReplay()) {
4456       bundleInstWithWaitcnt(MI);
4457       return BB;
4458     }
4459 
4460     return emitGWSMemViolTestLoop(MI, BB);
4461   case AMDGPU::S_SETREG_B32: {
4462     // Try to optimize cases that only set the denormal mode or rounding mode.
4463     //
4464     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4465     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4466     // instead.
4467     //
4468     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4469     // allow you to have a no side effect instruction in the output of a
4470     // sideeffecting pattern.
4471     unsigned ID, Offset, Width;
4472     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4473     if (ID != AMDGPU::Hwreg::ID_MODE)
4474       return BB;
4475 
4476     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4477     const unsigned SetMask = WidthMask << Offset;
4478 
4479     if (getSubtarget()->hasDenormModeInst()) {
4480       unsigned SetDenormOp = 0;
4481       unsigned SetRoundOp = 0;
4482 
4483       // The dedicated instructions can only set the whole denorm or round mode
4484       // at once, not a subset of bits in either.
4485       if (SetMask ==
4486           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4487         // If this fully sets both the round and denorm mode, emit the two
4488         // dedicated instructions for these.
4489         SetRoundOp = AMDGPU::S_ROUND_MODE;
4490         SetDenormOp = AMDGPU::S_DENORM_MODE;
4491       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4492         SetRoundOp = AMDGPU::S_ROUND_MODE;
4493       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4494         SetDenormOp = AMDGPU::S_DENORM_MODE;
4495       }
4496 
4497       if (SetRoundOp || SetDenormOp) {
4498         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4499         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4500         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4501           unsigned ImmVal = Def->getOperand(1).getImm();
4502           if (SetRoundOp) {
4503             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4504                 .addImm(ImmVal & 0xf);
4505 
4506             // If we also have the denorm mode, get just the denorm mode bits.
4507             ImmVal >>= 4;
4508           }
4509 
4510           if (SetDenormOp) {
4511             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4512                 .addImm(ImmVal & 0xf);
4513           }
4514 
4515           MI.eraseFromParent();
4516           return BB;
4517         }
4518       }
4519     }
4520 
4521     // If only FP bits are touched, used the no side effects pseudo.
4522     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4523                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4524       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4525 
4526     return BB;
4527   }
4528   default:
4529     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4530   }
4531 }
4532 
4533 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4534   return isTypeLegal(VT.getScalarType());
4535 }
4536 
4537 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4538   // This currently forces unfolding various combinations of fsub into fma with
4539   // free fneg'd operands. As long as we have fast FMA (controlled by
4540   // isFMAFasterThanFMulAndFAdd), we should perform these.
4541 
4542   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4543   // most of these combines appear to be cycle neutral but save on instruction
4544   // count / code size.
4545   return true;
4546 }
4547 
4548 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; }
4549 
4550 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4551                                          EVT VT) const {
4552   if (!VT.isVector()) {
4553     return MVT::i1;
4554   }
4555   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4556 }
4557 
4558 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4559   // TODO: Should i16 be used always if legal? For now it would force VALU
4560   // shifts.
4561   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4562 }
4563 
4564 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4565   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4566              ? Ty.changeElementSize(16)
4567              : Ty.changeElementSize(32);
4568 }
4569 
4570 // Answering this is somewhat tricky and depends on the specific device which
4571 // have different rates for fma or all f64 operations.
4572 //
4573 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4574 // regardless of which device (although the number of cycles differs between
4575 // devices), so it is always profitable for f64.
4576 //
4577 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4578 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4579 // which we can always do even without fused FP ops since it returns the same
4580 // result as the separate operations and since it is always full
4581 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4582 // however does not support denormals, so we do report fma as faster if we have
4583 // a fast fma device and require denormals.
4584 //
4585 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4586                                                   EVT VT) const {
4587   VT = VT.getScalarType();
4588 
4589   switch (VT.getSimpleVT().SimpleTy) {
4590   case MVT::f32: {
4591     // If mad is not available this depends only on if f32 fma is full rate.
4592     if (!Subtarget->hasMadMacF32Insts())
4593       return Subtarget->hasFastFMAF32();
4594 
4595     // Otherwise f32 mad is always full rate and returns the same result as
4596     // the separate operations so should be preferred over fma.
4597     // However does not support denormals.
4598     if (hasFP32Denormals(MF))
4599       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4600 
4601     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4602     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4603   }
4604   case MVT::f64:
4605     return true;
4606   case MVT::f16:
4607     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4608   default:
4609     break;
4610   }
4611 
4612   return false;
4613 }
4614 
4615 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4616                                                   LLT Ty) const {
4617   switch (Ty.getScalarSizeInBits()) {
4618   case 16:
4619     return isFMAFasterThanFMulAndFAdd(MF, MVT::f16);
4620   case 32:
4621     return isFMAFasterThanFMulAndFAdd(MF, MVT::f32);
4622   case 64:
4623     return isFMAFasterThanFMulAndFAdd(MF, MVT::f64);
4624   default:
4625     break;
4626   }
4627 
4628   return false;
4629 }
4630 
4631 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const {
4632   if (!Ty.isScalar())
4633     return false;
4634 
4635   if (Ty.getScalarSizeInBits() == 16)
4636     return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF());
4637   if (Ty.getScalarSizeInBits() == 32)
4638     return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF());
4639 
4640   return false;
4641 }
4642 
4643 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4644                                    const SDNode *N) const {
4645   // TODO: Check future ftz flag
4646   // v_mad_f32/v_mac_f32 do not support denormals.
4647   EVT VT = N->getValueType(0);
4648   if (VT == MVT::f32)
4649     return Subtarget->hasMadMacF32Insts() &&
4650            !hasFP32Denormals(DAG.getMachineFunction());
4651   if (VT == MVT::f16) {
4652     return Subtarget->hasMadF16() &&
4653            !hasFP64FP16Denormals(DAG.getMachineFunction());
4654   }
4655 
4656   return false;
4657 }
4658 
4659 //===----------------------------------------------------------------------===//
4660 // Custom DAG Lowering Operations
4661 //===----------------------------------------------------------------------===//
4662 
4663 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4664 // wider vector type is legal.
4665 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4666                                              SelectionDAG &DAG) const {
4667   unsigned Opc = Op.getOpcode();
4668   EVT VT = Op.getValueType();
4669   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4670 
4671   SDValue Lo, Hi;
4672   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4673 
4674   SDLoc SL(Op);
4675   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4676                              Op->getFlags());
4677   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4678                              Op->getFlags());
4679 
4680   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4681 }
4682 
4683 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4684 // wider vector type is legal.
4685 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4686                                               SelectionDAG &DAG) const {
4687   unsigned Opc = Op.getOpcode();
4688   EVT VT = Op.getValueType();
4689   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4690          VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8f32 ||
4691          VT == MVT::v16f32 || VT == MVT::v32f32);
4692 
4693   SDValue Lo0, Hi0;
4694   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4695   SDValue Lo1, Hi1;
4696   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4697 
4698   SDLoc SL(Op);
4699 
4700   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4701                              Op->getFlags());
4702   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4703                              Op->getFlags());
4704 
4705   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4706 }
4707 
4708 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4709                                               SelectionDAG &DAG) const {
4710   unsigned Opc = Op.getOpcode();
4711   EVT VT = Op.getValueType();
4712   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 ||
4713          VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v8f32 ||
4714          VT == MVT::v16f32 || VT == MVT::v32f32);
4715 
4716   SDValue Lo0, Hi0;
4717   SDValue Op0 = Op.getOperand(0);
4718   std::tie(Lo0, Hi0) = Op0.getValueType().isVector()
4719                          ? DAG.SplitVectorOperand(Op.getNode(), 0)
4720                          : std::make_pair(Op0, Op0);
4721   SDValue Lo1, Hi1;
4722   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4723   SDValue Lo2, Hi2;
4724   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4725 
4726   SDLoc SL(Op);
4727   auto ResVT = DAG.GetSplitDestVTs(VT);
4728 
4729   SDValue OpLo = DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2,
4730                              Op->getFlags());
4731   SDValue OpHi = DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2,
4732                              Op->getFlags());
4733 
4734   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4735 }
4736 
4737 
4738 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4739   switch (Op.getOpcode()) {
4740   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4741   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4742   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4743   case ISD::LOAD: {
4744     SDValue Result = LowerLOAD(Op, DAG);
4745     assert((!Result.getNode() ||
4746             Result.getNode()->getNumValues() == 2) &&
4747            "Load should return a value and a chain");
4748     return Result;
4749   }
4750 
4751   case ISD::FSIN:
4752   case ISD::FCOS:
4753     return LowerTrig(Op, DAG);
4754   case ISD::SELECT: return LowerSELECT(Op, DAG);
4755   case ISD::FDIV: return LowerFDIV(Op, DAG);
4756   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4757   case ISD::STORE: return LowerSTORE(Op, DAG);
4758   case ISD::GlobalAddress: {
4759     MachineFunction &MF = DAG.getMachineFunction();
4760     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4761     return LowerGlobalAddress(MFI, Op, DAG);
4762   }
4763   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4764   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4765   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4766   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4767   case ISD::INSERT_SUBVECTOR:
4768     return lowerINSERT_SUBVECTOR(Op, DAG);
4769   case ISD::INSERT_VECTOR_ELT:
4770     return lowerINSERT_VECTOR_ELT(Op, DAG);
4771   case ISD::EXTRACT_VECTOR_ELT:
4772     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4773   case ISD::VECTOR_SHUFFLE:
4774     return lowerVECTOR_SHUFFLE(Op, DAG);
4775   case ISD::BUILD_VECTOR:
4776     return lowerBUILD_VECTOR(Op, DAG);
4777   case ISD::FP_ROUND:
4778     return lowerFP_ROUND(Op, DAG);
4779   case ISD::FPTRUNC_ROUND: {
4780     unsigned Opc;
4781     SDLoc DL(Op);
4782 
4783     if (Op.getOperand(0)->getValueType(0) != MVT::f32)
4784       return SDValue();
4785 
4786     // Get the rounding mode from the last operand
4787     int RoundMode = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4788     if (RoundMode == (int)RoundingMode::TowardPositive)
4789       Opc = AMDGPUISD::FPTRUNC_ROUND_UPWARD;
4790     else if (RoundMode == (int)RoundingMode::TowardNegative)
4791       Opc = AMDGPUISD::FPTRUNC_ROUND_DOWNWARD;
4792     else
4793       return SDValue();
4794 
4795     return DAG.getNode(Opc, DL, Op.getNode()->getVTList(), Op->getOperand(0));
4796   }
4797   case ISD::TRAP:
4798     return lowerTRAP(Op, DAG);
4799   case ISD::DEBUGTRAP:
4800     return lowerDEBUGTRAP(Op, DAG);
4801   case ISD::FABS:
4802   case ISD::FNEG:
4803   case ISD::FCANONICALIZE:
4804   case ISD::BSWAP:
4805     return splitUnaryVectorOp(Op, DAG);
4806   case ISD::FMINNUM:
4807   case ISD::FMAXNUM:
4808     return lowerFMINNUM_FMAXNUM(Op, DAG);
4809   case ISD::FMA:
4810     return splitTernaryVectorOp(Op, DAG);
4811   case ISD::FP_TO_SINT:
4812   case ISD::FP_TO_UINT:
4813     return LowerFP_TO_INT(Op, DAG);
4814   case ISD::SHL:
4815   case ISD::SRA:
4816   case ISD::SRL:
4817   case ISD::ADD:
4818   case ISD::SUB:
4819   case ISD::MUL:
4820   case ISD::SMIN:
4821   case ISD::SMAX:
4822   case ISD::UMIN:
4823   case ISD::UMAX:
4824   case ISD::FADD:
4825   case ISD::FMUL:
4826   case ISD::FMINNUM_IEEE:
4827   case ISD::FMAXNUM_IEEE:
4828   case ISD::UADDSAT:
4829   case ISD::USUBSAT:
4830   case ISD::SADDSAT:
4831   case ISD::SSUBSAT:
4832     return splitBinaryVectorOp(Op, DAG);
4833   case ISD::SMULO:
4834   case ISD::UMULO:
4835     return lowerXMULO(Op, DAG);
4836   case ISD::SMUL_LOHI:
4837   case ISD::UMUL_LOHI:
4838     return lowerXMUL_LOHI(Op, DAG);
4839   case ISD::DYNAMIC_STACKALLOC:
4840     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4841   }
4842   return SDValue();
4843 }
4844 
4845 // Used for D16: Casts the result of an instruction into the right vector,
4846 // packs values if loads return unpacked values.
4847 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4848                                        const SDLoc &DL,
4849                                        SelectionDAG &DAG, bool Unpacked) {
4850   if (!LoadVT.isVector())
4851     return Result;
4852 
4853   // Cast back to the original packed type or to a larger type that is a
4854   // multiple of 32 bit for D16. Widening the return type is a required for
4855   // legalization.
4856   EVT FittingLoadVT = LoadVT;
4857   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4858     FittingLoadVT =
4859         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4860                          LoadVT.getVectorNumElements() + 1);
4861   }
4862 
4863   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4864     // Truncate to v2i16/v4i16.
4865     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4866 
4867     // Workaround legalizer not scalarizing truncate after vector op
4868     // legalization but not creating intermediate vector trunc.
4869     SmallVector<SDValue, 4> Elts;
4870     DAG.ExtractVectorElements(Result, Elts);
4871     for (SDValue &Elt : Elts)
4872       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4873 
4874     // Pad illegal v1i16/v3fi6 to v4i16
4875     if ((LoadVT.getVectorNumElements() % 2) == 1)
4876       Elts.push_back(DAG.getUNDEF(MVT::i16));
4877 
4878     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4879 
4880     // Bitcast to original type (v2f16/v4f16).
4881     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4882   }
4883 
4884   // Cast back to the original packed type.
4885   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4886 }
4887 
4888 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4889                                               MemSDNode *M,
4890                                               SelectionDAG &DAG,
4891                                               ArrayRef<SDValue> Ops,
4892                                               bool IsIntrinsic) const {
4893   SDLoc DL(M);
4894 
4895   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4896   EVT LoadVT = M->getValueType(0);
4897 
4898   EVT EquivLoadVT = LoadVT;
4899   if (LoadVT.isVector()) {
4900     if (Unpacked) {
4901       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4902                                      LoadVT.getVectorNumElements());
4903     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4904       // Widen v3f16 to legal type
4905       EquivLoadVT =
4906           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4907                            LoadVT.getVectorNumElements() + 1);
4908     }
4909   }
4910 
4911   // Change from v4f16/v2f16 to EquivLoadVT.
4912   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4913 
4914   SDValue Load
4915     = DAG.getMemIntrinsicNode(
4916       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4917       VTList, Ops, M->getMemoryVT(),
4918       M->getMemOperand());
4919 
4920   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4921 
4922   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4923 }
4924 
4925 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4926                                              SelectionDAG &DAG,
4927                                              ArrayRef<SDValue> Ops) const {
4928   SDLoc DL(M);
4929   EVT LoadVT = M->getValueType(0);
4930   EVT EltType = LoadVT.getScalarType();
4931   EVT IntVT = LoadVT.changeTypeToInteger();
4932 
4933   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4934 
4935   unsigned Opc =
4936       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4937 
4938   if (IsD16) {
4939     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4940   }
4941 
4942   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4943   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4944     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4945 
4946   if (isTypeLegal(LoadVT)) {
4947     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4948                                M->getMemOperand(), DAG);
4949   }
4950 
4951   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4952   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4953   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4954                                         M->getMemOperand(), DAG);
4955   return DAG.getMergeValues(
4956       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4957       DL);
4958 }
4959 
4960 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4961                                   SDNode *N, SelectionDAG &DAG) {
4962   EVT VT = N->getValueType(0);
4963   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4964   unsigned CondCode = CD->getZExtValue();
4965   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4966     return DAG.getUNDEF(VT);
4967 
4968   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4969 
4970   SDValue LHS = N->getOperand(1);
4971   SDValue RHS = N->getOperand(2);
4972 
4973   SDLoc DL(N);
4974 
4975   EVT CmpVT = LHS.getValueType();
4976   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4977     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4978       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4979     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4980     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4981   }
4982 
4983   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4984 
4985   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4986   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4987 
4988   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4989                               DAG.getCondCode(CCOpcode));
4990   if (VT.bitsEq(CCVT))
4991     return SetCC;
4992   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4993 }
4994 
4995 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4996                                   SDNode *N, SelectionDAG &DAG) {
4997   EVT VT = N->getValueType(0);
4998   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4999 
5000   unsigned CondCode = CD->getZExtValue();
5001   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
5002     return DAG.getUNDEF(VT);
5003 
5004   SDValue Src0 = N->getOperand(1);
5005   SDValue Src1 = N->getOperand(2);
5006   EVT CmpVT = Src0.getValueType();
5007   SDLoc SL(N);
5008 
5009   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
5010     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
5011     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
5012   }
5013 
5014   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
5015   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
5016   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
5017   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
5018   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
5019                               Src1, DAG.getCondCode(CCOpcode));
5020   if (VT.bitsEq(CCVT))
5021     return SetCC;
5022   return DAG.getZExtOrTrunc(SetCC, SL, VT);
5023 }
5024 
5025 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
5026                                     SelectionDAG &DAG) {
5027   EVT VT = N->getValueType(0);
5028   SDValue Src = N->getOperand(1);
5029   SDLoc SL(N);
5030 
5031   if (Src.getOpcode() == ISD::SETCC) {
5032     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
5033     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
5034                        Src.getOperand(1), Src.getOperand(2));
5035   }
5036   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
5037     // (ballot 0) -> 0
5038     if (Arg->isZero())
5039       return DAG.getConstant(0, SL, VT);
5040 
5041     // (ballot 1) -> EXEC/EXEC_LO
5042     if (Arg->isOne()) {
5043       Register Exec;
5044       if (VT.getScalarSizeInBits() == 32)
5045         Exec = AMDGPU::EXEC_LO;
5046       else if (VT.getScalarSizeInBits() == 64)
5047         Exec = AMDGPU::EXEC;
5048       else
5049         return SDValue();
5050 
5051       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
5052     }
5053   }
5054 
5055   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
5056   // ISD::SETNE)
5057   return DAG.getNode(
5058       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
5059       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
5060 }
5061 
5062 void SITargetLowering::ReplaceNodeResults(SDNode *N,
5063                                           SmallVectorImpl<SDValue> &Results,
5064                                           SelectionDAG &DAG) const {
5065   switch (N->getOpcode()) {
5066   case ISD::INSERT_VECTOR_ELT: {
5067     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
5068       Results.push_back(Res);
5069     return;
5070   }
5071   case ISD::EXTRACT_VECTOR_ELT: {
5072     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
5073       Results.push_back(Res);
5074     return;
5075   }
5076   case ISD::INTRINSIC_WO_CHAIN: {
5077     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5078     switch (IID) {
5079     case Intrinsic::amdgcn_cvt_pkrtz: {
5080       SDValue Src0 = N->getOperand(1);
5081       SDValue Src1 = N->getOperand(2);
5082       SDLoc SL(N);
5083       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
5084                                 Src0, Src1);
5085       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
5086       return;
5087     }
5088     case Intrinsic::amdgcn_cvt_pknorm_i16:
5089     case Intrinsic::amdgcn_cvt_pknorm_u16:
5090     case Intrinsic::amdgcn_cvt_pk_i16:
5091     case Intrinsic::amdgcn_cvt_pk_u16: {
5092       SDValue Src0 = N->getOperand(1);
5093       SDValue Src1 = N->getOperand(2);
5094       SDLoc SL(N);
5095       unsigned Opcode;
5096 
5097       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
5098         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
5099       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
5100         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
5101       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
5102         Opcode = AMDGPUISD::CVT_PK_I16_I32;
5103       else
5104         Opcode = AMDGPUISD::CVT_PK_U16_U32;
5105 
5106       EVT VT = N->getValueType(0);
5107       if (isTypeLegal(VT))
5108         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
5109       else {
5110         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
5111         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
5112       }
5113       return;
5114     }
5115     }
5116     break;
5117   }
5118   case ISD::INTRINSIC_W_CHAIN: {
5119     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
5120       if (Res.getOpcode() == ISD::MERGE_VALUES) {
5121         // FIXME: Hacky
5122         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
5123           Results.push_back(Res.getOperand(I));
5124         }
5125       } else {
5126         Results.push_back(Res);
5127         Results.push_back(Res.getValue(1));
5128       }
5129       return;
5130     }
5131 
5132     break;
5133   }
5134   case ISD::SELECT: {
5135     SDLoc SL(N);
5136     EVT VT = N->getValueType(0);
5137     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
5138     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
5139     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
5140 
5141     EVT SelectVT = NewVT;
5142     if (NewVT.bitsLT(MVT::i32)) {
5143       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
5144       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
5145       SelectVT = MVT::i32;
5146     }
5147 
5148     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
5149                                     N->getOperand(0), LHS, RHS);
5150 
5151     if (NewVT != SelectVT)
5152       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
5153     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
5154     return;
5155   }
5156   case ISD::FNEG: {
5157     if (N->getValueType(0) != MVT::v2f16)
5158       break;
5159 
5160     SDLoc SL(N);
5161     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5162 
5163     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
5164                              BC,
5165                              DAG.getConstant(0x80008000, SL, MVT::i32));
5166     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5167     return;
5168   }
5169   case ISD::FABS: {
5170     if (N->getValueType(0) != MVT::v2f16)
5171       break;
5172 
5173     SDLoc SL(N);
5174     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5175 
5176     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
5177                              BC,
5178                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
5179     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5180     return;
5181   }
5182   default:
5183     break;
5184   }
5185 }
5186 
5187 /// Helper function for LowerBRCOND
5188 static SDNode *findUser(SDValue Value, unsigned Opcode) {
5189 
5190   SDNode *Parent = Value.getNode();
5191   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
5192        I != E; ++I) {
5193 
5194     if (I.getUse().get() != Value)
5195       continue;
5196 
5197     if (I->getOpcode() == Opcode)
5198       return *I;
5199   }
5200   return nullptr;
5201 }
5202 
5203 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
5204   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
5205     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
5206     case Intrinsic::amdgcn_if:
5207       return AMDGPUISD::IF;
5208     case Intrinsic::amdgcn_else:
5209       return AMDGPUISD::ELSE;
5210     case Intrinsic::amdgcn_loop:
5211       return AMDGPUISD::LOOP;
5212     case Intrinsic::amdgcn_end_cf:
5213       llvm_unreachable("should not occur");
5214     default:
5215       return 0;
5216     }
5217   }
5218 
5219   // break, if_break, else_break are all only used as inputs to loop, not
5220   // directly as branch conditions.
5221   return 0;
5222 }
5223 
5224 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
5225   const Triple &TT = getTargetMachine().getTargetTriple();
5226   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5227           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5228          AMDGPU::shouldEmitConstantsToTextSection(TT);
5229 }
5230 
5231 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
5232   // FIXME: Either avoid relying on address space here or change the default
5233   // address space for functions to avoid the explicit check.
5234   return (GV->getValueType()->isFunctionTy() ||
5235           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
5236          !shouldEmitFixup(GV) &&
5237          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
5238 }
5239 
5240 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
5241   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
5242 }
5243 
5244 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
5245   if (!GV->hasExternalLinkage())
5246     return true;
5247 
5248   const auto OS = getTargetMachine().getTargetTriple().getOS();
5249   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
5250 }
5251 
5252 /// This transforms the control flow intrinsics to get the branch destination as
5253 /// last parameter, also switches branch target with BR if the need arise
5254 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
5255                                       SelectionDAG &DAG) const {
5256   SDLoc DL(BRCOND);
5257 
5258   SDNode *Intr = BRCOND.getOperand(1).getNode();
5259   SDValue Target = BRCOND.getOperand(2);
5260   SDNode *BR = nullptr;
5261   SDNode *SetCC = nullptr;
5262 
5263   if (Intr->getOpcode() == ISD::SETCC) {
5264     // As long as we negate the condition everything is fine
5265     SetCC = Intr;
5266     Intr = SetCC->getOperand(0).getNode();
5267 
5268   } else {
5269     // Get the target from BR if we don't negate the condition
5270     BR = findUser(BRCOND, ISD::BR);
5271     assert(BR && "brcond missing unconditional branch user");
5272     Target = BR->getOperand(1);
5273   }
5274 
5275   unsigned CFNode = isCFIntrinsic(Intr);
5276   if (CFNode == 0) {
5277     // This is a uniform branch so we don't need to legalize.
5278     return BRCOND;
5279   }
5280 
5281   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5282                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5283 
5284   assert(!SetCC ||
5285         (SetCC->getConstantOperandVal(1) == 1 &&
5286          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5287                                                              ISD::SETNE));
5288 
5289   // operands of the new intrinsic call
5290   SmallVector<SDValue, 4> Ops;
5291   if (HaveChain)
5292     Ops.push_back(BRCOND.getOperand(0));
5293 
5294   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5295   Ops.push_back(Target);
5296 
5297   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5298 
5299   // build the new intrinsic call
5300   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5301 
5302   if (!HaveChain) {
5303     SDValue Ops[] =  {
5304       SDValue(Result, 0),
5305       BRCOND.getOperand(0)
5306     };
5307 
5308     Result = DAG.getMergeValues(Ops, DL).getNode();
5309   }
5310 
5311   if (BR) {
5312     // Give the branch instruction our target
5313     SDValue Ops[] = {
5314       BR->getOperand(0),
5315       BRCOND.getOperand(2)
5316     };
5317     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5318     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5319   }
5320 
5321   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5322 
5323   // Copy the intrinsic results to registers
5324   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5325     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5326     if (!CopyToReg)
5327       continue;
5328 
5329     Chain = DAG.getCopyToReg(
5330       Chain, DL,
5331       CopyToReg->getOperand(1),
5332       SDValue(Result, i - 1),
5333       SDValue());
5334 
5335     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5336   }
5337 
5338   // Remove the old intrinsic from the chain
5339   DAG.ReplaceAllUsesOfValueWith(
5340     SDValue(Intr, Intr->getNumValues() - 1),
5341     Intr->getOperand(0));
5342 
5343   return Chain;
5344 }
5345 
5346 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5347                                           SelectionDAG &DAG) const {
5348   MVT VT = Op.getSimpleValueType();
5349   SDLoc DL(Op);
5350   // Checking the depth
5351   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5352     return DAG.getConstant(0, DL, VT);
5353 
5354   MachineFunction &MF = DAG.getMachineFunction();
5355   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5356   // Check for kernel and shader functions
5357   if (Info->isEntryFunction())
5358     return DAG.getConstant(0, DL, VT);
5359 
5360   MachineFrameInfo &MFI = MF.getFrameInfo();
5361   // There is a call to @llvm.returnaddress in this function
5362   MFI.setReturnAddressIsTaken(true);
5363 
5364   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5365   // Get the return address reg and mark it as an implicit live-in
5366   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5367 
5368   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5369 }
5370 
5371 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5372                                             SDValue Op,
5373                                             const SDLoc &DL,
5374                                             EVT VT) const {
5375   return Op.getValueType().bitsLE(VT) ?
5376       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5377     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5378                 DAG.getTargetConstant(0, DL, MVT::i32));
5379 }
5380 
5381 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5382   assert(Op.getValueType() == MVT::f16 &&
5383          "Do not know how to custom lower FP_ROUND for non-f16 type");
5384 
5385   SDValue Src = Op.getOperand(0);
5386   EVT SrcVT = Src.getValueType();
5387   if (SrcVT != MVT::f64)
5388     return Op;
5389 
5390   SDLoc DL(Op);
5391 
5392   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5393   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5394   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5395 }
5396 
5397 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5398                                                SelectionDAG &DAG) const {
5399   EVT VT = Op.getValueType();
5400   const MachineFunction &MF = DAG.getMachineFunction();
5401   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5402   bool IsIEEEMode = Info->getMode().IEEE;
5403 
5404   // FIXME: Assert during selection that this is only selected for
5405   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5406   // mode functions, but this happens to be OK since it's only done in cases
5407   // where there is known no sNaN.
5408   if (IsIEEEMode)
5409     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5410 
5411   if (VT == MVT::v4f16 || VT == MVT::v8f16)
5412     return splitBinaryVectorOp(Op, DAG);
5413   return Op;
5414 }
5415 
5416 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5417   EVT VT = Op.getValueType();
5418   SDLoc SL(Op);
5419   SDValue LHS = Op.getOperand(0);
5420   SDValue RHS = Op.getOperand(1);
5421   bool isSigned = Op.getOpcode() == ISD::SMULO;
5422 
5423   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5424     const APInt &C = RHSC->getAPIntValue();
5425     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5426     if (C.isPowerOf2()) {
5427       // smulo(x, signed_min) is same as umulo(x, signed_min).
5428       bool UseArithShift = isSigned && !C.isMinSignedValue();
5429       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5430       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5431       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5432           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5433                       SL, VT, Result, ShiftAmt),
5434           LHS, ISD::SETNE);
5435       return DAG.getMergeValues({ Result, Overflow }, SL);
5436     }
5437   }
5438 
5439   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5440   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5441                             SL, VT, LHS, RHS);
5442 
5443   SDValue Sign = isSigned
5444     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5445                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5446     : DAG.getConstant(0, SL, VT);
5447   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5448 
5449   return DAG.getMergeValues({ Result, Overflow }, SL);
5450 }
5451 
5452 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const {
5453   if (Op->isDivergent()) {
5454     // Select to V_MAD_[IU]64_[IU]32.
5455     return Op;
5456   }
5457   if (Subtarget->hasSMulHi()) {
5458     // Expand to S_MUL_I32 + S_MUL_HI_[IU]32.
5459     return SDValue();
5460   }
5461   // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to
5462   // calculate the high part, so we might as well do the whole thing with
5463   // V_MAD_[IU]64_[IU]32.
5464   return Op;
5465 }
5466 
5467 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5468   if (!Subtarget->isTrapHandlerEnabled() ||
5469       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5470     return lowerTrapEndpgm(Op, DAG);
5471 
5472   if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) {
5473     switch (*HsaAbiVer) {
5474     case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
5475     case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
5476       return lowerTrapHsaQueuePtr(Op, DAG);
5477     case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
5478     case ELF::ELFABIVERSION_AMDGPU_HSA_V5:
5479       return Subtarget->supportsGetDoorbellID() ?
5480           lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG);
5481     }
5482   }
5483 
5484   llvm_unreachable("Unknown trap handler");
5485 }
5486 
5487 SDValue SITargetLowering::lowerTrapEndpgm(
5488     SDValue Op, SelectionDAG &DAG) const {
5489   SDLoc SL(Op);
5490   SDValue Chain = Op.getOperand(0);
5491   return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5492 }
5493 
5494 SDValue SITargetLowering::loadImplicitKernelArgument(SelectionDAG &DAG, MVT VT,
5495     const SDLoc &DL, Align Alignment, ImplicitParameter Param) const {
5496   MachineFunction &MF = DAG.getMachineFunction();
5497   uint64_t Offset = getImplicitParameterOffset(MF, Param);
5498   SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), Offset);
5499   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5500   return DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, PtrInfo, Alignment,
5501                      MachineMemOperand::MODereferenceable |
5502                          MachineMemOperand::MOInvariant);
5503 }
5504 
5505 SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5506     SDValue Op, SelectionDAG &DAG) const {
5507   SDLoc SL(Op);
5508   SDValue Chain = Op.getOperand(0);
5509 
5510   SDValue QueuePtr;
5511   // For code object version 5, QueuePtr is passed through implicit kernarg.
5512   if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) {
5513     QueuePtr =
5514         loadImplicitKernelArgument(DAG, MVT::i64, SL, Align(8), QUEUE_PTR);
5515   } else {
5516     MachineFunction &MF = DAG.getMachineFunction();
5517     SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5518     Register UserSGPR = Info->getQueuePtrUserSGPR();
5519 
5520     if (UserSGPR == AMDGPU::NoRegister) {
5521       // We probably are in a function incorrectly marked with
5522       // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the
5523       // trap, so just use a null pointer.
5524       QueuePtr = DAG.getConstant(0, SL, MVT::i64);
5525     } else {
5526       QueuePtr = CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, UserSGPR,
5527                                       MVT::i64);
5528     }
5529   }
5530 
5531   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5532   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5533                                    QueuePtr, SDValue());
5534 
5535   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5536   SDValue Ops[] = {
5537     ToReg,
5538     DAG.getTargetConstant(TrapID, SL, MVT::i16),
5539     SGPR01,
5540     ToReg.getValue(1)
5541   };
5542   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5543 }
5544 
5545 SDValue SITargetLowering::lowerTrapHsa(
5546     SDValue Op, SelectionDAG &DAG) const {
5547   SDLoc SL(Op);
5548   SDValue Chain = Op.getOperand(0);
5549 
5550   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5551   SDValue Ops[] = {
5552     Chain,
5553     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5554   };
5555   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5556 }
5557 
5558 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5559   SDLoc SL(Op);
5560   SDValue Chain = Op.getOperand(0);
5561   MachineFunction &MF = DAG.getMachineFunction();
5562 
5563   if (!Subtarget->isTrapHandlerEnabled() ||
5564       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5565     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5566                                      "debugtrap handler not supported",
5567                                      Op.getDebugLoc(),
5568                                      DS_Warning);
5569     LLVMContext &Ctx = MF.getFunction().getContext();
5570     Ctx.diagnose(NoTrap);
5571     return Chain;
5572   }
5573 
5574   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5575   SDValue Ops[] = {
5576     Chain,
5577     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5578   };
5579   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5580 }
5581 
5582 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5583                                              SelectionDAG &DAG) const {
5584   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5585   if (Subtarget->hasApertureRegs()) {
5586     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5587         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5588         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5589     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5590         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5591         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5592     unsigned Encoding =
5593         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5594         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5595         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5596 
5597     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5598     SDValue ApertureReg = SDValue(
5599         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5600     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5601     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5602   }
5603 
5604   // For code object version 5, private_base and shared_base are passed through
5605   // implicit kernargs.
5606   if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) {
5607     ImplicitParameter Param =
5608         (AS == AMDGPUAS::LOCAL_ADDRESS) ? SHARED_BASE : PRIVATE_BASE;
5609     return loadImplicitKernelArgument(DAG, MVT::i32, DL, Align(4), Param);
5610   }
5611 
5612   MachineFunction &MF = DAG.getMachineFunction();
5613   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5614   Register UserSGPR = Info->getQueuePtrUserSGPR();
5615   if (UserSGPR == AMDGPU::NoRegister) {
5616     // We probably are in a function incorrectly marked with
5617     // amdgpu-no-queue-ptr. This is undefined.
5618     return DAG.getUNDEF(MVT::i32);
5619   }
5620 
5621   SDValue QueuePtr = CreateLiveInRegister(
5622     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5623 
5624   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5625   // private_segment_aperture_base_hi.
5626   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5627 
5628   SDValue Ptr =
5629       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5630 
5631   // TODO: Use custom target PseudoSourceValue.
5632   // TODO: We should use the value from the IR intrinsic call, but it might not
5633   // be available and how do we get it?
5634   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5635   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5636                      commonAlignment(Align(64), StructOffset),
5637                      MachineMemOperand::MODereferenceable |
5638                          MachineMemOperand::MOInvariant);
5639 }
5640 
5641 /// Return true if the value is a known valid address, such that a null check is
5642 /// not necessary.
5643 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG,
5644                            const AMDGPUTargetMachine &TM, unsigned AddrSpace) {
5645   if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) ||
5646       isa<BasicBlockSDNode>(Val))
5647     return true;
5648 
5649   if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val))
5650     return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace);
5651 
5652   // TODO: Search through arithmetic, handle arguments and loads
5653   // marked nonnull.
5654   return false;
5655 }
5656 
5657 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5658                                              SelectionDAG &DAG) const {
5659   SDLoc SL(Op);
5660   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5661 
5662   SDValue Src = ASC->getOperand(0);
5663   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5664   unsigned SrcAS = ASC->getSrcAddressSpace();
5665 
5666   const AMDGPUTargetMachine &TM =
5667     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5668 
5669   // flat -> local/private
5670   if (SrcAS == AMDGPUAS::FLAT_ADDRESS) {
5671     unsigned DestAS = ASC->getDestAddressSpace();
5672 
5673     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5674         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5675       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5676 
5677       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5678         return Ptr;
5679 
5680       unsigned NullVal = TM.getNullPointerValue(DestAS);
5681       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5682       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5683 
5684       return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr,
5685                          SegmentNullPtr);
5686     }
5687   }
5688 
5689   // local/private -> flat
5690   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5691     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5692         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5693 
5694       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5695       SDValue CvtPtr =
5696           DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5697       CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr);
5698 
5699       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5700         return CvtPtr;
5701 
5702       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5703       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5704 
5705       SDValue NonNull
5706         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5707 
5708       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr,
5709                          FlatNullPtr);
5710     }
5711   }
5712 
5713   if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5714       Op.getValueType() == MVT::i64) {
5715     const SIMachineFunctionInfo *Info =
5716         DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>();
5717     SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32);
5718     SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi);
5719     return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
5720   }
5721 
5722   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5723       Src.getValueType() == MVT::i64)
5724     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5725 
5726   // global <-> flat are no-ops and never emitted.
5727 
5728   const MachineFunction &MF = DAG.getMachineFunction();
5729   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5730     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5731   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5732 
5733   return DAG.getUNDEF(ASC->getValueType(0));
5734 }
5735 
5736 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5737 // the small vector and inserting them into the big vector. That is better than
5738 // the default expansion of doing it via a stack slot. Even though the use of
5739 // the stack slot would be optimized away afterwards, the stack slot itself
5740 // remains.
5741 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5742                                                 SelectionDAG &DAG) const {
5743   SDValue Vec = Op.getOperand(0);
5744   SDValue Ins = Op.getOperand(1);
5745   SDValue Idx = Op.getOperand(2);
5746   EVT VecVT = Vec.getValueType();
5747   EVT InsVT = Ins.getValueType();
5748   EVT EltVT = VecVT.getVectorElementType();
5749   unsigned InsNumElts = InsVT.getVectorNumElements();
5750   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5751   SDLoc SL(Op);
5752 
5753   for (unsigned I = 0; I != InsNumElts; ++I) {
5754     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5755                               DAG.getConstant(I, SL, MVT::i32));
5756     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5757                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5758   }
5759   return Vec;
5760 }
5761 
5762 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5763                                                  SelectionDAG &DAG) const {
5764   SDValue Vec = Op.getOperand(0);
5765   SDValue InsVal = Op.getOperand(1);
5766   SDValue Idx = Op.getOperand(2);
5767   EVT VecVT = Vec.getValueType();
5768   EVT EltVT = VecVT.getVectorElementType();
5769   unsigned VecSize = VecVT.getSizeInBits();
5770   unsigned EltSize = EltVT.getSizeInBits();
5771 
5772 
5773   assert(VecSize <= 64);
5774 
5775   unsigned NumElts = VecVT.getVectorNumElements();
5776   SDLoc SL(Op);
5777   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5778 
5779   if (NumElts == 4 && EltSize == 16 && KIdx) {
5780     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5781 
5782     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5783                                  DAG.getConstant(0, SL, MVT::i32));
5784     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5785                                  DAG.getConstant(1, SL, MVT::i32));
5786 
5787     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5788     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5789 
5790     unsigned Idx = KIdx->getZExtValue();
5791     bool InsertLo = Idx < 2;
5792     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5793       InsertLo ? LoVec : HiVec,
5794       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5795       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5796 
5797     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5798 
5799     SDValue Concat = InsertLo ?
5800       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5801       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5802 
5803     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5804   }
5805 
5806   if (isa<ConstantSDNode>(Idx))
5807     return SDValue();
5808 
5809   MVT IntVT = MVT::getIntegerVT(VecSize);
5810 
5811   // Avoid stack access for dynamic indexing.
5812   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5813 
5814   // Create a congruent vector with the target value in each element so that
5815   // the required element can be masked and ORed into the target vector.
5816   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5817                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5818 
5819   assert(isPowerOf2_32(EltSize));
5820   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5821 
5822   // Convert vector index to bit-index.
5823   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5824 
5825   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5826   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5827                             DAG.getConstant(0xffff, SL, IntVT),
5828                             ScaledIdx);
5829 
5830   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5831   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5832                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5833 
5834   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5835   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5836 }
5837 
5838 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5839                                                   SelectionDAG &DAG) const {
5840   SDLoc SL(Op);
5841 
5842   EVT ResultVT = Op.getValueType();
5843   SDValue Vec = Op.getOperand(0);
5844   SDValue Idx = Op.getOperand(1);
5845   EVT VecVT = Vec.getValueType();
5846   unsigned VecSize = VecVT.getSizeInBits();
5847   EVT EltVT = VecVT.getVectorElementType();
5848 
5849   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5850 
5851   // Make sure we do any optimizations that will make it easier to fold
5852   // source modifiers before obscuring it with bit operations.
5853 
5854   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5855   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5856     return Combined;
5857 
5858   if (VecSize == 128) {
5859     SDValue Lo, Hi;
5860     EVT LoVT, HiVT;
5861     SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec);
5862     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5863     Lo =
5864         DAG.getBitcast(LoVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5865                                          V2, DAG.getConstant(0, SL, MVT::i32)));
5866     Hi =
5867         DAG.getBitcast(HiVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5868                                          V2, DAG.getConstant(1, SL, MVT::i32)));
5869     EVT IdxVT = Idx.getValueType();
5870     unsigned NElem = VecVT.getVectorNumElements();
5871     assert(isPowerOf2_32(NElem));
5872     SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT);
5873     SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask);
5874     SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT);
5875     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx);
5876   }
5877 
5878   assert(VecSize <= 64);
5879 
5880   unsigned EltSize = EltVT.getSizeInBits();
5881   assert(isPowerOf2_32(EltSize));
5882 
5883   MVT IntVT = MVT::getIntegerVT(VecSize);
5884   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5885 
5886   // Convert vector index to bit-index (* EltSize)
5887   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5888 
5889   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5890   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5891 
5892   if (ResultVT == MVT::f16) {
5893     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5894     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5895   }
5896 
5897   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5898 }
5899 
5900 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5901   assert(Elt % 2 == 0);
5902   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5903 }
5904 
5905 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5906                                               SelectionDAG &DAG) const {
5907   SDLoc SL(Op);
5908   EVT ResultVT = Op.getValueType();
5909   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5910 
5911   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5912   EVT EltVT = PackVT.getVectorElementType();
5913   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5914 
5915   // vector_shuffle <0,1,6,7> lhs, rhs
5916   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5917   //
5918   // vector_shuffle <6,7,2,3> lhs, rhs
5919   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5920   //
5921   // vector_shuffle <6,7,0,1> lhs, rhs
5922   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5923 
5924   // Avoid scalarizing when both halves are reading from consecutive elements.
5925   SmallVector<SDValue, 4> Pieces;
5926   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5927     if (elementPairIsContiguous(SVN->getMask(), I)) {
5928       const int Idx = SVN->getMaskElt(I);
5929       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5930       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5931       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5932                                     PackVT, SVN->getOperand(VecIdx),
5933                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5934       Pieces.push_back(SubVec);
5935     } else {
5936       const int Idx0 = SVN->getMaskElt(I);
5937       const int Idx1 = SVN->getMaskElt(I + 1);
5938       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5939       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5940       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5941       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5942 
5943       SDValue Vec0 = SVN->getOperand(VecIdx0);
5944       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5945                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5946 
5947       SDValue Vec1 = SVN->getOperand(VecIdx1);
5948       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5949                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5950       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5951     }
5952   }
5953 
5954   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5955 }
5956 
5957 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5958                                             SelectionDAG &DAG) const {
5959   SDLoc SL(Op);
5960   EVT VT = Op.getValueType();
5961 
5962   if (VT == MVT::v4i16 || VT == MVT::v4f16 ||
5963       VT == MVT::v8i16 || VT == MVT::v8f16) {
5964     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(),
5965                                   VT.getVectorNumElements() / 2);
5966     MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits());
5967 
5968     // Turn into pair of packed build_vectors.
5969     // TODO: Special case for constants that can be materialized with s_mov_b64.
5970     SmallVector<SDValue, 4> LoOps, HiOps;
5971     for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) {
5972       LoOps.push_back(Op.getOperand(I));
5973       HiOps.push_back(Op.getOperand(I + E));
5974     }
5975     SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps);
5976     SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps);
5977 
5978     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo);
5979     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi);
5980 
5981     SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL,
5982                                        { CastLo, CastHi });
5983     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5984   }
5985 
5986   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5987   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5988 
5989   SDValue Lo = Op.getOperand(0);
5990   SDValue Hi = Op.getOperand(1);
5991 
5992   // Avoid adding defined bits with the zero_extend.
5993   if (Hi.isUndef()) {
5994     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5995     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5996     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5997   }
5998 
5999   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
6000   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
6001 
6002   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
6003                               DAG.getConstant(16, SL, MVT::i32));
6004   if (Lo.isUndef())
6005     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
6006 
6007   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
6008   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
6009 
6010   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
6011   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
6012 }
6013 
6014 bool
6015 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
6016   // We can fold offsets for anything that doesn't require a GOT relocation.
6017   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
6018           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
6019           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
6020          !shouldEmitGOTReloc(GA->getGlobal());
6021 }
6022 
6023 static SDValue
6024 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
6025                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
6026                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
6027   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
6028   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
6029   // lowered to the following code sequence:
6030   //
6031   // For constant address space:
6032   //   s_getpc_b64 s[0:1]
6033   //   s_add_u32 s0, s0, $symbol
6034   //   s_addc_u32 s1, s1, 0
6035   //
6036   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
6037   //   a fixup or relocation is emitted to replace $symbol with a literal
6038   //   constant, which is a pc-relative offset from the encoding of the $symbol
6039   //   operand to the global variable.
6040   //
6041   // For global address space:
6042   //   s_getpc_b64 s[0:1]
6043   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
6044   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
6045   //
6046   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
6047   //   fixups or relocations are emitted to replace $symbol@*@lo and
6048   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
6049   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
6050   //   operand to the global variable.
6051   //
6052   // What we want here is an offset from the value returned by s_getpc
6053   // (which is the address of the s_add_u32 instruction) to the global
6054   // variable, but since the encoding of $symbol starts 4 bytes after the start
6055   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
6056   // small. This requires us to add 4 to the global variable offset in order to
6057   // compute the correct address. Similarly for the s_addc_u32 instruction, the
6058   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
6059   // instruction.
6060   SDValue PtrLo =
6061       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
6062   SDValue PtrHi;
6063   if (GAFlags == SIInstrInfo::MO_NONE) {
6064     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
6065   } else {
6066     PtrHi =
6067         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
6068   }
6069   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
6070 }
6071 
6072 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
6073                                              SDValue Op,
6074                                              SelectionDAG &DAG) const {
6075   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
6076   SDLoc DL(GSD);
6077   EVT PtrVT = Op.getValueType();
6078 
6079   const GlobalValue *GV = GSD->getGlobal();
6080   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
6081        shouldUseLDSConstAddress(GV)) ||
6082       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
6083       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
6084     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
6085         GV->hasExternalLinkage()) {
6086       Type *Ty = GV->getValueType();
6087       // HIP uses an unsized array `extern __shared__ T s[]` or similar
6088       // zero-sized type in other languages to declare the dynamic shared
6089       // memory which size is not known at the compile time. They will be
6090       // allocated by the runtime and placed directly after the static
6091       // allocated ones. They all share the same offset.
6092       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
6093         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
6094         // Adjust alignment for that dynamic shared memory array.
6095         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
6096         return SDValue(
6097             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
6098       }
6099     }
6100     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
6101   }
6102 
6103   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
6104     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
6105                                             SIInstrInfo::MO_ABS32_LO);
6106     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
6107   }
6108 
6109   if (shouldEmitFixup(GV))
6110     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
6111   else if (shouldEmitPCReloc(GV))
6112     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
6113                                    SIInstrInfo::MO_REL32);
6114 
6115   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
6116                                             SIInstrInfo::MO_GOTPCREL32);
6117 
6118   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
6119   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
6120   const DataLayout &DataLayout = DAG.getDataLayout();
6121   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
6122   MachinePointerInfo PtrInfo
6123     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
6124 
6125   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
6126                      MachineMemOperand::MODereferenceable |
6127                          MachineMemOperand::MOInvariant);
6128 }
6129 
6130 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
6131                                    const SDLoc &DL, SDValue V) const {
6132   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
6133   // the destination register.
6134   //
6135   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
6136   // so we will end up with redundant moves to m0.
6137   //
6138   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
6139 
6140   // A Null SDValue creates a glue result.
6141   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
6142                                   V, Chain);
6143   return SDValue(M0, 0);
6144 }
6145 
6146 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
6147                                                  SDValue Op,
6148                                                  MVT VT,
6149                                                  unsigned Offset) const {
6150   SDLoc SL(Op);
6151   SDValue Param = lowerKernargMemParameter(
6152       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
6153   // The local size values will have the hi 16-bits as zero.
6154   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
6155                      DAG.getValueType(VT));
6156 }
6157 
6158 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6159                                         EVT VT) {
6160   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6161                                       "non-hsa intrinsic with hsa target",
6162                                       DL.getDebugLoc());
6163   DAG.getContext()->diagnose(BadIntrin);
6164   return DAG.getUNDEF(VT);
6165 }
6166 
6167 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6168                                          EVT VT) {
6169   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6170                                       "intrinsic not supported on subtarget",
6171                                       DL.getDebugLoc());
6172   DAG.getContext()->diagnose(BadIntrin);
6173   return DAG.getUNDEF(VT);
6174 }
6175 
6176 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
6177                                     ArrayRef<SDValue> Elts) {
6178   assert(!Elts.empty());
6179   MVT Type;
6180   unsigned NumElts = Elts.size();
6181 
6182   if (NumElts <= 8) {
6183     Type = MVT::getVectorVT(MVT::f32, NumElts);
6184   } else {
6185     assert(Elts.size() <= 16);
6186     Type = MVT::v16f32;
6187     NumElts = 16;
6188   }
6189 
6190   SmallVector<SDValue, 16> VecElts(NumElts);
6191   for (unsigned i = 0; i < Elts.size(); ++i) {
6192     SDValue Elt = Elts[i];
6193     if (Elt.getValueType() != MVT::f32)
6194       Elt = DAG.getBitcast(MVT::f32, Elt);
6195     VecElts[i] = Elt;
6196   }
6197   for (unsigned i = Elts.size(); i < NumElts; ++i)
6198     VecElts[i] = DAG.getUNDEF(MVT::f32);
6199 
6200   if (NumElts == 1)
6201     return VecElts[0];
6202   return DAG.getBuildVector(Type, DL, VecElts);
6203 }
6204 
6205 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
6206                               SDValue Src, int ExtraElts) {
6207   EVT SrcVT = Src.getValueType();
6208 
6209   SmallVector<SDValue, 8> Elts;
6210 
6211   if (SrcVT.isVector())
6212     DAG.ExtractVectorElements(Src, Elts);
6213   else
6214     Elts.push_back(Src);
6215 
6216   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
6217   while (ExtraElts--)
6218     Elts.push_back(Undef);
6219 
6220   return DAG.getBuildVector(CastVT, DL, Elts);
6221 }
6222 
6223 // Re-construct the required return value for a image load intrinsic.
6224 // This is more complicated due to the optional use TexFailCtrl which means the required
6225 // return type is an aggregate
6226 static SDValue constructRetValue(SelectionDAG &DAG,
6227                                  MachineSDNode *Result,
6228                                  ArrayRef<EVT> ResultTypes,
6229                                  bool IsTexFail, bool Unpacked, bool IsD16,
6230                                  int DMaskPop, int NumVDataDwords,
6231                                  const SDLoc &DL) {
6232   // Determine the required return type. This is the same regardless of IsTexFail flag
6233   EVT ReqRetVT = ResultTypes[0];
6234   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
6235   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6236     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
6237 
6238   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6239     DMaskPop : (DMaskPop + 1) / 2;
6240 
6241   MVT DataDwordVT = NumDataDwords == 1 ?
6242     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
6243 
6244   MVT MaskPopVT = MaskPopDwords == 1 ?
6245     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
6246 
6247   SDValue Data(Result, 0);
6248   SDValue TexFail;
6249 
6250   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
6251     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
6252     if (MaskPopVT.isVector()) {
6253       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
6254                          SDValue(Result, 0), ZeroIdx);
6255     } else {
6256       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
6257                          SDValue(Result, 0), ZeroIdx);
6258     }
6259   }
6260 
6261   if (DataDwordVT.isVector())
6262     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
6263                           NumDataDwords - MaskPopDwords);
6264 
6265   if (IsD16)
6266     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
6267 
6268   EVT LegalReqRetVT = ReqRetVT;
6269   if (!ReqRetVT.isVector()) {
6270     if (!Data.getValueType().isInteger())
6271       Data = DAG.getNode(ISD::BITCAST, DL,
6272                          Data.getValueType().changeTypeToInteger(), Data);
6273     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
6274   } else {
6275     // We need to widen the return vector to a legal type
6276     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
6277         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
6278       LegalReqRetVT =
6279           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
6280                            ReqRetVT.getVectorNumElements() + 1);
6281     }
6282   }
6283   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
6284 
6285   if (IsTexFail) {
6286     TexFail =
6287         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
6288                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
6289 
6290     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
6291   }
6292 
6293   if (Result->getNumValues() == 1)
6294     return Data;
6295 
6296   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
6297 }
6298 
6299 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
6300                          SDValue *LWE, bool &IsTexFail) {
6301   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
6302 
6303   uint64_t Value = TexFailCtrlConst->getZExtValue();
6304   if (Value) {
6305     IsTexFail = true;
6306   }
6307 
6308   SDLoc DL(TexFailCtrlConst);
6309   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
6310   Value &= ~(uint64_t)0x1;
6311   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
6312   Value &= ~(uint64_t)0x2;
6313 
6314   return Value == 0;
6315 }
6316 
6317 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
6318                                       MVT PackVectorVT,
6319                                       SmallVectorImpl<SDValue> &PackedAddrs,
6320                                       unsigned DimIdx, unsigned EndIdx,
6321                                       unsigned NumGradients) {
6322   SDLoc DL(Op);
6323   for (unsigned I = DimIdx; I < EndIdx; I++) {
6324     SDValue Addr = Op.getOperand(I);
6325 
6326     // Gradients are packed with undef for each coordinate.
6327     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
6328     // 1D: undef,dx/dh; undef,dx/dv
6329     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
6330     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
6331     if (((I + 1) >= EndIdx) ||
6332         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
6333                                          I == DimIdx + NumGradients - 1))) {
6334       if (Addr.getValueType() != MVT::i16)
6335         Addr = DAG.getBitcast(MVT::i16, Addr);
6336       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
6337     } else {
6338       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
6339       I++;
6340     }
6341     Addr = DAG.getBitcast(MVT::f32, Addr);
6342     PackedAddrs.push_back(Addr);
6343   }
6344 }
6345 
6346 SDValue SITargetLowering::lowerImage(SDValue Op,
6347                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
6348                                      SelectionDAG &DAG, bool WithChain) const {
6349   SDLoc DL(Op);
6350   MachineFunction &MF = DAG.getMachineFunction();
6351   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
6352   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
6353       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
6354   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
6355   unsigned IntrOpcode = Intr->BaseOpcode;
6356   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6357 
6358   SmallVector<EVT, 3> ResultTypes(Op->values());
6359   SmallVector<EVT, 3> OrigResultTypes(Op->values());
6360   bool IsD16 = false;
6361   bool IsG16 = false;
6362   bool IsA16 = false;
6363   SDValue VData;
6364   int NumVDataDwords;
6365   bool AdjustRetType = false;
6366 
6367   // Offset of intrinsic arguments
6368   const unsigned ArgOffset = WithChain ? 2 : 1;
6369 
6370   unsigned DMask;
6371   unsigned DMaskLanes = 0;
6372 
6373   if (BaseOpcode->Atomic) {
6374     VData = Op.getOperand(2);
6375 
6376     bool Is64Bit = VData.getValueType() == MVT::i64;
6377     if (BaseOpcode->AtomicX2) {
6378       SDValue VData2 = Op.getOperand(3);
6379       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6380                                  {VData, VData2});
6381       if (Is64Bit)
6382         VData = DAG.getBitcast(MVT::v4i32, VData);
6383 
6384       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6385       DMask = Is64Bit ? 0xf : 0x3;
6386       NumVDataDwords = Is64Bit ? 4 : 2;
6387     } else {
6388       DMask = Is64Bit ? 0x3 : 0x1;
6389       NumVDataDwords = Is64Bit ? 2 : 1;
6390     }
6391   } else {
6392     auto *DMaskConst =
6393         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6394     DMask = DMaskConst->getZExtValue();
6395     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6396 
6397     if (BaseOpcode->Store) {
6398       VData = Op.getOperand(2);
6399 
6400       MVT StoreVT = VData.getSimpleValueType();
6401       if (StoreVT.getScalarType() == MVT::f16) {
6402         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6403           return Op; // D16 is unsupported for this instruction
6404 
6405         IsD16 = true;
6406         VData = handleD16VData(VData, DAG, true);
6407       }
6408 
6409       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6410     } else {
6411       // Work out the num dwords based on the dmask popcount and underlying type
6412       // and whether packing is supported.
6413       MVT LoadVT = ResultTypes[0].getSimpleVT();
6414       if (LoadVT.getScalarType() == MVT::f16) {
6415         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6416           return Op; // D16 is unsupported for this instruction
6417 
6418         IsD16 = true;
6419       }
6420 
6421       // Confirm that the return type is large enough for the dmask specified
6422       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6423           (!LoadVT.isVector() && DMaskLanes > 1))
6424           return Op;
6425 
6426       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6427       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6428       // instructions.
6429       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6430           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6431         NumVDataDwords = (DMaskLanes + 1) / 2;
6432       else
6433         NumVDataDwords = DMaskLanes;
6434 
6435       AdjustRetType = true;
6436     }
6437   }
6438 
6439   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6440   SmallVector<SDValue, 4> VAddrs;
6441 
6442   // Check for 16 bit addresses or derivatives and pack if true.
6443   MVT VAddrVT =
6444       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6445   MVT VAddrScalarVT = VAddrVT.getScalarType();
6446   MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6447   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6448 
6449   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6450   VAddrScalarVT = VAddrVT.getScalarType();
6451   MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6452   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6453 
6454   // Push back extra arguments.
6455   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) {
6456     if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) {
6457       assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument");
6458       // Special handling of bias when A16 is on. Bias is of type half but
6459       // occupies full 32-bit.
6460       SDValue Bias = DAG.getBuildVector(
6461           MVT::v2f16, DL,
6462           {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)});
6463       VAddrs.push_back(Bias);
6464     } else {
6465       assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) &&
6466              "Bias needs to be converted to 16 bit in A16 mode");
6467       VAddrs.push_back(Op.getOperand(ArgOffset + I));
6468     }
6469   }
6470 
6471   if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
6472     // 16 bit gradients are supported, but are tied to the A16 control
6473     // so both gradients and addresses must be 16 bit
6474     LLVM_DEBUG(
6475         dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6476                   "require 16 bit args for both gradients and addresses");
6477     return Op;
6478   }
6479 
6480   if (IsA16) {
6481     if (!ST->hasA16()) {
6482       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6483                            "support 16 bit addresses\n");
6484       return Op;
6485     }
6486   }
6487 
6488   // We've dealt with incorrect input so we know that if IsA16, IsG16
6489   // are set then we have to compress/pack operands (either address,
6490   // gradient or both)
6491   // In the case where a16 and gradients are tied (no G16 support) then we
6492   // have already verified that both IsA16 and IsG16 are true
6493   if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
6494     // Activate g16
6495     const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6496         AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6497     IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6498   }
6499 
6500   // Add gradients (packed or unpacked)
6501   if (IsG16) {
6502     // Pack the gradients
6503     // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6504     packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
6505                               ArgOffset + Intr->GradientStart,
6506                               ArgOffset + Intr->CoordStart, Intr->NumGradients);
6507   } else {
6508     for (unsigned I = ArgOffset + Intr->GradientStart;
6509          I < ArgOffset + Intr->CoordStart; I++)
6510       VAddrs.push_back(Op.getOperand(I));
6511   }
6512 
6513   // Add addresses (packed or unpacked)
6514   if (IsA16) {
6515     packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
6516                               ArgOffset + Intr->CoordStart, VAddrEnd,
6517                               0 /* No gradients */);
6518   } else {
6519     // Add uncompressed address
6520     for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6521       VAddrs.push_back(Op.getOperand(I));
6522   }
6523 
6524   // If the register allocator cannot place the address registers contiguously
6525   // without introducing moves, then using the non-sequential address encoding
6526   // is always preferable, since it saves VALU instructions and is usually a
6527   // wash in terms of code size or even better.
6528   //
6529   // However, we currently have no way of hinting to the register allocator that
6530   // MIMG addresses should be placed contiguously when it is possible to do so,
6531   // so force non-NSA for the common 2-address case as a heuristic.
6532   //
6533   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6534   // allocation when possible.
6535   bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) &&
6536                 VAddrs.size() >= 3 &&
6537                 VAddrs.size() <= (unsigned)ST->getNSAMaxSize();
6538   SDValue VAddr;
6539   if (!UseNSA)
6540     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6541 
6542   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6543   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6544   SDValue Unorm;
6545   if (!BaseOpcode->Sampler) {
6546     Unorm = True;
6547   } else {
6548     auto UnormConst =
6549         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6550 
6551     Unorm = UnormConst->getZExtValue() ? True : False;
6552   }
6553 
6554   SDValue TFE;
6555   SDValue LWE;
6556   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6557   bool IsTexFail = false;
6558   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6559     return Op;
6560 
6561   if (IsTexFail) {
6562     if (!DMaskLanes) {
6563       // Expecting to get an error flag since TFC is on - and dmask is 0
6564       // Force dmask to be at least 1 otherwise the instruction will fail
6565       DMask = 0x1;
6566       DMaskLanes = 1;
6567       NumVDataDwords = 1;
6568     }
6569     NumVDataDwords += 1;
6570     AdjustRetType = true;
6571   }
6572 
6573   // Has something earlier tagged that the return type needs adjusting
6574   // This happens if the instruction is a load or has set TexFailCtrl flags
6575   if (AdjustRetType) {
6576     // NumVDataDwords reflects the true number of dwords required in the return type
6577     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6578       // This is a no-op load. This can be eliminated
6579       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6580       if (isa<MemSDNode>(Op))
6581         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6582       return Undef;
6583     }
6584 
6585     EVT NewVT = NumVDataDwords > 1 ?
6586                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6587                 : MVT::i32;
6588 
6589     ResultTypes[0] = NewVT;
6590     if (ResultTypes.size() == 3) {
6591       // Original result was aggregate type used for TexFailCtrl results
6592       // The actual instruction returns as a vector type which has now been
6593       // created. Remove the aggregate result.
6594       ResultTypes.erase(&ResultTypes[1]);
6595     }
6596   }
6597 
6598   unsigned CPol = cast<ConstantSDNode>(
6599       Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6600   if (BaseOpcode->Atomic)
6601     CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6602   if (CPol & ~AMDGPU::CPol::ALL)
6603     return Op;
6604 
6605   SmallVector<SDValue, 26> Ops;
6606   if (BaseOpcode->Store || BaseOpcode->Atomic)
6607     Ops.push_back(VData); // vdata
6608   if (UseNSA)
6609     append_range(Ops, VAddrs);
6610   else
6611     Ops.push_back(VAddr);
6612   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6613   if (BaseOpcode->Sampler)
6614     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6615   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6616   if (IsGFX10Plus)
6617     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6618   Ops.push_back(Unorm);
6619   Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6620   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6621                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6622   if (IsGFX10Plus)
6623     Ops.push_back(IsA16 ? True : False);
6624   if (!Subtarget->hasGFX90AInsts()) {
6625     Ops.push_back(TFE); //tfe
6626   } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6627     report_fatal_error("TFE is not supported on this GPU");
6628   }
6629   Ops.push_back(LWE); // lwe
6630   if (!IsGFX10Plus)
6631     Ops.push_back(DimInfo->DA ? True : False);
6632   if (BaseOpcode->HasD16)
6633     Ops.push_back(IsD16 ? True : False);
6634   if (isa<MemSDNode>(Op))
6635     Ops.push_back(Op.getOperand(0)); // chain
6636 
6637   int NumVAddrDwords =
6638       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6639   int Opcode = -1;
6640 
6641   if (IsGFX10Plus) {
6642     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6643                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6644                                           : AMDGPU::MIMGEncGfx10Default,
6645                                    NumVDataDwords, NumVAddrDwords);
6646   } else {
6647     if (Subtarget->hasGFX90AInsts()) {
6648       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6649                                      NumVDataDwords, NumVAddrDwords);
6650       if (Opcode == -1)
6651         report_fatal_error(
6652             "requested image instruction is not supported on this GPU");
6653     }
6654     if (Opcode == -1 &&
6655         Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6656       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6657                                      NumVDataDwords, NumVAddrDwords);
6658     if (Opcode == -1)
6659       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6660                                      NumVDataDwords, NumVAddrDwords);
6661   }
6662   assert(Opcode != -1);
6663 
6664   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6665   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6666     MachineMemOperand *MemRef = MemOp->getMemOperand();
6667     DAG.setNodeMemRefs(NewNode, {MemRef});
6668   }
6669 
6670   if (BaseOpcode->AtomicX2) {
6671     SmallVector<SDValue, 1> Elt;
6672     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6673     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6674   }
6675   if (BaseOpcode->Store)
6676     return SDValue(NewNode, 0);
6677   return constructRetValue(DAG, NewNode,
6678                            OrigResultTypes, IsTexFail,
6679                            Subtarget->hasUnpackedD16VMem(), IsD16,
6680                            DMaskLanes, NumVDataDwords, DL);
6681 }
6682 
6683 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6684                                        SDValue Offset, SDValue CachePolicy,
6685                                        SelectionDAG &DAG) const {
6686   MachineFunction &MF = DAG.getMachineFunction();
6687 
6688   const DataLayout &DataLayout = DAG.getDataLayout();
6689   Align Alignment =
6690       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6691 
6692   MachineMemOperand *MMO = MF.getMachineMemOperand(
6693       MachinePointerInfo(),
6694       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6695           MachineMemOperand::MOInvariant,
6696       VT.getStoreSize(), Alignment);
6697 
6698   if (!Offset->isDivergent()) {
6699     SDValue Ops[] = {
6700         Rsrc,
6701         Offset, // Offset
6702         CachePolicy
6703     };
6704 
6705     // Widen vec3 load to vec4.
6706     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6707       EVT WidenedVT =
6708           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6709       auto WidenedOp = DAG.getMemIntrinsicNode(
6710           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6711           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6712       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6713                                    DAG.getVectorIdxConstant(0, DL));
6714       return Subvector;
6715     }
6716 
6717     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6718                                    DAG.getVTList(VT), Ops, VT, MMO);
6719   }
6720 
6721   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6722   // assume that the buffer is unswizzled.
6723   SmallVector<SDValue, 4> Loads;
6724   unsigned NumLoads = 1;
6725   MVT LoadVT = VT.getSimpleVT();
6726   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6727   assert((LoadVT.getScalarType() == MVT::i32 ||
6728           LoadVT.getScalarType() == MVT::f32));
6729 
6730   if (NumElts == 8 || NumElts == 16) {
6731     NumLoads = NumElts / 4;
6732     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6733   }
6734 
6735   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6736   SDValue Ops[] = {
6737       DAG.getEntryNode(),                               // Chain
6738       Rsrc,                                             // rsrc
6739       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6740       {},                                               // voffset
6741       {},                                               // soffset
6742       {},                                               // offset
6743       CachePolicy,                                      // cachepolicy
6744       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6745   };
6746 
6747   // Use the alignment to ensure that the required offsets will fit into the
6748   // immediate offsets.
6749   setBufferOffsets(Offset, DAG, &Ops[3],
6750                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6751 
6752   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6753   for (unsigned i = 0; i < NumLoads; ++i) {
6754     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6755     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6756                                         LoadVT, MMO, DAG));
6757   }
6758 
6759   if (NumElts == 8 || NumElts == 16)
6760     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6761 
6762   return Loads[0];
6763 }
6764 
6765 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6766                                                   SelectionDAG &DAG) const {
6767   MachineFunction &MF = DAG.getMachineFunction();
6768   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6769 
6770   EVT VT = Op.getValueType();
6771   SDLoc DL(Op);
6772   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6773 
6774   // TODO: Should this propagate fast-math-flags?
6775 
6776   switch (IntrinsicID) {
6777   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6778     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6779       return emitNonHSAIntrinsicError(DAG, DL, VT);
6780     return getPreloadedValue(DAG, *MFI, VT,
6781                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6782   }
6783   case Intrinsic::amdgcn_dispatch_ptr:
6784   case Intrinsic::amdgcn_queue_ptr: {
6785     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6786       DiagnosticInfoUnsupported BadIntrin(
6787           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6788           DL.getDebugLoc());
6789       DAG.getContext()->diagnose(BadIntrin);
6790       return DAG.getUNDEF(VT);
6791     }
6792 
6793     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6794       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6795     return getPreloadedValue(DAG, *MFI, VT, RegID);
6796   }
6797   case Intrinsic::amdgcn_implicitarg_ptr: {
6798     if (MFI->isEntryFunction())
6799       return getImplicitArgPtr(DAG, DL);
6800     return getPreloadedValue(DAG, *MFI, VT,
6801                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6802   }
6803   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6804     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6805       // This only makes sense to call in a kernel, so just lower to null.
6806       return DAG.getConstant(0, DL, VT);
6807     }
6808 
6809     return getPreloadedValue(DAG, *MFI, VT,
6810                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6811   }
6812   case Intrinsic::amdgcn_dispatch_id: {
6813     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6814   }
6815   case Intrinsic::amdgcn_rcp:
6816     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6817   case Intrinsic::amdgcn_rsq:
6818     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6819   case Intrinsic::amdgcn_rsq_legacy:
6820     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6821       return emitRemovedIntrinsicError(DAG, DL, VT);
6822     return SDValue();
6823   case Intrinsic::amdgcn_rcp_legacy:
6824     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6825       return emitRemovedIntrinsicError(DAG, DL, VT);
6826     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6827   case Intrinsic::amdgcn_rsq_clamp: {
6828     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6829       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6830 
6831     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6832     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6833     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6834 
6835     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6836     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6837                               DAG.getConstantFP(Max, DL, VT));
6838     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6839                        DAG.getConstantFP(Min, DL, VT));
6840   }
6841   case Intrinsic::r600_read_ngroups_x:
6842     if (Subtarget->isAmdHsaOS())
6843       return emitNonHSAIntrinsicError(DAG, DL, VT);
6844 
6845     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6846                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6847                                     false);
6848   case Intrinsic::r600_read_ngroups_y:
6849     if (Subtarget->isAmdHsaOS())
6850       return emitNonHSAIntrinsicError(DAG, DL, VT);
6851 
6852     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6853                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6854                                     false);
6855   case Intrinsic::r600_read_ngroups_z:
6856     if (Subtarget->isAmdHsaOS())
6857       return emitNonHSAIntrinsicError(DAG, DL, VT);
6858 
6859     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6860                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6861                                     false);
6862   case Intrinsic::r600_read_global_size_x:
6863     if (Subtarget->isAmdHsaOS())
6864       return emitNonHSAIntrinsicError(DAG, DL, VT);
6865 
6866     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6867                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6868                                     Align(4), false);
6869   case Intrinsic::r600_read_global_size_y:
6870     if (Subtarget->isAmdHsaOS())
6871       return emitNonHSAIntrinsicError(DAG, DL, VT);
6872 
6873     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6874                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6875                                     Align(4), false);
6876   case Intrinsic::r600_read_global_size_z:
6877     if (Subtarget->isAmdHsaOS())
6878       return emitNonHSAIntrinsicError(DAG, DL, VT);
6879 
6880     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6881                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6882                                     Align(4), false);
6883   case Intrinsic::r600_read_local_size_x:
6884     if (Subtarget->isAmdHsaOS())
6885       return emitNonHSAIntrinsicError(DAG, DL, VT);
6886 
6887     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6888                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6889   case Intrinsic::r600_read_local_size_y:
6890     if (Subtarget->isAmdHsaOS())
6891       return emitNonHSAIntrinsicError(DAG, DL, VT);
6892 
6893     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6894                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6895   case Intrinsic::r600_read_local_size_z:
6896     if (Subtarget->isAmdHsaOS())
6897       return emitNonHSAIntrinsicError(DAG, DL, VT);
6898 
6899     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6900                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6901   case Intrinsic::amdgcn_workgroup_id_x:
6902     return getPreloadedValue(DAG, *MFI, VT,
6903                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6904   case Intrinsic::amdgcn_workgroup_id_y:
6905     return getPreloadedValue(DAG, *MFI, VT,
6906                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6907   case Intrinsic::amdgcn_workgroup_id_z:
6908     return getPreloadedValue(DAG, *MFI, VT,
6909                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6910   case Intrinsic::amdgcn_workitem_id_x:
6911     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 0) == 0)
6912       return DAG.getConstant(0, DL, MVT::i32);
6913 
6914     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6915                           SDLoc(DAG.getEntryNode()),
6916                           MFI->getArgInfo().WorkItemIDX);
6917   case Intrinsic::amdgcn_workitem_id_y:
6918     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 1) == 0)
6919       return DAG.getConstant(0, DL, MVT::i32);
6920 
6921     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6922                           SDLoc(DAG.getEntryNode()),
6923                           MFI->getArgInfo().WorkItemIDY);
6924   case Intrinsic::amdgcn_workitem_id_z:
6925     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 2) == 0)
6926       return DAG.getConstant(0, DL, MVT::i32);
6927 
6928     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6929                           SDLoc(DAG.getEntryNode()),
6930                           MFI->getArgInfo().WorkItemIDZ);
6931   case Intrinsic::amdgcn_wavefrontsize:
6932     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6933                            SDLoc(Op), MVT::i32);
6934   case Intrinsic::amdgcn_s_buffer_load: {
6935     unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6936     if (CPol & ~AMDGPU::CPol::ALL)
6937       return Op;
6938     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6939                         DAG);
6940   }
6941   case Intrinsic::amdgcn_fdiv_fast:
6942     return lowerFDIV_FAST(Op, DAG);
6943   case Intrinsic::amdgcn_sin:
6944     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6945 
6946   case Intrinsic::amdgcn_cos:
6947     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6948 
6949   case Intrinsic::amdgcn_mul_u24:
6950     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6951   case Intrinsic::amdgcn_mul_i24:
6952     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6953 
6954   case Intrinsic::amdgcn_log_clamp: {
6955     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6956       return SDValue();
6957 
6958     return emitRemovedIntrinsicError(DAG, DL, VT);
6959   }
6960   case Intrinsic::amdgcn_ldexp:
6961     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6962                        Op.getOperand(1), Op.getOperand(2));
6963 
6964   case Intrinsic::amdgcn_fract:
6965     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6966 
6967   case Intrinsic::amdgcn_class:
6968     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6969                        Op.getOperand(1), Op.getOperand(2));
6970   case Intrinsic::amdgcn_div_fmas:
6971     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6972                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6973                        Op.getOperand(4));
6974 
6975   case Intrinsic::amdgcn_div_fixup:
6976     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6977                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6978 
6979   case Intrinsic::amdgcn_div_scale: {
6980     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6981 
6982     // Translate to the operands expected by the machine instruction. The
6983     // first parameter must be the same as the first instruction.
6984     SDValue Numerator = Op.getOperand(1);
6985     SDValue Denominator = Op.getOperand(2);
6986 
6987     // Note this order is opposite of the machine instruction's operations,
6988     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6989     // intrinsic has the numerator as the first operand to match a normal
6990     // division operation.
6991 
6992     SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator;
6993 
6994     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6995                        Denominator, Numerator);
6996   }
6997   case Intrinsic::amdgcn_icmp: {
6998     // There is a Pat that handles this variant, so return it as-is.
6999     if (Op.getOperand(1).getValueType() == MVT::i1 &&
7000         Op.getConstantOperandVal(2) == 0 &&
7001         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
7002       return Op;
7003     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
7004   }
7005   case Intrinsic::amdgcn_fcmp: {
7006     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
7007   }
7008   case Intrinsic::amdgcn_ballot:
7009     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
7010   case Intrinsic::amdgcn_fmed3:
7011     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
7012                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
7013   case Intrinsic::amdgcn_fdot2:
7014     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
7015                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
7016                        Op.getOperand(4));
7017   case Intrinsic::amdgcn_fmul_legacy:
7018     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
7019                        Op.getOperand(1), Op.getOperand(2));
7020   case Intrinsic::amdgcn_sffbh:
7021     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
7022   case Intrinsic::amdgcn_sbfe:
7023     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
7024                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
7025   case Intrinsic::amdgcn_ubfe:
7026     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
7027                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
7028   case Intrinsic::amdgcn_cvt_pkrtz:
7029   case Intrinsic::amdgcn_cvt_pknorm_i16:
7030   case Intrinsic::amdgcn_cvt_pknorm_u16:
7031   case Intrinsic::amdgcn_cvt_pk_i16:
7032   case Intrinsic::amdgcn_cvt_pk_u16: {
7033     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
7034     EVT VT = Op.getValueType();
7035     unsigned Opcode;
7036 
7037     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
7038       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
7039     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
7040       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
7041     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
7042       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
7043     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
7044       Opcode = AMDGPUISD::CVT_PK_I16_I32;
7045     else
7046       Opcode = AMDGPUISD::CVT_PK_U16_U32;
7047 
7048     if (isTypeLegal(VT))
7049       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
7050 
7051     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
7052                                Op.getOperand(1), Op.getOperand(2));
7053     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
7054   }
7055   case Intrinsic::amdgcn_fmad_ftz:
7056     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
7057                        Op.getOperand(2), Op.getOperand(3));
7058 
7059   case Intrinsic::amdgcn_if_break:
7060     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
7061                                       Op->getOperand(1), Op->getOperand(2)), 0);
7062 
7063   case Intrinsic::amdgcn_groupstaticsize: {
7064     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
7065     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
7066       return Op;
7067 
7068     const Module *M = MF.getFunction().getParent();
7069     const GlobalValue *GV =
7070         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
7071     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
7072                                             SIInstrInfo::MO_ABS32_LO);
7073     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
7074   }
7075   case Intrinsic::amdgcn_is_shared:
7076   case Intrinsic::amdgcn_is_private: {
7077     SDLoc SL(Op);
7078     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
7079       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
7080     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
7081     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
7082                                  Op.getOperand(1));
7083 
7084     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
7085                                 DAG.getConstant(1, SL, MVT::i32));
7086     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
7087   }
7088   case Intrinsic::amdgcn_perm:
7089     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
7090                        Op.getOperand(2), Op.getOperand(3));
7091   case Intrinsic::amdgcn_reloc_constant: {
7092     Module *M = const_cast<Module *>(MF.getFunction().getParent());
7093     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
7094     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
7095     auto RelocSymbol = cast<GlobalVariable>(
7096         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
7097     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
7098                                             SIInstrInfo::MO_ABS32_LO);
7099     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
7100   }
7101   default:
7102     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7103             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7104       return lowerImage(Op, ImageDimIntr, DAG, false);
7105 
7106     return Op;
7107   }
7108 }
7109 
7110 /// Update \p MMO based on the offset inputs to an intrinsic.
7111 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset,
7112                             SDValue SOffset, SDValue Offset,
7113                             SDValue VIndex = SDValue()) {
7114   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
7115       !isa<ConstantSDNode>(Offset)) {
7116     // The combined offset is not known to be constant, so we cannot represent
7117     // it in the MMO. Give up.
7118     MMO->setValue((Value *)nullptr);
7119     return;
7120   }
7121 
7122   if (VIndex && (!isa<ConstantSDNode>(VIndex) ||
7123                  !cast<ConstantSDNode>(VIndex)->isZero())) {
7124     // The strided index component of the address is not known to be zero, so we
7125     // cannot represent it in the MMO. Give up.
7126     MMO->setValue((Value *)nullptr);
7127     return;
7128   }
7129 
7130   MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() +
7131                  cast<ConstantSDNode>(SOffset)->getSExtValue() +
7132                  cast<ConstantSDNode>(Offset)->getSExtValue());
7133 }
7134 
7135 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
7136                                                      SelectionDAG &DAG,
7137                                                      unsigned NewOpcode) const {
7138   SDLoc DL(Op);
7139 
7140   SDValue VData = Op.getOperand(2);
7141   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7142   SDValue Ops[] = {
7143     Op.getOperand(0), // Chain
7144     VData,            // vdata
7145     Op.getOperand(3), // rsrc
7146     DAG.getConstant(0, DL, MVT::i32), // vindex
7147     Offsets.first,    // voffset
7148     Op.getOperand(5), // soffset
7149     Offsets.second,   // offset
7150     Op.getOperand(6), // cachepolicy
7151     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7152   };
7153 
7154   auto *M = cast<MemSDNode>(Op);
7155   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
7156 
7157   EVT MemVT = VData.getValueType();
7158   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7159                                  M->getMemOperand());
7160 }
7161 
7162 // Return a value to use for the idxen operand by examining the vindex operand.
7163 static unsigned getIdxEn(SDValue VIndex) {
7164   if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex))
7165     // No need to set idxen if vindex is known to be zero.
7166     return VIndexC->getZExtValue() != 0;
7167   return 1;
7168 }
7169 
7170 SDValue
7171 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
7172                                                 unsigned NewOpcode) const {
7173   SDLoc DL(Op);
7174 
7175   SDValue VData = Op.getOperand(2);
7176   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7177   SDValue Ops[] = {
7178     Op.getOperand(0), // Chain
7179     VData,            // vdata
7180     Op.getOperand(3), // rsrc
7181     Op.getOperand(4), // vindex
7182     Offsets.first,    // voffset
7183     Op.getOperand(6), // soffset
7184     Offsets.second,   // offset
7185     Op.getOperand(7), // cachepolicy
7186     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7187   };
7188 
7189   auto *M = cast<MemSDNode>(Op);
7190   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7191 
7192   EVT MemVT = VData.getValueType();
7193   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7194                                  M->getMemOperand());
7195 }
7196 
7197 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
7198                                                  SelectionDAG &DAG) const {
7199   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7200   SDLoc DL(Op);
7201 
7202   switch (IntrID) {
7203   case Intrinsic::amdgcn_ds_ordered_add:
7204   case Intrinsic::amdgcn_ds_ordered_swap: {
7205     MemSDNode *M = cast<MemSDNode>(Op);
7206     SDValue Chain = M->getOperand(0);
7207     SDValue M0 = M->getOperand(2);
7208     SDValue Value = M->getOperand(3);
7209     unsigned IndexOperand = M->getConstantOperandVal(7);
7210     unsigned WaveRelease = M->getConstantOperandVal(8);
7211     unsigned WaveDone = M->getConstantOperandVal(9);
7212 
7213     unsigned OrderedCountIndex = IndexOperand & 0x3f;
7214     IndexOperand &= ~0x3f;
7215     unsigned CountDw = 0;
7216 
7217     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
7218       CountDw = (IndexOperand >> 24) & 0xf;
7219       IndexOperand &= ~(0xf << 24);
7220 
7221       if (CountDw < 1 || CountDw > 4) {
7222         report_fatal_error(
7223             "ds_ordered_count: dword count must be between 1 and 4");
7224       }
7225     }
7226 
7227     if (IndexOperand)
7228       report_fatal_error("ds_ordered_count: bad index operand");
7229 
7230     if (WaveDone && !WaveRelease)
7231       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
7232 
7233     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
7234     unsigned ShaderType =
7235         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
7236     unsigned Offset0 = OrderedCountIndex << 2;
7237     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
7238                        (Instruction << 4);
7239 
7240     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
7241       Offset1 |= (CountDw - 1) << 6;
7242 
7243     unsigned Offset = Offset0 | (Offset1 << 8);
7244 
7245     SDValue Ops[] = {
7246       Chain,
7247       Value,
7248       DAG.getTargetConstant(Offset, DL, MVT::i16),
7249       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
7250     };
7251     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
7252                                    M->getVTList(), Ops, M->getMemoryVT(),
7253                                    M->getMemOperand());
7254   }
7255   case Intrinsic::amdgcn_ds_fadd: {
7256     MemSDNode *M = cast<MemSDNode>(Op);
7257     unsigned Opc;
7258     switch (IntrID) {
7259     case Intrinsic::amdgcn_ds_fadd:
7260       Opc = ISD::ATOMIC_LOAD_FADD;
7261       break;
7262     }
7263 
7264     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
7265                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
7266                          M->getMemOperand());
7267   }
7268   case Intrinsic::amdgcn_atomic_inc:
7269   case Intrinsic::amdgcn_atomic_dec:
7270   case Intrinsic::amdgcn_ds_fmin:
7271   case Intrinsic::amdgcn_ds_fmax: {
7272     MemSDNode *M = cast<MemSDNode>(Op);
7273     unsigned Opc;
7274     switch (IntrID) {
7275     case Intrinsic::amdgcn_atomic_inc:
7276       Opc = AMDGPUISD::ATOMIC_INC;
7277       break;
7278     case Intrinsic::amdgcn_atomic_dec:
7279       Opc = AMDGPUISD::ATOMIC_DEC;
7280       break;
7281     case Intrinsic::amdgcn_ds_fmin:
7282       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
7283       break;
7284     case Intrinsic::amdgcn_ds_fmax:
7285       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
7286       break;
7287     default:
7288       llvm_unreachable("Unknown intrinsic!");
7289     }
7290     SDValue Ops[] = {
7291       M->getOperand(0), // Chain
7292       M->getOperand(2), // Ptr
7293       M->getOperand(3)  // Value
7294     };
7295 
7296     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
7297                                    M->getMemoryVT(), M->getMemOperand());
7298   }
7299   case Intrinsic::amdgcn_buffer_load:
7300   case Intrinsic::amdgcn_buffer_load_format: {
7301     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
7302     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7303     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7304     SDValue Ops[] = {
7305       Op.getOperand(0), // Chain
7306       Op.getOperand(2), // rsrc
7307       Op.getOperand(3), // vindex
7308       SDValue(),        // voffset -- will be set by setBufferOffsets
7309       SDValue(),        // soffset -- will be set by setBufferOffsets
7310       SDValue(),        // offset -- will be set by setBufferOffsets
7311       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7312       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7313     };
7314     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
7315 
7316     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
7317         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
7318 
7319     EVT VT = Op.getValueType();
7320     EVT IntVT = VT.changeTypeToInteger();
7321     auto *M = cast<MemSDNode>(Op);
7322     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7323     EVT LoadVT = Op.getValueType();
7324 
7325     if (LoadVT.getScalarType() == MVT::f16)
7326       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
7327                                  M, DAG, Ops);
7328 
7329     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
7330     if (LoadVT.getScalarType() == MVT::i8 ||
7331         LoadVT.getScalarType() == MVT::i16)
7332       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
7333 
7334     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
7335                                M->getMemOperand(), DAG);
7336   }
7337   case Intrinsic::amdgcn_raw_buffer_load:
7338   case Intrinsic::amdgcn_raw_buffer_load_format: {
7339     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
7340 
7341     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7342     SDValue Ops[] = {
7343       Op.getOperand(0), // Chain
7344       Op.getOperand(2), // rsrc
7345       DAG.getConstant(0, DL, MVT::i32), // vindex
7346       Offsets.first,    // voffset
7347       Op.getOperand(4), // soffset
7348       Offsets.second,   // offset
7349       Op.getOperand(5), // cachepolicy, swizzled buffer
7350       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7351     };
7352 
7353     auto *M = cast<MemSDNode>(Op);
7354     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]);
7355     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
7356   }
7357   case Intrinsic::amdgcn_struct_buffer_load:
7358   case Intrinsic::amdgcn_struct_buffer_load_format: {
7359     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
7360 
7361     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7362     SDValue Ops[] = {
7363       Op.getOperand(0), // Chain
7364       Op.getOperand(2), // rsrc
7365       Op.getOperand(3), // vindex
7366       Offsets.first,    // voffset
7367       Op.getOperand(5), // soffset
7368       Offsets.second,   // offset
7369       Op.getOperand(6), // cachepolicy, swizzled buffer
7370       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7371     };
7372 
7373     auto *M = cast<MemSDNode>(Op);
7374     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7375     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7376   }
7377   case Intrinsic::amdgcn_tbuffer_load: {
7378     MemSDNode *M = cast<MemSDNode>(Op);
7379     EVT LoadVT = Op.getValueType();
7380 
7381     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7382     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7383     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7384     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7385     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7386     SDValue Ops[] = {
7387       Op.getOperand(0),  // Chain
7388       Op.getOperand(2),  // rsrc
7389       Op.getOperand(3),  // vindex
7390       Op.getOperand(4),  // voffset
7391       Op.getOperand(5),  // soffset
7392       Op.getOperand(6),  // offset
7393       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7394       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7395       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7396     };
7397 
7398     if (LoadVT.getScalarType() == MVT::f16)
7399       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7400                                  M, DAG, Ops);
7401     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7402                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7403                                DAG);
7404   }
7405   case Intrinsic::amdgcn_raw_tbuffer_load: {
7406     MemSDNode *M = cast<MemSDNode>(Op);
7407     EVT LoadVT = Op.getValueType();
7408     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7409 
7410     SDValue Ops[] = {
7411       Op.getOperand(0),  // Chain
7412       Op.getOperand(2),  // rsrc
7413       DAG.getConstant(0, DL, MVT::i32), // vindex
7414       Offsets.first,     // voffset
7415       Op.getOperand(4),  // soffset
7416       Offsets.second,    // offset
7417       Op.getOperand(5),  // format
7418       Op.getOperand(6),  // cachepolicy, swizzled buffer
7419       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7420     };
7421 
7422     if (LoadVT.getScalarType() == MVT::f16)
7423       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7424                                  M, DAG, Ops);
7425     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7426                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7427                                DAG);
7428   }
7429   case Intrinsic::amdgcn_struct_tbuffer_load: {
7430     MemSDNode *M = cast<MemSDNode>(Op);
7431     EVT LoadVT = Op.getValueType();
7432     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7433 
7434     SDValue Ops[] = {
7435       Op.getOperand(0),  // Chain
7436       Op.getOperand(2),  // rsrc
7437       Op.getOperand(3),  // vindex
7438       Offsets.first,     // voffset
7439       Op.getOperand(5),  // soffset
7440       Offsets.second,    // offset
7441       Op.getOperand(6),  // format
7442       Op.getOperand(7),  // cachepolicy, swizzled buffer
7443       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7444     };
7445 
7446     if (LoadVT.getScalarType() == MVT::f16)
7447       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7448                                  M, DAG, Ops);
7449     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7450                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7451                                DAG);
7452   }
7453   case Intrinsic::amdgcn_buffer_atomic_swap:
7454   case Intrinsic::amdgcn_buffer_atomic_add:
7455   case Intrinsic::amdgcn_buffer_atomic_sub:
7456   case Intrinsic::amdgcn_buffer_atomic_csub:
7457   case Intrinsic::amdgcn_buffer_atomic_smin:
7458   case Intrinsic::amdgcn_buffer_atomic_umin:
7459   case Intrinsic::amdgcn_buffer_atomic_smax:
7460   case Intrinsic::amdgcn_buffer_atomic_umax:
7461   case Intrinsic::amdgcn_buffer_atomic_and:
7462   case Intrinsic::amdgcn_buffer_atomic_or:
7463   case Intrinsic::amdgcn_buffer_atomic_xor:
7464   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7465     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7466     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7467     SDValue Ops[] = {
7468       Op.getOperand(0), // Chain
7469       Op.getOperand(2), // vdata
7470       Op.getOperand(3), // rsrc
7471       Op.getOperand(4), // vindex
7472       SDValue(),        // voffset -- will be set by setBufferOffsets
7473       SDValue(),        // soffset -- will be set by setBufferOffsets
7474       SDValue(),        // offset -- will be set by setBufferOffsets
7475       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7476       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7477     };
7478     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7479 
7480     EVT VT = Op.getValueType();
7481 
7482     auto *M = cast<MemSDNode>(Op);
7483     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7484     unsigned Opcode = 0;
7485 
7486     switch (IntrID) {
7487     case Intrinsic::amdgcn_buffer_atomic_swap:
7488       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7489       break;
7490     case Intrinsic::amdgcn_buffer_atomic_add:
7491       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7492       break;
7493     case Intrinsic::amdgcn_buffer_atomic_sub:
7494       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7495       break;
7496     case Intrinsic::amdgcn_buffer_atomic_csub:
7497       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7498       break;
7499     case Intrinsic::amdgcn_buffer_atomic_smin:
7500       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7501       break;
7502     case Intrinsic::amdgcn_buffer_atomic_umin:
7503       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7504       break;
7505     case Intrinsic::amdgcn_buffer_atomic_smax:
7506       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7507       break;
7508     case Intrinsic::amdgcn_buffer_atomic_umax:
7509       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7510       break;
7511     case Intrinsic::amdgcn_buffer_atomic_and:
7512       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7513       break;
7514     case Intrinsic::amdgcn_buffer_atomic_or:
7515       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7516       break;
7517     case Intrinsic::amdgcn_buffer_atomic_xor:
7518       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7519       break;
7520     case Intrinsic::amdgcn_buffer_atomic_fadd:
7521       if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7522         DiagnosticInfoUnsupported
7523           NoFpRet(DAG.getMachineFunction().getFunction(),
7524                   "return versions of fp atomics not supported",
7525                   DL.getDebugLoc(), DS_Error);
7526         DAG.getContext()->diagnose(NoFpRet);
7527         return SDValue();
7528       }
7529       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7530       break;
7531     default:
7532       llvm_unreachable("unhandled atomic opcode");
7533     }
7534 
7535     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7536                                    M->getMemOperand());
7537   }
7538   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7539     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7540   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7541     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7542   case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7543     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7544   case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7545     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7546   case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7547     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7548   case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7549     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7550   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7551     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7552   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7553     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7554   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7555     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7556   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7557     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7558   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7559     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7560   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7561     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7562   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7563     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7564   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7565     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7566   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7567     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7568   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7569     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7570   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7571     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7572   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7573     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7574   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7575     return lowerStructBufferAtomicIntrin(Op, DAG,
7576                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7577   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7578     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7579   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7580     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7581   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7582     return lowerStructBufferAtomicIntrin(Op, DAG,
7583                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7584   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7585     return lowerStructBufferAtomicIntrin(Op, DAG,
7586                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7587   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7588     return lowerStructBufferAtomicIntrin(Op, DAG,
7589                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7590   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7591     return lowerStructBufferAtomicIntrin(Op, DAG,
7592                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7593   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7594     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7595   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7596     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7597   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7598     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7599   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7600     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7601   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7602     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7603 
7604   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7605     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7606     unsigned IdxEn = getIdxEn(Op.getOperand(5));
7607     SDValue Ops[] = {
7608       Op.getOperand(0), // Chain
7609       Op.getOperand(2), // src
7610       Op.getOperand(3), // cmp
7611       Op.getOperand(4), // rsrc
7612       Op.getOperand(5), // vindex
7613       SDValue(),        // voffset -- will be set by setBufferOffsets
7614       SDValue(),        // soffset -- will be set by setBufferOffsets
7615       SDValue(),        // offset -- will be set by setBufferOffsets
7616       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7617       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7618     };
7619     setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7620 
7621     EVT VT = Op.getValueType();
7622     auto *M = cast<MemSDNode>(Op);
7623     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7624 
7625     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7626                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7627   }
7628   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7629     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7630     SDValue Ops[] = {
7631       Op.getOperand(0), // Chain
7632       Op.getOperand(2), // src
7633       Op.getOperand(3), // cmp
7634       Op.getOperand(4), // rsrc
7635       DAG.getConstant(0, DL, MVT::i32), // vindex
7636       Offsets.first,    // voffset
7637       Op.getOperand(6), // soffset
7638       Offsets.second,   // offset
7639       Op.getOperand(7), // cachepolicy
7640       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7641     };
7642     EVT VT = Op.getValueType();
7643     auto *M = cast<MemSDNode>(Op);
7644     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]);
7645 
7646     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7647                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7648   }
7649   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7650     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7651     SDValue Ops[] = {
7652       Op.getOperand(0), // Chain
7653       Op.getOperand(2), // src
7654       Op.getOperand(3), // cmp
7655       Op.getOperand(4), // rsrc
7656       Op.getOperand(5), // vindex
7657       Offsets.first,    // voffset
7658       Op.getOperand(7), // soffset
7659       Offsets.second,   // offset
7660       Op.getOperand(8), // cachepolicy
7661       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7662     };
7663     EVT VT = Op.getValueType();
7664     auto *M = cast<MemSDNode>(Op);
7665     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7666 
7667     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7668                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7669   }
7670   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7671     MemSDNode *M = cast<MemSDNode>(Op);
7672     SDValue NodePtr = M->getOperand(2);
7673     SDValue RayExtent = M->getOperand(3);
7674     SDValue RayOrigin = M->getOperand(4);
7675     SDValue RayDir = M->getOperand(5);
7676     SDValue RayInvDir = M->getOperand(6);
7677     SDValue TDescr = M->getOperand(7);
7678 
7679     assert(NodePtr.getValueType() == MVT::i32 ||
7680            NodePtr.getValueType() == MVT::i64);
7681     assert(RayDir.getValueType() == MVT::v3f16 ||
7682            RayDir.getValueType() == MVT::v3f32);
7683 
7684     if (!Subtarget->hasGFX10_AEncoding()) {
7685       emitRemovedIntrinsicError(DAG, DL, Op.getValueType());
7686       return SDValue();
7687     }
7688 
7689     const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7690     const bool Is64 = NodePtr.getValueType() == MVT::i64;
7691     const unsigned NumVDataDwords = 4;
7692     const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
7693     const bool UseNSA = Subtarget->hasNSAEncoding() &&
7694                         NumVAddrDwords <= Subtarget->getNSAMaxSize();
7695     const unsigned BaseOpcodes[2][2] = {
7696         {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
7697         {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
7698          AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
7699     int Opcode;
7700     if (UseNSA) {
7701       Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7702                                      AMDGPU::MIMGEncGfx10NSA, NumVDataDwords,
7703                                      NumVAddrDwords);
7704     } else {
7705       Opcode = AMDGPU::getMIMGOpcode(
7706           BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords,
7707           PowerOf2Ceil(NumVAddrDwords));
7708     }
7709     assert(Opcode != -1);
7710 
7711     SmallVector<SDValue, 16> Ops;
7712 
7713     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7714       SmallVector<SDValue, 3> Lanes;
7715       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7716       if (Lanes[0].getValueSizeInBits() == 32) {
7717         for (unsigned I = 0; I < 3; ++I)
7718           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7719       } else {
7720         if (IsAligned) {
7721           Ops.push_back(
7722             DAG.getBitcast(MVT::i32,
7723                            DAG.getBuildVector(MVT::v2f16, DL,
7724                                               { Lanes[0], Lanes[1] })));
7725           Ops.push_back(Lanes[2]);
7726         } else {
7727           SDValue Elt0 = Ops.pop_back_val();
7728           Ops.push_back(
7729             DAG.getBitcast(MVT::i32,
7730                            DAG.getBuildVector(MVT::v2f16, DL,
7731                                               { Elt0, Lanes[0] })));
7732           Ops.push_back(
7733             DAG.getBitcast(MVT::i32,
7734                            DAG.getBuildVector(MVT::v2f16, DL,
7735                                               { Lanes[1], Lanes[2] })));
7736         }
7737       }
7738     };
7739 
7740     if (Is64)
7741       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7742     else
7743       Ops.push_back(NodePtr);
7744 
7745     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7746     packLanes(RayOrigin, true);
7747     packLanes(RayDir, true);
7748     packLanes(RayInvDir, false);
7749 
7750     if (!UseNSA) {
7751       // Build a single vector containing all the operands so far prepared.
7752       if (NumVAddrDwords > 8) {
7753         SDValue Undef = DAG.getUNDEF(MVT::i32);
7754         Ops.append(16 - Ops.size(), Undef);
7755       }
7756       assert(Ops.size() == 8 || Ops.size() == 16);
7757       SDValue MergedOps = DAG.getBuildVector(
7758           Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops);
7759       Ops.clear();
7760       Ops.push_back(MergedOps);
7761     }
7762 
7763     Ops.push_back(TDescr);
7764     if (IsA16)
7765       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7766     Ops.push_back(M->getChain());
7767 
7768     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7769     MachineMemOperand *MemRef = M->getMemOperand();
7770     DAG.setNodeMemRefs(NewNode, {MemRef});
7771     return SDValue(NewNode, 0);
7772   }
7773   case Intrinsic::amdgcn_global_atomic_fadd:
7774     if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7775       DiagnosticInfoUnsupported
7776         NoFpRet(DAG.getMachineFunction().getFunction(),
7777                 "return versions of fp atomics not supported",
7778                 DL.getDebugLoc(), DS_Error);
7779       DAG.getContext()->diagnose(NoFpRet);
7780       return SDValue();
7781     }
7782     LLVM_FALLTHROUGH;
7783   case Intrinsic::amdgcn_global_atomic_fmin:
7784   case Intrinsic::amdgcn_global_atomic_fmax:
7785   case Intrinsic::amdgcn_flat_atomic_fadd:
7786   case Intrinsic::amdgcn_flat_atomic_fmin:
7787   case Intrinsic::amdgcn_flat_atomic_fmax: {
7788     MemSDNode *M = cast<MemSDNode>(Op);
7789     SDValue Ops[] = {
7790       M->getOperand(0), // Chain
7791       M->getOperand(2), // Ptr
7792       M->getOperand(3)  // Value
7793     };
7794     unsigned Opcode = 0;
7795     switch (IntrID) {
7796     case Intrinsic::amdgcn_global_atomic_fadd:
7797     case Intrinsic::amdgcn_flat_atomic_fadd: {
7798       EVT VT = Op.getOperand(3).getValueType();
7799       return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7800                            DAG.getVTList(VT, MVT::Other), Ops,
7801                            M->getMemOperand());
7802     }
7803     case Intrinsic::amdgcn_global_atomic_fmin:
7804     case Intrinsic::amdgcn_flat_atomic_fmin: {
7805       Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7806       break;
7807     }
7808     case Intrinsic::amdgcn_global_atomic_fmax:
7809     case Intrinsic::amdgcn_flat_atomic_fmax: {
7810       Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7811       break;
7812     }
7813     default:
7814       llvm_unreachable("unhandled atomic opcode");
7815     }
7816     return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7817                                    M->getVTList(), Ops, M->getMemoryVT(),
7818                                    M->getMemOperand());
7819   }
7820   default:
7821 
7822     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7823             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7824       return lowerImage(Op, ImageDimIntr, DAG, true);
7825 
7826     return SDValue();
7827   }
7828 }
7829 
7830 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7831 // dwordx4 if on SI.
7832 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7833                                               SDVTList VTList,
7834                                               ArrayRef<SDValue> Ops, EVT MemVT,
7835                                               MachineMemOperand *MMO,
7836                                               SelectionDAG &DAG) const {
7837   EVT VT = VTList.VTs[0];
7838   EVT WidenedVT = VT;
7839   EVT WidenedMemVT = MemVT;
7840   if (!Subtarget->hasDwordx3LoadStores() &&
7841       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7842     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7843                                  WidenedVT.getVectorElementType(), 4);
7844     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7845                                     WidenedMemVT.getVectorElementType(), 4);
7846     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7847   }
7848 
7849   assert(VTList.NumVTs == 2);
7850   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7851 
7852   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7853                                        WidenedMemVT, MMO);
7854   if (WidenedVT != VT) {
7855     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7856                                DAG.getVectorIdxConstant(0, DL));
7857     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7858   }
7859   return NewOp;
7860 }
7861 
7862 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7863                                          bool ImageStore) const {
7864   EVT StoreVT = VData.getValueType();
7865 
7866   // No change for f16 and legal vector D16 types.
7867   if (!StoreVT.isVector())
7868     return VData;
7869 
7870   SDLoc DL(VData);
7871   unsigned NumElements = StoreVT.getVectorNumElements();
7872 
7873   if (Subtarget->hasUnpackedD16VMem()) {
7874     // We need to unpack the packed data to store.
7875     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7876     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7877 
7878     EVT EquivStoreVT =
7879         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7880     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7881     return DAG.UnrollVectorOp(ZExt.getNode());
7882   }
7883 
7884   // The sq block of gfx8.1 does not estimate register use correctly for d16
7885   // image store instructions. The data operand is computed as if it were not a
7886   // d16 image instruction.
7887   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7888     // Bitcast to i16
7889     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7890     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7891 
7892     // Decompose into scalars
7893     SmallVector<SDValue, 4> Elts;
7894     DAG.ExtractVectorElements(IntVData, Elts);
7895 
7896     // Group pairs of i16 into v2i16 and bitcast to i32
7897     SmallVector<SDValue, 4> PackedElts;
7898     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7899       SDValue Pair =
7900           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7901       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7902       PackedElts.push_back(IntPair);
7903     }
7904     if ((NumElements % 2) == 1) {
7905       // Handle v3i16
7906       unsigned I = Elts.size() / 2;
7907       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7908                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7909       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7910       PackedElts.push_back(IntPair);
7911     }
7912 
7913     // Pad using UNDEF
7914     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7915 
7916     // Build final vector
7917     EVT VecVT =
7918         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7919     return DAG.getBuildVector(VecVT, DL, PackedElts);
7920   }
7921 
7922   if (NumElements == 3) {
7923     EVT IntStoreVT =
7924         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7925     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7926 
7927     EVT WidenedStoreVT = EVT::getVectorVT(
7928         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7929     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7930                                          WidenedStoreVT.getStoreSizeInBits());
7931     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7932     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7933   }
7934 
7935   assert(isTypeLegal(StoreVT));
7936   return VData;
7937 }
7938 
7939 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7940                                               SelectionDAG &DAG) const {
7941   SDLoc DL(Op);
7942   SDValue Chain = Op.getOperand(0);
7943   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7944   MachineFunction &MF = DAG.getMachineFunction();
7945 
7946   switch (IntrinsicID) {
7947   case Intrinsic::amdgcn_exp_compr: {
7948     SDValue Src0 = Op.getOperand(4);
7949     SDValue Src1 = Op.getOperand(5);
7950     // Hack around illegal type on SI by directly selecting it.
7951     if (isTypeLegal(Src0.getValueType()))
7952       return SDValue();
7953 
7954     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7955     SDValue Undef = DAG.getUNDEF(MVT::f32);
7956     const SDValue Ops[] = {
7957       Op.getOperand(2), // tgt
7958       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7959       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7960       Undef, // src2
7961       Undef, // src3
7962       Op.getOperand(7), // vm
7963       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7964       Op.getOperand(3), // en
7965       Op.getOperand(0) // Chain
7966     };
7967 
7968     unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7969     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7970   }
7971   case Intrinsic::amdgcn_s_barrier: {
7972     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7973       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7974       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7975       if (WGSize <= ST.getWavefrontSize())
7976         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7977                                           Op.getOperand(0)), 0);
7978     }
7979     return SDValue();
7980   };
7981   case Intrinsic::amdgcn_tbuffer_store: {
7982     SDValue VData = Op.getOperand(2);
7983     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7984     if (IsD16)
7985       VData = handleD16VData(VData, DAG);
7986     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7987     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7988     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7989     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7990     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7991     SDValue Ops[] = {
7992       Chain,
7993       VData,             // vdata
7994       Op.getOperand(3),  // rsrc
7995       Op.getOperand(4),  // vindex
7996       Op.getOperand(5),  // voffset
7997       Op.getOperand(6),  // soffset
7998       Op.getOperand(7),  // offset
7999       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
8000       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
8001       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
8002     };
8003     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
8004                            AMDGPUISD::TBUFFER_STORE_FORMAT;
8005     MemSDNode *M = cast<MemSDNode>(Op);
8006     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8007                                    M->getMemoryVT(), M->getMemOperand());
8008   }
8009 
8010   case Intrinsic::amdgcn_struct_tbuffer_store: {
8011     SDValue VData = Op.getOperand(2);
8012     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8013     if (IsD16)
8014       VData = handleD16VData(VData, DAG);
8015     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
8016     SDValue Ops[] = {
8017       Chain,
8018       VData,             // vdata
8019       Op.getOperand(3),  // rsrc
8020       Op.getOperand(4),  // vindex
8021       Offsets.first,     // voffset
8022       Op.getOperand(6),  // soffset
8023       Offsets.second,    // offset
8024       Op.getOperand(7),  // format
8025       Op.getOperand(8),  // cachepolicy, swizzled buffer
8026       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8027     };
8028     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
8029                            AMDGPUISD::TBUFFER_STORE_FORMAT;
8030     MemSDNode *M = cast<MemSDNode>(Op);
8031     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8032                                    M->getMemoryVT(), M->getMemOperand());
8033   }
8034 
8035   case Intrinsic::amdgcn_raw_tbuffer_store: {
8036     SDValue VData = Op.getOperand(2);
8037     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8038     if (IsD16)
8039       VData = handleD16VData(VData, DAG);
8040     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
8041     SDValue Ops[] = {
8042       Chain,
8043       VData,             // vdata
8044       Op.getOperand(3),  // rsrc
8045       DAG.getConstant(0, DL, MVT::i32), // vindex
8046       Offsets.first,     // voffset
8047       Op.getOperand(5),  // soffset
8048       Offsets.second,    // offset
8049       Op.getOperand(6),  // format
8050       Op.getOperand(7),  // cachepolicy, swizzled buffer
8051       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8052     };
8053     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
8054                            AMDGPUISD::TBUFFER_STORE_FORMAT;
8055     MemSDNode *M = cast<MemSDNode>(Op);
8056     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8057                                    M->getMemoryVT(), M->getMemOperand());
8058   }
8059 
8060   case Intrinsic::amdgcn_buffer_store:
8061   case Intrinsic::amdgcn_buffer_store_format: {
8062     SDValue VData = Op.getOperand(2);
8063     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8064     if (IsD16)
8065       VData = handleD16VData(VData, DAG);
8066     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
8067     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
8068     unsigned IdxEn = getIdxEn(Op.getOperand(4));
8069     SDValue Ops[] = {
8070       Chain,
8071       VData,
8072       Op.getOperand(3), // rsrc
8073       Op.getOperand(4), // vindex
8074       SDValue(), // voffset -- will be set by setBufferOffsets
8075       SDValue(), // soffset -- will be set by setBufferOffsets
8076       SDValue(), // offset -- will be set by setBufferOffsets
8077       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
8078       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
8079     };
8080     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
8081 
8082     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
8083                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8084     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8085     MemSDNode *M = cast<MemSDNode>(Op);
8086     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8087 
8088     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8089     EVT VDataType = VData.getValueType().getScalarType();
8090     if (VDataType == MVT::i8 || VDataType == MVT::i16)
8091       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8092 
8093     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8094                                    M->getMemoryVT(), M->getMemOperand());
8095   }
8096 
8097   case Intrinsic::amdgcn_raw_buffer_store:
8098   case Intrinsic::amdgcn_raw_buffer_store_format: {
8099     const bool IsFormat =
8100         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
8101 
8102     SDValue VData = Op.getOperand(2);
8103     EVT VDataVT = VData.getValueType();
8104     EVT EltType = VDataVT.getScalarType();
8105     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8106     if (IsD16) {
8107       VData = handleD16VData(VData, DAG);
8108       VDataVT = VData.getValueType();
8109     }
8110 
8111     if (!isTypeLegal(VDataVT)) {
8112       VData =
8113           DAG.getNode(ISD::BITCAST, DL,
8114                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8115     }
8116 
8117     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
8118     SDValue Ops[] = {
8119       Chain,
8120       VData,
8121       Op.getOperand(3), // rsrc
8122       DAG.getConstant(0, DL, MVT::i32), // vindex
8123       Offsets.first,    // voffset
8124       Op.getOperand(5), // soffset
8125       Offsets.second,   // offset
8126       Op.getOperand(6), // cachepolicy, swizzled buffer
8127       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8128     };
8129     unsigned Opc =
8130         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
8131     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8132     MemSDNode *M = cast<MemSDNode>(Op);
8133     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
8134 
8135     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8136     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8137       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
8138 
8139     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8140                                    M->getMemoryVT(), M->getMemOperand());
8141   }
8142 
8143   case Intrinsic::amdgcn_struct_buffer_store:
8144   case Intrinsic::amdgcn_struct_buffer_store_format: {
8145     const bool IsFormat =
8146         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
8147 
8148     SDValue VData = Op.getOperand(2);
8149     EVT VDataVT = VData.getValueType();
8150     EVT EltType = VDataVT.getScalarType();
8151     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8152 
8153     if (IsD16) {
8154       VData = handleD16VData(VData, DAG);
8155       VDataVT = VData.getValueType();
8156     }
8157 
8158     if (!isTypeLegal(VDataVT)) {
8159       VData =
8160           DAG.getNode(ISD::BITCAST, DL,
8161                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8162     }
8163 
8164     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
8165     SDValue Ops[] = {
8166       Chain,
8167       VData,
8168       Op.getOperand(3), // rsrc
8169       Op.getOperand(4), // vindex
8170       Offsets.first,    // voffset
8171       Op.getOperand(6), // soffset
8172       Offsets.second,   // offset
8173       Op.getOperand(7), // cachepolicy, swizzled buffer
8174       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8175     };
8176     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
8177                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8178     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8179     MemSDNode *M = cast<MemSDNode>(Op);
8180     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8181 
8182     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8183     EVT VDataType = VData.getValueType().getScalarType();
8184     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8185       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8186 
8187     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8188                                    M->getMemoryVT(), M->getMemOperand());
8189   }
8190   case Intrinsic::amdgcn_end_cf:
8191     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
8192                                       Op->getOperand(2), Chain), 0);
8193 
8194   default: {
8195     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
8196             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
8197       return lowerImage(Op, ImageDimIntr, DAG, true);
8198 
8199     return Op;
8200   }
8201   }
8202 }
8203 
8204 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
8205 // offset (the offset that is included in bounds checking and swizzling, to be
8206 // split between the instruction's voffset and immoffset fields) and soffset
8207 // (the offset that is excluded from bounds checking and swizzling, to go in
8208 // the instruction's soffset field).  This function takes the first kind of
8209 // offset and figures out how to split it between voffset and immoffset.
8210 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
8211     SDValue Offset, SelectionDAG &DAG) const {
8212   SDLoc DL(Offset);
8213   const unsigned MaxImm = 4095;
8214   SDValue N0 = Offset;
8215   ConstantSDNode *C1 = nullptr;
8216 
8217   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
8218     N0 = SDValue();
8219   else if (DAG.isBaseWithConstantOffset(N0)) {
8220     C1 = cast<ConstantSDNode>(N0.getOperand(1));
8221     N0 = N0.getOperand(0);
8222   }
8223 
8224   if (C1) {
8225     unsigned ImmOffset = C1->getZExtValue();
8226     // If the immediate value is too big for the immoffset field, put the value
8227     // and -4096 into the immoffset field so that the value that is copied/added
8228     // for the voffset field is a multiple of 4096, and it stands more chance
8229     // of being CSEd with the copy/add for another similar load/store.
8230     // However, do not do that rounding down to a multiple of 4096 if that is a
8231     // negative number, as it appears to be illegal to have a negative offset
8232     // in the vgpr, even if adding the immediate offset makes it positive.
8233     unsigned Overflow = ImmOffset & ~MaxImm;
8234     ImmOffset -= Overflow;
8235     if ((int32_t)Overflow < 0) {
8236       Overflow += ImmOffset;
8237       ImmOffset = 0;
8238     }
8239     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
8240     if (Overflow) {
8241       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
8242       if (!N0)
8243         N0 = OverflowVal;
8244       else {
8245         SDValue Ops[] = { N0, OverflowVal };
8246         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
8247       }
8248     }
8249   }
8250   if (!N0)
8251     N0 = DAG.getConstant(0, DL, MVT::i32);
8252   if (!C1)
8253     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
8254   return {N0, SDValue(C1, 0)};
8255 }
8256 
8257 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
8258 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
8259 // pointed to by Offsets.
8260 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
8261                                         SelectionDAG &DAG, SDValue *Offsets,
8262                                         Align Alignment) const {
8263   SDLoc DL(CombinedOffset);
8264   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
8265     uint32_t Imm = C->getZExtValue();
8266     uint32_t SOffset, ImmOffset;
8267     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
8268                                  Alignment)) {
8269       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
8270       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8271       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8272       return;
8273     }
8274   }
8275   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
8276     SDValue N0 = CombinedOffset.getOperand(0);
8277     SDValue N1 = CombinedOffset.getOperand(1);
8278     uint32_t SOffset, ImmOffset;
8279     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
8280     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
8281                                                 Subtarget, Alignment)) {
8282       Offsets[0] = N0;
8283       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8284       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8285       return;
8286     }
8287   }
8288   Offsets[0] = CombinedOffset;
8289   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
8290   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
8291 }
8292 
8293 // Handle 8 bit and 16 bit buffer loads
8294 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
8295                                                      EVT LoadVT, SDLoc DL,
8296                                                      ArrayRef<SDValue> Ops,
8297                                                      MemSDNode *M) const {
8298   EVT IntVT = LoadVT.changeTypeToInteger();
8299   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
8300          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
8301 
8302   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
8303   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
8304                                                Ops, IntVT,
8305                                                M->getMemOperand());
8306   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
8307   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
8308 
8309   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
8310 }
8311 
8312 // Handle 8 bit and 16 bit buffer stores
8313 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
8314                                                       EVT VDataType, SDLoc DL,
8315                                                       SDValue Ops[],
8316                                                       MemSDNode *M) const {
8317   if (VDataType == MVT::f16)
8318     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
8319 
8320   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
8321   Ops[1] = BufferStoreExt;
8322   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
8323                                  AMDGPUISD::BUFFER_STORE_SHORT;
8324   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
8325   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
8326                                      M->getMemOperand());
8327 }
8328 
8329 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
8330                                  ISD::LoadExtType ExtType, SDValue Op,
8331                                  const SDLoc &SL, EVT VT) {
8332   if (VT.bitsLT(Op.getValueType()))
8333     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
8334 
8335   switch (ExtType) {
8336   case ISD::SEXTLOAD:
8337     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
8338   case ISD::ZEXTLOAD:
8339     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
8340   case ISD::EXTLOAD:
8341     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
8342   case ISD::NON_EXTLOAD:
8343     return Op;
8344   }
8345 
8346   llvm_unreachable("invalid ext type");
8347 }
8348 
8349 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
8350   SelectionDAG &DAG = DCI.DAG;
8351   if (Ld->getAlignment() < 4 || Ld->isDivergent())
8352     return SDValue();
8353 
8354   // FIXME: Constant loads should all be marked invariant.
8355   unsigned AS = Ld->getAddressSpace();
8356   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
8357       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
8358       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
8359     return SDValue();
8360 
8361   // Don't do this early, since it may interfere with adjacent load merging for
8362   // illegal types. We can avoid losing alignment information for exotic types
8363   // pre-legalize.
8364   EVT MemVT = Ld->getMemoryVT();
8365   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
8366       MemVT.getSizeInBits() >= 32)
8367     return SDValue();
8368 
8369   SDLoc SL(Ld);
8370 
8371   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
8372          "unexpected vector extload");
8373 
8374   // TODO: Drop only high part of range.
8375   SDValue Ptr = Ld->getBasePtr();
8376   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
8377                                 MVT::i32, SL, Ld->getChain(), Ptr,
8378                                 Ld->getOffset(),
8379                                 Ld->getPointerInfo(), MVT::i32,
8380                                 Ld->getAlignment(),
8381                                 Ld->getMemOperand()->getFlags(),
8382                                 Ld->getAAInfo(),
8383                                 nullptr); // Drop ranges
8384 
8385   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
8386   if (MemVT.isFloatingPoint()) {
8387     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
8388            "unexpected fp extload");
8389     TruncVT = MemVT.changeTypeToInteger();
8390   }
8391 
8392   SDValue Cvt = NewLoad;
8393   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
8394     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
8395                       DAG.getValueType(TruncVT));
8396   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
8397              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
8398     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
8399   } else {
8400     assert(Ld->getExtensionType() == ISD::EXTLOAD);
8401   }
8402 
8403   EVT VT = Ld->getValueType(0);
8404   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8405 
8406   DCI.AddToWorklist(Cvt.getNode());
8407 
8408   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
8409   // the appropriate extension from the 32-bit load.
8410   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
8411   DCI.AddToWorklist(Cvt.getNode());
8412 
8413   // Handle conversion back to floating point if necessary.
8414   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8415 
8416   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8417 }
8418 
8419 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8420   SDLoc DL(Op);
8421   LoadSDNode *Load = cast<LoadSDNode>(Op);
8422   ISD::LoadExtType ExtType = Load->getExtensionType();
8423   EVT MemVT = Load->getMemoryVT();
8424 
8425   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8426     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8427       return SDValue();
8428 
8429     // FIXME: Copied from PPC
8430     // First, load into 32 bits, then truncate to 1 bit.
8431 
8432     SDValue Chain = Load->getChain();
8433     SDValue BasePtr = Load->getBasePtr();
8434     MachineMemOperand *MMO = Load->getMemOperand();
8435 
8436     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8437 
8438     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8439                                    BasePtr, RealMemVT, MMO);
8440 
8441     if (!MemVT.isVector()) {
8442       SDValue Ops[] = {
8443         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8444         NewLD.getValue(1)
8445       };
8446 
8447       return DAG.getMergeValues(Ops, DL);
8448     }
8449 
8450     SmallVector<SDValue, 3> Elts;
8451     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8452       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8453                                 DAG.getConstant(I, DL, MVT::i32));
8454 
8455       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8456     }
8457 
8458     SDValue Ops[] = {
8459       DAG.getBuildVector(MemVT, DL, Elts),
8460       NewLD.getValue(1)
8461     };
8462 
8463     return DAG.getMergeValues(Ops, DL);
8464   }
8465 
8466   if (!MemVT.isVector())
8467     return SDValue();
8468 
8469   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8470          "Custom lowering for non-i32 vectors hasn't been implemented.");
8471 
8472   unsigned Alignment = Load->getAlignment();
8473   unsigned AS = Load->getAddressSpace();
8474   if (Subtarget->hasLDSMisalignedBug() &&
8475       AS == AMDGPUAS::FLAT_ADDRESS &&
8476       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8477     return SplitVectorLoad(Op, DAG);
8478   }
8479 
8480   MachineFunction &MF = DAG.getMachineFunction();
8481   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8482   // If there is a possibility that flat instruction access scratch memory
8483   // then we need to use the same legalization rules we use for private.
8484   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8485       !Subtarget->hasMultiDwordFlatScratchAddressing())
8486     AS = MFI->hasFlatScratchInit() ?
8487          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8488 
8489   unsigned NumElements = MemVT.getVectorNumElements();
8490 
8491   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8492       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8493     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8494       if (MemVT.isPow2VectorType())
8495         return SDValue();
8496       return WidenOrSplitVectorLoad(Op, DAG);
8497     }
8498     // Non-uniform loads will be selected to MUBUF instructions, so they
8499     // have the same legalization requirements as global and private
8500     // loads.
8501     //
8502   }
8503 
8504   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8505       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8506       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8507     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8508         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8509         Alignment >= 4 && NumElements < 32) {
8510       if (MemVT.isPow2VectorType())
8511         return SDValue();
8512       return WidenOrSplitVectorLoad(Op, DAG);
8513     }
8514     // Non-uniform loads will be selected to MUBUF instructions, so they
8515     // have the same legalization requirements as global and private
8516     // loads.
8517     //
8518   }
8519   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8520       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8521       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8522       AS == AMDGPUAS::FLAT_ADDRESS) {
8523     if (NumElements > 4)
8524       return SplitVectorLoad(Op, DAG);
8525     // v3 loads not supported on SI.
8526     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8527       return WidenOrSplitVectorLoad(Op, DAG);
8528 
8529     // v3 and v4 loads are supported for private and global memory.
8530     return SDValue();
8531   }
8532   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8533     // Depending on the setting of the private_element_size field in the
8534     // resource descriptor, we can only make private accesses up to a certain
8535     // size.
8536     switch (Subtarget->getMaxPrivateElementSize()) {
8537     case 4: {
8538       SDValue Ops[2];
8539       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8540       return DAG.getMergeValues(Ops, DL);
8541     }
8542     case 8:
8543       if (NumElements > 2)
8544         return SplitVectorLoad(Op, DAG);
8545       return SDValue();
8546     case 16:
8547       // Same as global/flat
8548       if (NumElements > 4)
8549         return SplitVectorLoad(Op, DAG);
8550       // v3 loads not supported on SI.
8551       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8552         return WidenOrSplitVectorLoad(Op, DAG);
8553 
8554       return SDValue();
8555     default:
8556       llvm_unreachable("unsupported private_element_size");
8557     }
8558   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8559     bool Fast = false;
8560     auto Flags = Load->getMemOperand()->getFlags();
8561     if (allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8562                                            Load->getAlign(), Flags, &Fast) &&
8563         Fast)
8564       return SDValue();
8565 
8566     if (MemVT.isVector())
8567       return SplitVectorLoad(Op, DAG);
8568   }
8569 
8570   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8571                                       MemVT, *Load->getMemOperand())) {
8572     SDValue Ops[2];
8573     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8574     return DAG.getMergeValues(Ops, DL);
8575   }
8576 
8577   return SDValue();
8578 }
8579 
8580 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8581   EVT VT = Op.getValueType();
8582   if (VT.getSizeInBits() == 128)
8583     return splitTernaryVectorOp(Op, DAG);
8584 
8585   assert(VT.getSizeInBits() == 64);
8586 
8587   SDLoc DL(Op);
8588   SDValue Cond = Op.getOperand(0);
8589 
8590   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8591   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8592 
8593   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8594   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8595 
8596   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8597   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8598 
8599   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8600 
8601   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8602   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8603 
8604   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8605 
8606   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8607   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8608 }
8609 
8610 // Catch division cases where we can use shortcuts with rcp and rsq
8611 // instructions.
8612 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8613                                               SelectionDAG &DAG) const {
8614   SDLoc SL(Op);
8615   SDValue LHS = Op.getOperand(0);
8616   SDValue RHS = Op.getOperand(1);
8617   EVT VT = Op.getValueType();
8618   const SDNodeFlags Flags = Op->getFlags();
8619 
8620   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8621 
8622   // Without !fpmath accuracy information, we can't do more because we don't
8623   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8624   if (!AllowInaccurateRcp)
8625     return SDValue();
8626 
8627   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8628     if (CLHS->isExactlyValue(1.0)) {
8629       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8630       // the CI documentation has a worst case error of 1 ulp.
8631       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8632       // use it as long as we aren't trying to use denormals.
8633       //
8634       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8635 
8636       // 1.0 / sqrt(x) -> rsq(x)
8637 
8638       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8639       // error seems really high at 2^29 ULP.
8640       if (RHS.getOpcode() == ISD::FSQRT)
8641         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8642 
8643       // 1.0 / x -> rcp(x)
8644       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8645     }
8646 
8647     // Same as for 1.0, but expand the sign out of the constant.
8648     if (CLHS->isExactlyValue(-1.0)) {
8649       // -1.0 / x -> rcp (fneg x)
8650       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8651       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8652     }
8653   }
8654 
8655   // Turn into multiply by the reciprocal.
8656   // x / y -> x * (1.0 / y)
8657   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8658   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8659 }
8660 
8661 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8662                                                 SelectionDAG &DAG) const {
8663   SDLoc SL(Op);
8664   SDValue X = Op.getOperand(0);
8665   SDValue Y = Op.getOperand(1);
8666   EVT VT = Op.getValueType();
8667   const SDNodeFlags Flags = Op->getFlags();
8668 
8669   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8670                             DAG.getTarget().Options.UnsafeFPMath;
8671   if (!AllowInaccurateDiv)
8672     return SDValue();
8673 
8674   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8675   SDValue One = DAG.getConstantFP(1.0, SL, VT);
8676 
8677   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8678   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8679 
8680   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8681   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8682   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8683   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8684   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8685   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8686 }
8687 
8688 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8689                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8690                           SDNodeFlags Flags) {
8691   if (GlueChain->getNumValues() <= 1) {
8692     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8693   }
8694 
8695   assert(GlueChain->getNumValues() == 3);
8696 
8697   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8698   switch (Opcode) {
8699   default: llvm_unreachable("no chain equivalent for opcode");
8700   case ISD::FMUL:
8701     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8702     break;
8703   }
8704 
8705   return DAG.getNode(Opcode, SL, VTList,
8706                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8707                      Flags);
8708 }
8709 
8710 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8711                            EVT VT, SDValue A, SDValue B, SDValue C,
8712                            SDValue GlueChain, SDNodeFlags Flags) {
8713   if (GlueChain->getNumValues() <= 1) {
8714     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8715   }
8716 
8717   assert(GlueChain->getNumValues() == 3);
8718 
8719   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8720   switch (Opcode) {
8721   default: llvm_unreachable("no chain equivalent for opcode");
8722   case ISD::FMA:
8723     Opcode = AMDGPUISD::FMA_W_CHAIN;
8724     break;
8725   }
8726 
8727   return DAG.getNode(Opcode, SL, VTList,
8728                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8729                      Flags);
8730 }
8731 
8732 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8733   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8734     return FastLowered;
8735 
8736   SDLoc SL(Op);
8737   SDValue Src0 = Op.getOperand(0);
8738   SDValue Src1 = Op.getOperand(1);
8739 
8740   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8741   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8742 
8743   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8744   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8745 
8746   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8747   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8748 
8749   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8750 }
8751 
8752 // Faster 2.5 ULP division that does not support denormals.
8753 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8754   SDLoc SL(Op);
8755   SDValue LHS = Op.getOperand(1);
8756   SDValue RHS = Op.getOperand(2);
8757 
8758   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8759 
8760   const APFloat K0Val(BitsToFloat(0x6f800000));
8761   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8762 
8763   const APFloat K1Val(BitsToFloat(0x2f800000));
8764   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8765 
8766   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8767 
8768   EVT SetCCVT =
8769     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8770 
8771   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8772 
8773   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8774 
8775   // TODO: Should this propagate fast-math-flags?
8776   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8777 
8778   // rcp does not support denormals.
8779   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8780 
8781   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8782 
8783   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8784 }
8785 
8786 // Returns immediate value for setting the F32 denorm mode when using the
8787 // S_DENORM_MODE instruction.
8788 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8789                                     const SDLoc &SL, const GCNSubtarget *ST) {
8790   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8791   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8792                                 ? FP_DENORM_FLUSH_NONE
8793                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8794 
8795   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8796   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8797 }
8798 
8799 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8800   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8801     return FastLowered;
8802 
8803   // The selection matcher assumes anything with a chain selecting to a
8804   // mayRaiseFPException machine instruction. Since we're introducing a chain
8805   // here, we need to explicitly report nofpexcept for the regular fdiv
8806   // lowering.
8807   SDNodeFlags Flags = Op->getFlags();
8808   Flags.setNoFPExcept(true);
8809 
8810   SDLoc SL(Op);
8811   SDValue LHS = Op.getOperand(0);
8812   SDValue RHS = Op.getOperand(1);
8813 
8814   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8815 
8816   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8817 
8818   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8819                                           {RHS, RHS, LHS}, Flags);
8820   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8821                                         {LHS, RHS, LHS}, Flags);
8822 
8823   // Denominator is scaled to not be denormal, so using rcp is ok.
8824   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8825                                   DenominatorScaled, Flags);
8826   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8827                                      DenominatorScaled, Flags);
8828 
8829   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8830                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8831                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8832   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8833 
8834   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8835 
8836   if (!HasFP32Denormals) {
8837     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8838     // lowering. The chain dependence is insufficient, and we need glue. We do
8839     // not need the glue variants in a strictfp function.
8840 
8841     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8842 
8843     SDNode *EnableDenorm;
8844     if (Subtarget->hasDenormModeInst()) {
8845       const SDValue EnableDenormValue =
8846           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8847 
8848       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8849                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8850     } else {
8851       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8852                                                         SL, MVT::i32);
8853       EnableDenorm =
8854           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8855                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8856     }
8857 
8858     SDValue Ops[3] = {
8859       NegDivScale0,
8860       SDValue(EnableDenorm, 0),
8861       SDValue(EnableDenorm, 1)
8862     };
8863 
8864     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8865   }
8866 
8867   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8868                              ApproxRcp, One, NegDivScale0, Flags);
8869 
8870   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8871                              ApproxRcp, Fma0, Flags);
8872 
8873   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8874                            Fma1, Fma1, Flags);
8875 
8876   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8877                              NumeratorScaled, Mul, Flags);
8878 
8879   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8880                              Fma2, Fma1, Mul, Fma2, Flags);
8881 
8882   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8883                              NumeratorScaled, Fma3, Flags);
8884 
8885   if (!HasFP32Denormals) {
8886     SDNode *DisableDenorm;
8887     if (Subtarget->hasDenormModeInst()) {
8888       const SDValue DisableDenormValue =
8889           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8890 
8891       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8892                                   Fma4.getValue(1), DisableDenormValue,
8893                                   Fma4.getValue(2)).getNode();
8894     } else {
8895       const SDValue DisableDenormValue =
8896           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8897 
8898       DisableDenorm = DAG.getMachineNode(
8899           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8900           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8901     }
8902 
8903     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8904                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8905     DAG.setRoot(OutputChain);
8906   }
8907 
8908   SDValue Scale = NumeratorScaled.getValue(1);
8909   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8910                              {Fma4, Fma1, Fma3, Scale}, Flags);
8911 
8912   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8913 }
8914 
8915 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8916   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
8917     return FastLowered;
8918 
8919   SDLoc SL(Op);
8920   SDValue X = Op.getOperand(0);
8921   SDValue Y = Op.getOperand(1);
8922 
8923   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8924 
8925   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8926 
8927   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8928 
8929   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8930 
8931   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8932 
8933   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8934 
8935   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8936 
8937   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8938 
8939   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8940 
8941   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8942   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8943 
8944   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8945                              NegDivScale0, Mul, DivScale1);
8946 
8947   SDValue Scale;
8948 
8949   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8950     // Workaround a hardware bug on SI where the condition output from div_scale
8951     // is not usable.
8952 
8953     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8954 
8955     // Figure out if the scale to use for div_fmas.
8956     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8957     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8958     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8959     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8960 
8961     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8962     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8963 
8964     SDValue Scale0Hi
8965       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8966     SDValue Scale1Hi
8967       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8968 
8969     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8970     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8971     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8972   } else {
8973     Scale = DivScale1.getValue(1);
8974   }
8975 
8976   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8977                              Fma4, Fma3, Mul, Scale);
8978 
8979   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8980 }
8981 
8982 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8983   EVT VT = Op.getValueType();
8984 
8985   if (VT == MVT::f32)
8986     return LowerFDIV32(Op, DAG);
8987 
8988   if (VT == MVT::f64)
8989     return LowerFDIV64(Op, DAG);
8990 
8991   if (VT == MVT::f16)
8992     return LowerFDIV16(Op, DAG);
8993 
8994   llvm_unreachable("Unexpected type for fdiv");
8995 }
8996 
8997 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8998   SDLoc DL(Op);
8999   StoreSDNode *Store = cast<StoreSDNode>(Op);
9000   EVT VT = Store->getMemoryVT();
9001 
9002   if (VT == MVT::i1) {
9003     return DAG.getTruncStore(Store->getChain(), DL,
9004        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
9005        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
9006   }
9007 
9008   assert(VT.isVector() &&
9009          Store->getValue().getValueType().getScalarType() == MVT::i32);
9010 
9011   unsigned AS = Store->getAddressSpace();
9012   if (Subtarget->hasLDSMisalignedBug() &&
9013       AS == AMDGPUAS::FLAT_ADDRESS &&
9014       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
9015     return SplitVectorStore(Op, DAG);
9016   }
9017 
9018   MachineFunction &MF = DAG.getMachineFunction();
9019   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
9020   // If there is a possibility that flat instruction access scratch memory
9021   // then we need to use the same legalization rules we use for private.
9022   if (AS == AMDGPUAS::FLAT_ADDRESS &&
9023       !Subtarget->hasMultiDwordFlatScratchAddressing())
9024     AS = MFI->hasFlatScratchInit() ?
9025          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
9026 
9027   unsigned NumElements = VT.getVectorNumElements();
9028   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
9029       AS == AMDGPUAS::FLAT_ADDRESS) {
9030     if (NumElements > 4)
9031       return SplitVectorStore(Op, DAG);
9032     // v3 stores not supported on SI.
9033     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
9034       return SplitVectorStore(Op, DAG);
9035 
9036     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
9037                                         VT, *Store->getMemOperand()))
9038       return expandUnalignedStore(Store, DAG);
9039 
9040     return SDValue();
9041   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
9042     switch (Subtarget->getMaxPrivateElementSize()) {
9043     case 4:
9044       return scalarizeVectorStore(Store, DAG);
9045     case 8:
9046       if (NumElements > 2)
9047         return SplitVectorStore(Op, DAG);
9048       return SDValue();
9049     case 16:
9050       if (NumElements > 4 ||
9051           (NumElements == 3 && !Subtarget->enableFlatScratch()))
9052         return SplitVectorStore(Op, DAG);
9053       return SDValue();
9054     default:
9055       llvm_unreachable("unsupported private_element_size");
9056     }
9057   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
9058     bool Fast = false;
9059     auto Flags = Store->getMemOperand()->getFlags();
9060     if (allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
9061                                            Store->getAlign(), Flags, &Fast) &&
9062         Fast)
9063       return SDValue();
9064 
9065     if (VT.isVector())
9066       return SplitVectorStore(Op, DAG);
9067 
9068     return expandUnalignedStore(Store, DAG);
9069   }
9070 
9071   // Probably an invalid store. If so we'll end up emitting a selection error.
9072   return SDValue();
9073 }
9074 
9075 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
9076   SDLoc DL(Op);
9077   EVT VT = Op.getValueType();
9078   SDValue Arg = Op.getOperand(0);
9079   SDValue TrigVal;
9080 
9081   // Propagate fast-math flags so that the multiply we introduce can be folded
9082   // if Arg is already the result of a multiply by constant.
9083   auto Flags = Op->getFlags();
9084 
9085   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
9086 
9087   if (Subtarget->hasTrigReducedRange()) {
9088     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9089     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
9090   } else {
9091     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9092   }
9093 
9094   switch (Op.getOpcode()) {
9095   case ISD::FCOS:
9096     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
9097   case ISD::FSIN:
9098     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
9099   default:
9100     llvm_unreachable("Wrong trig opcode");
9101   }
9102 }
9103 
9104 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9105   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
9106   assert(AtomicNode->isCompareAndSwap());
9107   unsigned AS = AtomicNode->getAddressSpace();
9108 
9109   // No custom lowering required for local address space
9110   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
9111     return Op;
9112 
9113   // Non-local address space requires custom lowering for atomic compare
9114   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
9115   SDLoc DL(Op);
9116   SDValue ChainIn = Op.getOperand(0);
9117   SDValue Addr = Op.getOperand(1);
9118   SDValue Old = Op.getOperand(2);
9119   SDValue New = Op.getOperand(3);
9120   EVT VT = Op.getValueType();
9121   MVT SimpleVT = VT.getSimpleVT();
9122   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
9123 
9124   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
9125   SDValue Ops[] = { ChainIn, Addr, NewOld };
9126 
9127   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
9128                                  Ops, VT, AtomicNode->getMemOperand());
9129 }
9130 
9131 //===----------------------------------------------------------------------===//
9132 // Custom DAG optimizations
9133 //===----------------------------------------------------------------------===//
9134 
9135 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
9136                                                      DAGCombinerInfo &DCI) const {
9137   EVT VT = N->getValueType(0);
9138   EVT ScalarVT = VT.getScalarType();
9139   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
9140     return SDValue();
9141 
9142   SelectionDAG &DAG = DCI.DAG;
9143   SDLoc DL(N);
9144 
9145   SDValue Src = N->getOperand(0);
9146   EVT SrcVT = Src.getValueType();
9147 
9148   // TODO: We could try to match extracting the higher bytes, which would be
9149   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
9150   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
9151   // about in practice.
9152   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
9153     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
9154       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
9155       DCI.AddToWorklist(Cvt.getNode());
9156 
9157       // For the f16 case, fold to a cast to f32 and then cast back to f16.
9158       if (ScalarVT != MVT::f32) {
9159         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
9160                           DAG.getTargetConstant(0, DL, MVT::i32));
9161       }
9162       return Cvt;
9163     }
9164   }
9165 
9166   return SDValue();
9167 }
9168 
9169 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
9170 
9171 // This is a variant of
9172 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
9173 //
9174 // The normal DAG combiner will do this, but only if the add has one use since
9175 // that would increase the number of instructions.
9176 //
9177 // This prevents us from seeing a constant offset that can be folded into a
9178 // memory instruction's addressing mode. If we know the resulting add offset of
9179 // a pointer can be folded into an addressing offset, we can replace the pointer
9180 // operand with the add of new constant offset. This eliminates one of the uses,
9181 // and may allow the remaining use to also be simplified.
9182 //
9183 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
9184                                                unsigned AddrSpace,
9185                                                EVT MemVT,
9186                                                DAGCombinerInfo &DCI) const {
9187   SDValue N0 = N->getOperand(0);
9188   SDValue N1 = N->getOperand(1);
9189 
9190   // We only do this to handle cases where it's profitable when there are
9191   // multiple uses of the add, so defer to the standard combine.
9192   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
9193       N0->hasOneUse())
9194     return SDValue();
9195 
9196   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
9197   if (!CN1)
9198     return SDValue();
9199 
9200   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9201   if (!CAdd)
9202     return SDValue();
9203 
9204   // If the resulting offset is too large, we can't fold it into the addressing
9205   // mode offset.
9206   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
9207   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
9208 
9209   AddrMode AM;
9210   AM.HasBaseReg = true;
9211   AM.BaseOffs = Offset.getSExtValue();
9212   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
9213     return SDValue();
9214 
9215   SelectionDAG &DAG = DCI.DAG;
9216   SDLoc SL(N);
9217   EVT VT = N->getValueType(0);
9218 
9219   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
9220   SDValue COffset = DAG.getConstant(Offset, SL, VT);
9221 
9222   SDNodeFlags Flags;
9223   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
9224                           (N0.getOpcode() == ISD::OR ||
9225                            N0->getFlags().hasNoUnsignedWrap()));
9226 
9227   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
9228 }
9229 
9230 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
9231 /// by the chain and intrinsic ID. Theoretically we would also need to check the
9232 /// specific intrinsic, but they all place the pointer operand first.
9233 static unsigned getBasePtrIndex(const MemSDNode *N) {
9234   switch (N->getOpcode()) {
9235   case ISD::STORE:
9236   case ISD::INTRINSIC_W_CHAIN:
9237   case ISD::INTRINSIC_VOID:
9238     return 2;
9239   default:
9240     return 1;
9241   }
9242 }
9243 
9244 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
9245                                                   DAGCombinerInfo &DCI) const {
9246   SelectionDAG &DAG = DCI.DAG;
9247   SDLoc SL(N);
9248 
9249   unsigned PtrIdx = getBasePtrIndex(N);
9250   SDValue Ptr = N->getOperand(PtrIdx);
9251 
9252   // TODO: We could also do this for multiplies.
9253   if (Ptr.getOpcode() == ISD::SHL) {
9254     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
9255                                           N->getMemoryVT(), DCI);
9256     if (NewPtr) {
9257       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
9258 
9259       NewOps[PtrIdx] = NewPtr;
9260       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
9261     }
9262   }
9263 
9264   return SDValue();
9265 }
9266 
9267 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
9268   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
9269          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
9270          (Opc == ISD::XOR && Val == 0);
9271 }
9272 
9273 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
9274 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
9275 // integer combine opportunities since most 64-bit operations are decomposed
9276 // this way.  TODO: We won't want this for SALU especially if it is an inline
9277 // immediate.
9278 SDValue SITargetLowering::splitBinaryBitConstantOp(
9279   DAGCombinerInfo &DCI,
9280   const SDLoc &SL,
9281   unsigned Opc, SDValue LHS,
9282   const ConstantSDNode *CRHS) const {
9283   uint64_t Val = CRHS->getZExtValue();
9284   uint32_t ValLo = Lo_32(Val);
9285   uint32_t ValHi = Hi_32(Val);
9286   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9287 
9288     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
9289          bitOpWithConstantIsReducible(Opc, ValHi)) ||
9290         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
9291     // If we need to materialize a 64-bit immediate, it will be split up later
9292     // anyway. Avoid creating the harder to understand 64-bit immediate
9293     // materialization.
9294     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
9295   }
9296 
9297   return SDValue();
9298 }
9299 
9300 // Returns true if argument is a boolean value which is not serialized into
9301 // memory or argument and does not require v_cndmask_b32 to be deserialized.
9302 static bool isBoolSGPR(SDValue V) {
9303   if (V.getValueType() != MVT::i1)
9304     return false;
9305   switch (V.getOpcode()) {
9306   default:
9307     break;
9308   case ISD::SETCC:
9309   case AMDGPUISD::FP_CLASS:
9310     return true;
9311   case ISD::AND:
9312   case ISD::OR:
9313   case ISD::XOR:
9314     return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
9315   }
9316   return false;
9317 }
9318 
9319 // If a constant has all zeroes or all ones within each byte return it.
9320 // Otherwise return 0.
9321 static uint32_t getConstantPermuteMask(uint32_t C) {
9322   // 0xff for any zero byte in the mask
9323   uint32_t ZeroByteMask = 0;
9324   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
9325   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
9326   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
9327   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
9328   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
9329   if ((NonZeroByteMask & C) != NonZeroByteMask)
9330     return 0; // Partial bytes selected.
9331   return C;
9332 }
9333 
9334 // Check if a node selects whole bytes from its operand 0 starting at a byte
9335 // boundary while masking the rest. Returns select mask as in the v_perm_b32
9336 // or -1 if not succeeded.
9337 // Note byte select encoding:
9338 // value 0-3 selects corresponding source byte;
9339 // value 0xc selects zero;
9340 // value 0xff selects 0xff.
9341 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
9342   assert(V.getValueSizeInBits() == 32);
9343 
9344   if (V.getNumOperands() != 2)
9345     return ~0;
9346 
9347   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
9348   if (!N1)
9349     return ~0;
9350 
9351   uint32_t C = N1->getZExtValue();
9352 
9353   switch (V.getOpcode()) {
9354   default:
9355     break;
9356   case ISD::AND:
9357     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9358       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
9359     }
9360     break;
9361 
9362   case ISD::OR:
9363     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9364       return (0x03020100 & ~ConstMask) | ConstMask;
9365     }
9366     break;
9367 
9368   case ISD::SHL:
9369     if (C % 8)
9370       return ~0;
9371 
9372     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
9373 
9374   case ISD::SRL:
9375     if (C % 8)
9376       return ~0;
9377 
9378     return uint32_t(0x0c0c0c0c03020100ull >> C);
9379   }
9380 
9381   return ~0;
9382 }
9383 
9384 SDValue SITargetLowering::performAndCombine(SDNode *N,
9385                                             DAGCombinerInfo &DCI) const {
9386   if (DCI.isBeforeLegalize())
9387     return SDValue();
9388 
9389   SelectionDAG &DAG = DCI.DAG;
9390   EVT VT = N->getValueType(0);
9391   SDValue LHS = N->getOperand(0);
9392   SDValue RHS = N->getOperand(1);
9393 
9394 
9395   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9396   if (VT == MVT::i64 && CRHS) {
9397     if (SDValue Split
9398         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9399       return Split;
9400   }
9401 
9402   if (CRHS && VT == MVT::i32) {
9403     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9404     // nb = number of trailing zeroes in mask
9405     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9406     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9407     uint64_t Mask = CRHS->getZExtValue();
9408     unsigned Bits = countPopulation(Mask);
9409     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9410         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9411       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9412         unsigned Shift = CShift->getZExtValue();
9413         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9414         unsigned Offset = NB + Shift;
9415         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9416           SDLoc SL(N);
9417           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9418                                     LHS->getOperand(0),
9419                                     DAG.getConstant(Offset, SL, MVT::i32),
9420                                     DAG.getConstant(Bits, SL, MVT::i32));
9421           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9422           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9423                                     DAG.getValueType(NarrowVT));
9424           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9425                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9426           return Shl;
9427         }
9428       }
9429     }
9430 
9431     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9432     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9433         isa<ConstantSDNode>(LHS.getOperand(2))) {
9434       uint32_t Sel = getConstantPermuteMask(Mask);
9435       if (!Sel)
9436         return SDValue();
9437 
9438       // Select 0xc for all zero bytes
9439       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9440       SDLoc DL(N);
9441       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9442                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9443     }
9444   }
9445 
9446   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9447   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9448   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9449     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9450     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9451 
9452     SDValue X = LHS.getOperand(0);
9453     SDValue Y = RHS.getOperand(0);
9454     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9455       return SDValue();
9456 
9457     if (LCC == ISD::SETO) {
9458       if (X != LHS.getOperand(1))
9459         return SDValue();
9460 
9461       if (RCC == ISD::SETUNE) {
9462         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9463         if (!C1 || !C1->isInfinity() || C1->isNegative())
9464           return SDValue();
9465 
9466         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9467                               SIInstrFlags::N_SUBNORMAL |
9468                               SIInstrFlags::N_ZERO |
9469                               SIInstrFlags::P_ZERO |
9470                               SIInstrFlags::P_SUBNORMAL |
9471                               SIInstrFlags::P_NORMAL;
9472 
9473         static_assert(((~(SIInstrFlags::S_NAN |
9474                           SIInstrFlags::Q_NAN |
9475                           SIInstrFlags::N_INFINITY |
9476                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9477                       "mask not equal");
9478 
9479         SDLoc DL(N);
9480         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9481                            X, DAG.getConstant(Mask, DL, MVT::i32));
9482       }
9483     }
9484   }
9485 
9486   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9487     std::swap(LHS, RHS);
9488 
9489   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9490       RHS.hasOneUse()) {
9491     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9492     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9493     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9494     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9495     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9496         (RHS.getOperand(0) == LHS.getOperand(0) &&
9497          LHS.getOperand(0) == LHS.getOperand(1))) {
9498       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9499       unsigned NewMask = LCC == ISD::SETO ?
9500         Mask->getZExtValue() & ~OrdMask :
9501         Mask->getZExtValue() & OrdMask;
9502 
9503       SDLoc DL(N);
9504       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9505                          DAG.getConstant(NewMask, DL, MVT::i32));
9506     }
9507   }
9508 
9509   if (VT == MVT::i32 &&
9510       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9511     // and x, (sext cc from i1) => select cc, x, 0
9512     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9513       std::swap(LHS, RHS);
9514     if (isBoolSGPR(RHS.getOperand(0)))
9515       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9516                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9517   }
9518 
9519   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9520   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9521   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9522       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9523     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9524     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9525     if (LHSMask != ~0u && RHSMask != ~0u) {
9526       // Canonicalize the expression in an attempt to have fewer unique masks
9527       // and therefore fewer registers used to hold the masks.
9528       if (LHSMask > RHSMask) {
9529         std::swap(LHSMask, RHSMask);
9530         std::swap(LHS, RHS);
9531       }
9532 
9533       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9534       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9535       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9536       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9537 
9538       // Check of we need to combine values from two sources within a byte.
9539       if (!(LHSUsedLanes & RHSUsedLanes) &&
9540           // If we select high and lower word keep it for SDWA.
9541           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9542           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9543         // Each byte in each mask is either selector mask 0-3, or has higher
9544         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9545         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9546         // mask which is not 0xff wins. By anding both masks we have a correct
9547         // result except that 0x0c shall be corrected to give 0x0c only.
9548         uint32_t Mask = LHSMask & RHSMask;
9549         for (unsigned I = 0; I < 32; I += 8) {
9550           uint32_t ByteSel = 0xff << I;
9551           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9552             Mask &= (0x0c << I) & 0xffffffff;
9553         }
9554 
9555         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9556         // or 0x0c.
9557         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9558         SDLoc DL(N);
9559 
9560         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9561                            LHS.getOperand(0), RHS.getOperand(0),
9562                            DAG.getConstant(Sel, DL, MVT::i32));
9563       }
9564     }
9565   }
9566 
9567   return SDValue();
9568 }
9569 
9570 SDValue SITargetLowering::performOrCombine(SDNode *N,
9571                                            DAGCombinerInfo &DCI) const {
9572   SelectionDAG &DAG = DCI.DAG;
9573   SDValue LHS = N->getOperand(0);
9574   SDValue RHS = N->getOperand(1);
9575 
9576   EVT VT = N->getValueType(0);
9577   if (VT == MVT::i1) {
9578     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9579     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9580         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9581       SDValue Src = LHS.getOperand(0);
9582       if (Src != RHS.getOperand(0))
9583         return SDValue();
9584 
9585       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9586       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9587       if (!CLHS || !CRHS)
9588         return SDValue();
9589 
9590       // Only 10 bits are used.
9591       static const uint32_t MaxMask = 0x3ff;
9592 
9593       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9594       SDLoc DL(N);
9595       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9596                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9597     }
9598 
9599     return SDValue();
9600   }
9601 
9602   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9603   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9604       LHS.getOpcode() == AMDGPUISD::PERM &&
9605       isa<ConstantSDNode>(LHS.getOperand(2))) {
9606     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9607     if (!Sel)
9608       return SDValue();
9609 
9610     Sel |= LHS.getConstantOperandVal(2);
9611     SDLoc DL(N);
9612     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9613                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9614   }
9615 
9616   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9617   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9618   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9619       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9620     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9621     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9622     if (LHSMask != ~0u && RHSMask != ~0u) {
9623       // Canonicalize the expression in an attempt to have fewer unique masks
9624       // and therefore fewer registers used to hold the masks.
9625       if (LHSMask > RHSMask) {
9626         std::swap(LHSMask, RHSMask);
9627         std::swap(LHS, RHS);
9628       }
9629 
9630       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9631       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9632       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9633       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9634 
9635       // Check of we need to combine values from two sources within a byte.
9636       if (!(LHSUsedLanes & RHSUsedLanes) &&
9637           // If we select high and lower word keep it for SDWA.
9638           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9639           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9640         // Kill zero bytes selected by other mask. Zero value is 0xc.
9641         LHSMask &= ~RHSUsedLanes;
9642         RHSMask &= ~LHSUsedLanes;
9643         // Add 4 to each active LHS lane
9644         LHSMask |= LHSUsedLanes & 0x04040404;
9645         // Combine masks
9646         uint32_t Sel = LHSMask | RHSMask;
9647         SDLoc DL(N);
9648 
9649         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9650                            LHS.getOperand(0), RHS.getOperand(0),
9651                            DAG.getConstant(Sel, DL, MVT::i32));
9652       }
9653     }
9654   }
9655 
9656   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9657     return SDValue();
9658 
9659   // TODO: This could be a generic combine with a predicate for extracting the
9660   // high half of an integer being free.
9661 
9662   // (or i64:x, (zero_extend i32:y)) ->
9663   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9664   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9665       RHS.getOpcode() != ISD::ZERO_EXTEND)
9666     std::swap(LHS, RHS);
9667 
9668   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9669     SDValue ExtSrc = RHS.getOperand(0);
9670     EVT SrcVT = ExtSrc.getValueType();
9671     if (SrcVT == MVT::i32) {
9672       SDLoc SL(N);
9673       SDValue LowLHS, HiBits;
9674       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9675       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9676 
9677       DCI.AddToWorklist(LowOr.getNode());
9678       DCI.AddToWorklist(HiBits.getNode());
9679 
9680       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9681                                 LowOr, HiBits);
9682       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9683     }
9684   }
9685 
9686   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9687   if (CRHS) {
9688     if (SDValue Split
9689           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR,
9690                                      N->getOperand(0), CRHS))
9691       return Split;
9692   }
9693 
9694   return SDValue();
9695 }
9696 
9697 SDValue SITargetLowering::performXorCombine(SDNode *N,
9698                                             DAGCombinerInfo &DCI) const {
9699   if (SDValue RV = reassociateScalarOps(N, DCI.DAG))
9700     return RV;
9701 
9702   EVT VT = N->getValueType(0);
9703   if (VT != MVT::i64)
9704     return SDValue();
9705 
9706   SDValue LHS = N->getOperand(0);
9707   SDValue RHS = N->getOperand(1);
9708 
9709   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9710   if (CRHS) {
9711     if (SDValue Split
9712           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9713       return Split;
9714   }
9715 
9716   return SDValue();
9717 }
9718 
9719 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9720                                                    DAGCombinerInfo &DCI) const {
9721   if (!Subtarget->has16BitInsts() ||
9722       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9723     return SDValue();
9724 
9725   EVT VT = N->getValueType(0);
9726   if (VT != MVT::i32)
9727     return SDValue();
9728 
9729   SDValue Src = N->getOperand(0);
9730   if (Src.getValueType() != MVT::i16)
9731     return SDValue();
9732 
9733   return SDValue();
9734 }
9735 
9736 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9737                                                         DAGCombinerInfo &DCI)
9738                                                         const {
9739   SDValue Src = N->getOperand(0);
9740   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9741 
9742   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9743       VTSign->getVT() == MVT::i8) ||
9744       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9745       VTSign->getVT() == MVT::i16)) &&
9746       Src.hasOneUse()) {
9747     auto *M = cast<MemSDNode>(Src);
9748     SDValue Ops[] = {
9749       Src.getOperand(0), // Chain
9750       Src.getOperand(1), // rsrc
9751       Src.getOperand(2), // vindex
9752       Src.getOperand(3), // voffset
9753       Src.getOperand(4), // soffset
9754       Src.getOperand(5), // offset
9755       Src.getOperand(6),
9756       Src.getOperand(7)
9757     };
9758     // replace with BUFFER_LOAD_BYTE/SHORT
9759     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9760                                          Src.getOperand(0).getValueType());
9761     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9762                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9763     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9764                                                           ResList,
9765                                                           Ops, M->getMemoryVT(),
9766                                                           M->getMemOperand());
9767     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9768                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9769   }
9770   return SDValue();
9771 }
9772 
9773 SDValue SITargetLowering::performClassCombine(SDNode *N,
9774                                               DAGCombinerInfo &DCI) const {
9775   SelectionDAG &DAG = DCI.DAG;
9776   SDValue Mask = N->getOperand(1);
9777 
9778   // fp_class x, 0 -> false
9779   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9780     if (CMask->isZero())
9781       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9782   }
9783 
9784   if (N->getOperand(0).isUndef())
9785     return DAG.getUNDEF(MVT::i1);
9786 
9787   return SDValue();
9788 }
9789 
9790 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9791                                             DAGCombinerInfo &DCI) const {
9792   EVT VT = N->getValueType(0);
9793   SDValue N0 = N->getOperand(0);
9794 
9795   if (N0.isUndef())
9796     return N0;
9797 
9798   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9799                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9800     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9801                            N->getFlags());
9802   }
9803 
9804   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9805     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9806                            N0.getOperand(0), N->getFlags());
9807   }
9808 
9809   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9810 }
9811 
9812 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9813                                        unsigned MaxDepth) const {
9814   unsigned Opcode = Op.getOpcode();
9815   if (Opcode == ISD::FCANONICALIZE)
9816     return true;
9817 
9818   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9819     auto F = CFP->getValueAPF();
9820     if (F.isNaN() && F.isSignaling())
9821       return false;
9822     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9823   }
9824 
9825   // If source is a result of another standard FP operation it is already in
9826   // canonical form.
9827   if (MaxDepth == 0)
9828     return false;
9829 
9830   switch (Opcode) {
9831   // These will flush denorms if required.
9832   case ISD::FADD:
9833   case ISD::FSUB:
9834   case ISD::FMUL:
9835   case ISD::FCEIL:
9836   case ISD::FFLOOR:
9837   case ISD::FMA:
9838   case ISD::FMAD:
9839   case ISD::FSQRT:
9840   case ISD::FDIV:
9841   case ISD::FREM:
9842   case ISD::FP_ROUND:
9843   case ISD::FP_EXTEND:
9844   case AMDGPUISD::FMUL_LEGACY:
9845   case AMDGPUISD::FMAD_FTZ:
9846   case AMDGPUISD::RCP:
9847   case AMDGPUISD::RSQ:
9848   case AMDGPUISD::RSQ_CLAMP:
9849   case AMDGPUISD::RCP_LEGACY:
9850   case AMDGPUISD::RCP_IFLAG:
9851   case AMDGPUISD::DIV_SCALE:
9852   case AMDGPUISD::DIV_FMAS:
9853   case AMDGPUISD::DIV_FIXUP:
9854   case AMDGPUISD::FRACT:
9855   case AMDGPUISD::LDEXP:
9856   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9857   case AMDGPUISD::CVT_F32_UBYTE0:
9858   case AMDGPUISD::CVT_F32_UBYTE1:
9859   case AMDGPUISD::CVT_F32_UBYTE2:
9860   case AMDGPUISD::CVT_F32_UBYTE3:
9861     return true;
9862 
9863   // It can/will be lowered or combined as a bit operation.
9864   // Need to check their input recursively to handle.
9865   case ISD::FNEG:
9866   case ISD::FABS:
9867   case ISD::FCOPYSIGN:
9868     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9869 
9870   case ISD::FSIN:
9871   case ISD::FCOS:
9872   case ISD::FSINCOS:
9873     return Op.getValueType().getScalarType() != MVT::f16;
9874 
9875   case ISD::FMINNUM:
9876   case ISD::FMAXNUM:
9877   case ISD::FMINNUM_IEEE:
9878   case ISD::FMAXNUM_IEEE:
9879   case AMDGPUISD::CLAMP:
9880   case AMDGPUISD::FMED3:
9881   case AMDGPUISD::FMAX3:
9882   case AMDGPUISD::FMIN3: {
9883     // FIXME: Shouldn't treat the generic operations different based these.
9884     // However, we aren't really required to flush the result from
9885     // minnum/maxnum..
9886 
9887     // snans will be quieted, so we only need to worry about denormals.
9888     if (Subtarget->supportsMinMaxDenormModes() ||
9889         denormalsEnabledForType(DAG, Op.getValueType()))
9890       return true;
9891 
9892     // Flushing may be required.
9893     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9894     // targets need to check their input recursively.
9895 
9896     // FIXME: Does this apply with clamp? It's implemented with max.
9897     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9898       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9899         return false;
9900     }
9901 
9902     return true;
9903   }
9904   case ISD::SELECT: {
9905     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9906            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9907   }
9908   case ISD::BUILD_VECTOR: {
9909     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9910       SDValue SrcOp = Op.getOperand(i);
9911       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9912         return false;
9913     }
9914 
9915     return true;
9916   }
9917   case ISD::EXTRACT_VECTOR_ELT:
9918   case ISD::EXTRACT_SUBVECTOR: {
9919     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9920   }
9921   case ISD::INSERT_VECTOR_ELT: {
9922     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9923            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9924   }
9925   case ISD::UNDEF:
9926     // Could be anything.
9927     return false;
9928 
9929   case ISD::BITCAST:
9930     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9931   case ISD::TRUNCATE: {
9932     // Hack round the mess we make when legalizing extract_vector_elt
9933     if (Op.getValueType() == MVT::i16) {
9934       SDValue TruncSrc = Op.getOperand(0);
9935       if (TruncSrc.getValueType() == MVT::i32 &&
9936           TruncSrc.getOpcode() == ISD::BITCAST &&
9937           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9938         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9939       }
9940     }
9941     return false;
9942   }
9943   case ISD::INTRINSIC_WO_CHAIN: {
9944     unsigned IntrinsicID
9945       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9946     // TODO: Handle more intrinsics
9947     switch (IntrinsicID) {
9948     case Intrinsic::amdgcn_cvt_pkrtz:
9949     case Intrinsic::amdgcn_cubeid:
9950     case Intrinsic::amdgcn_frexp_mant:
9951     case Intrinsic::amdgcn_fdot2:
9952     case Intrinsic::amdgcn_rcp:
9953     case Intrinsic::amdgcn_rsq:
9954     case Intrinsic::amdgcn_rsq_clamp:
9955     case Intrinsic::amdgcn_rcp_legacy:
9956     case Intrinsic::amdgcn_rsq_legacy:
9957     case Intrinsic::amdgcn_trig_preop:
9958       return true;
9959     default:
9960       break;
9961     }
9962 
9963     LLVM_FALLTHROUGH;
9964   }
9965   default:
9966     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9967            DAG.isKnownNeverSNaN(Op);
9968   }
9969 
9970   llvm_unreachable("invalid operation");
9971 }
9972 
9973 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
9974                                        unsigned MaxDepth) const {
9975   MachineRegisterInfo &MRI = MF.getRegInfo();
9976   MachineInstr *MI = MRI.getVRegDef(Reg);
9977   unsigned Opcode = MI->getOpcode();
9978 
9979   if (Opcode == AMDGPU::G_FCANONICALIZE)
9980     return true;
9981 
9982   Optional<FPValueAndVReg> FCR;
9983   // Constant splat (can be padded with undef) or scalar constant.
9984   if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) {
9985     if (FCR->Value.isSignaling())
9986       return false;
9987     return !FCR->Value.isDenormal() ||
9988            denormalsEnabledForType(MRI.getType(FCR->VReg), MF);
9989   }
9990 
9991   if (MaxDepth == 0)
9992     return false;
9993 
9994   switch (Opcode) {
9995   case AMDGPU::G_FMINNUM_IEEE:
9996   case AMDGPU::G_FMAXNUM_IEEE: {
9997     if (Subtarget->supportsMinMaxDenormModes() ||
9998         denormalsEnabledForType(MRI.getType(Reg), MF))
9999       return true;
10000     for (const MachineOperand &MO : llvm::drop_begin(MI->operands()))
10001       if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1))
10002         return false;
10003     return true;
10004   }
10005   default:
10006     return denormalsEnabledForType(MRI.getType(Reg), MF) &&
10007            isKnownNeverSNaN(Reg, MRI);
10008   }
10009 
10010   llvm_unreachable("invalid operation");
10011 }
10012 
10013 // Constant fold canonicalize.
10014 SDValue SITargetLowering::getCanonicalConstantFP(
10015   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
10016   // Flush denormals to 0 if not enabled.
10017   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
10018     return DAG.getConstantFP(0.0, SL, VT);
10019 
10020   if (C.isNaN()) {
10021     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
10022     if (C.isSignaling()) {
10023       // Quiet a signaling NaN.
10024       // FIXME: Is this supposed to preserve payload bits?
10025       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
10026     }
10027 
10028     // Make sure it is the canonical NaN bitpattern.
10029     //
10030     // TODO: Can we use -1 as the canonical NaN value since it's an inline
10031     // immediate?
10032     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
10033       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
10034   }
10035 
10036   // Already canonical.
10037   return DAG.getConstantFP(C, SL, VT);
10038 }
10039 
10040 static bool vectorEltWillFoldAway(SDValue Op) {
10041   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
10042 }
10043 
10044 SDValue SITargetLowering::performFCanonicalizeCombine(
10045   SDNode *N,
10046   DAGCombinerInfo &DCI) const {
10047   SelectionDAG &DAG = DCI.DAG;
10048   SDValue N0 = N->getOperand(0);
10049   EVT VT = N->getValueType(0);
10050 
10051   // fcanonicalize undef -> qnan
10052   if (N0.isUndef()) {
10053     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
10054     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
10055   }
10056 
10057   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
10058     EVT VT = N->getValueType(0);
10059     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
10060   }
10061 
10062   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
10063   //                                                   (fcanonicalize k)
10064   //
10065   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
10066 
10067   // TODO: This could be better with wider vectors that will be split to v2f16,
10068   // and to consider uses since there aren't that many packed operations.
10069   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
10070       isTypeLegal(MVT::v2f16)) {
10071     SDLoc SL(N);
10072     SDValue NewElts[2];
10073     SDValue Lo = N0.getOperand(0);
10074     SDValue Hi = N0.getOperand(1);
10075     EVT EltVT = Lo.getValueType();
10076 
10077     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
10078       for (unsigned I = 0; I != 2; ++I) {
10079         SDValue Op = N0.getOperand(I);
10080         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
10081           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
10082                                               CFP->getValueAPF());
10083         } else if (Op.isUndef()) {
10084           // Handled below based on what the other operand is.
10085           NewElts[I] = Op;
10086         } else {
10087           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
10088         }
10089       }
10090 
10091       // If one half is undef, and one is constant, prefer a splat vector rather
10092       // than the normal qNaN. If it's a register, prefer 0.0 since that's
10093       // cheaper to use and may be free with a packed operation.
10094       if (NewElts[0].isUndef()) {
10095         if (isa<ConstantFPSDNode>(NewElts[1]))
10096           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
10097             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
10098       }
10099 
10100       if (NewElts[1].isUndef()) {
10101         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
10102           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
10103       }
10104 
10105       return DAG.getBuildVector(VT, SL, NewElts);
10106     }
10107   }
10108 
10109   unsigned SrcOpc = N0.getOpcode();
10110 
10111   // If it's free to do so, push canonicalizes further up the source, which may
10112   // find a canonical source.
10113   //
10114   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
10115   // sNaNs.
10116   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
10117     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10118     if (CRHS && N0.hasOneUse()) {
10119       SDLoc SL(N);
10120       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
10121                                    N0.getOperand(0));
10122       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
10123       DCI.AddToWorklist(Canon0.getNode());
10124 
10125       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
10126     }
10127   }
10128 
10129   return isCanonicalized(DAG, N0) ? N0 : SDValue();
10130 }
10131 
10132 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
10133   switch (Opc) {
10134   case ISD::FMAXNUM:
10135   case ISD::FMAXNUM_IEEE:
10136     return AMDGPUISD::FMAX3;
10137   case ISD::SMAX:
10138     return AMDGPUISD::SMAX3;
10139   case ISD::UMAX:
10140     return AMDGPUISD::UMAX3;
10141   case ISD::FMINNUM:
10142   case ISD::FMINNUM_IEEE:
10143     return AMDGPUISD::FMIN3;
10144   case ISD::SMIN:
10145     return AMDGPUISD::SMIN3;
10146   case ISD::UMIN:
10147     return AMDGPUISD::UMIN3;
10148   default:
10149     llvm_unreachable("Not a min/max opcode");
10150   }
10151 }
10152 
10153 SDValue SITargetLowering::performIntMed3ImmCombine(
10154   SelectionDAG &DAG, const SDLoc &SL,
10155   SDValue Op0, SDValue Op1, bool Signed) const {
10156   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
10157   if (!K1)
10158     return SDValue();
10159 
10160   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
10161   if (!K0)
10162     return SDValue();
10163 
10164   if (Signed) {
10165     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
10166       return SDValue();
10167   } else {
10168     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
10169       return SDValue();
10170   }
10171 
10172   EVT VT = K0->getValueType(0);
10173   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
10174   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
10175     return DAG.getNode(Med3Opc, SL, VT,
10176                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
10177   }
10178 
10179   // If there isn't a 16-bit med3 operation, convert to 32-bit.
10180   if (VT == MVT::i16) {
10181     MVT NVT = MVT::i32;
10182     unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
10183 
10184     SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
10185     SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
10186     SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
10187 
10188     SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
10189     return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
10190   }
10191 
10192   return SDValue();
10193 }
10194 
10195 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
10196   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
10197     return C;
10198 
10199   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
10200     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
10201       return C;
10202   }
10203 
10204   return nullptr;
10205 }
10206 
10207 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
10208                                                   const SDLoc &SL,
10209                                                   SDValue Op0,
10210                                                   SDValue Op1) const {
10211   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
10212   if (!K1)
10213     return SDValue();
10214 
10215   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
10216   if (!K0)
10217     return SDValue();
10218 
10219   // Ordered >= (although NaN inputs should have folded away by now).
10220   if (K0->getValueAPF() > K1->getValueAPF())
10221     return SDValue();
10222 
10223   const MachineFunction &MF = DAG.getMachineFunction();
10224   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10225 
10226   // TODO: Check IEEE bit enabled?
10227   EVT VT = Op0.getValueType();
10228   if (Info->getMode().DX10Clamp) {
10229     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
10230     // hardware fmed3 behavior converting to a min.
10231     // FIXME: Should this be allowing -0.0?
10232     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
10233       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
10234   }
10235 
10236   // med3 for f16 is only available on gfx9+, and not available for v2f16.
10237   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
10238     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
10239     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
10240     // then give the other result, which is different from med3 with a NaN
10241     // input.
10242     SDValue Var = Op0.getOperand(0);
10243     if (!DAG.isKnownNeverSNaN(Var))
10244       return SDValue();
10245 
10246     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10247 
10248     if ((!K0->hasOneUse() ||
10249          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
10250         (!K1->hasOneUse() ||
10251          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
10252       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
10253                          Var, SDValue(K0, 0), SDValue(K1, 0));
10254     }
10255   }
10256 
10257   return SDValue();
10258 }
10259 
10260 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
10261                                                DAGCombinerInfo &DCI) const {
10262   SelectionDAG &DAG = DCI.DAG;
10263 
10264   EVT VT = N->getValueType(0);
10265   unsigned Opc = N->getOpcode();
10266   SDValue Op0 = N->getOperand(0);
10267   SDValue Op1 = N->getOperand(1);
10268 
10269   // Only do this if the inner op has one use since this will just increases
10270   // register pressure for no benefit.
10271 
10272   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
10273       !VT.isVector() &&
10274       (VT == MVT::i32 || VT == MVT::f32 ||
10275        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
10276     // max(max(a, b), c) -> max3(a, b, c)
10277     // min(min(a, b), c) -> min3(a, b, c)
10278     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
10279       SDLoc DL(N);
10280       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10281                          DL,
10282                          N->getValueType(0),
10283                          Op0.getOperand(0),
10284                          Op0.getOperand(1),
10285                          Op1);
10286     }
10287 
10288     // Try commuted.
10289     // max(a, max(b, c)) -> max3(a, b, c)
10290     // min(a, min(b, c)) -> min3(a, b, c)
10291     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
10292       SDLoc DL(N);
10293       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10294                          DL,
10295                          N->getValueType(0),
10296                          Op0,
10297                          Op1.getOperand(0),
10298                          Op1.getOperand(1));
10299     }
10300   }
10301 
10302   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
10303   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
10304     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
10305       return Med3;
10306   }
10307 
10308   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
10309     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
10310       return Med3;
10311   }
10312 
10313   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
10314   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
10315        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
10316        (Opc == AMDGPUISD::FMIN_LEGACY &&
10317         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
10318       (VT == MVT::f32 || VT == MVT::f64 ||
10319        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
10320        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
10321       Op0.hasOneUse()) {
10322     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
10323       return Res;
10324   }
10325 
10326   return SDValue();
10327 }
10328 
10329 static bool isClampZeroToOne(SDValue A, SDValue B) {
10330   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
10331     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
10332       // FIXME: Should this be allowing -0.0?
10333       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
10334              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
10335     }
10336   }
10337 
10338   return false;
10339 }
10340 
10341 // FIXME: Should only worry about snans for version with chain.
10342 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
10343                                               DAGCombinerInfo &DCI) const {
10344   EVT VT = N->getValueType(0);
10345   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
10346   // NaNs. With a NaN input, the order of the operands may change the result.
10347 
10348   SelectionDAG &DAG = DCI.DAG;
10349   SDLoc SL(N);
10350 
10351   SDValue Src0 = N->getOperand(0);
10352   SDValue Src1 = N->getOperand(1);
10353   SDValue Src2 = N->getOperand(2);
10354 
10355   if (isClampZeroToOne(Src0, Src1)) {
10356     // const_a, const_b, x -> clamp is safe in all cases including signaling
10357     // nans.
10358     // FIXME: Should this be allowing -0.0?
10359     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
10360   }
10361 
10362   const MachineFunction &MF = DAG.getMachineFunction();
10363   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10364 
10365   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
10366   // handling no dx10-clamp?
10367   if (Info->getMode().DX10Clamp) {
10368     // If NaNs is clamped to 0, we are free to reorder the inputs.
10369 
10370     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10371       std::swap(Src0, Src1);
10372 
10373     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10374       std::swap(Src1, Src2);
10375 
10376     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10377       std::swap(Src0, Src1);
10378 
10379     if (isClampZeroToOne(Src1, Src2))
10380       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10381   }
10382 
10383   return SDValue();
10384 }
10385 
10386 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10387                                                  DAGCombinerInfo &DCI) const {
10388   SDValue Src0 = N->getOperand(0);
10389   SDValue Src1 = N->getOperand(1);
10390   if (Src0.isUndef() && Src1.isUndef())
10391     return DCI.DAG.getUNDEF(N->getValueType(0));
10392   return SDValue();
10393 }
10394 
10395 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10396 // expanded into a set of cmp/select instructions.
10397 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10398                                                 unsigned NumElem,
10399                                                 bool IsDivergentIdx) {
10400   if (UseDivergentRegisterIndexing)
10401     return false;
10402 
10403   unsigned VecSize = EltSize * NumElem;
10404 
10405   // Sub-dword vectors of size 2 dword or less have better implementation.
10406   if (VecSize <= 64 && EltSize < 32)
10407     return false;
10408 
10409   // Always expand the rest of sub-dword instructions, otherwise it will be
10410   // lowered via memory.
10411   if (EltSize < 32)
10412     return true;
10413 
10414   // Always do this if var-idx is divergent, otherwise it will become a loop.
10415   if (IsDivergentIdx)
10416     return true;
10417 
10418   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10419   unsigned NumInsts = NumElem /* Number of compares */ +
10420                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10421   return NumInsts <= 16;
10422 }
10423 
10424 static bool shouldExpandVectorDynExt(SDNode *N) {
10425   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10426   if (isa<ConstantSDNode>(Idx))
10427     return false;
10428 
10429   SDValue Vec = N->getOperand(0);
10430   EVT VecVT = Vec.getValueType();
10431   EVT EltVT = VecVT.getVectorElementType();
10432   unsigned EltSize = EltVT.getSizeInBits();
10433   unsigned NumElem = VecVT.getVectorNumElements();
10434 
10435   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
10436                                                     Idx->isDivergent());
10437 }
10438 
10439 SDValue SITargetLowering::performExtractVectorEltCombine(
10440   SDNode *N, DAGCombinerInfo &DCI) const {
10441   SDValue Vec = N->getOperand(0);
10442   SelectionDAG &DAG = DCI.DAG;
10443 
10444   EVT VecVT = Vec.getValueType();
10445   EVT EltVT = VecVT.getVectorElementType();
10446 
10447   if ((Vec.getOpcode() == ISD::FNEG ||
10448        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10449     SDLoc SL(N);
10450     EVT EltVT = N->getValueType(0);
10451     SDValue Idx = N->getOperand(1);
10452     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10453                               Vec.getOperand(0), Idx);
10454     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10455   }
10456 
10457   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10458   //    =>
10459   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10460   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10461   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10462   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10463     SDLoc SL(N);
10464     EVT EltVT = N->getValueType(0);
10465     SDValue Idx = N->getOperand(1);
10466     unsigned Opc = Vec.getOpcode();
10467 
10468     switch(Opc) {
10469     default:
10470       break;
10471       // TODO: Support other binary operations.
10472     case ISD::FADD:
10473     case ISD::FSUB:
10474     case ISD::FMUL:
10475     case ISD::ADD:
10476     case ISD::UMIN:
10477     case ISD::UMAX:
10478     case ISD::SMIN:
10479     case ISD::SMAX:
10480     case ISD::FMAXNUM:
10481     case ISD::FMINNUM:
10482     case ISD::FMAXNUM_IEEE:
10483     case ISD::FMINNUM_IEEE: {
10484       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10485                                  Vec.getOperand(0), Idx);
10486       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10487                                  Vec.getOperand(1), Idx);
10488 
10489       DCI.AddToWorklist(Elt0.getNode());
10490       DCI.AddToWorklist(Elt1.getNode());
10491       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10492     }
10493     }
10494   }
10495 
10496   unsigned VecSize = VecVT.getSizeInBits();
10497   unsigned EltSize = EltVT.getSizeInBits();
10498 
10499   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10500   if (::shouldExpandVectorDynExt(N)) {
10501     SDLoc SL(N);
10502     SDValue Idx = N->getOperand(1);
10503     SDValue V;
10504     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10505       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10506       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10507       if (I == 0)
10508         V = Elt;
10509       else
10510         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10511     }
10512     return V;
10513   }
10514 
10515   if (!DCI.isBeforeLegalize())
10516     return SDValue();
10517 
10518   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10519   // elements. This exposes more load reduction opportunities by replacing
10520   // multiple small extract_vector_elements with a single 32-bit extract.
10521   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10522   if (isa<MemSDNode>(Vec) &&
10523       EltSize <= 16 &&
10524       EltVT.isByteSized() &&
10525       VecSize > 32 &&
10526       VecSize % 32 == 0 &&
10527       Idx) {
10528     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10529 
10530     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10531     unsigned EltIdx = BitIndex / 32;
10532     unsigned LeftoverBitIdx = BitIndex % 32;
10533     SDLoc SL(N);
10534 
10535     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10536     DCI.AddToWorklist(Cast.getNode());
10537 
10538     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10539                               DAG.getConstant(EltIdx, SL, MVT::i32));
10540     DCI.AddToWorklist(Elt.getNode());
10541     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10542                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10543     DCI.AddToWorklist(Srl.getNode());
10544 
10545     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10546     DCI.AddToWorklist(Trunc.getNode());
10547     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10548   }
10549 
10550   return SDValue();
10551 }
10552 
10553 SDValue
10554 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10555                                                 DAGCombinerInfo &DCI) const {
10556   SDValue Vec = N->getOperand(0);
10557   SDValue Idx = N->getOperand(2);
10558   EVT VecVT = Vec.getValueType();
10559   EVT EltVT = VecVT.getVectorElementType();
10560 
10561   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10562   // => BUILD_VECTOR n x select (e, const-idx)
10563   if (!::shouldExpandVectorDynExt(N))
10564     return SDValue();
10565 
10566   SelectionDAG &DAG = DCI.DAG;
10567   SDLoc SL(N);
10568   SDValue Ins = N->getOperand(1);
10569   EVT IdxVT = Idx.getValueType();
10570 
10571   SmallVector<SDValue, 16> Ops;
10572   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10573     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10574     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10575     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10576     Ops.push_back(V);
10577   }
10578 
10579   return DAG.getBuildVector(VecVT, SL, Ops);
10580 }
10581 
10582 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10583                                           const SDNode *N0,
10584                                           const SDNode *N1) const {
10585   EVT VT = N0->getValueType(0);
10586 
10587   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10588   // support denormals ever.
10589   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10590        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10591         getSubtarget()->hasMadF16())) &&
10592        isOperationLegal(ISD::FMAD, VT))
10593     return ISD::FMAD;
10594 
10595   const TargetOptions &Options = DAG.getTarget().Options;
10596   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10597        (N0->getFlags().hasAllowContract() &&
10598         N1->getFlags().hasAllowContract())) &&
10599       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10600     return ISD::FMA;
10601   }
10602 
10603   return 0;
10604 }
10605 
10606 // For a reassociatable opcode perform:
10607 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10608 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10609                                                SelectionDAG &DAG) const {
10610   EVT VT = N->getValueType(0);
10611   if (VT != MVT::i32 && VT != MVT::i64)
10612     return SDValue();
10613 
10614   if (DAG.isBaseWithConstantOffset(SDValue(N, 0)))
10615     return SDValue();
10616 
10617   unsigned Opc = N->getOpcode();
10618   SDValue Op0 = N->getOperand(0);
10619   SDValue Op1 = N->getOperand(1);
10620 
10621   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10622     return SDValue();
10623 
10624   if (Op0->isDivergent())
10625     std::swap(Op0, Op1);
10626 
10627   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10628     return SDValue();
10629 
10630   SDValue Op2 = Op1.getOperand(1);
10631   Op1 = Op1.getOperand(0);
10632   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10633     return SDValue();
10634 
10635   if (Op1->isDivergent())
10636     std::swap(Op1, Op2);
10637 
10638   SDLoc SL(N);
10639   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10640   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10641 }
10642 
10643 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10644                            EVT VT,
10645                            SDValue N0, SDValue N1, SDValue N2,
10646                            bool Signed) {
10647   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10648   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10649   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10650   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10651 }
10652 
10653 SDValue SITargetLowering::performAddCombine(SDNode *N,
10654                                             DAGCombinerInfo &DCI) const {
10655   SelectionDAG &DAG = DCI.DAG;
10656   EVT VT = N->getValueType(0);
10657   SDLoc SL(N);
10658   SDValue LHS = N->getOperand(0);
10659   SDValue RHS = N->getOperand(1);
10660 
10661   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10662       && Subtarget->hasMad64_32() &&
10663       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10664       VT.getScalarSizeInBits() <= 64) {
10665     if (LHS.getOpcode() != ISD::MUL)
10666       std::swap(LHS, RHS);
10667 
10668     SDValue MulLHS = LHS.getOperand(0);
10669     SDValue MulRHS = LHS.getOperand(1);
10670     SDValue AddRHS = RHS;
10671 
10672     // TODO: Maybe restrict if SGPR inputs.
10673     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10674         numBitsUnsigned(MulRHS, DAG) <= 32) {
10675       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10676       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10677       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10678       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10679     }
10680 
10681     if (numBitsSigned(MulLHS, DAG) <= 32 && numBitsSigned(MulRHS, DAG) <= 32) {
10682       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10683       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10684       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10685       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10686     }
10687 
10688     return SDValue();
10689   }
10690 
10691   if (SDValue V = reassociateScalarOps(N, DAG)) {
10692     return V;
10693   }
10694 
10695   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10696     return SDValue();
10697 
10698   // add x, zext (setcc) => addcarry x, 0, setcc
10699   // add x, sext (setcc) => subcarry x, 0, setcc
10700   unsigned Opc = LHS.getOpcode();
10701   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10702       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10703     std::swap(RHS, LHS);
10704 
10705   Opc = RHS.getOpcode();
10706   switch (Opc) {
10707   default: break;
10708   case ISD::ZERO_EXTEND:
10709   case ISD::SIGN_EXTEND:
10710   case ISD::ANY_EXTEND: {
10711     auto Cond = RHS.getOperand(0);
10712     // If this won't be a real VOPC output, we would still need to insert an
10713     // extra instruction anyway.
10714     if (!isBoolSGPR(Cond))
10715       break;
10716     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10717     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10718     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10719     return DAG.getNode(Opc, SL, VTList, Args);
10720   }
10721   case ISD::ADDCARRY: {
10722     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10723     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10724     if (!C || C->getZExtValue() != 0) break;
10725     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10726     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10727   }
10728   }
10729   return SDValue();
10730 }
10731 
10732 SDValue SITargetLowering::performSubCombine(SDNode *N,
10733                                             DAGCombinerInfo &DCI) const {
10734   SelectionDAG &DAG = DCI.DAG;
10735   EVT VT = N->getValueType(0);
10736 
10737   if (VT != MVT::i32)
10738     return SDValue();
10739 
10740   SDLoc SL(N);
10741   SDValue LHS = N->getOperand(0);
10742   SDValue RHS = N->getOperand(1);
10743 
10744   // sub x, zext (setcc) => subcarry x, 0, setcc
10745   // sub x, sext (setcc) => addcarry x, 0, setcc
10746   unsigned Opc = RHS.getOpcode();
10747   switch (Opc) {
10748   default: break;
10749   case ISD::ZERO_EXTEND:
10750   case ISD::SIGN_EXTEND:
10751   case ISD::ANY_EXTEND: {
10752     auto Cond = RHS.getOperand(0);
10753     // If this won't be a real VOPC output, we would still need to insert an
10754     // extra instruction anyway.
10755     if (!isBoolSGPR(Cond))
10756       break;
10757     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10758     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10759     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10760     return DAG.getNode(Opc, SL, VTList, Args);
10761   }
10762   }
10763 
10764   if (LHS.getOpcode() == ISD::SUBCARRY) {
10765     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10766     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10767     if (!C || !C->isZero())
10768       return SDValue();
10769     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10770     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10771   }
10772   return SDValue();
10773 }
10774 
10775 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10776   DAGCombinerInfo &DCI) const {
10777 
10778   if (N->getValueType(0) != MVT::i32)
10779     return SDValue();
10780 
10781   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10782   if (!C || C->getZExtValue() != 0)
10783     return SDValue();
10784 
10785   SelectionDAG &DAG = DCI.DAG;
10786   SDValue LHS = N->getOperand(0);
10787 
10788   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10789   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10790   unsigned LHSOpc = LHS.getOpcode();
10791   unsigned Opc = N->getOpcode();
10792   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10793       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10794     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10795     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10796   }
10797   return SDValue();
10798 }
10799 
10800 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10801                                              DAGCombinerInfo &DCI) const {
10802   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10803     return SDValue();
10804 
10805   SelectionDAG &DAG = DCI.DAG;
10806   EVT VT = N->getValueType(0);
10807 
10808   SDLoc SL(N);
10809   SDValue LHS = N->getOperand(0);
10810   SDValue RHS = N->getOperand(1);
10811 
10812   // These should really be instruction patterns, but writing patterns with
10813   // source modifiers is a pain.
10814 
10815   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10816   if (LHS.getOpcode() == ISD::FADD) {
10817     SDValue A = LHS.getOperand(0);
10818     if (A == LHS.getOperand(1)) {
10819       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10820       if (FusedOp != 0) {
10821         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10822         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10823       }
10824     }
10825   }
10826 
10827   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10828   if (RHS.getOpcode() == ISD::FADD) {
10829     SDValue A = RHS.getOperand(0);
10830     if (A == RHS.getOperand(1)) {
10831       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10832       if (FusedOp != 0) {
10833         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10834         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10835       }
10836     }
10837   }
10838 
10839   return SDValue();
10840 }
10841 
10842 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10843                                              DAGCombinerInfo &DCI) const {
10844   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10845     return SDValue();
10846 
10847   SelectionDAG &DAG = DCI.DAG;
10848   SDLoc SL(N);
10849   EVT VT = N->getValueType(0);
10850   assert(!VT.isVector());
10851 
10852   // Try to get the fneg to fold into the source modifier. This undoes generic
10853   // DAG combines and folds them into the mad.
10854   //
10855   // Only do this if we are not trying to support denormals. v_mad_f32 does
10856   // not support denormals ever.
10857   SDValue LHS = N->getOperand(0);
10858   SDValue RHS = N->getOperand(1);
10859   if (LHS.getOpcode() == ISD::FADD) {
10860     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10861     SDValue A = LHS.getOperand(0);
10862     if (A == LHS.getOperand(1)) {
10863       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10864       if (FusedOp != 0){
10865         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10866         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10867 
10868         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10869       }
10870     }
10871   }
10872 
10873   if (RHS.getOpcode() == ISD::FADD) {
10874     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10875 
10876     SDValue A = RHS.getOperand(0);
10877     if (A == RHS.getOperand(1)) {
10878       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10879       if (FusedOp != 0){
10880         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10881         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10882       }
10883     }
10884   }
10885 
10886   return SDValue();
10887 }
10888 
10889 SDValue SITargetLowering::performFMACombine(SDNode *N,
10890                                             DAGCombinerInfo &DCI) const {
10891   SelectionDAG &DAG = DCI.DAG;
10892   EVT VT = N->getValueType(0);
10893   SDLoc SL(N);
10894 
10895   if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
10896     return SDValue();
10897 
10898   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10899   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10900   SDValue Op1 = N->getOperand(0);
10901   SDValue Op2 = N->getOperand(1);
10902   SDValue FMA = N->getOperand(2);
10903 
10904   if (FMA.getOpcode() != ISD::FMA ||
10905       Op1.getOpcode() != ISD::FP_EXTEND ||
10906       Op2.getOpcode() != ISD::FP_EXTEND)
10907     return SDValue();
10908 
10909   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10910   // regardless of the denorm mode setting. Therefore,
10911   // unsafe-fp-math/fp-contract is sufficient to allow generating fdot2.
10912   const TargetOptions &Options = DAG.getTarget().Options;
10913   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10914       (N->getFlags().hasAllowContract() &&
10915        FMA->getFlags().hasAllowContract())) {
10916     Op1 = Op1.getOperand(0);
10917     Op2 = Op2.getOperand(0);
10918     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10919         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10920       return SDValue();
10921 
10922     SDValue Vec1 = Op1.getOperand(0);
10923     SDValue Idx1 = Op1.getOperand(1);
10924     SDValue Vec2 = Op2.getOperand(0);
10925 
10926     SDValue FMAOp1 = FMA.getOperand(0);
10927     SDValue FMAOp2 = FMA.getOperand(1);
10928     SDValue FMAAcc = FMA.getOperand(2);
10929 
10930     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10931         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10932       return SDValue();
10933 
10934     FMAOp1 = FMAOp1.getOperand(0);
10935     FMAOp2 = FMAOp2.getOperand(0);
10936     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10937         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10938       return SDValue();
10939 
10940     SDValue Vec3 = FMAOp1.getOperand(0);
10941     SDValue Vec4 = FMAOp2.getOperand(0);
10942     SDValue Idx2 = FMAOp1.getOperand(1);
10943 
10944     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10945         // Idx1 and Idx2 cannot be the same.
10946         Idx1 == Idx2)
10947       return SDValue();
10948 
10949     if (Vec1 == Vec2 || Vec3 == Vec4)
10950       return SDValue();
10951 
10952     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10953       return SDValue();
10954 
10955     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10956         (Vec1 == Vec4 && Vec2 == Vec3)) {
10957       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10958                          DAG.getTargetConstant(0, SL, MVT::i1));
10959     }
10960   }
10961   return SDValue();
10962 }
10963 
10964 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10965                                               DAGCombinerInfo &DCI) const {
10966   SelectionDAG &DAG = DCI.DAG;
10967   SDLoc SL(N);
10968 
10969   SDValue LHS = N->getOperand(0);
10970   SDValue RHS = N->getOperand(1);
10971   EVT VT = LHS.getValueType();
10972   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10973 
10974   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10975   if (!CRHS) {
10976     CRHS = dyn_cast<ConstantSDNode>(LHS);
10977     if (CRHS) {
10978       std::swap(LHS, RHS);
10979       CC = getSetCCSwappedOperands(CC);
10980     }
10981   }
10982 
10983   if (CRHS) {
10984     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10985         isBoolSGPR(LHS.getOperand(0))) {
10986       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10987       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10988       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10989       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10990       if ((CRHS->isAllOnes() &&
10991            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10992           (CRHS->isZero() &&
10993            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10994         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10995                            DAG.getConstant(-1, SL, MVT::i1));
10996       if ((CRHS->isAllOnes() &&
10997            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10998           (CRHS->isZero() &&
10999            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
11000         return LHS.getOperand(0);
11001     }
11002 
11003     const APInt &CRHSVal = CRHS->getAPIntValue();
11004     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
11005         LHS.getOpcode() == ISD::SELECT &&
11006         isa<ConstantSDNode>(LHS.getOperand(1)) &&
11007         isa<ConstantSDNode>(LHS.getOperand(2)) &&
11008         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
11009         isBoolSGPR(LHS.getOperand(0))) {
11010       // Given CT != FT:
11011       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
11012       // setcc (select cc, CT, CF), CF, ne => cc
11013       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
11014       // setcc (select cc, CT, CF), CT, eq => cc
11015       const APInt &CT = LHS.getConstantOperandAPInt(1);
11016       const APInt &CF = LHS.getConstantOperandAPInt(2);
11017 
11018       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
11019           (CT == CRHSVal && CC == ISD::SETNE))
11020         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
11021                            DAG.getConstant(-1, SL, MVT::i1));
11022       if ((CF == CRHSVal && CC == ISD::SETNE) ||
11023           (CT == CRHSVal && CC == ISD::SETEQ))
11024         return LHS.getOperand(0);
11025     }
11026   }
11027 
11028   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
11029                                            VT != MVT::f16))
11030     return SDValue();
11031 
11032   // Match isinf/isfinite pattern
11033   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
11034   // (fcmp one (fabs x), inf) -> (fp_class x,
11035   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
11036   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
11037     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
11038     if (!CRHS)
11039       return SDValue();
11040 
11041     const APFloat &APF = CRHS->getValueAPF();
11042     if (APF.isInfinity() && !APF.isNegative()) {
11043       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
11044                                  SIInstrFlags::N_INFINITY;
11045       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
11046                                     SIInstrFlags::P_ZERO |
11047                                     SIInstrFlags::N_NORMAL |
11048                                     SIInstrFlags::P_NORMAL |
11049                                     SIInstrFlags::N_SUBNORMAL |
11050                                     SIInstrFlags::P_SUBNORMAL;
11051       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
11052       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
11053                          DAG.getConstant(Mask, SL, MVT::i32));
11054     }
11055   }
11056 
11057   return SDValue();
11058 }
11059 
11060 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
11061                                                      DAGCombinerInfo &DCI) const {
11062   SelectionDAG &DAG = DCI.DAG;
11063   SDLoc SL(N);
11064   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
11065 
11066   SDValue Src = N->getOperand(0);
11067   SDValue Shift = N->getOperand(0);
11068 
11069   // TODO: Extend type shouldn't matter (assuming legal types).
11070   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
11071     Shift = Shift.getOperand(0);
11072 
11073   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
11074     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
11075     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
11076     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
11077     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
11078     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
11079     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
11080       SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0),
11081                                  SDLoc(Shift.getOperand(0)), MVT::i32);
11082 
11083       unsigned ShiftOffset = 8 * Offset;
11084       if (Shift.getOpcode() == ISD::SHL)
11085         ShiftOffset -= C->getZExtValue();
11086       else
11087         ShiftOffset += C->getZExtValue();
11088 
11089       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
11090         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
11091                            MVT::f32, Shifted);
11092       }
11093     }
11094   }
11095 
11096   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11097   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
11098   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
11099     // We simplified Src. If this node is not dead, visit it again so it is
11100     // folded properly.
11101     if (N->getOpcode() != ISD::DELETED_NODE)
11102       DCI.AddToWorklist(N);
11103     return SDValue(N, 0);
11104   }
11105 
11106   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
11107   if (SDValue DemandedSrc =
11108           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
11109     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
11110 
11111   return SDValue();
11112 }
11113 
11114 SDValue SITargetLowering::performClampCombine(SDNode *N,
11115                                               DAGCombinerInfo &DCI) const {
11116   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
11117   if (!CSrc)
11118     return SDValue();
11119 
11120   const MachineFunction &MF = DCI.DAG.getMachineFunction();
11121   const APFloat &F = CSrc->getValueAPF();
11122   APFloat Zero = APFloat::getZero(F.getSemantics());
11123   if (F < Zero ||
11124       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
11125     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
11126   }
11127 
11128   APFloat One(F.getSemantics(), "1.0");
11129   if (F > One)
11130     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
11131 
11132   return SDValue(CSrc, 0);
11133 }
11134 
11135 
11136 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
11137                                             DAGCombinerInfo &DCI) const {
11138   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
11139     return SDValue();
11140   switch (N->getOpcode()) {
11141   case ISD::ADD:
11142     return performAddCombine(N, DCI);
11143   case ISD::SUB:
11144     return performSubCombine(N, DCI);
11145   case ISD::ADDCARRY:
11146   case ISD::SUBCARRY:
11147     return performAddCarrySubCarryCombine(N, DCI);
11148   case ISD::FADD:
11149     return performFAddCombine(N, DCI);
11150   case ISD::FSUB:
11151     return performFSubCombine(N, DCI);
11152   case ISD::SETCC:
11153     return performSetCCCombine(N, DCI);
11154   case ISD::FMAXNUM:
11155   case ISD::FMINNUM:
11156   case ISD::FMAXNUM_IEEE:
11157   case ISD::FMINNUM_IEEE:
11158   case ISD::SMAX:
11159   case ISD::SMIN:
11160   case ISD::UMAX:
11161   case ISD::UMIN:
11162   case AMDGPUISD::FMIN_LEGACY:
11163   case AMDGPUISD::FMAX_LEGACY:
11164     return performMinMaxCombine(N, DCI);
11165   case ISD::FMA:
11166     return performFMACombine(N, DCI);
11167   case ISD::AND:
11168     return performAndCombine(N, DCI);
11169   case ISD::OR:
11170     return performOrCombine(N, DCI);
11171   case ISD::XOR:
11172     return performXorCombine(N, DCI);
11173   case ISD::ZERO_EXTEND:
11174     return performZeroExtendCombine(N, DCI);
11175   case ISD::SIGN_EXTEND_INREG:
11176     return performSignExtendInRegCombine(N , DCI);
11177   case AMDGPUISD::FP_CLASS:
11178     return performClassCombine(N, DCI);
11179   case ISD::FCANONICALIZE:
11180     return performFCanonicalizeCombine(N, DCI);
11181   case AMDGPUISD::RCP:
11182     return performRcpCombine(N, DCI);
11183   case AMDGPUISD::FRACT:
11184   case AMDGPUISD::RSQ:
11185   case AMDGPUISD::RCP_LEGACY:
11186   case AMDGPUISD::RCP_IFLAG:
11187   case AMDGPUISD::RSQ_CLAMP:
11188   case AMDGPUISD::LDEXP: {
11189     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
11190     SDValue Src = N->getOperand(0);
11191     if (Src.isUndef())
11192       return Src;
11193     break;
11194   }
11195   case ISD::SINT_TO_FP:
11196   case ISD::UINT_TO_FP:
11197     return performUCharToFloatCombine(N, DCI);
11198   case AMDGPUISD::CVT_F32_UBYTE0:
11199   case AMDGPUISD::CVT_F32_UBYTE1:
11200   case AMDGPUISD::CVT_F32_UBYTE2:
11201   case AMDGPUISD::CVT_F32_UBYTE3:
11202     return performCvtF32UByteNCombine(N, DCI);
11203   case AMDGPUISD::FMED3:
11204     return performFMed3Combine(N, DCI);
11205   case AMDGPUISD::CVT_PKRTZ_F16_F32:
11206     return performCvtPkRTZCombine(N, DCI);
11207   case AMDGPUISD::CLAMP:
11208     return performClampCombine(N, DCI);
11209   case ISD::SCALAR_TO_VECTOR: {
11210     SelectionDAG &DAG = DCI.DAG;
11211     EVT VT = N->getValueType(0);
11212 
11213     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
11214     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
11215       SDLoc SL(N);
11216       SDValue Src = N->getOperand(0);
11217       EVT EltVT = Src.getValueType();
11218       if (EltVT == MVT::f16)
11219         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
11220 
11221       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
11222       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
11223     }
11224 
11225     break;
11226   }
11227   case ISD::EXTRACT_VECTOR_ELT:
11228     return performExtractVectorEltCombine(N, DCI);
11229   case ISD::INSERT_VECTOR_ELT:
11230     return performInsertVectorEltCombine(N, DCI);
11231   case ISD::LOAD: {
11232     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
11233       return Widended;
11234     LLVM_FALLTHROUGH;
11235   }
11236   default: {
11237     if (!DCI.isBeforeLegalize()) {
11238       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
11239         return performMemSDNodeCombine(MemNode, DCI);
11240     }
11241 
11242     break;
11243   }
11244   }
11245 
11246   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
11247 }
11248 
11249 /// Helper function for adjustWritemask
11250 static unsigned SubIdx2Lane(unsigned Idx) {
11251   switch (Idx) {
11252   default: return ~0u;
11253   case AMDGPU::sub0: return 0;
11254   case AMDGPU::sub1: return 1;
11255   case AMDGPU::sub2: return 2;
11256   case AMDGPU::sub3: return 3;
11257   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
11258   }
11259 }
11260 
11261 /// Adjust the writemask of MIMG instructions
11262 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
11263                                           SelectionDAG &DAG) const {
11264   unsigned Opcode = Node->getMachineOpcode();
11265 
11266   // Subtract 1 because the vdata output is not a MachineSDNode operand.
11267   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
11268   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
11269     return Node; // not implemented for D16
11270 
11271   SDNode *Users[5] = { nullptr };
11272   unsigned Lane = 0;
11273   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
11274   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
11275   unsigned NewDmask = 0;
11276   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
11277   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
11278   bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
11279                   Node->getConstantOperandVal(LWEIdx))
11280                      ? true
11281                      : false;
11282   unsigned TFCLane = 0;
11283   bool HasChain = Node->getNumValues() > 1;
11284 
11285   if (OldDmask == 0) {
11286     // These are folded out, but on the chance it happens don't assert.
11287     return Node;
11288   }
11289 
11290   unsigned OldBitsSet = countPopulation(OldDmask);
11291   // Work out which is the TFE/LWE lane if that is enabled.
11292   if (UsesTFC) {
11293     TFCLane = OldBitsSet;
11294   }
11295 
11296   // Try to figure out the used register components
11297   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
11298        I != E; ++I) {
11299 
11300     // Don't look at users of the chain.
11301     if (I.getUse().getResNo() != 0)
11302       continue;
11303 
11304     // Abort if we can't understand the usage
11305     if (!I->isMachineOpcode() ||
11306         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
11307       return Node;
11308 
11309     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
11310     // Note that subregs are packed, i.e. Lane==0 is the first bit set
11311     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
11312     // set, etc.
11313     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
11314     if (Lane == ~0u)
11315       return Node;
11316 
11317     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
11318     if (UsesTFC && Lane == TFCLane) {
11319       Users[Lane] = *I;
11320     } else {
11321       // Set which texture component corresponds to the lane.
11322       unsigned Comp;
11323       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
11324         Comp = countTrailingZeros(Dmask);
11325         Dmask &= ~(1 << Comp);
11326       }
11327 
11328       // Abort if we have more than one user per component.
11329       if (Users[Lane])
11330         return Node;
11331 
11332       Users[Lane] = *I;
11333       NewDmask |= 1 << Comp;
11334     }
11335   }
11336 
11337   // Don't allow 0 dmask, as hardware assumes one channel enabled.
11338   bool NoChannels = !NewDmask;
11339   if (NoChannels) {
11340     if (!UsesTFC) {
11341       // No uses of the result and not using TFC. Then do nothing.
11342       return Node;
11343     }
11344     // If the original dmask has one channel - then nothing to do
11345     if (OldBitsSet == 1)
11346       return Node;
11347     // Use an arbitrary dmask - required for the instruction to work
11348     NewDmask = 1;
11349   }
11350   // Abort if there's no change
11351   if (NewDmask == OldDmask)
11352     return Node;
11353 
11354   unsigned BitsSet = countPopulation(NewDmask);
11355 
11356   // Check for TFE or LWE - increase the number of channels by one to account
11357   // for the extra return value
11358   // This will need adjustment for D16 if this is also included in
11359   // adjustWriteMask (this function) but at present D16 are excluded.
11360   unsigned NewChannels = BitsSet + UsesTFC;
11361 
11362   int NewOpcode =
11363       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
11364   assert(NewOpcode != -1 &&
11365          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
11366          "failed to find equivalent MIMG op");
11367 
11368   // Adjust the writemask in the node
11369   SmallVector<SDValue, 12> Ops;
11370   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
11371   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
11372   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11373 
11374   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11375 
11376   MVT ResultVT = NewChannels == 1 ?
11377     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11378                            NewChannels == 5 ? 8 : NewChannels);
11379   SDVTList NewVTList = HasChain ?
11380     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11381 
11382 
11383   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11384                                               NewVTList, Ops);
11385 
11386   if (HasChain) {
11387     // Update chain.
11388     DAG.setNodeMemRefs(NewNode, Node->memoperands());
11389     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11390   }
11391 
11392   if (NewChannels == 1) {
11393     assert(Node->hasNUsesOfValue(1, 0));
11394     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11395                                       SDLoc(Node), Users[Lane]->getValueType(0),
11396                                       SDValue(NewNode, 0));
11397     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11398     return nullptr;
11399   }
11400 
11401   // Update the users of the node with the new indices
11402   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11403     SDNode *User = Users[i];
11404     if (!User) {
11405       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11406       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11407       if (i || !NoChannels)
11408         continue;
11409     } else {
11410       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11411       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11412     }
11413 
11414     switch (Idx) {
11415     default: break;
11416     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11417     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11418     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11419     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11420     }
11421   }
11422 
11423   DAG.RemoveDeadNode(Node);
11424   return nullptr;
11425 }
11426 
11427 static bool isFrameIndexOp(SDValue Op) {
11428   if (Op.getOpcode() == ISD::AssertZext)
11429     Op = Op.getOperand(0);
11430 
11431   return isa<FrameIndexSDNode>(Op);
11432 }
11433 
11434 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11435 /// with frame index operands.
11436 /// LLVM assumes that inputs are to these instructions are registers.
11437 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11438                                                         SelectionDAG &DAG) const {
11439   if (Node->getOpcode() == ISD::CopyToReg) {
11440     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11441     SDValue SrcVal = Node->getOperand(2);
11442 
11443     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11444     // to try understanding copies to physical registers.
11445     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11446       SDLoc SL(Node);
11447       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11448       SDValue VReg = DAG.getRegister(
11449         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11450 
11451       SDNode *Glued = Node->getGluedNode();
11452       SDValue ToVReg
11453         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11454                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11455       SDValue ToResultReg
11456         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11457                            VReg, ToVReg.getValue(1));
11458       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11459       DAG.RemoveDeadNode(Node);
11460       return ToResultReg.getNode();
11461     }
11462   }
11463 
11464   SmallVector<SDValue, 8> Ops;
11465   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11466     if (!isFrameIndexOp(Node->getOperand(i))) {
11467       Ops.push_back(Node->getOperand(i));
11468       continue;
11469     }
11470 
11471     SDLoc DL(Node);
11472     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11473                                      Node->getOperand(i).getValueType(),
11474                                      Node->getOperand(i)), 0));
11475   }
11476 
11477   return DAG.UpdateNodeOperands(Node, Ops);
11478 }
11479 
11480 /// Fold the instructions after selecting them.
11481 /// Returns null if users were already updated.
11482 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11483                                           SelectionDAG &DAG) const {
11484   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11485   unsigned Opcode = Node->getMachineOpcode();
11486 
11487   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11488       !TII->isGather4(Opcode) &&
11489       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11490     return adjustWritemask(Node, DAG);
11491   }
11492 
11493   if (Opcode == AMDGPU::INSERT_SUBREG ||
11494       Opcode == AMDGPU::REG_SEQUENCE) {
11495     legalizeTargetIndependentNode(Node, DAG);
11496     return Node;
11497   }
11498 
11499   switch (Opcode) {
11500   case AMDGPU::V_DIV_SCALE_F32_e64:
11501   case AMDGPU::V_DIV_SCALE_F64_e64: {
11502     // Satisfy the operand register constraint when one of the inputs is
11503     // undefined. Ordinarily each undef value will have its own implicit_def of
11504     // a vreg, so force these to use a single register.
11505     SDValue Src0 = Node->getOperand(1);
11506     SDValue Src1 = Node->getOperand(3);
11507     SDValue Src2 = Node->getOperand(5);
11508 
11509     if ((Src0.isMachineOpcode() &&
11510          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11511         (Src0 == Src1 || Src0 == Src2))
11512       break;
11513 
11514     MVT VT = Src0.getValueType().getSimpleVT();
11515     const TargetRegisterClass *RC =
11516         getRegClassFor(VT, Src0.getNode()->isDivergent());
11517 
11518     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11519     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11520 
11521     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11522                                       UndefReg, Src0, SDValue());
11523 
11524     // src0 must be the same register as src1 or src2, even if the value is
11525     // undefined, so make sure we don't violate this constraint.
11526     if (Src0.isMachineOpcode() &&
11527         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11528       if (Src1.isMachineOpcode() &&
11529           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11530         Src0 = Src1;
11531       else if (Src2.isMachineOpcode() &&
11532                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11533         Src0 = Src2;
11534       else {
11535         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11536         Src0 = UndefReg;
11537         Src1 = UndefReg;
11538       }
11539     } else
11540       break;
11541 
11542     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11543     Ops[1] = Src0;
11544     Ops[3] = Src1;
11545     Ops[5] = Src2;
11546     Ops.push_back(ImpDef.getValue(1));
11547     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11548   }
11549   default:
11550     break;
11551   }
11552 
11553   return Node;
11554 }
11555 
11556 // Any MIMG instructions that use tfe or lwe require an initialization of the
11557 // result register that will be written in the case of a memory access failure.
11558 // The required code is also added to tie this init code to the result of the
11559 // img instruction.
11560 void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
11561   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11562   const SIRegisterInfo &TRI = TII->getRegisterInfo();
11563   MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11564   MachineBasicBlock &MBB = *MI.getParent();
11565 
11566   MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
11567   MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
11568   MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
11569 
11570   if (!TFE && !LWE) // intersect_ray
11571     return;
11572 
11573   unsigned TFEVal = TFE ? TFE->getImm() : 0;
11574   unsigned LWEVal = LWE->getImm();
11575   unsigned D16Val = D16 ? D16->getImm() : 0;
11576 
11577   if (!TFEVal && !LWEVal)
11578     return;
11579 
11580   // At least one of TFE or LWE are non-zero
11581   // We have to insert a suitable initialization of the result value and
11582   // tie this to the dest of the image instruction.
11583 
11584   const DebugLoc &DL = MI.getDebugLoc();
11585 
11586   int DstIdx =
11587       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
11588 
11589   // Calculate which dword we have to initialize to 0.
11590   MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
11591 
11592   // check that dmask operand is found.
11593   assert(MO_Dmask && "Expected dmask operand in instruction");
11594 
11595   unsigned dmask = MO_Dmask->getImm();
11596   // Determine the number of active lanes taking into account the
11597   // Gather4 special case
11598   unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask);
11599 
11600   bool Packed = !Subtarget->hasUnpackedD16VMem();
11601 
11602   unsigned InitIdx =
11603       D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
11604 
11605   // Abandon attempt if the dst size isn't large enough
11606   // - this is in fact an error but this is picked up elsewhere and
11607   // reported correctly.
11608   uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
11609   if (DstSize < InitIdx)
11610     return;
11611 
11612   // Create a register for the initialization value.
11613   Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11614   unsigned NewDst = 0; // Final initialized value will be in here
11615 
11616   // If PRTStrictNull feature is enabled (the default) then initialize
11617   // all the result registers to 0, otherwise just the error indication
11618   // register (VGPRn+1)
11619   unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
11620   unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
11621 
11622   BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
11623   for (; SizeLeft; SizeLeft--, CurrIdx++) {
11624     NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11625     // Initialize dword
11626     Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
11627     BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
11628       .addImm(0);
11629     // Insert into the super-reg
11630     BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
11631       .addReg(PrevDst)
11632       .addReg(SubReg)
11633       .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
11634 
11635     PrevDst = NewDst;
11636   }
11637 
11638   // Add as an implicit operand
11639   MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
11640 
11641   // Tie the just added implicit operand to the dst
11642   MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
11643 }
11644 
11645 /// Assign the register class depending on the number of
11646 /// bits set in the writemask
11647 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11648                                                      SDNode *Node) const {
11649   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11650 
11651   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11652 
11653   if (TII->isVOP3(MI.getOpcode())) {
11654     // Make sure constant bus requirements are respected.
11655     TII->legalizeOperandsVOP3(MRI, MI);
11656 
11657     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11658     // This saves a chain-copy of registers and better balance register
11659     // use between vgpr and agpr as agpr tuples tend to be big.
11660     if (MI.getDesc().OpInfo) {
11661       unsigned Opc = MI.getOpcode();
11662       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11663       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11664                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11665         if (I == -1)
11666           break;
11667         MachineOperand &Op = MI.getOperand(I);
11668         if (!Op.isReg() || !Op.getReg().isVirtual())
11669           continue;
11670         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11671         if (!TRI->hasAGPRs(RC))
11672           continue;
11673         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11674         if (!Src || !Src->isCopy() ||
11675             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11676           continue;
11677         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11678         // All uses of agpr64 and agpr32 can also accept vgpr except for
11679         // v_accvgpr_read, but we do not produce agpr reads during selection,
11680         // so no use checks are needed.
11681         MRI.setRegClass(Op.getReg(), NewRC);
11682       }
11683 
11684       // Resolve the rest of AV operands to AGPRs.
11685       if (auto *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2)) {
11686         if (Src2->isReg() && Src2->getReg().isVirtual()) {
11687           auto *RC = TRI->getRegClassForReg(MRI, Src2->getReg());
11688           if (TRI->isVectorSuperClass(RC)) {
11689             auto *NewRC = TRI->getEquivalentAGPRClass(RC);
11690             MRI.setRegClass(Src2->getReg(), NewRC);
11691             if (Src2->isTied())
11692               MRI.setRegClass(MI.getOperand(0).getReg(), NewRC);
11693           }
11694         }
11695       }
11696     }
11697 
11698     return;
11699   }
11700 
11701   if (TII->isMIMG(MI) && !MI.mayStore())
11702     AddIMGInit(MI);
11703 }
11704 
11705 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11706                               uint64_t Val) {
11707   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11708   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11709 }
11710 
11711 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11712                                                 const SDLoc &DL,
11713                                                 SDValue Ptr) const {
11714   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11715 
11716   // Build the half of the subregister with the constants before building the
11717   // full 128-bit register. If we are building multiple resource descriptors,
11718   // this will allow CSEing of the 2-component register.
11719   const SDValue Ops0[] = {
11720     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11721     buildSMovImm32(DAG, DL, 0),
11722     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11723     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11724     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11725   };
11726 
11727   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11728                                                 MVT::v2i32, Ops0), 0);
11729 
11730   // Combine the constants and the pointer.
11731   const SDValue Ops1[] = {
11732     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11733     Ptr,
11734     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11735     SubRegHi,
11736     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11737   };
11738 
11739   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11740 }
11741 
11742 /// Return a resource descriptor with the 'Add TID' bit enabled
11743 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11744 ///        of the resource descriptor) to create an offset, which is added to
11745 ///        the resource pointer.
11746 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11747                                            SDValue Ptr, uint32_t RsrcDword1,
11748                                            uint64_t RsrcDword2And3) const {
11749   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11750   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11751   if (RsrcDword1) {
11752     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11753                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11754                     0);
11755   }
11756 
11757   SDValue DataLo = buildSMovImm32(DAG, DL,
11758                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11759   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11760 
11761   const SDValue Ops[] = {
11762     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11763     PtrLo,
11764     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11765     PtrHi,
11766     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11767     DataLo,
11768     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11769     DataHi,
11770     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11771   };
11772 
11773   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11774 }
11775 
11776 //===----------------------------------------------------------------------===//
11777 //                         SI Inline Assembly Support
11778 //===----------------------------------------------------------------------===//
11779 
11780 std::pair<unsigned, const TargetRegisterClass *>
11781 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
11782                                                StringRef Constraint,
11783                                                MVT VT) const {
11784   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
11785 
11786   const TargetRegisterClass *RC = nullptr;
11787   if (Constraint.size() == 1) {
11788     const unsigned BitWidth = VT.getSizeInBits();
11789     switch (Constraint[0]) {
11790     default:
11791       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11792     case 's':
11793     case 'r':
11794       switch (BitWidth) {
11795       case 16:
11796         RC = &AMDGPU::SReg_32RegClass;
11797         break;
11798       case 64:
11799         RC = &AMDGPU::SGPR_64RegClass;
11800         break;
11801       default:
11802         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11803         if (!RC)
11804           return std::make_pair(0U, nullptr);
11805         break;
11806       }
11807       break;
11808     case 'v':
11809       switch (BitWidth) {
11810       case 16:
11811         RC = &AMDGPU::VGPR_32RegClass;
11812         break;
11813       default:
11814         RC = TRI->getVGPRClassForBitWidth(BitWidth);
11815         if (!RC)
11816           return std::make_pair(0U, nullptr);
11817         break;
11818       }
11819       break;
11820     case 'a':
11821       if (!Subtarget->hasMAIInsts())
11822         break;
11823       switch (BitWidth) {
11824       case 16:
11825         RC = &AMDGPU::AGPR_32RegClass;
11826         break;
11827       default:
11828         RC = TRI->getAGPRClassForBitWidth(BitWidth);
11829         if (!RC)
11830           return std::make_pair(0U, nullptr);
11831         break;
11832       }
11833       break;
11834     }
11835     // We actually support i128, i16 and f16 as inline parameters
11836     // even if they are not reported as legal
11837     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11838                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11839       return std::make_pair(0U, RC);
11840   }
11841 
11842   if (Constraint.startswith("{") && Constraint.endswith("}")) {
11843     StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
11844     if (RegName.consume_front("v")) {
11845       RC = &AMDGPU::VGPR_32RegClass;
11846     } else if (RegName.consume_front("s")) {
11847       RC = &AMDGPU::SGPR_32RegClass;
11848     } else if (RegName.consume_front("a")) {
11849       RC = &AMDGPU::AGPR_32RegClass;
11850     }
11851 
11852     if (RC) {
11853       uint32_t Idx;
11854       if (RegName.consume_front("[")) {
11855         uint32_t End;
11856         bool Failed = RegName.consumeInteger(10, Idx);
11857         Failed |= !RegName.consume_front(":");
11858         Failed |= RegName.consumeInteger(10, End);
11859         Failed |= !RegName.consume_back("]");
11860         if (!Failed) {
11861           uint32_t Width = (End - Idx + 1) * 32;
11862           MCRegister Reg = RC->getRegister(Idx);
11863           if (SIRegisterInfo::isVGPRClass(RC))
11864             RC = TRI->getVGPRClassForBitWidth(Width);
11865           else if (SIRegisterInfo::isSGPRClass(RC))
11866             RC = TRI->getSGPRClassForBitWidth(Width);
11867           else if (SIRegisterInfo::isAGPRClass(RC))
11868             RC = TRI->getAGPRClassForBitWidth(Width);
11869           if (RC) {
11870             Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC);
11871             return std::make_pair(Reg, RC);
11872           }
11873         }
11874       } else {
11875         bool Failed = RegName.getAsInteger(10, Idx);
11876         if (!Failed && Idx < RC->getNumRegs())
11877           return std::make_pair(RC->getRegister(Idx), RC);
11878       }
11879     }
11880   }
11881 
11882   auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11883   if (Ret.first)
11884     Ret.second = TRI->getPhysRegClass(Ret.first);
11885 
11886   return Ret;
11887 }
11888 
11889 static bool isImmConstraint(StringRef Constraint) {
11890   if (Constraint.size() == 1) {
11891     switch (Constraint[0]) {
11892     default: break;
11893     case 'I':
11894     case 'J':
11895     case 'A':
11896     case 'B':
11897     case 'C':
11898       return true;
11899     }
11900   } else if (Constraint == "DA" ||
11901              Constraint == "DB") {
11902     return true;
11903   }
11904   return false;
11905 }
11906 
11907 SITargetLowering::ConstraintType
11908 SITargetLowering::getConstraintType(StringRef Constraint) const {
11909   if (Constraint.size() == 1) {
11910     switch (Constraint[0]) {
11911     default: break;
11912     case 's':
11913     case 'v':
11914     case 'a':
11915       return C_RegisterClass;
11916     }
11917   }
11918   if (isImmConstraint(Constraint)) {
11919     return C_Other;
11920   }
11921   return TargetLowering::getConstraintType(Constraint);
11922 }
11923 
11924 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11925   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11926     Val = Val & maskTrailingOnes<uint64_t>(Size);
11927   }
11928   return Val;
11929 }
11930 
11931 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11932                                                     std::string &Constraint,
11933                                                     std::vector<SDValue> &Ops,
11934                                                     SelectionDAG &DAG) const {
11935   if (isImmConstraint(Constraint)) {
11936     uint64_t Val;
11937     if (getAsmOperandConstVal(Op, Val) &&
11938         checkAsmConstraintVal(Op, Constraint, Val)) {
11939       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11940       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11941     }
11942   } else {
11943     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11944   }
11945 }
11946 
11947 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11948   unsigned Size = Op.getScalarValueSizeInBits();
11949   if (Size > 64)
11950     return false;
11951 
11952   if (Size == 16 && !Subtarget->has16BitInsts())
11953     return false;
11954 
11955   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11956     Val = C->getSExtValue();
11957     return true;
11958   }
11959   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11960     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11961     return true;
11962   }
11963   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11964     if (Size != 16 || Op.getNumOperands() != 2)
11965       return false;
11966     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11967       return false;
11968     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11969       Val = C->getSExtValue();
11970       return true;
11971     }
11972     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11973       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11974       return true;
11975     }
11976   }
11977 
11978   return false;
11979 }
11980 
11981 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11982                                              const std::string &Constraint,
11983                                              uint64_t Val) const {
11984   if (Constraint.size() == 1) {
11985     switch (Constraint[0]) {
11986     case 'I':
11987       return AMDGPU::isInlinableIntLiteral(Val);
11988     case 'J':
11989       return isInt<16>(Val);
11990     case 'A':
11991       return checkAsmConstraintValA(Op, Val);
11992     case 'B':
11993       return isInt<32>(Val);
11994     case 'C':
11995       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11996              AMDGPU::isInlinableIntLiteral(Val);
11997     default:
11998       break;
11999     }
12000   } else if (Constraint.size() == 2) {
12001     if (Constraint == "DA") {
12002       int64_t HiBits = static_cast<int32_t>(Val >> 32);
12003       int64_t LoBits = static_cast<int32_t>(Val);
12004       return checkAsmConstraintValA(Op, HiBits, 32) &&
12005              checkAsmConstraintValA(Op, LoBits, 32);
12006     }
12007     if (Constraint == "DB") {
12008       return true;
12009     }
12010   }
12011   llvm_unreachable("Invalid asm constraint");
12012 }
12013 
12014 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
12015                                               uint64_t Val,
12016                                               unsigned MaxSize) const {
12017   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
12018   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
12019   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
12020       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
12021       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
12022     return true;
12023   }
12024   return false;
12025 }
12026 
12027 static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
12028   switch (UnalignedClassID) {
12029   case AMDGPU::VReg_64RegClassID:
12030     return AMDGPU::VReg_64_Align2RegClassID;
12031   case AMDGPU::VReg_96RegClassID:
12032     return AMDGPU::VReg_96_Align2RegClassID;
12033   case AMDGPU::VReg_128RegClassID:
12034     return AMDGPU::VReg_128_Align2RegClassID;
12035   case AMDGPU::VReg_160RegClassID:
12036     return AMDGPU::VReg_160_Align2RegClassID;
12037   case AMDGPU::VReg_192RegClassID:
12038     return AMDGPU::VReg_192_Align2RegClassID;
12039   case AMDGPU::VReg_224RegClassID:
12040     return AMDGPU::VReg_224_Align2RegClassID;
12041   case AMDGPU::VReg_256RegClassID:
12042     return AMDGPU::VReg_256_Align2RegClassID;
12043   case AMDGPU::VReg_512RegClassID:
12044     return AMDGPU::VReg_512_Align2RegClassID;
12045   case AMDGPU::VReg_1024RegClassID:
12046     return AMDGPU::VReg_1024_Align2RegClassID;
12047   case AMDGPU::AReg_64RegClassID:
12048     return AMDGPU::AReg_64_Align2RegClassID;
12049   case AMDGPU::AReg_96RegClassID:
12050     return AMDGPU::AReg_96_Align2RegClassID;
12051   case AMDGPU::AReg_128RegClassID:
12052     return AMDGPU::AReg_128_Align2RegClassID;
12053   case AMDGPU::AReg_160RegClassID:
12054     return AMDGPU::AReg_160_Align2RegClassID;
12055   case AMDGPU::AReg_192RegClassID:
12056     return AMDGPU::AReg_192_Align2RegClassID;
12057   case AMDGPU::AReg_256RegClassID:
12058     return AMDGPU::AReg_256_Align2RegClassID;
12059   case AMDGPU::AReg_512RegClassID:
12060     return AMDGPU::AReg_512_Align2RegClassID;
12061   case AMDGPU::AReg_1024RegClassID:
12062     return AMDGPU::AReg_1024_Align2RegClassID;
12063   default:
12064     return -1;
12065   }
12066 }
12067 
12068 // Figure out which registers should be reserved for stack access. Only after
12069 // the function is legalized do we know all of the non-spill stack objects or if
12070 // calls are present.
12071 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
12072   MachineRegisterInfo &MRI = MF.getRegInfo();
12073   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12074   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
12075   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12076   const SIInstrInfo *TII = ST.getInstrInfo();
12077 
12078   if (Info->isEntryFunction()) {
12079     // Callable functions have fixed registers used for stack access.
12080     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
12081   }
12082 
12083   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
12084                              Info->getStackPtrOffsetReg()));
12085   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
12086     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
12087 
12088   // We need to worry about replacing the default register with itself in case
12089   // of MIR testcases missing the MFI.
12090   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
12091     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
12092 
12093   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
12094     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
12095 
12096   Info->limitOccupancy(MF);
12097 
12098   if (ST.isWave32() && !MF.empty()) {
12099     for (auto &MBB : MF) {
12100       for (auto &MI : MBB) {
12101         TII->fixImplicitOperands(MI);
12102       }
12103     }
12104   }
12105 
12106   // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
12107   // classes if required. Ideally the register class constraints would differ
12108   // per-subtarget, but there's no easy way to achieve that right now. This is
12109   // not a problem for VGPRs because the correctly aligned VGPR class is implied
12110   // from using them as the register class for legal types.
12111   if (ST.needsAlignedVGPRs()) {
12112     for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
12113       const Register Reg = Register::index2VirtReg(I);
12114       const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
12115       if (!RC)
12116         continue;
12117       int NewClassID = getAlignedAGPRClassID(RC->getID());
12118       if (NewClassID != -1)
12119         MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
12120     }
12121   }
12122 
12123   TargetLoweringBase::finalizeLowering(MF);
12124 }
12125 
12126 void SITargetLowering::computeKnownBitsForFrameIndex(
12127   const int FI, KnownBits &Known, const MachineFunction &MF) const {
12128   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
12129 
12130   // Set the high bits to zero based on the maximum allowed scratch size per
12131   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
12132   // calculation won't overflow, so assume the sign bit is never set.
12133   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
12134 }
12135 
12136 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
12137                                    KnownBits &Known, unsigned Dim) {
12138   unsigned MaxValue =
12139       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
12140   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
12141 }
12142 
12143 void SITargetLowering::computeKnownBitsForTargetInstr(
12144     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
12145     const MachineRegisterInfo &MRI, unsigned Depth) const {
12146   const MachineInstr *MI = MRI.getVRegDef(R);
12147   switch (MI->getOpcode()) {
12148   case AMDGPU::G_INTRINSIC: {
12149     switch (MI->getIntrinsicID()) {
12150     case Intrinsic::amdgcn_workitem_id_x:
12151       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
12152       break;
12153     case Intrinsic::amdgcn_workitem_id_y:
12154       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
12155       break;
12156     case Intrinsic::amdgcn_workitem_id_z:
12157       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
12158       break;
12159     case Intrinsic::amdgcn_mbcnt_lo:
12160     case Intrinsic::amdgcn_mbcnt_hi: {
12161       // These return at most the wavefront size - 1.
12162       unsigned Size = MRI.getType(R).getSizeInBits();
12163       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
12164       break;
12165     }
12166     case Intrinsic::amdgcn_groupstaticsize: {
12167       // We can report everything over the maximum size as 0. We can't report
12168       // based on the actual size because we don't know if it's accurate or not
12169       // at any given point.
12170       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
12171       break;
12172     }
12173     }
12174     break;
12175   }
12176   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
12177     Known.Zero.setHighBits(24);
12178     break;
12179   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
12180     Known.Zero.setHighBits(16);
12181     break;
12182   }
12183 }
12184 
12185 Align SITargetLowering::computeKnownAlignForTargetInstr(
12186   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
12187   unsigned Depth) const {
12188   const MachineInstr *MI = MRI.getVRegDef(R);
12189   switch (MI->getOpcode()) {
12190   case AMDGPU::G_INTRINSIC:
12191   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
12192     // FIXME: Can this move to generic code? What about the case where the call
12193     // site specifies a lower alignment?
12194     Intrinsic::ID IID = MI->getIntrinsicID();
12195     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
12196     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
12197     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
12198       return *RetAlign;
12199     return Align(1);
12200   }
12201   default:
12202     return Align(1);
12203   }
12204 }
12205 
12206 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12207   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
12208   const Align CacheLineAlign = Align(64);
12209 
12210   // Pre-GFX10 target did not benefit from loop alignment
12211   if (!ML || DisableLoopAlignment ||
12212       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
12213       getSubtarget()->hasInstFwdPrefetchBug())
12214     return PrefAlign;
12215 
12216   // On GFX10 I$ is 4 x 64 bytes cache lines.
12217   // By default prefetcher keeps one cache line behind and reads two ahead.
12218   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
12219   // behind and one ahead.
12220   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
12221   // If loop fits 64 bytes it always spans no more than two cache lines and
12222   // does not need an alignment.
12223   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
12224   // Else if loop is less or equal 192 bytes we need two lines behind.
12225 
12226   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12227   const MachineBasicBlock *Header = ML->getHeader();
12228   if (Header->getAlignment() != PrefAlign)
12229     return Header->getAlignment(); // Already processed.
12230 
12231   unsigned LoopSize = 0;
12232   for (const MachineBasicBlock *MBB : ML->blocks()) {
12233     // If inner loop block is aligned assume in average half of the alignment
12234     // size to be added as nops.
12235     if (MBB != Header)
12236       LoopSize += MBB->getAlignment().value() / 2;
12237 
12238     for (const MachineInstr &MI : *MBB) {
12239       LoopSize += TII->getInstSizeInBytes(MI);
12240       if (LoopSize > 192)
12241         return PrefAlign;
12242     }
12243   }
12244 
12245   if (LoopSize <= 64)
12246     return PrefAlign;
12247 
12248   if (LoopSize <= 128)
12249     return CacheLineAlign;
12250 
12251   // If any of parent loops is surrounded by prefetch instructions do not
12252   // insert new for inner loop, which would reset parent's settings.
12253   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
12254     if (MachineBasicBlock *Exit = P->getExitBlock()) {
12255       auto I = Exit->getFirstNonDebugInstr();
12256       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
12257         return CacheLineAlign;
12258     }
12259   }
12260 
12261   MachineBasicBlock *Pre = ML->getLoopPreheader();
12262   MachineBasicBlock *Exit = ML->getExitBlock();
12263 
12264   if (Pre && Exit) {
12265     auto PreTerm = Pre->getFirstTerminator();
12266     if (PreTerm == Pre->begin() ||
12267         std::prev(PreTerm)->getOpcode() != AMDGPU::S_INST_PREFETCH)
12268       BuildMI(*Pre, PreTerm, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH))
12269           .addImm(1); // prefetch 2 lines behind PC
12270 
12271     auto ExitHead = Exit->getFirstNonDebugInstr();
12272     if (ExitHead == Exit->end() ||
12273         ExitHead->getOpcode() != AMDGPU::S_INST_PREFETCH)
12274       BuildMI(*Exit, ExitHead, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH))
12275           .addImm(2); // prefetch 1 line behind PC
12276   }
12277 
12278   return CacheLineAlign;
12279 }
12280 
12281 LLVM_ATTRIBUTE_UNUSED
12282 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
12283   assert(N->getOpcode() == ISD::CopyFromReg);
12284   do {
12285     // Follow the chain until we find an INLINEASM node.
12286     N = N->getOperand(0).getNode();
12287     if (N->getOpcode() == ISD::INLINEASM ||
12288         N->getOpcode() == ISD::INLINEASM_BR)
12289       return true;
12290   } while (N->getOpcode() == ISD::CopyFromReg);
12291   return false;
12292 }
12293 
12294 bool SITargetLowering::isSDNodeSourceOfDivergence(
12295     const SDNode *N, FunctionLoweringInfo *FLI,
12296     LegacyDivergenceAnalysis *KDA) const {
12297   switch (N->getOpcode()) {
12298   case ISD::CopyFromReg: {
12299     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
12300     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
12301     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12302     Register Reg = R->getReg();
12303 
12304     // FIXME: Why does this need to consider isLiveIn?
12305     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
12306       return !TRI->isSGPRReg(MRI, Reg);
12307 
12308     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
12309       return KDA->isDivergent(V);
12310 
12311     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
12312     return !TRI->isSGPRReg(MRI, Reg);
12313   }
12314   case ISD::LOAD: {
12315     const LoadSDNode *L = cast<LoadSDNode>(N);
12316     unsigned AS = L->getAddressSpace();
12317     // A flat load may access private memory.
12318     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
12319   }
12320   case ISD::CALLSEQ_END:
12321     return true;
12322   case ISD::INTRINSIC_WO_CHAIN:
12323     return AMDGPU::isIntrinsicSourceOfDivergence(
12324         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
12325   case ISD::INTRINSIC_W_CHAIN:
12326     return AMDGPU::isIntrinsicSourceOfDivergence(
12327         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
12328   case AMDGPUISD::ATOMIC_CMP_SWAP:
12329   case AMDGPUISD::ATOMIC_INC:
12330   case AMDGPUISD::ATOMIC_DEC:
12331   case AMDGPUISD::ATOMIC_LOAD_FMIN:
12332   case AMDGPUISD::ATOMIC_LOAD_FMAX:
12333   case AMDGPUISD::BUFFER_ATOMIC_SWAP:
12334   case AMDGPUISD::BUFFER_ATOMIC_ADD:
12335   case AMDGPUISD::BUFFER_ATOMIC_SUB:
12336   case AMDGPUISD::BUFFER_ATOMIC_SMIN:
12337   case AMDGPUISD::BUFFER_ATOMIC_UMIN:
12338   case AMDGPUISD::BUFFER_ATOMIC_SMAX:
12339   case AMDGPUISD::BUFFER_ATOMIC_UMAX:
12340   case AMDGPUISD::BUFFER_ATOMIC_AND:
12341   case AMDGPUISD::BUFFER_ATOMIC_OR:
12342   case AMDGPUISD::BUFFER_ATOMIC_XOR:
12343   case AMDGPUISD::BUFFER_ATOMIC_INC:
12344   case AMDGPUISD::BUFFER_ATOMIC_DEC:
12345   case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
12346   case AMDGPUISD::BUFFER_ATOMIC_CSUB:
12347   case AMDGPUISD::BUFFER_ATOMIC_FADD:
12348   case AMDGPUISD::BUFFER_ATOMIC_FMIN:
12349   case AMDGPUISD::BUFFER_ATOMIC_FMAX:
12350     // Target-specific read-modify-write atomics are sources of divergence.
12351     return true;
12352   default:
12353     if (auto *A = dyn_cast<AtomicSDNode>(N)) {
12354       // Generic read-modify-write atomics are sources of divergence.
12355       return A->readMem() && A->writeMem();
12356     }
12357     return false;
12358   }
12359 }
12360 
12361 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
12362                                                EVT VT) const {
12363   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
12364   case MVT::f32:
12365     return hasFP32Denormals(DAG.getMachineFunction());
12366   case MVT::f64:
12367   case MVT::f16:
12368     return hasFP64FP16Denormals(DAG.getMachineFunction());
12369   default:
12370     return false;
12371   }
12372 }
12373 
12374 bool SITargetLowering::denormalsEnabledForType(LLT Ty,
12375                                                MachineFunction &MF) const {
12376   switch (Ty.getScalarSizeInBits()) {
12377   case 32:
12378     return hasFP32Denormals(MF);
12379   case 64:
12380   case 16:
12381     return hasFP64FP16Denormals(MF);
12382   default:
12383     return false;
12384   }
12385 }
12386 
12387 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
12388                                                     const SelectionDAG &DAG,
12389                                                     bool SNaN,
12390                                                     unsigned Depth) const {
12391   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
12392     const MachineFunction &MF = DAG.getMachineFunction();
12393     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12394 
12395     if (Info->getMode().DX10Clamp)
12396       return true; // Clamped to 0.
12397     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
12398   }
12399 
12400   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
12401                                                             SNaN, Depth);
12402 }
12403 
12404 // Global FP atomic instructions have a hardcoded FP mode and do not support
12405 // FP32 denormals, and only support v2f16 denormals.
12406 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
12407   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
12408   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
12409   if (&Flt == &APFloat::IEEEsingle())
12410     return DenormMode == DenormalMode::getPreserveSign();
12411   return DenormMode == DenormalMode::getIEEE();
12412 }
12413 
12414 TargetLowering::AtomicExpansionKind
12415 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
12416   unsigned AS = RMW->getPointerAddressSpace();
12417   if (AS == AMDGPUAS::PRIVATE_ADDRESS)
12418     return AtomicExpansionKind::NotAtomic;
12419 
12420   auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) {
12421     OptimizationRemarkEmitter ORE(RMW->getFunction());
12422     LLVMContext &Ctx = RMW->getFunction()->getContext();
12423     SmallVector<StringRef> SSNs;
12424     Ctx.getSyncScopeNames(SSNs);
12425     auto MemScope = SSNs[RMW->getSyncScopeID()].empty()
12426                         ? "system"
12427                         : SSNs[RMW->getSyncScopeID()];
12428     ORE.emit([&]() {
12429       return OptimizationRemark(DEBUG_TYPE, "Passed", RMW)
12430              << "Hardware instruction generated for atomic "
12431              << RMW->getOperationName(RMW->getOperation())
12432              << " operation at memory scope " << MemScope
12433              << " due to an unsafe request.";
12434     });
12435     return Kind;
12436   };
12437 
12438   switch (RMW->getOperation()) {
12439   case AtomicRMWInst::FAdd: {
12440     Type *Ty = RMW->getType();
12441 
12442     // We don't have a way to support 16-bit atomics now, so just leave them
12443     // as-is.
12444     if (Ty->isHalfTy())
12445       return AtomicExpansionKind::None;
12446 
12447     if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
12448       return AtomicExpansionKind::CmpXChg;
12449 
12450     if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) &&
12451          Subtarget->hasAtomicFaddInsts()) {
12452       if (Subtarget->hasGFX940Insts())
12453         return AtomicExpansionKind::None;
12454 
12455       // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
12456       // floating point atomic instructions. May generate more efficient code,
12457       // but may not respect rounding and denormal modes, and may give incorrect
12458       // results for certain memory destinations.
12459       if (RMW->getFunction()
12460               ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12461               .getValueAsString() != "true")
12462         return AtomicExpansionKind::CmpXChg;
12463 
12464       if (Subtarget->hasGFX90AInsts()) {
12465         if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS)
12466           return AtomicExpansionKind::CmpXChg;
12467 
12468         auto SSID = RMW->getSyncScopeID();
12469         if (SSID == SyncScope::System ||
12470             SSID == RMW->getContext().getOrInsertSyncScopeID("one-as"))
12471           return AtomicExpansionKind::CmpXChg;
12472 
12473         return ReportUnsafeHWInst(AtomicExpansionKind::None);
12474       }
12475 
12476       if (AS == AMDGPUAS::FLAT_ADDRESS)
12477         return AtomicExpansionKind::CmpXChg;
12478 
12479       return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12480                               : AtomicExpansionKind::CmpXChg;
12481     }
12482 
12483     // DS FP atomics do respect the denormal mode, but the rounding mode is
12484     // fixed to round-to-nearest-even.
12485     // The only exception is DS_ADD_F64 which never flushes regardless of mode.
12486     if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) {
12487       if (!Ty->isDoubleTy())
12488         return AtomicExpansionKind::None;
12489 
12490       if (fpModeMatchesGlobalFPAtomicMode(RMW))
12491         return AtomicExpansionKind::None;
12492 
12493       return RMW->getFunction()
12494                          ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12495                          .getValueAsString() == "true"
12496                  ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12497                  : AtomicExpansionKind::CmpXChg;
12498     }
12499 
12500     return AtomicExpansionKind::CmpXChg;
12501   }
12502   default:
12503     break;
12504   }
12505 
12506   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
12507 }
12508 
12509 TargetLowering::AtomicExpansionKind
12510 SITargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
12511   return LI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12512              ? AtomicExpansionKind::NotAtomic
12513              : AtomicExpansionKind::None;
12514 }
12515 
12516 TargetLowering::AtomicExpansionKind
12517 SITargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
12518   return SI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12519              ? AtomicExpansionKind::NotAtomic
12520              : AtomicExpansionKind::None;
12521 }
12522 
12523 TargetLowering::AtomicExpansionKind
12524 SITargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *CmpX) const {
12525   return CmpX->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12526              ? AtomicExpansionKind::NotAtomic
12527              : AtomicExpansionKind::None;
12528 }
12529 
12530 const TargetRegisterClass *
12531 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
12532   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
12533   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12534   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
12535     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
12536                                                : &AMDGPU::SReg_32RegClass;
12537   if (!TRI->isSGPRClass(RC) && !isDivergent)
12538     return TRI->getEquivalentSGPRClass(RC);
12539   else if (TRI->isSGPRClass(RC) && isDivergent)
12540     return TRI->getEquivalentVGPRClass(RC);
12541 
12542   return RC;
12543 }
12544 
12545 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
12546 // uniform values (as produced by the mask results of control flow intrinsics)
12547 // used outside of divergent blocks. The phi users need to also be treated as
12548 // always uniform.
12549 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
12550                       unsigned WaveSize) {
12551   // FIXME: We assume we never cast the mask results of a control flow
12552   // intrinsic.
12553   // Early exit if the type won't be consistent as a compile time hack.
12554   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
12555   if (!IT || IT->getBitWidth() != WaveSize)
12556     return false;
12557 
12558   if (!isa<Instruction>(V))
12559     return false;
12560   if (!Visited.insert(V).second)
12561     return false;
12562   bool Result = false;
12563   for (auto U : V->users()) {
12564     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
12565       if (V == U->getOperand(1)) {
12566         switch (Intrinsic->getIntrinsicID()) {
12567         default:
12568           Result = false;
12569           break;
12570         case Intrinsic::amdgcn_if_break:
12571         case Intrinsic::amdgcn_if:
12572         case Intrinsic::amdgcn_else:
12573           Result = true;
12574           break;
12575         }
12576       }
12577       if (V == U->getOperand(0)) {
12578         switch (Intrinsic->getIntrinsicID()) {
12579         default:
12580           Result = false;
12581           break;
12582         case Intrinsic::amdgcn_end_cf:
12583         case Intrinsic::amdgcn_loop:
12584           Result = true;
12585           break;
12586         }
12587       }
12588     } else {
12589       Result = hasCFUser(U, Visited, WaveSize);
12590     }
12591     if (Result)
12592       break;
12593   }
12594   return Result;
12595 }
12596 
12597 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
12598                                                const Value *V) const {
12599   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
12600     if (CI->isInlineAsm()) {
12601       // FIXME: This cannot give a correct answer. This should only trigger in
12602       // the case where inline asm returns mixed SGPR and VGPR results, used
12603       // outside the defining block. We don't have a specific result to
12604       // consider, so this assumes if any value is SGPR, the overall register
12605       // also needs to be SGPR.
12606       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
12607       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
12608           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
12609       for (auto &TC : TargetConstraints) {
12610         if (TC.Type == InlineAsm::isOutput) {
12611           ComputeConstraintToUse(TC, SDValue());
12612           const TargetRegisterClass *RC = getRegForInlineAsmConstraint(
12613               SIRI, TC.ConstraintCode, TC.ConstraintVT).second;
12614           if (RC && SIRI->isSGPRClass(RC))
12615             return true;
12616         }
12617       }
12618     }
12619   }
12620   SmallPtrSet<const Value *, 16> Visited;
12621   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
12622 }
12623 
12624 std::pair<InstructionCost, MVT>
12625 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
12626                                           Type *Ty) const {
12627   std::pair<InstructionCost, MVT> Cost =
12628       TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
12629   auto Size = DL.getTypeSizeInBits(Ty);
12630   // Maximum load or store can handle 8 dwords for scalar and 4 for
12631   // vector ALU. Let's assume anything above 8 dwords is expensive
12632   // even if legal.
12633   if (Size <= 256)
12634     return Cost;
12635 
12636   Cost.first += (Size + 255) / 256;
12637   return Cost;
12638 }
12639 
12640 bool SITargetLowering::hasMemSDNodeUser(SDNode *N) const {
12641   SDNode::use_iterator I = N->use_begin(), E = N->use_end();
12642   for (; I != E; ++I) {
12643     if (MemSDNode *M = dyn_cast<MemSDNode>(*I)) {
12644       if (getBasePtrIndex(M) == I.getOperandNo())
12645         return true;
12646     }
12647   }
12648   return false;
12649 }
12650 
12651 bool SITargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0,
12652                                            SDValue N1) const {
12653   if (!N0.hasOneUse())
12654     return false;
12655   // Take care of the opportunity to keep N0 uniform
12656   if (N0->isDivergent() || !N1->isDivergent())
12657     return true;
12658   // Check if we have a good chance to form the memory access pattern with the
12659   // base and offset
12660   return (DAG.isBaseWithConstantOffset(N0) &&
12661           hasMemSDNodeUser(*N0->use_begin()));
12662 }
12663 
12664 MachineMemOperand::Flags
12665 SITargetLowering::getTargetMMOFlags(const Instruction &I) const {
12666   // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load.
12667   if (I.getMetadata("amdgpu.noclobber"))
12668     return MONoClobber;
12669   return MachineMemOperand::MONone;
12670 }
12671