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       break;
1549     case 96:
1550       if (!Subtarget->hasDS96AndDS128())
1551         return false;
1552 
1553       // 12 byte accessing via ds_read/write_b96 require 16-byte alignment on
1554       // gfx8 and older.
1555 
1556       if (Subtarget->hasUnalignedDSAccessEnabled()) {
1557         // Naturally aligned access is fastest. However, also report it is Fast
1558         // if memory is aligned less than DWORD. A narrow load or store will be
1559         // be equally slow as a single ds_read_b96/ds_write_b96, but there will
1560         // be more of them, so overall we will pay less penalty issuing a single
1561         // instruction.
1562         if (IsFast)
1563           *IsFast = Alignment >= RequiredAlignment || Alignment < Align(4);
1564         return true;
1565       }
1566 
1567       break;
1568     case 128:
1569       if (!Subtarget->hasDS96AndDS128() || !Subtarget->useDS128())
1570         return false;
1571 
1572       // 16 byte accessing via ds_read/write_b128 require 16-byte alignment on
1573       // gfx8 and older, but  we can do a 8 byte aligned, 16 byte access in a
1574       // single operation using ds_read2/write2_b64.
1575       RequiredAlignment = Align(8);
1576 
1577       if (Subtarget->hasUnalignedDSAccessEnabled()) {
1578         // Naturally aligned access is fastest. However, also report it is Fast
1579         // if memory is aligned less than DWORD. A narrow load or store will be
1580         // be equally slow as a single ds_read_b128/ds_write_b128, but there
1581         // will be more of them, so overall we will pay less penalty issuing a
1582         // single instruction.
1583         if (IsFast)
1584           *IsFast = Alignment >= RequiredAlignment || Alignment < Align(4);
1585         return true;
1586       }
1587 
1588       break;
1589     default:
1590       if (Size > 32)
1591         return false;
1592 
1593       break;
1594     }
1595 
1596     if (IsFast) {
1597       // FIXME: Lie it is fast if +unaligned-access-mode is passed so that
1598       // DS accesses get vectorized. Do this only for sizes below 96 as
1599       // b96 and b128 cases already properly handled.
1600       // Remove Subtarget check once all sizes properly handled.
1601       *IsFast = Alignment >= RequiredAlignment ||
1602                 (Subtarget->hasUnalignedDSAccessEnabled() && Size < 96);
1603     }
1604 
1605     return Alignment >= RequiredAlignment ||
1606            Subtarget->hasUnalignedDSAccessEnabled();
1607   }
1608 
1609   if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) {
1610     bool AlignedBy4 = Alignment >= Align(4);
1611     if (IsFast)
1612       *IsFast = AlignedBy4;
1613 
1614     return AlignedBy4 ||
1615            Subtarget->enableFlatScratch() ||
1616            Subtarget->hasUnalignedScratchAccess();
1617   }
1618 
1619   // FIXME: We have to be conservative here and assume that flat operations
1620   // will access scratch.  If we had access to the IR function, then we
1621   // could determine if any private memory was used in the function.
1622   if (AddrSpace == AMDGPUAS::FLAT_ADDRESS &&
1623       !Subtarget->hasUnalignedScratchAccess()) {
1624     bool AlignedBy4 = Alignment >= Align(4);
1625     if (IsFast)
1626       *IsFast = AlignedBy4;
1627 
1628     return AlignedBy4;
1629   }
1630 
1631   if (Subtarget->hasUnalignedBufferAccessEnabled()) {
1632     // If we have a uniform constant load, it still requires using a slow
1633     // buffer instruction if unaligned.
1634     if (IsFast) {
1635       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1636       // 2-byte alignment is worse than 1 unless doing a 2-byte access.
1637       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1638                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1639         Alignment >= Align(4) : Alignment != Align(2);
1640     }
1641 
1642     return true;
1643   }
1644 
1645   // Smaller than dword value must be aligned.
1646   if (Size < 32)
1647     return false;
1648 
1649   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1650   // byte-address are ignored, thus forcing Dword alignment.
1651   // This applies to private, global, and constant memory.
1652   if (IsFast)
1653     *IsFast = true;
1654 
1655   return Size >= 32 && Alignment >= Align(4);
1656 }
1657 
1658 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1659     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
1660     bool *IsFast) const {
1661   bool Allow = allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1662                                                   Alignment, Flags, IsFast);
1663 
1664   if (Allow && IsFast && Subtarget->hasUnalignedDSAccessEnabled() &&
1665       (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1666        AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1667     // Lie it is fast if +unaligned-access-mode is passed so that DS accesses
1668     // get vectorized. We could use ds_read2_b*/ds_write2_b* instructions on a
1669     // misaligned data which is faster than a pair of ds_read_b*/ds_write_b*
1670     // which would be equally misaligned.
1671     // This is only used by the common passes, selection always calls the
1672     // allowsMisalignedMemoryAccessesImpl version.
1673     *IsFast = true;
1674   }
1675 
1676   return Allow;
1677 }
1678 
1679 EVT SITargetLowering::getOptimalMemOpType(
1680     const MemOp &Op, const AttributeList &FuncAttributes) const {
1681   // FIXME: Should account for address space here.
1682 
1683   // The default fallback uses the private pointer size as a guess for a type to
1684   // use. Make sure we switch these to 64-bit accesses.
1685 
1686   if (Op.size() >= 16 &&
1687       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1688     return MVT::v4i32;
1689 
1690   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1691     return MVT::v2i32;
1692 
1693   // Use the default.
1694   return MVT::Other;
1695 }
1696 
1697 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1698   const MemSDNode *MemNode = cast<MemSDNode>(N);
1699   return MemNode->getMemOperand()->getFlags() & MONoClobber;
1700 }
1701 
1702 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) {
1703   return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS ||
1704          AS == AMDGPUAS::PRIVATE_ADDRESS;
1705 }
1706 
1707 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1708                                            unsigned DestAS) const {
1709   // Flat -> private/local is a simple truncate.
1710   // Flat -> global is no-op
1711   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1712     return true;
1713 
1714   const GCNTargetMachine &TM =
1715       static_cast<const GCNTargetMachine &>(getTargetMachine());
1716   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1717 }
1718 
1719 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1720   const MemSDNode *MemNode = cast<MemSDNode>(N);
1721 
1722   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1723 }
1724 
1725 TargetLoweringBase::LegalizeTypeAction
1726 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1727   if (!VT.isScalableVector() && VT.getVectorNumElements() != 1 &&
1728       VT.getScalarType().bitsLE(MVT::i16))
1729     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1730   return TargetLoweringBase::getPreferredVectorAction(VT);
1731 }
1732 
1733 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1734                                                          Type *Ty) const {
1735   // FIXME: Could be smarter if called for vector constants.
1736   return true;
1737 }
1738 
1739 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1740   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1741     switch (Op) {
1742     case ISD::LOAD:
1743     case ISD::STORE:
1744 
1745     // These operations are done with 32-bit instructions anyway.
1746     case ISD::AND:
1747     case ISD::OR:
1748     case ISD::XOR:
1749     case ISD::SELECT:
1750       // TODO: Extensions?
1751       return true;
1752     default:
1753       return false;
1754     }
1755   }
1756 
1757   // SimplifySetCC uses this function to determine whether or not it should
1758   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1759   if (VT == MVT::i1 && Op == ISD::SETCC)
1760     return false;
1761 
1762   return TargetLowering::isTypeDesirableForOp(Op, VT);
1763 }
1764 
1765 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1766                                                    const SDLoc &SL,
1767                                                    SDValue Chain,
1768                                                    uint64_t Offset) const {
1769   const DataLayout &DL = DAG.getDataLayout();
1770   MachineFunction &MF = DAG.getMachineFunction();
1771   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1772 
1773   const ArgDescriptor *InputPtrReg;
1774   const TargetRegisterClass *RC;
1775   LLT ArgTy;
1776   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1777 
1778   std::tie(InputPtrReg, RC, ArgTy) =
1779       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1780 
1781   // We may not have the kernarg segment argument if we have no kernel
1782   // arguments.
1783   if (!InputPtrReg)
1784     return DAG.getConstant(0, SL, PtrVT);
1785 
1786   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1787   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1788     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1789 
1790   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1791 }
1792 
1793 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1794                                             const SDLoc &SL) const {
1795   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1796                                                FIRST_IMPLICIT);
1797   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1798 }
1799 
1800 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1801                                          const SDLoc &SL, SDValue Val,
1802                                          bool Signed,
1803                                          const ISD::InputArg *Arg) const {
1804   // First, if it is a widened vector, narrow it.
1805   if (VT.isVector() &&
1806       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1807     EVT NarrowedVT =
1808         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1809                          VT.getVectorNumElements());
1810     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1811                       DAG.getConstant(0, SL, MVT::i32));
1812   }
1813 
1814   // Then convert the vector elements or scalar value.
1815   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1816       VT.bitsLT(MemVT)) {
1817     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1818     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1819   }
1820 
1821   if (MemVT.isFloatingPoint())
1822     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1823   else if (Signed)
1824     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1825   else
1826     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1827 
1828   return Val;
1829 }
1830 
1831 SDValue SITargetLowering::lowerKernargMemParameter(
1832     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1833     uint64_t Offset, Align Alignment, bool Signed,
1834     const ISD::InputArg *Arg) const {
1835   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1836 
1837   // Try to avoid using an extload by loading earlier than the argument address,
1838   // and extracting the relevant bits. The load should hopefully be merged with
1839   // the previous argument.
1840   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1841     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1842     int64_t AlignDownOffset = alignDown(Offset, 4);
1843     int64_t OffsetDiff = Offset - AlignDownOffset;
1844 
1845     EVT IntVT = MemVT.changeTypeToInteger();
1846 
1847     // TODO: If we passed in the base kernel offset we could have a better
1848     // alignment than 4, but we don't really need it.
1849     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1850     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1851                                MachineMemOperand::MODereferenceable |
1852                                    MachineMemOperand::MOInvariant);
1853 
1854     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1855     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1856 
1857     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1858     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1859     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1860 
1861 
1862     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1863   }
1864 
1865   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1866   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1867                              MachineMemOperand::MODereferenceable |
1868                                  MachineMemOperand::MOInvariant);
1869 
1870   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1871   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1872 }
1873 
1874 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1875                                               const SDLoc &SL, SDValue Chain,
1876                                               const ISD::InputArg &Arg) const {
1877   MachineFunction &MF = DAG.getMachineFunction();
1878   MachineFrameInfo &MFI = MF.getFrameInfo();
1879 
1880   if (Arg.Flags.isByVal()) {
1881     unsigned Size = Arg.Flags.getByValSize();
1882     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1883     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1884   }
1885 
1886   unsigned ArgOffset = VA.getLocMemOffset();
1887   unsigned ArgSize = VA.getValVT().getStoreSize();
1888 
1889   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1890 
1891   // Create load nodes to retrieve arguments from the stack.
1892   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1893   SDValue ArgValue;
1894 
1895   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1896   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1897   MVT MemVT = VA.getValVT();
1898 
1899   switch (VA.getLocInfo()) {
1900   default:
1901     break;
1902   case CCValAssign::BCvt:
1903     MemVT = VA.getLocVT();
1904     break;
1905   case CCValAssign::SExt:
1906     ExtType = ISD::SEXTLOAD;
1907     break;
1908   case CCValAssign::ZExt:
1909     ExtType = ISD::ZEXTLOAD;
1910     break;
1911   case CCValAssign::AExt:
1912     ExtType = ISD::EXTLOAD;
1913     break;
1914   }
1915 
1916   ArgValue = DAG.getExtLoad(
1917     ExtType, SL, VA.getLocVT(), Chain, FIN,
1918     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1919     MemVT);
1920   return ArgValue;
1921 }
1922 
1923 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1924   const SIMachineFunctionInfo &MFI,
1925   EVT VT,
1926   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1927   const ArgDescriptor *Reg;
1928   const TargetRegisterClass *RC;
1929   LLT Ty;
1930 
1931   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1932   if (!Reg) {
1933     if (PVID == AMDGPUFunctionArgInfo::PreloadedValue::KERNARG_SEGMENT_PTR) {
1934       // It's possible for a kernarg intrinsic call to appear in a kernel with
1935       // no allocated segment, in which case we do not add the user sgpr
1936       // argument, so just return null.
1937       return DAG.getConstant(0, SDLoc(), VT);
1938     }
1939 
1940     // It's undefined behavior if a function marked with the amdgpu-no-*
1941     // attributes uses the corresponding intrinsic.
1942     return DAG.getUNDEF(VT);
1943   }
1944 
1945   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1946 }
1947 
1948 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1949                                CallingConv::ID CallConv,
1950                                ArrayRef<ISD::InputArg> Ins, BitVector &Skipped,
1951                                FunctionType *FType,
1952                                SIMachineFunctionInfo *Info) {
1953   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1954     const ISD::InputArg *Arg = &Ins[I];
1955 
1956     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1957            "vector type argument should have been split");
1958 
1959     // First check if it's a PS input addr.
1960     if (CallConv == CallingConv::AMDGPU_PS &&
1961         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1962       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1963 
1964       // Inconveniently only the first part of the split is marked as isSplit,
1965       // so skip to the end. We only want to increment PSInputNum once for the
1966       // entire split argument.
1967       if (Arg->Flags.isSplit()) {
1968         while (!Arg->Flags.isSplitEnd()) {
1969           assert((!Arg->VT.isVector() ||
1970                   Arg->VT.getScalarSizeInBits() == 16) &&
1971                  "unexpected vector split in ps argument type");
1972           if (!SkipArg)
1973             Splits.push_back(*Arg);
1974           Arg = &Ins[++I];
1975         }
1976       }
1977 
1978       if (SkipArg) {
1979         // We can safely skip PS inputs.
1980         Skipped.set(Arg->getOrigArgIndex());
1981         ++PSInputNum;
1982         continue;
1983       }
1984 
1985       Info->markPSInputAllocated(PSInputNum);
1986       if (Arg->Used)
1987         Info->markPSInputEnabled(PSInputNum);
1988 
1989       ++PSInputNum;
1990     }
1991 
1992     Splits.push_back(*Arg);
1993   }
1994 }
1995 
1996 // Allocate special inputs passed in VGPRs.
1997 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1998                                                       MachineFunction &MF,
1999                                                       const SIRegisterInfo &TRI,
2000                                                       SIMachineFunctionInfo &Info) const {
2001   const LLT S32 = LLT::scalar(32);
2002   MachineRegisterInfo &MRI = MF.getRegInfo();
2003 
2004   if (Info.hasWorkItemIDX()) {
2005     Register Reg = AMDGPU::VGPR0;
2006     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
2007 
2008     CCInfo.AllocateReg(Reg);
2009     unsigned Mask = (Subtarget->hasPackedTID() &&
2010                      Info.hasWorkItemIDY()) ? 0x3ff : ~0u;
2011     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2012   }
2013 
2014   if (Info.hasWorkItemIDY()) {
2015     assert(Info.hasWorkItemIDX());
2016     if (Subtarget->hasPackedTID()) {
2017       Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0,
2018                                                         0x3ff << 10));
2019     } else {
2020       unsigned Reg = AMDGPU::VGPR1;
2021       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
2022 
2023       CCInfo.AllocateReg(Reg);
2024       Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
2025     }
2026   }
2027 
2028   if (Info.hasWorkItemIDZ()) {
2029     assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY());
2030     if (Subtarget->hasPackedTID()) {
2031       Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0,
2032                                                         0x3ff << 20));
2033     } else {
2034       unsigned Reg = AMDGPU::VGPR2;
2035       MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
2036 
2037       CCInfo.AllocateReg(Reg);
2038       Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
2039     }
2040   }
2041 }
2042 
2043 // Try to allocate a VGPR at the end of the argument list, or if no argument
2044 // VGPRs are left allocating a stack slot.
2045 // If \p Mask is is given it indicates bitfield position in the register.
2046 // If \p Arg is given use it with new ]p Mask instead of allocating new.
2047 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
2048                                          ArgDescriptor Arg = ArgDescriptor()) {
2049   if (Arg.isSet())
2050     return ArgDescriptor::createArg(Arg, Mask);
2051 
2052   ArrayRef<MCPhysReg> ArgVGPRs
2053     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
2054   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
2055   if (RegIdx == ArgVGPRs.size()) {
2056     // Spill to stack required.
2057     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
2058 
2059     return ArgDescriptor::createStack(Offset, Mask);
2060   }
2061 
2062   unsigned Reg = ArgVGPRs[RegIdx];
2063   Reg = CCInfo.AllocateReg(Reg);
2064   assert(Reg != AMDGPU::NoRegister);
2065 
2066   MachineFunction &MF = CCInfo.getMachineFunction();
2067   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
2068   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
2069   return ArgDescriptor::createRegister(Reg, Mask);
2070 }
2071 
2072 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
2073                                              const TargetRegisterClass *RC,
2074                                              unsigned NumArgRegs) {
2075   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
2076   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
2077   if (RegIdx == ArgSGPRs.size())
2078     report_fatal_error("ran out of SGPRs for arguments");
2079 
2080   unsigned Reg = ArgSGPRs[RegIdx];
2081   Reg = CCInfo.AllocateReg(Reg);
2082   assert(Reg != AMDGPU::NoRegister);
2083 
2084   MachineFunction &MF = CCInfo.getMachineFunction();
2085   MF.addLiveIn(Reg, RC);
2086   return ArgDescriptor::createRegister(Reg);
2087 }
2088 
2089 // If this has a fixed position, we still should allocate the register in the
2090 // CCInfo state. Technically we could get away with this for values passed
2091 // outside of the normal argument range.
2092 static void allocateFixedSGPRInputImpl(CCState &CCInfo,
2093                                        const TargetRegisterClass *RC,
2094                                        MCRegister Reg) {
2095   Reg = CCInfo.AllocateReg(Reg);
2096   assert(Reg != AMDGPU::NoRegister);
2097   MachineFunction &MF = CCInfo.getMachineFunction();
2098   MF.addLiveIn(Reg, RC);
2099 }
2100 
2101 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) {
2102   if (Arg) {
2103     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass,
2104                                Arg.getRegister());
2105   } else
2106     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
2107 }
2108 
2109 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) {
2110   if (Arg) {
2111     allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass,
2112                                Arg.getRegister());
2113   } else
2114     Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
2115 }
2116 
2117 /// Allocate implicit function VGPR arguments at the end of allocated user
2118 /// arguments.
2119 void SITargetLowering::allocateSpecialInputVGPRs(
2120   CCState &CCInfo, MachineFunction &MF,
2121   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2122   const unsigned Mask = 0x3ff;
2123   ArgDescriptor Arg;
2124 
2125   if (Info.hasWorkItemIDX()) {
2126     Arg = allocateVGPR32Input(CCInfo, Mask);
2127     Info.setWorkItemIDX(Arg);
2128   }
2129 
2130   if (Info.hasWorkItemIDY()) {
2131     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
2132     Info.setWorkItemIDY(Arg);
2133   }
2134 
2135   if (Info.hasWorkItemIDZ())
2136     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
2137 }
2138 
2139 /// Allocate implicit function VGPR arguments in fixed registers.
2140 void SITargetLowering::allocateSpecialInputVGPRsFixed(
2141   CCState &CCInfo, MachineFunction &MF,
2142   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
2143   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
2144   if (!Reg)
2145     report_fatal_error("failed to allocated VGPR for implicit arguments");
2146 
2147   const unsigned Mask = 0x3ff;
2148   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
2149   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
2150   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
2151 }
2152 
2153 void SITargetLowering::allocateSpecialInputSGPRs(
2154   CCState &CCInfo,
2155   MachineFunction &MF,
2156   const SIRegisterInfo &TRI,
2157   SIMachineFunctionInfo &Info) const {
2158   auto &ArgInfo = Info.getArgInfo();
2159 
2160   // TODO: Unify handling with private memory pointers.
2161   if (Info.hasDispatchPtr())
2162     allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr);
2163 
2164   if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5)
2165     allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr);
2166 
2167   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
2168   // constant offset from the kernarg segment.
2169   if (Info.hasImplicitArgPtr())
2170     allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr);
2171 
2172   if (Info.hasDispatchID())
2173     allocateSGPR64Input(CCInfo, ArgInfo.DispatchID);
2174 
2175   // flat_scratch_init is not applicable for non-kernel functions.
2176 
2177   if (Info.hasWorkGroupIDX())
2178     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX);
2179 
2180   if (Info.hasWorkGroupIDY())
2181     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY);
2182 
2183   if (Info.hasWorkGroupIDZ())
2184     allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ);
2185 }
2186 
2187 // Allocate special inputs passed in user SGPRs.
2188 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
2189                                             MachineFunction &MF,
2190                                             const SIRegisterInfo &TRI,
2191                                             SIMachineFunctionInfo &Info) const {
2192   if (Info.hasImplicitBufferPtr()) {
2193     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
2194     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
2195     CCInfo.AllocateReg(ImplicitBufferPtrReg);
2196   }
2197 
2198   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2199   if (Info.hasPrivateSegmentBuffer()) {
2200     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2201     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2202     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2203   }
2204 
2205   if (Info.hasDispatchPtr()) {
2206     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2207     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2208     CCInfo.AllocateReg(DispatchPtrReg);
2209   }
2210 
2211   if (Info.hasQueuePtr() && AMDGPU::getAmdhsaCodeObjectVersion() < 5) {
2212     Register QueuePtrReg = Info.addQueuePtr(TRI);
2213     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2214     CCInfo.AllocateReg(QueuePtrReg);
2215   }
2216 
2217   if (Info.hasKernargSegmentPtr()) {
2218     MachineRegisterInfo &MRI = MF.getRegInfo();
2219     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2220     CCInfo.AllocateReg(InputPtrReg);
2221 
2222     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2223     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2224   }
2225 
2226   if (Info.hasDispatchID()) {
2227     Register DispatchIDReg = Info.addDispatchID(TRI);
2228     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2229     CCInfo.AllocateReg(DispatchIDReg);
2230   }
2231 
2232   if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) {
2233     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2234     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2235     CCInfo.AllocateReg(FlatScratchInitReg);
2236   }
2237 
2238   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2239   // these from the dispatch pointer.
2240 }
2241 
2242 // Allocate special input registers that are initialized per-wave.
2243 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2244                                            MachineFunction &MF,
2245                                            SIMachineFunctionInfo &Info,
2246                                            CallingConv::ID CallConv,
2247                                            bool IsShader) const {
2248   if (Info.hasWorkGroupIDX()) {
2249     Register Reg = Info.addWorkGroupIDX();
2250     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2251     CCInfo.AllocateReg(Reg);
2252   }
2253 
2254   if (Info.hasWorkGroupIDY()) {
2255     Register Reg = Info.addWorkGroupIDY();
2256     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2257     CCInfo.AllocateReg(Reg);
2258   }
2259 
2260   if (Info.hasWorkGroupIDZ()) {
2261     Register Reg = Info.addWorkGroupIDZ();
2262     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2263     CCInfo.AllocateReg(Reg);
2264   }
2265 
2266   if (Info.hasWorkGroupInfo()) {
2267     Register Reg = Info.addWorkGroupInfo();
2268     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2269     CCInfo.AllocateReg(Reg);
2270   }
2271 
2272   if (Info.hasPrivateSegmentWaveByteOffset()) {
2273     // Scratch wave offset passed in system SGPR.
2274     unsigned PrivateSegmentWaveByteOffsetReg;
2275 
2276     if (IsShader) {
2277       PrivateSegmentWaveByteOffsetReg =
2278         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2279 
2280       // This is true if the scratch wave byte offset doesn't have a fixed
2281       // location.
2282       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2283         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2284         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2285       }
2286     } else
2287       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2288 
2289     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2290     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2291   }
2292 }
2293 
2294 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2295                                      MachineFunction &MF,
2296                                      const SIRegisterInfo &TRI,
2297                                      SIMachineFunctionInfo &Info) {
2298   // Now that we've figured out where the scratch register inputs are, see if
2299   // should reserve the arguments and use them directly.
2300   MachineFrameInfo &MFI = MF.getFrameInfo();
2301   bool HasStackObjects = MFI.hasStackObjects();
2302   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2303 
2304   // Record that we know we have non-spill stack objects so we don't need to
2305   // check all stack objects later.
2306   if (HasStackObjects)
2307     Info.setHasNonSpillStackObjects(true);
2308 
2309   // Everything live out of a block is spilled with fast regalloc, so it's
2310   // almost certain that spilling will be required.
2311   if (TM.getOptLevel() == CodeGenOpt::None)
2312     HasStackObjects = true;
2313 
2314   // For now assume stack access is needed in any callee functions, so we need
2315   // the scratch registers to pass in.
2316   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2317 
2318   if (!ST.enableFlatScratch()) {
2319     if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2320       // If we have stack objects, we unquestionably need the private buffer
2321       // resource. For the Code Object V2 ABI, this will be the first 4 user
2322       // SGPR inputs. We can reserve those and use them directly.
2323 
2324       Register PrivateSegmentBufferReg =
2325           Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2326       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2327     } else {
2328       unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2329       // We tentatively reserve the last registers (skipping the last registers
2330       // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2331       // we'll replace these with the ones immediately after those which were
2332       // really allocated. In the prologue copies will be inserted from the
2333       // argument to these reserved registers.
2334 
2335       // Without HSA, relocations are used for the scratch pointer and the
2336       // buffer resource setup is always inserted in the prologue. Scratch wave
2337       // offset is still in an input SGPR.
2338       Info.setScratchRSrcReg(ReservedBufferReg);
2339     }
2340   }
2341 
2342   MachineRegisterInfo &MRI = MF.getRegInfo();
2343 
2344   // For entry functions we have to set up the stack pointer if we use it,
2345   // whereas non-entry functions get this "for free". This means there is no
2346   // intrinsic advantage to using S32 over S34 in cases where we do not have
2347   // calls but do need a frame pointer (i.e. if we are requested to have one
2348   // because frame pointer elimination is disabled). To keep things simple we
2349   // only ever use S32 as the call ABI stack pointer, and so using it does not
2350   // imply we need a separate frame pointer.
2351   //
2352   // Try to use s32 as the SP, but move it if it would interfere with input
2353   // arguments. This won't work with calls though.
2354   //
2355   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2356   // registers.
2357   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2358     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2359   } else {
2360     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2361 
2362     if (MFI.hasCalls())
2363       report_fatal_error("call in graphics shader with too many input SGPRs");
2364 
2365     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2366       if (!MRI.isLiveIn(Reg)) {
2367         Info.setStackPtrOffsetReg(Reg);
2368         break;
2369       }
2370     }
2371 
2372     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2373       report_fatal_error("failed to find register for SP");
2374   }
2375 
2376   // hasFP should be accurate for entry functions even before the frame is
2377   // finalized, because it does not rely on the known stack size, only
2378   // properties like whether variable sized objects are present.
2379   if (ST.getFrameLowering()->hasFP(MF)) {
2380     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2381   }
2382 }
2383 
2384 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2385   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2386   return !Info->isEntryFunction();
2387 }
2388 
2389 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2390 
2391 }
2392 
2393 void SITargetLowering::insertCopiesSplitCSR(
2394   MachineBasicBlock *Entry,
2395   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2396   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2397 
2398   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2399   if (!IStart)
2400     return;
2401 
2402   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2403   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2404   MachineBasicBlock::iterator MBBI = Entry->begin();
2405   for (const MCPhysReg *I = IStart; *I; ++I) {
2406     const TargetRegisterClass *RC = nullptr;
2407     if (AMDGPU::SReg_64RegClass.contains(*I))
2408       RC = &AMDGPU::SGPR_64RegClass;
2409     else if (AMDGPU::SReg_32RegClass.contains(*I))
2410       RC = &AMDGPU::SGPR_32RegClass;
2411     else
2412       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2413 
2414     Register NewVR = MRI->createVirtualRegister(RC);
2415     // Create copy from CSR to a virtual register.
2416     Entry->addLiveIn(*I);
2417     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2418       .addReg(*I);
2419 
2420     // Insert the copy-back instructions right before the terminator.
2421     for (auto *Exit : Exits)
2422       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2423               TII->get(TargetOpcode::COPY), *I)
2424         .addReg(NewVR);
2425   }
2426 }
2427 
2428 SDValue SITargetLowering::LowerFormalArguments(
2429     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2430     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2431     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2432   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2433 
2434   MachineFunction &MF = DAG.getMachineFunction();
2435   const Function &Fn = MF.getFunction();
2436   FunctionType *FType = MF.getFunction().getFunctionType();
2437   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2438 
2439   if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) {
2440     DiagnosticInfoUnsupported NoGraphicsHSA(
2441         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2442     DAG.getContext()->diagnose(NoGraphicsHSA);
2443     return DAG.getEntryNode();
2444   }
2445 
2446   Info->allocateModuleLDSGlobal(Fn.getParent());
2447 
2448   SmallVector<ISD::InputArg, 16> Splits;
2449   SmallVector<CCValAssign, 16> ArgLocs;
2450   BitVector Skipped(Ins.size());
2451   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2452                  *DAG.getContext());
2453 
2454   bool IsGraphics = AMDGPU::isGraphics(CallConv);
2455   bool IsKernel = AMDGPU::isKernel(CallConv);
2456   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2457 
2458   if (IsGraphics) {
2459     assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() &&
2460            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2461            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2462            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2463            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2464            !Info->hasWorkItemIDZ());
2465   }
2466 
2467   if (CallConv == CallingConv::AMDGPU_PS) {
2468     processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2469 
2470     // At least one interpolation mode must be enabled or else the GPU will
2471     // hang.
2472     //
2473     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2474     // set PSInputAddr, the user wants to enable some bits after the compilation
2475     // based on run-time states. Since we can't know what the final PSInputEna
2476     // will look like, so we shouldn't do anything here and the user should take
2477     // responsibility for the correct programming.
2478     //
2479     // Otherwise, the following restrictions apply:
2480     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2481     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2482     //   enabled too.
2483     if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2484         ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) {
2485       CCInfo.AllocateReg(AMDGPU::VGPR0);
2486       CCInfo.AllocateReg(AMDGPU::VGPR1);
2487       Info->markPSInputAllocated(0);
2488       Info->markPSInputEnabled(0);
2489     }
2490     if (Subtarget->isAmdPalOS()) {
2491       // For isAmdPalOS, the user does not enable some bits after compilation
2492       // based on run-time states; the register values being generated here are
2493       // the final ones set in hardware. Therefore we need to apply the
2494       // workaround to PSInputAddr and PSInputEnable together.  (The case where
2495       // a bit is set in PSInputAddr but not PSInputEnable is where the
2496       // frontend set up an input arg for a particular interpolation mode, but
2497       // nothing uses that input arg. Really we should have an earlier pass
2498       // that removes such an arg.)
2499       unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2500       if ((PsInputBits & 0x7F) == 0 ||
2501           ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1)))
2502         Info->markPSInputEnabled(
2503             countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2504     }
2505   } else if (IsKernel) {
2506     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2507   } else {
2508     Splits.append(Ins.begin(), Ins.end());
2509   }
2510 
2511   if (IsEntryFunc) {
2512     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2513     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2514   } else if (!IsGraphics) {
2515     // For the fixed ABI, pass workitem IDs in the last argument register.
2516     allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2517   }
2518 
2519   if (IsKernel) {
2520     analyzeFormalArgumentsCompute(CCInfo, Ins);
2521   } else {
2522     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2523     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2524   }
2525 
2526   SmallVector<SDValue, 16> Chains;
2527 
2528   // FIXME: This is the minimum kernel argument alignment. We should improve
2529   // this to the maximum alignment of the arguments.
2530   //
2531   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2532   // kern arg offset.
2533   const Align KernelArgBaseAlign = Align(16);
2534 
2535   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2536     const ISD::InputArg &Arg = Ins[i];
2537     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2538       InVals.push_back(DAG.getUNDEF(Arg.VT));
2539       continue;
2540     }
2541 
2542     CCValAssign &VA = ArgLocs[ArgIdx++];
2543     MVT VT = VA.getLocVT();
2544 
2545     if (IsEntryFunc && VA.isMemLoc()) {
2546       VT = Ins[i].VT;
2547       EVT MemVT = VA.getLocVT();
2548 
2549       const uint64_t Offset = VA.getLocMemOffset();
2550       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2551 
2552       if (Arg.Flags.isByRef()) {
2553         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2554 
2555         const GCNTargetMachine &TM =
2556             static_cast<const GCNTargetMachine &>(getTargetMachine());
2557         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2558                                     Arg.Flags.getPointerAddrSpace())) {
2559           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2560                                      Arg.Flags.getPointerAddrSpace());
2561         }
2562 
2563         InVals.push_back(Ptr);
2564         continue;
2565       }
2566 
2567       SDValue Arg = lowerKernargMemParameter(
2568         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2569       Chains.push_back(Arg.getValue(1));
2570 
2571       auto *ParamTy =
2572         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2573       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2574           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2575                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2576         // On SI local pointers are just offsets into LDS, so they are always
2577         // less than 16-bits.  On CI and newer they could potentially be
2578         // real pointers, so we can't guarantee their size.
2579         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2580                           DAG.getValueType(MVT::i16));
2581       }
2582 
2583       InVals.push_back(Arg);
2584       continue;
2585     } else if (!IsEntryFunc && VA.isMemLoc()) {
2586       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2587       InVals.push_back(Val);
2588       if (!Arg.Flags.isByVal())
2589         Chains.push_back(Val.getValue(1));
2590       continue;
2591     }
2592 
2593     assert(VA.isRegLoc() && "Parameter must be in a register!");
2594 
2595     Register Reg = VA.getLocReg();
2596     const TargetRegisterClass *RC = nullptr;
2597     if (AMDGPU::VGPR_32RegClass.contains(Reg))
2598       RC = &AMDGPU::VGPR_32RegClass;
2599     else if (AMDGPU::SGPR_32RegClass.contains(Reg))
2600       RC = &AMDGPU::SGPR_32RegClass;
2601     else
2602       llvm_unreachable("Unexpected register class in LowerFormalArguments!");
2603     EVT ValVT = VA.getValVT();
2604 
2605     Reg = MF.addLiveIn(Reg, RC);
2606     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2607 
2608     if (Arg.Flags.isSRet()) {
2609       // The return object should be reasonably addressable.
2610 
2611       // FIXME: This helps when the return is a real sret. If it is a
2612       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2613       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2614       unsigned NumBits
2615         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2616       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2617         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2618     }
2619 
2620     // If this is an 8 or 16-bit value, it is really passed promoted
2621     // to 32 bits. Insert an assert[sz]ext to capture this, then
2622     // truncate to the right size.
2623     switch (VA.getLocInfo()) {
2624     case CCValAssign::Full:
2625       break;
2626     case CCValAssign::BCvt:
2627       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2628       break;
2629     case CCValAssign::SExt:
2630       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2631                         DAG.getValueType(ValVT));
2632       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2633       break;
2634     case CCValAssign::ZExt:
2635       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2636                         DAG.getValueType(ValVT));
2637       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2638       break;
2639     case CCValAssign::AExt:
2640       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2641       break;
2642     default:
2643       llvm_unreachable("Unknown loc info!");
2644     }
2645 
2646     InVals.push_back(Val);
2647   }
2648 
2649   // Start adding system SGPRs.
2650   if (IsEntryFunc) {
2651     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics);
2652   } else {
2653     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2654     if (!IsGraphics)
2655       allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2656   }
2657 
2658   auto &ArgUsageInfo =
2659     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2660   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2661 
2662   unsigned StackArgSize = CCInfo.getNextStackOffset();
2663   Info->setBytesInStackArgArea(StackArgSize);
2664 
2665   return Chains.empty() ? Chain :
2666     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2667 }
2668 
2669 // TODO: If return values can't fit in registers, we should return as many as
2670 // possible in registers before passing on stack.
2671 bool SITargetLowering::CanLowerReturn(
2672   CallingConv::ID CallConv,
2673   MachineFunction &MF, bool IsVarArg,
2674   const SmallVectorImpl<ISD::OutputArg> &Outs,
2675   LLVMContext &Context) const {
2676   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2677   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2678   // for shaders. Vector types should be explicitly handled by CC.
2679   if (AMDGPU::isEntryFunctionCC(CallConv))
2680     return true;
2681 
2682   SmallVector<CCValAssign, 16> RVLocs;
2683   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2684   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2685 }
2686 
2687 SDValue
2688 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2689                               bool isVarArg,
2690                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2691                               const SmallVectorImpl<SDValue> &OutVals,
2692                               const SDLoc &DL, SelectionDAG &DAG) const {
2693   MachineFunction &MF = DAG.getMachineFunction();
2694   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2695 
2696   if (AMDGPU::isKernel(CallConv)) {
2697     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2698                                              OutVals, DL, DAG);
2699   }
2700 
2701   bool IsShader = AMDGPU::isShader(CallConv);
2702 
2703   Info->setIfReturnsVoid(Outs.empty());
2704   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2705 
2706   // CCValAssign - represent the assignment of the return value to a location.
2707   SmallVector<CCValAssign, 48> RVLocs;
2708   SmallVector<ISD::OutputArg, 48> Splits;
2709 
2710   // CCState - Info about the registers and stack slots.
2711   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2712                  *DAG.getContext());
2713 
2714   // Analyze outgoing return values.
2715   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2716 
2717   SDValue Flag;
2718   SmallVector<SDValue, 48> RetOps;
2719   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2720 
2721   // Copy the result values into the output registers.
2722   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2723        ++I, ++RealRVLocIdx) {
2724     CCValAssign &VA = RVLocs[I];
2725     assert(VA.isRegLoc() && "Can only return in registers!");
2726     // TODO: Partially return in registers if return values don't fit.
2727     SDValue Arg = OutVals[RealRVLocIdx];
2728 
2729     // Copied from other backends.
2730     switch (VA.getLocInfo()) {
2731     case CCValAssign::Full:
2732       break;
2733     case CCValAssign::BCvt:
2734       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2735       break;
2736     case CCValAssign::SExt:
2737       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2738       break;
2739     case CCValAssign::ZExt:
2740       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2741       break;
2742     case CCValAssign::AExt:
2743       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2744       break;
2745     default:
2746       llvm_unreachable("Unknown loc info!");
2747     }
2748 
2749     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2750     Flag = Chain.getValue(1);
2751     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2752   }
2753 
2754   // FIXME: Does sret work properly?
2755   if (!Info->isEntryFunction()) {
2756     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2757     const MCPhysReg *I =
2758       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2759     if (I) {
2760       for (; *I; ++I) {
2761         if (AMDGPU::SReg_64RegClass.contains(*I))
2762           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2763         else if (AMDGPU::SReg_32RegClass.contains(*I))
2764           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2765         else
2766           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2767       }
2768     }
2769   }
2770 
2771   // Update chain and glue.
2772   RetOps[0] = Chain;
2773   if (Flag.getNode())
2774     RetOps.push_back(Flag);
2775 
2776   unsigned Opc = AMDGPUISD::ENDPGM;
2777   if (!IsWaveEnd)
2778     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2779   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2780 }
2781 
2782 SDValue SITargetLowering::LowerCallResult(
2783     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2784     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2785     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2786     SDValue ThisVal) const {
2787   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2788 
2789   // Assign locations to each value returned by this call.
2790   SmallVector<CCValAssign, 16> RVLocs;
2791   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2792                  *DAG.getContext());
2793   CCInfo.AnalyzeCallResult(Ins, RetCC);
2794 
2795   // Copy all of the result registers out of their specified physreg.
2796   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2797     CCValAssign VA = RVLocs[i];
2798     SDValue Val;
2799 
2800     if (VA.isRegLoc()) {
2801       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2802       Chain = Val.getValue(1);
2803       InFlag = Val.getValue(2);
2804     } else if (VA.isMemLoc()) {
2805       report_fatal_error("TODO: return values in memory");
2806     } else
2807       llvm_unreachable("unknown argument location type");
2808 
2809     switch (VA.getLocInfo()) {
2810     case CCValAssign::Full:
2811       break;
2812     case CCValAssign::BCvt:
2813       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2814       break;
2815     case CCValAssign::ZExt:
2816       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2817                         DAG.getValueType(VA.getValVT()));
2818       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2819       break;
2820     case CCValAssign::SExt:
2821       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2822                         DAG.getValueType(VA.getValVT()));
2823       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2824       break;
2825     case CCValAssign::AExt:
2826       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2827       break;
2828     default:
2829       llvm_unreachable("Unknown loc info!");
2830     }
2831 
2832     InVals.push_back(Val);
2833   }
2834 
2835   return Chain;
2836 }
2837 
2838 // Add code to pass special inputs required depending on used features separate
2839 // from the explicit user arguments present in the IR.
2840 void SITargetLowering::passSpecialInputs(
2841     CallLoweringInfo &CLI,
2842     CCState &CCInfo,
2843     const SIMachineFunctionInfo &Info,
2844     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2845     SmallVectorImpl<SDValue> &MemOpChains,
2846     SDValue Chain) const {
2847   // If we don't have a call site, this was a call inserted by
2848   // legalization. These can never use special inputs.
2849   if (!CLI.CB)
2850     return;
2851 
2852   SelectionDAG &DAG = CLI.DAG;
2853   const SDLoc &DL = CLI.DL;
2854   const Function &F = DAG.getMachineFunction().getFunction();
2855 
2856   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2857   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2858 
2859   const AMDGPUFunctionArgInfo *CalleeArgInfo
2860     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2861   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2862     auto &ArgUsageInfo =
2863       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2864     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2865   }
2866 
2867   // TODO: Unify with private memory register handling. This is complicated by
2868   // the fact that at least in kernels, the input argument is not necessarily
2869   // in the same location as the input.
2870   static constexpr std::pair<AMDGPUFunctionArgInfo::PreloadedValue,
2871                              StringLiteral> ImplicitAttrs[] = {
2872     {AMDGPUFunctionArgInfo::DISPATCH_PTR, "amdgpu-no-dispatch-ptr"},
2873     {AMDGPUFunctionArgInfo::QUEUE_PTR, "amdgpu-no-queue-ptr" },
2874     {AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, "amdgpu-no-implicitarg-ptr"},
2875     {AMDGPUFunctionArgInfo::DISPATCH_ID, "amdgpu-no-dispatch-id"},
2876     {AMDGPUFunctionArgInfo::WORKGROUP_ID_X, "amdgpu-no-workgroup-id-x"},
2877     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,"amdgpu-no-workgroup-id-y"},
2878     {AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,"amdgpu-no-workgroup-id-z"}
2879   };
2880 
2881   for (auto Attr : ImplicitAttrs) {
2882     const ArgDescriptor *OutgoingArg;
2883     const TargetRegisterClass *ArgRC;
2884     LLT ArgTy;
2885 
2886     AMDGPUFunctionArgInfo::PreloadedValue InputID = Attr.first;
2887 
2888     // If the callee does not use the attribute value, skip copying the value.
2889     if (CLI.CB->hasFnAttr(Attr.second))
2890       continue;
2891 
2892     std::tie(OutgoingArg, ArgRC, ArgTy) =
2893         CalleeArgInfo->getPreloadedValue(InputID);
2894     if (!OutgoingArg)
2895       continue;
2896 
2897     const ArgDescriptor *IncomingArg;
2898     const TargetRegisterClass *IncomingArgRC;
2899     LLT Ty;
2900     std::tie(IncomingArg, IncomingArgRC, Ty) =
2901         CallerArgInfo.getPreloadedValue(InputID);
2902     assert(IncomingArgRC == ArgRC);
2903 
2904     // All special arguments are ints for now.
2905     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2906     SDValue InputReg;
2907 
2908     if (IncomingArg) {
2909       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2910     } else if (InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR) {
2911       // The implicit arg ptr is special because it doesn't have a corresponding
2912       // input for kernels, and is computed from the kernarg segment pointer.
2913       InputReg = getImplicitArgPtr(DAG, DL);
2914     } else {
2915       // We may have proven the input wasn't needed, although the ABI is
2916       // requiring it. We just need to allocate the register appropriately.
2917       InputReg = DAG.getUNDEF(ArgVT);
2918     }
2919 
2920     if (OutgoingArg->isRegister()) {
2921       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2922       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2923         report_fatal_error("failed to allocate implicit input argument");
2924     } else {
2925       unsigned SpecialArgOffset =
2926           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2927       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2928                                               SpecialArgOffset);
2929       MemOpChains.push_back(ArgStore);
2930     }
2931   }
2932 
2933   // Pack workitem IDs into a single register or pass it as is if already
2934   // packed.
2935   const ArgDescriptor *OutgoingArg;
2936   const TargetRegisterClass *ArgRC;
2937   LLT Ty;
2938 
2939   std::tie(OutgoingArg, ArgRC, Ty) =
2940       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2941   if (!OutgoingArg)
2942     std::tie(OutgoingArg, ArgRC, Ty) =
2943         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2944   if (!OutgoingArg)
2945     std::tie(OutgoingArg, ArgRC, Ty) =
2946         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2947   if (!OutgoingArg)
2948     return;
2949 
2950   const ArgDescriptor *IncomingArgX = std::get<0>(
2951       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2952   const ArgDescriptor *IncomingArgY = std::get<0>(
2953       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2954   const ArgDescriptor *IncomingArgZ = std::get<0>(
2955       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2956 
2957   SDValue InputReg;
2958   SDLoc SL;
2959 
2960   const bool NeedWorkItemIDX = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-x");
2961   const bool NeedWorkItemIDY = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-y");
2962   const bool NeedWorkItemIDZ = !CLI.CB->hasFnAttr("amdgpu-no-workitem-id-z");
2963 
2964   // If incoming ids are not packed we need to pack them.
2965   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX &&
2966       NeedWorkItemIDX) {
2967     if (Subtarget->getMaxWorkitemID(F, 0) != 0) {
2968       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2969     } else {
2970       InputReg = DAG.getConstant(0, DL, MVT::i32);
2971     }
2972   }
2973 
2974   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY &&
2975       NeedWorkItemIDY && Subtarget->getMaxWorkitemID(F, 1) != 0) {
2976     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2977     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2978                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2979     InputReg = InputReg.getNode() ?
2980                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2981   }
2982 
2983   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ &&
2984       NeedWorkItemIDZ && Subtarget->getMaxWorkitemID(F, 2) != 0) {
2985     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2986     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2987                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2988     InputReg = InputReg.getNode() ?
2989                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2990   }
2991 
2992   if (!InputReg && (NeedWorkItemIDX || NeedWorkItemIDY || NeedWorkItemIDZ)) {
2993     if (!IncomingArgX && !IncomingArgY && !IncomingArgZ) {
2994       // We're in a situation where the outgoing function requires the workitem
2995       // ID, but the calling function does not have it (e.g a graphics function
2996       // calling a C calling convention function). This is illegal, but we need
2997       // to produce something.
2998       InputReg = DAG.getUNDEF(MVT::i32);
2999     } else {
3000       // Workitem ids are already packed, any of present incoming arguments
3001       // will carry all required fields.
3002       ArgDescriptor IncomingArg = ArgDescriptor::createArg(
3003         IncomingArgX ? *IncomingArgX :
3004         IncomingArgY ? *IncomingArgY :
3005         *IncomingArgZ, ~0u);
3006       InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
3007     }
3008   }
3009 
3010   if (OutgoingArg->isRegister()) {
3011     if (InputReg)
3012       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
3013 
3014     CCInfo.AllocateReg(OutgoingArg->getRegister());
3015   } else {
3016     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
3017     if (InputReg) {
3018       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
3019                                               SpecialArgOffset);
3020       MemOpChains.push_back(ArgStore);
3021     }
3022   }
3023 }
3024 
3025 static bool canGuaranteeTCO(CallingConv::ID CC) {
3026   return CC == CallingConv::Fast;
3027 }
3028 
3029 /// Return true if we might ever do TCO for calls with this calling convention.
3030 static bool mayTailCallThisCC(CallingConv::ID CC) {
3031   switch (CC) {
3032   case CallingConv::C:
3033   case CallingConv::AMDGPU_Gfx:
3034     return true;
3035   default:
3036     return canGuaranteeTCO(CC);
3037   }
3038 }
3039 
3040 bool SITargetLowering::isEligibleForTailCallOptimization(
3041     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
3042     const SmallVectorImpl<ISD::OutputArg> &Outs,
3043     const SmallVectorImpl<SDValue> &OutVals,
3044     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3045   if (!mayTailCallThisCC(CalleeCC))
3046     return false;
3047 
3048   // For a divergent call target, we need to do a waterfall loop over the
3049   // possible callees which precludes us from using a simple jump.
3050   if (Callee->isDivergent())
3051     return false;
3052 
3053   MachineFunction &MF = DAG.getMachineFunction();
3054   const Function &CallerF = MF.getFunction();
3055   CallingConv::ID CallerCC = CallerF.getCallingConv();
3056   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3057   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3058 
3059   // Kernels aren't callable, and don't have a live in return address so it
3060   // doesn't make sense to do a tail call with entry functions.
3061   if (!CallerPreserved)
3062     return false;
3063 
3064   bool CCMatch = CallerCC == CalleeCC;
3065 
3066   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3067     if (canGuaranteeTCO(CalleeCC) && CCMatch)
3068       return true;
3069     return false;
3070   }
3071 
3072   // TODO: Can we handle var args?
3073   if (IsVarArg)
3074     return false;
3075 
3076   for (const Argument &Arg : CallerF.args()) {
3077     if (Arg.hasByValAttr())
3078       return false;
3079   }
3080 
3081   LLVMContext &Ctx = *DAG.getContext();
3082 
3083   // Check that the call results are passed in the same way.
3084   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
3085                                   CCAssignFnForCall(CalleeCC, IsVarArg),
3086                                   CCAssignFnForCall(CallerCC, IsVarArg)))
3087     return false;
3088 
3089   // The callee has to preserve all registers the caller needs to preserve.
3090   if (!CCMatch) {
3091     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3092     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3093       return false;
3094   }
3095 
3096   // Nothing more to check if the callee is taking no arguments.
3097   if (Outs.empty())
3098     return true;
3099 
3100   SmallVector<CCValAssign, 16> ArgLocs;
3101   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
3102 
3103   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
3104 
3105   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
3106   // If the stack arguments for this call do not fit into our own save area then
3107   // the call cannot be made tail.
3108   // TODO: Is this really necessary?
3109   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3110     return false;
3111 
3112   const MachineRegisterInfo &MRI = MF.getRegInfo();
3113   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
3114 }
3115 
3116 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3117   if (!CI->isTailCall())
3118     return false;
3119 
3120   const Function *ParentFn = CI->getParent()->getParent();
3121   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
3122     return false;
3123   return true;
3124 }
3125 
3126 // The wave scratch offset register is used as the global base pointer.
3127 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
3128                                     SmallVectorImpl<SDValue> &InVals) const {
3129   SelectionDAG &DAG = CLI.DAG;
3130   const SDLoc &DL = CLI.DL;
3131   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3132   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3133   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3134   SDValue Chain = CLI.Chain;
3135   SDValue Callee = CLI.Callee;
3136   bool &IsTailCall = CLI.IsTailCall;
3137   CallingConv::ID CallConv = CLI.CallConv;
3138   bool IsVarArg = CLI.IsVarArg;
3139   bool IsSibCall = false;
3140   bool IsThisReturn = false;
3141   MachineFunction &MF = DAG.getMachineFunction();
3142 
3143   if (Callee.isUndef() || isNullConstant(Callee)) {
3144     if (!CLI.IsTailCall) {
3145       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
3146         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
3147     }
3148 
3149     return Chain;
3150   }
3151 
3152   if (IsVarArg) {
3153     return lowerUnhandledCall(CLI, InVals,
3154                               "unsupported call to variadic function ");
3155   }
3156 
3157   if (!CLI.CB)
3158     report_fatal_error("unsupported libcall legalization");
3159 
3160   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
3161     return lowerUnhandledCall(CLI, InVals,
3162                               "unsupported required tail call to function ");
3163   }
3164 
3165   if (AMDGPU::isShader(CallConv)) {
3166     // Note the issue is with the CC of the called function, not of the call
3167     // itself.
3168     return lowerUnhandledCall(CLI, InVals,
3169                               "unsupported call to a shader function ");
3170   }
3171 
3172   if (AMDGPU::isShader(MF.getFunction().getCallingConv()) &&
3173       CallConv != CallingConv::AMDGPU_Gfx) {
3174     // Only allow calls with specific calling conventions.
3175     return lowerUnhandledCall(CLI, InVals,
3176                               "unsupported calling convention for call from "
3177                               "graphics shader of function ");
3178   }
3179 
3180   if (IsTailCall) {
3181     IsTailCall = isEligibleForTailCallOptimization(
3182       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3183     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
3184       report_fatal_error("failed to perform tail call elimination on a call "
3185                          "site marked musttail");
3186     }
3187 
3188     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3189 
3190     // A sibling call is one where we're under the usual C ABI and not planning
3191     // to change that but can still do a tail call:
3192     if (!TailCallOpt && IsTailCall)
3193       IsSibCall = true;
3194 
3195     if (IsTailCall)
3196       ++NumTailCalls;
3197   }
3198 
3199   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3200   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3201   SmallVector<SDValue, 8> MemOpChains;
3202 
3203   // Analyze operands of the call, assigning locations to each operand.
3204   SmallVector<CCValAssign, 16> ArgLocs;
3205   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
3206   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
3207 
3208   if (CallConv != CallingConv::AMDGPU_Gfx) {
3209     // With a fixed ABI, allocate fixed registers before user arguments.
3210     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3211   }
3212 
3213   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
3214 
3215   // Get a count of how many bytes are to be pushed on the stack.
3216   unsigned NumBytes = CCInfo.getNextStackOffset();
3217 
3218   if (IsSibCall) {
3219     // Since we're not changing the ABI to make this a tail call, the memory
3220     // operands are already available in the caller's incoming argument space.
3221     NumBytes = 0;
3222   }
3223 
3224   // FPDiff is the byte offset of the call's argument area from the callee's.
3225   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3226   // by this amount for a tail call. In a sibling call it must be 0 because the
3227   // caller will deallocate the entire stack and the callee still expects its
3228   // arguments to begin at SP+0. Completely unused for non-tail calls.
3229   int32_t FPDiff = 0;
3230   MachineFrameInfo &MFI = MF.getFrameInfo();
3231 
3232   // Adjust the stack pointer for the new arguments...
3233   // These operations are automatically eliminated by the prolog/epilog pass
3234   if (!IsSibCall) {
3235     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3236 
3237     if (!Subtarget->enableFlatScratch()) {
3238       SmallVector<SDValue, 4> CopyFromChains;
3239 
3240       // In the HSA case, this should be an identity copy.
3241       SDValue ScratchRSrcReg
3242         = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3243       RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3244       CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3245       Chain = DAG.getTokenFactor(DL, CopyFromChains);
3246     }
3247   }
3248 
3249   MVT PtrVT = MVT::i32;
3250 
3251   // Walk the register/memloc assignments, inserting copies/loads.
3252   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3253     CCValAssign &VA = ArgLocs[i];
3254     SDValue Arg = OutVals[i];
3255 
3256     // Promote the value if needed.
3257     switch (VA.getLocInfo()) {
3258     case CCValAssign::Full:
3259       break;
3260     case CCValAssign::BCvt:
3261       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3262       break;
3263     case CCValAssign::ZExt:
3264       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3265       break;
3266     case CCValAssign::SExt:
3267       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3268       break;
3269     case CCValAssign::AExt:
3270       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3271       break;
3272     case CCValAssign::FPExt:
3273       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3274       break;
3275     default:
3276       llvm_unreachable("Unknown loc info!");
3277     }
3278 
3279     if (VA.isRegLoc()) {
3280       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3281     } else {
3282       assert(VA.isMemLoc());
3283 
3284       SDValue DstAddr;
3285       MachinePointerInfo DstInfo;
3286 
3287       unsigned LocMemOffset = VA.getLocMemOffset();
3288       int32_t Offset = LocMemOffset;
3289 
3290       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3291       MaybeAlign Alignment;
3292 
3293       if (IsTailCall) {
3294         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3295         unsigned OpSize = Flags.isByVal() ?
3296           Flags.getByValSize() : VA.getValVT().getStoreSize();
3297 
3298         // FIXME: We can have better than the minimum byval required alignment.
3299         Alignment =
3300             Flags.isByVal()
3301                 ? Flags.getNonZeroByValAlign()
3302                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3303 
3304         Offset = Offset + FPDiff;
3305         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3306 
3307         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3308         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3309 
3310         // Make sure any stack arguments overlapping with where we're storing
3311         // are loaded before this eventual operation. Otherwise they'll be
3312         // clobbered.
3313 
3314         // FIXME: Why is this really necessary? This seems to just result in a
3315         // lot of code to copy the stack and write them back to the same
3316         // locations, which are supposed to be immutable?
3317         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3318       } else {
3319         // Stores to the argument stack area are relative to the stack pointer.
3320         SDValue SP = DAG.getCopyFromReg(Chain, DL, Info->getStackPtrOffsetReg(),
3321                                         MVT::i32);
3322         DstAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, SP, PtrOff);
3323         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3324         Alignment =
3325             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3326       }
3327 
3328       if (Outs[i].Flags.isByVal()) {
3329         SDValue SizeNode =
3330             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3331         SDValue Cpy =
3332             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3333                           Outs[i].Flags.getNonZeroByValAlign(),
3334                           /*isVol = */ false, /*AlwaysInline = */ true,
3335                           /*isTailCall = */ false, DstInfo,
3336                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3337 
3338         MemOpChains.push_back(Cpy);
3339       } else {
3340         SDValue Store =
3341             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3342         MemOpChains.push_back(Store);
3343       }
3344     }
3345   }
3346 
3347   if (!MemOpChains.empty())
3348     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3349 
3350   // Build a sequence of copy-to-reg nodes chained together with token chain
3351   // and flag operands which copy the outgoing args into the appropriate regs.
3352   SDValue InFlag;
3353   for (auto &RegToPass : RegsToPass) {
3354     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3355                              RegToPass.second, InFlag);
3356     InFlag = Chain.getValue(1);
3357   }
3358 
3359 
3360   // We don't usually want to end the call-sequence here because we would tidy
3361   // the frame up *after* the call, however in the ABI-changing tail-call case
3362   // we've carefully laid out the parameters so that when sp is reset they'll be
3363   // in the correct location.
3364   if (IsTailCall && !IsSibCall) {
3365     Chain = DAG.getCALLSEQ_END(Chain,
3366                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3367                                DAG.getTargetConstant(0, DL, MVT::i32),
3368                                InFlag, DL);
3369     InFlag = Chain.getValue(1);
3370   }
3371 
3372   std::vector<SDValue> Ops;
3373   Ops.push_back(Chain);
3374   Ops.push_back(Callee);
3375   // Add a redundant copy of the callee global which will not be legalized, as
3376   // we need direct access to the callee later.
3377   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3378     const GlobalValue *GV = GSD->getGlobal();
3379     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3380   } else {
3381     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3382   }
3383 
3384   if (IsTailCall) {
3385     // Each tail call may have to adjust the stack by a different amount, so
3386     // this information must travel along with the operation for eventual
3387     // consumption by emitEpilogue.
3388     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3389   }
3390 
3391   // Add argument registers to the end of the list so that they are known live
3392   // into the call.
3393   for (auto &RegToPass : RegsToPass) {
3394     Ops.push_back(DAG.getRegister(RegToPass.first,
3395                                   RegToPass.second.getValueType()));
3396   }
3397 
3398   // Add a register mask operand representing the call-preserved registers.
3399 
3400   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3401   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3402   assert(Mask && "Missing call preserved mask for calling convention");
3403   Ops.push_back(DAG.getRegisterMask(Mask));
3404 
3405   if (InFlag.getNode())
3406     Ops.push_back(InFlag);
3407 
3408   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3409 
3410   // If we're doing a tall call, use a TC_RETURN here rather than an
3411   // actual call instruction.
3412   if (IsTailCall) {
3413     MFI.setHasTailCall();
3414     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3415   }
3416 
3417   // Returns a chain and a flag for retval copy to use.
3418   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3419   Chain = Call.getValue(0);
3420   InFlag = Call.getValue(1);
3421 
3422   uint64_t CalleePopBytes = NumBytes;
3423   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3424                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3425                              InFlag, DL);
3426   if (!Ins.empty())
3427     InFlag = Chain.getValue(1);
3428 
3429   // Handle result values, copying them out of physregs into vregs that we
3430   // return.
3431   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3432                          InVals, IsThisReturn,
3433                          IsThisReturn ? OutVals[0] : SDValue());
3434 }
3435 
3436 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3437 // except for applying the wave size scale to the increment amount.
3438 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3439     SDValue Op, SelectionDAG &DAG) const {
3440   const MachineFunction &MF = DAG.getMachineFunction();
3441   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3442 
3443   SDLoc dl(Op);
3444   EVT VT = Op.getValueType();
3445   SDValue Tmp1 = Op;
3446   SDValue Tmp2 = Op.getValue(1);
3447   SDValue Tmp3 = Op.getOperand(2);
3448   SDValue Chain = Tmp1.getOperand(0);
3449 
3450   Register SPReg = Info->getStackPtrOffsetReg();
3451 
3452   // Chain the dynamic stack allocation so that it doesn't modify the stack
3453   // pointer when other instructions are using the stack.
3454   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3455 
3456   SDValue Size  = Tmp2.getOperand(1);
3457   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3458   Chain = SP.getValue(1);
3459   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3460   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3461   const TargetFrameLowering *TFL = ST.getFrameLowering();
3462   unsigned Opc =
3463     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3464     ISD::ADD : ISD::SUB;
3465 
3466   SDValue ScaledSize = DAG.getNode(
3467       ISD::SHL, dl, VT, Size,
3468       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3469 
3470   Align StackAlign = TFL->getStackAlign();
3471   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3472   if (Alignment && *Alignment > StackAlign) {
3473     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3474                        DAG.getConstant(-(uint64_t)Alignment->value()
3475                                            << ST.getWavefrontSizeLog2(),
3476                                        dl, VT));
3477   }
3478 
3479   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3480   Tmp2 = DAG.getCALLSEQ_END(
3481       Chain, DAG.getIntPtrConstant(0, dl, true),
3482       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3483 
3484   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3485 }
3486 
3487 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3488                                                   SelectionDAG &DAG) const {
3489   // We only handle constant sizes here to allow non-entry block, static sized
3490   // allocas. A truly dynamic value is more difficult to support because we
3491   // don't know if the size value is uniform or not. If the size isn't uniform,
3492   // we would need to do a wave reduction to get the maximum size to know how
3493   // much to increment the uniform stack pointer.
3494   SDValue Size = Op.getOperand(1);
3495   if (isa<ConstantSDNode>(Size))
3496       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3497 
3498   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3499 }
3500 
3501 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3502                                              const MachineFunction &MF) const {
3503   Register Reg = StringSwitch<Register>(RegName)
3504     .Case("m0", AMDGPU::M0)
3505     .Case("exec", AMDGPU::EXEC)
3506     .Case("exec_lo", AMDGPU::EXEC_LO)
3507     .Case("exec_hi", AMDGPU::EXEC_HI)
3508     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3509     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3510     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3511     .Default(Register());
3512 
3513   if (Reg == AMDGPU::NoRegister) {
3514     report_fatal_error(Twine("invalid register name \""
3515                              + StringRef(RegName)  + "\"."));
3516 
3517   }
3518 
3519   if (!Subtarget->hasFlatScrRegister() &&
3520        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3521     report_fatal_error(Twine("invalid register \""
3522                              + StringRef(RegName)  + "\" for subtarget."));
3523   }
3524 
3525   switch (Reg) {
3526   case AMDGPU::M0:
3527   case AMDGPU::EXEC_LO:
3528   case AMDGPU::EXEC_HI:
3529   case AMDGPU::FLAT_SCR_LO:
3530   case AMDGPU::FLAT_SCR_HI:
3531     if (VT.getSizeInBits() == 32)
3532       return Reg;
3533     break;
3534   case AMDGPU::EXEC:
3535   case AMDGPU::FLAT_SCR:
3536     if (VT.getSizeInBits() == 64)
3537       return Reg;
3538     break;
3539   default:
3540     llvm_unreachable("missing register type checking");
3541   }
3542 
3543   report_fatal_error(Twine("invalid type for register \""
3544                            + StringRef(RegName) + "\"."));
3545 }
3546 
3547 // If kill is not the last instruction, split the block so kill is always a
3548 // proper terminator.
3549 MachineBasicBlock *
3550 SITargetLowering::splitKillBlock(MachineInstr &MI,
3551                                  MachineBasicBlock *BB) const {
3552   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3553   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3554   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3555   return SplitBB;
3556 }
3557 
3558 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3559 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3560 // be the first instruction in the remainder block.
3561 //
3562 /// \returns { LoopBody, Remainder }
3563 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3564 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3565   MachineFunction *MF = MBB.getParent();
3566   MachineBasicBlock::iterator I(&MI);
3567 
3568   // To insert the loop we need to split the block. Move everything after this
3569   // point to a new block, and insert a new empty block between the two.
3570   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3571   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3572   MachineFunction::iterator MBBI(MBB);
3573   ++MBBI;
3574 
3575   MF->insert(MBBI, LoopBB);
3576   MF->insert(MBBI, RemainderBB);
3577 
3578   LoopBB->addSuccessor(LoopBB);
3579   LoopBB->addSuccessor(RemainderBB);
3580 
3581   // Move the rest of the block into a new block.
3582   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3583 
3584   if (InstInLoop) {
3585     auto Next = std::next(I);
3586 
3587     // Move instruction to loop body.
3588     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3589 
3590     // Move the rest of the block.
3591     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3592   } else {
3593     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3594   }
3595 
3596   MBB.addSuccessor(LoopBB);
3597 
3598   return std::make_pair(LoopBB, RemainderBB);
3599 }
3600 
3601 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3602 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3603   MachineBasicBlock *MBB = MI.getParent();
3604   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3605   auto I = MI.getIterator();
3606   auto E = std::next(I);
3607 
3608   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3609     .addImm(0);
3610 
3611   MIBundleBuilder Bundler(*MBB, I, E);
3612   finalizeBundle(*MBB, Bundler.begin());
3613 }
3614 
3615 MachineBasicBlock *
3616 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3617                                          MachineBasicBlock *BB) const {
3618   const DebugLoc &DL = MI.getDebugLoc();
3619 
3620   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3621 
3622   MachineBasicBlock *LoopBB;
3623   MachineBasicBlock *RemainderBB;
3624   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3625 
3626   // Apparently kill flags are only valid if the def is in the same block?
3627   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3628     Src->setIsKill(false);
3629 
3630   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3631 
3632   MachineBasicBlock::iterator I = LoopBB->end();
3633 
3634   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3635     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3636 
3637   // Clear TRAP_STS.MEM_VIOL
3638   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3639     .addImm(0)
3640     .addImm(EncodedReg);
3641 
3642   bundleInstWithWaitcnt(MI);
3643 
3644   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3645 
3646   // Load and check TRAP_STS.MEM_VIOL
3647   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3648     .addImm(EncodedReg);
3649 
3650   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3651   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3652     .addReg(Reg, RegState::Kill)
3653     .addImm(0);
3654   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3655     .addMBB(LoopBB);
3656 
3657   return RemainderBB;
3658 }
3659 
3660 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3661 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3662 // will only do one iteration. In the worst case, this will loop 64 times.
3663 //
3664 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3665 static MachineBasicBlock::iterator
3666 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI,
3667                        MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB,
3668                        const DebugLoc &DL, const MachineOperand &Idx,
3669                        unsigned InitReg, unsigned ResultReg, unsigned PhiReg,
3670                        unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode,
3671                        Register &SGPRIdxReg) {
3672 
3673   MachineFunction *MF = OrigBB.getParent();
3674   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3675   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3676   MachineBasicBlock::iterator I = LoopBB.begin();
3677 
3678   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3679   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3680   Register NewExec = MRI.createVirtualRegister(BoolRC);
3681   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3682   Register CondReg = MRI.createVirtualRegister(BoolRC);
3683 
3684   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3685     .addReg(InitReg)
3686     .addMBB(&OrigBB)
3687     .addReg(ResultReg)
3688     .addMBB(&LoopBB);
3689 
3690   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3691     .addReg(InitSaveExecReg)
3692     .addMBB(&OrigBB)
3693     .addReg(NewExec)
3694     .addMBB(&LoopBB);
3695 
3696   // Read the next variant <- also loop target.
3697   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3698       .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef()));
3699 
3700   // Compare the just read M0 value to all possible Idx values.
3701   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3702       .addReg(CurrentIdxReg)
3703       .addReg(Idx.getReg(), 0, Idx.getSubReg());
3704 
3705   // Update EXEC, save the original EXEC value to VCC.
3706   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3707                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3708           NewExec)
3709     .addReg(CondReg, RegState::Kill);
3710 
3711   MRI.setSimpleHint(NewExec, CondReg);
3712 
3713   if (UseGPRIdxMode) {
3714     if (Offset == 0) {
3715       SGPRIdxReg = CurrentIdxReg;
3716     } else {
3717       SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3718       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg)
3719           .addReg(CurrentIdxReg, RegState::Kill)
3720           .addImm(Offset);
3721     }
3722   } else {
3723     // Move index from VCC into M0
3724     if (Offset == 0) {
3725       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3726         .addReg(CurrentIdxReg, RegState::Kill);
3727     } else {
3728       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3729         .addReg(CurrentIdxReg, RegState::Kill)
3730         .addImm(Offset);
3731     }
3732   }
3733 
3734   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3735   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3736   MachineInstr *InsertPt =
3737     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3738                                                   : AMDGPU::S_XOR_B64_term), Exec)
3739       .addReg(Exec)
3740       .addReg(NewExec);
3741 
3742   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3743   // s_cbranch_scc0?
3744 
3745   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3746   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3747     .addMBB(&LoopBB);
3748 
3749   return InsertPt->getIterator();
3750 }
3751 
3752 // This has slightly sub-optimal regalloc when the source vector is killed by
3753 // the read. The register allocator does not understand that the kill is
3754 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3755 // subregister from it, using 1 more VGPR than necessary. This was saved when
3756 // this was expanded after register allocation.
3757 static MachineBasicBlock::iterator
3758 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI,
3759                unsigned InitResultReg, unsigned PhiReg, int Offset,
3760                bool UseGPRIdxMode, Register &SGPRIdxReg) {
3761   MachineFunction *MF = MBB.getParent();
3762   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3763   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3764   MachineRegisterInfo &MRI = MF->getRegInfo();
3765   const DebugLoc &DL = MI.getDebugLoc();
3766   MachineBasicBlock::iterator I(&MI);
3767 
3768   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3769   Register DstReg = MI.getOperand(0).getReg();
3770   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3771   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3772   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3773   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3774 
3775   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3776 
3777   // Save the EXEC mask
3778   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3779     .addReg(Exec);
3780 
3781   MachineBasicBlock *LoopBB;
3782   MachineBasicBlock *RemainderBB;
3783   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3784 
3785   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3786 
3787   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3788                                       InitResultReg, DstReg, PhiReg, TmpExec,
3789                                       Offset, UseGPRIdxMode, SGPRIdxReg);
3790 
3791   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3792   MachineFunction::iterator MBBI(LoopBB);
3793   ++MBBI;
3794   MF->insert(MBBI, LandingPad);
3795   LoopBB->removeSuccessor(RemainderBB);
3796   LandingPad->addSuccessor(RemainderBB);
3797   LoopBB->addSuccessor(LandingPad);
3798   MachineBasicBlock::iterator First = LandingPad->begin();
3799   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3800     .addReg(SaveExec);
3801 
3802   return InsPt;
3803 }
3804 
3805 // Returns subreg index, offset
3806 static std::pair<unsigned, int>
3807 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3808                             const TargetRegisterClass *SuperRC,
3809                             unsigned VecReg,
3810                             int Offset) {
3811   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3812 
3813   // Skip out of bounds offsets, or else we would end up using an undefined
3814   // register.
3815   if (Offset >= NumElts || Offset < 0)
3816     return std::make_pair(AMDGPU::sub0, Offset);
3817 
3818   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3819 }
3820 
3821 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3822                                  MachineRegisterInfo &MRI, MachineInstr &MI,
3823                                  int Offset) {
3824   MachineBasicBlock *MBB = MI.getParent();
3825   const DebugLoc &DL = MI.getDebugLoc();
3826   MachineBasicBlock::iterator I(&MI);
3827 
3828   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3829 
3830   assert(Idx->getReg() != AMDGPU::NoRegister);
3831 
3832   if (Offset == 0) {
3833     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx);
3834   } else {
3835     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3836         .add(*Idx)
3837         .addImm(Offset);
3838   }
3839 }
3840 
3841 static Register getIndirectSGPRIdx(const SIInstrInfo *TII,
3842                                    MachineRegisterInfo &MRI, MachineInstr &MI,
3843                                    int Offset) {
3844   MachineBasicBlock *MBB = MI.getParent();
3845   const DebugLoc &DL = MI.getDebugLoc();
3846   MachineBasicBlock::iterator I(&MI);
3847 
3848   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3849 
3850   if (Offset == 0)
3851     return Idx->getReg();
3852 
3853   Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3854   BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3855       .add(*Idx)
3856       .addImm(Offset);
3857   return Tmp;
3858 }
3859 
3860 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3861                                           MachineBasicBlock &MBB,
3862                                           const GCNSubtarget &ST) {
3863   const SIInstrInfo *TII = ST.getInstrInfo();
3864   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3865   MachineFunction *MF = MBB.getParent();
3866   MachineRegisterInfo &MRI = MF->getRegInfo();
3867 
3868   Register Dst = MI.getOperand(0).getReg();
3869   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3870   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3871   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3872 
3873   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3874   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3875 
3876   unsigned SubReg;
3877   std::tie(SubReg, Offset)
3878     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3879 
3880   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3881 
3882   // Check for a SGPR index.
3883   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3884     MachineBasicBlock::iterator I(&MI);
3885     const DebugLoc &DL = MI.getDebugLoc();
3886 
3887     if (UseGPRIdxMode) {
3888       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3889       // to avoid interfering with other uses, so probably requires a new
3890       // optimization pass.
3891       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3892 
3893       const MCInstrDesc &GPRIDXDesc =
3894           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3895       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3896           .addReg(SrcReg)
3897           .addReg(Idx)
3898           .addImm(SubReg);
3899     } else {
3900       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
3901 
3902       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3903         .addReg(SrcReg, 0, SubReg)
3904         .addReg(SrcReg, RegState::Implicit);
3905     }
3906 
3907     MI.eraseFromParent();
3908 
3909     return &MBB;
3910   }
3911 
3912   // Control flow needs to be inserted if indexing with a VGPR.
3913   const DebugLoc &DL = MI.getDebugLoc();
3914   MachineBasicBlock::iterator I(&MI);
3915 
3916   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3917   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3918 
3919   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3920 
3921   Register SGPRIdxReg;
3922   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset,
3923                               UseGPRIdxMode, SGPRIdxReg);
3924 
3925   MachineBasicBlock *LoopBB = InsPt->getParent();
3926 
3927   if (UseGPRIdxMode) {
3928     const MCInstrDesc &GPRIDXDesc =
3929         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true);
3930 
3931     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
3932         .addReg(SrcReg)
3933         .addReg(SGPRIdxReg)
3934         .addImm(SubReg);
3935   } else {
3936     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3937       .addReg(SrcReg, 0, SubReg)
3938       .addReg(SrcReg, RegState::Implicit);
3939   }
3940 
3941   MI.eraseFromParent();
3942 
3943   return LoopBB;
3944 }
3945 
3946 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3947                                           MachineBasicBlock &MBB,
3948                                           const GCNSubtarget &ST) {
3949   const SIInstrInfo *TII = ST.getInstrInfo();
3950   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3951   MachineFunction *MF = MBB.getParent();
3952   MachineRegisterInfo &MRI = MF->getRegInfo();
3953 
3954   Register Dst = MI.getOperand(0).getReg();
3955   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3956   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3957   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3958   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3959   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3960   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3961 
3962   // This can be an immediate, but will be folded later.
3963   assert(Val->getReg());
3964 
3965   unsigned SubReg;
3966   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3967                                                          SrcVec->getReg(),
3968                                                          Offset);
3969   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3970 
3971   if (Idx->getReg() == AMDGPU::NoRegister) {
3972     MachineBasicBlock::iterator I(&MI);
3973     const DebugLoc &DL = MI.getDebugLoc();
3974 
3975     assert(Offset == 0);
3976 
3977     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3978         .add(*SrcVec)
3979         .add(*Val)
3980         .addImm(SubReg);
3981 
3982     MI.eraseFromParent();
3983     return &MBB;
3984   }
3985 
3986   // Check for a SGPR index.
3987   if (TII->getRegisterInfo().isSGPRClass(IdxRC)) {
3988     MachineBasicBlock::iterator I(&MI);
3989     const DebugLoc &DL = MI.getDebugLoc();
3990 
3991     if (UseGPRIdxMode) {
3992       Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset);
3993 
3994       const MCInstrDesc &GPRIDXDesc =
3995           TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
3996       BuildMI(MBB, I, DL, GPRIDXDesc, Dst)
3997           .addReg(SrcVec->getReg())
3998           .add(*Val)
3999           .addReg(Idx)
4000           .addImm(SubReg);
4001     } else {
4002       setM0ToIndexFromSGPR(TII, MRI, MI, Offset);
4003 
4004       const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
4005           TRI.getRegSizeInBits(*VecRC), 32, false);
4006       BuildMI(MBB, I, DL, MovRelDesc, Dst)
4007           .addReg(SrcVec->getReg())
4008           .add(*Val)
4009           .addImm(SubReg);
4010     }
4011     MI.eraseFromParent();
4012     return &MBB;
4013   }
4014 
4015   // Control flow needs to be inserted if indexing with a VGPR.
4016   if (Val->isReg())
4017     MRI.clearKillFlags(Val->getReg());
4018 
4019   const DebugLoc &DL = MI.getDebugLoc();
4020 
4021   Register PhiReg = MRI.createVirtualRegister(VecRC);
4022 
4023   Register SGPRIdxReg;
4024   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset,
4025                               UseGPRIdxMode, SGPRIdxReg);
4026   MachineBasicBlock *LoopBB = InsPt->getParent();
4027 
4028   if (UseGPRIdxMode) {
4029     const MCInstrDesc &GPRIDXDesc =
4030         TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false);
4031 
4032     BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst)
4033         .addReg(PhiReg)
4034         .add(*Val)
4035         .addReg(SGPRIdxReg)
4036         .addImm(AMDGPU::sub0);
4037   } else {
4038     const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo(
4039         TRI.getRegSizeInBits(*VecRC), 32, false);
4040     BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
4041         .addReg(PhiReg)
4042         .add(*Val)
4043         .addImm(AMDGPU::sub0);
4044   }
4045 
4046   MI.eraseFromParent();
4047   return LoopBB;
4048 }
4049 
4050 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
4051   MachineInstr &MI, MachineBasicBlock *BB) const {
4052 
4053   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4054   MachineFunction *MF = BB->getParent();
4055   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
4056 
4057   switch (MI.getOpcode()) {
4058   case AMDGPU::S_UADDO_PSEUDO:
4059   case AMDGPU::S_USUBO_PSEUDO: {
4060     const DebugLoc &DL = MI.getDebugLoc();
4061     MachineOperand &Dest0 = MI.getOperand(0);
4062     MachineOperand &Dest1 = MI.getOperand(1);
4063     MachineOperand &Src0 = MI.getOperand(2);
4064     MachineOperand &Src1 = MI.getOperand(3);
4065 
4066     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
4067                        ? AMDGPU::S_ADD_I32
4068                        : AMDGPU::S_SUB_I32;
4069     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
4070 
4071     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
4072         .addImm(1)
4073         .addImm(0);
4074 
4075     MI.eraseFromParent();
4076     return BB;
4077   }
4078   case AMDGPU::S_ADD_U64_PSEUDO:
4079   case AMDGPU::S_SUB_U64_PSEUDO: {
4080     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4081     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4082     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4083     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
4084     const DebugLoc &DL = MI.getDebugLoc();
4085 
4086     MachineOperand &Dest = MI.getOperand(0);
4087     MachineOperand &Src0 = MI.getOperand(1);
4088     MachineOperand &Src1 = MI.getOperand(2);
4089 
4090     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4091     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4092 
4093     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
4094         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4095     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
4096         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4097 
4098     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
4099         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
4100     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
4101         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
4102 
4103     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
4104 
4105     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
4106     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
4107     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
4108     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
4109     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4110         .addReg(DestSub0)
4111         .addImm(AMDGPU::sub0)
4112         .addReg(DestSub1)
4113         .addImm(AMDGPU::sub1);
4114     MI.eraseFromParent();
4115     return BB;
4116   }
4117   case AMDGPU::V_ADD_U64_PSEUDO:
4118   case AMDGPU::V_SUB_U64_PSEUDO: {
4119     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4120     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4121     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4122     const DebugLoc &DL = MI.getDebugLoc();
4123 
4124     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
4125 
4126     MachineOperand &Dest = MI.getOperand(0);
4127     MachineOperand &Src0 = MI.getOperand(1);
4128     MachineOperand &Src1 = MI.getOperand(2);
4129 
4130     if (IsAdd && ST.hasLshlAddB64()) {
4131       auto Add = BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_LSHL_ADD_U64_e64),
4132                          Dest.getReg())
4133                      .add(Src0)
4134                      .addImm(0)
4135                      .add(Src1);
4136       TII->legalizeOperands(*Add);
4137       MI.eraseFromParent();
4138       return BB;
4139     }
4140 
4141     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4142 
4143     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4144     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4145 
4146     Register CarryReg = MRI.createVirtualRegister(CarryRC);
4147     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
4148 
4149     const TargetRegisterClass *Src0RC = Src0.isReg()
4150                                             ? MRI.getRegClass(Src0.getReg())
4151                                             : &AMDGPU::VReg_64RegClass;
4152     const TargetRegisterClass *Src1RC = Src1.isReg()
4153                                             ? MRI.getRegClass(Src1.getReg())
4154                                             : &AMDGPU::VReg_64RegClass;
4155 
4156     const TargetRegisterClass *Src0SubRC =
4157         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
4158     const TargetRegisterClass *Src1SubRC =
4159         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
4160 
4161     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
4162         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
4163     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
4164         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
4165 
4166     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
4167         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
4168     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
4169         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
4170 
4171     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
4172     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
4173                                .addReg(CarryReg, RegState::Define)
4174                                .add(SrcReg0Sub0)
4175                                .add(SrcReg1Sub0)
4176                                .addImm(0); // clamp bit
4177 
4178     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
4179     MachineInstr *HiHalf =
4180         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
4181             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
4182             .add(SrcReg0Sub1)
4183             .add(SrcReg1Sub1)
4184             .addReg(CarryReg, RegState::Kill)
4185             .addImm(0); // clamp bit
4186 
4187     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
4188         .addReg(DestSub0)
4189         .addImm(AMDGPU::sub0)
4190         .addReg(DestSub1)
4191         .addImm(AMDGPU::sub1);
4192     TII->legalizeOperands(*LoHalf);
4193     TII->legalizeOperands(*HiHalf);
4194     MI.eraseFromParent();
4195     return BB;
4196   }
4197   case AMDGPU::S_ADD_CO_PSEUDO:
4198   case AMDGPU::S_SUB_CO_PSEUDO: {
4199     // This pseudo has a chance to be selected
4200     // only from uniform add/subcarry node. All the VGPR operands
4201     // therefore assumed to be splat vectors.
4202     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4203     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4204     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4205     MachineBasicBlock::iterator MII = MI;
4206     const DebugLoc &DL = MI.getDebugLoc();
4207     MachineOperand &Dest = MI.getOperand(0);
4208     MachineOperand &CarryDest = MI.getOperand(1);
4209     MachineOperand &Src0 = MI.getOperand(2);
4210     MachineOperand &Src1 = MI.getOperand(3);
4211     MachineOperand &Src2 = MI.getOperand(4);
4212     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
4213                        ? AMDGPU::S_ADDC_U32
4214                        : AMDGPU::S_SUBB_U32;
4215     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
4216       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4217       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
4218           .addReg(Src0.getReg());
4219       Src0.setReg(RegOp0);
4220     }
4221     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
4222       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4223       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4224           .addReg(Src1.getReg());
4225       Src1.setReg(RegOp1);
4226     }
4227     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4228     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4229       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4230           .addReg(Src2.getReg());
4231       Src2.setReg(RegOp2);
4232     }
4233 
4234     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4235     unsigned WaveSize = TRI->getRegSizeInBits(*Src2RC);
4236     assert(WaveSize == 64 || WaveSize == 32);
4237 
4238     if (WaveSize == 64) {
4239       if (ST.hasScalarCompareEq64()) {
4240         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4241             .addReg(Src2.getReg())
4242             .addImm(0);
4243       } else {
4244         const TargetRegisterClass *SubRC =
4245             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4246         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4247             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4248         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4249             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4250         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4251 
4252         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4253             .add(Src2Sub0)
4254             .add(Src2Sub1);
4255 
4256         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4257             .addReg(Src2_32, RegState::Kill)
4258             .addImm(0);
4259       }
4260     } else {
4261       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4262           .addReg(Src2.getReg())
4263           .addImm(0);
4264     }
4265 
4266     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4267 
4268     unsigned SelOpc =
4269         (WaveSize == 64) ? AMDGPU::S_CSELECT_B64 : AMDGPU::S_CSELECT_B32;
4270 
4271     BuildMI(*BB, MII, DL, TII->get(SelOpc), CarryDest.getReg())
4272         .addImm(-1)
4273         .addImm(0);
4274 
4275     MI.eraseFromParent();
4276     return BB;
4277   }
4278   case AMDGPU::SI_INIT_M0: {
4279     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4280             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4281         .add(MI.getOperand(0));
4282     MI.eraseFromParent();
4283     return BB;
4284   }
4285   case AMDGPU::GET_GROUPSTATICSIZE: {
4286     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4287            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4288     DebugLoc DL = MI.getDebugLoc();
4289     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4290         .add(MI.getOperand(0))
4291         .addImm(MFI->getLDSSize());
4292     MI.eraseFromParent();
4293     return BB;
4294   }
4295   case AMDGPU::SI_INDIRECT_SRC_V1:
4296   case AMDGPU::SI_INDIRECT_SRC_V2:
4297   case AMDGPU::SI_INDIRECT_SRC_V4:
4298   case AMDGPU::SI_INDIRECT_SRC_V8:
4299   case AMDGPU::SI_INDIRECT_SRC_V16:
4300   case AMDGPU::SI_INDIRECT_SRC_V32:
4301     return emitIndirectSrc(MI, *BB, *getSubtarget());
4302   case AMDGPU::SI_INDIRECT_DST_V1:
4303   case AMDGPU::SI_INDIRECT_DST_V2:
4304   case AMDGPU::SI_INDIRECT_DST_V4:
4305   case AMDGPU::SI_INDIRECT_DST_V8:
4306   case AMDGPU::SI_INDIRECT_DST_V16:
4307   case AMDGPU::SI_INDIRECT_DST_V32:
4308     return emitIndirectDst(MI, *BB, *getSubtarget());
4309   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4310   case AMDGPU::SI_KILL_I1_PSEUDO:
4311     return splitKillBlock(MI, BB);
4312   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4313     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4314     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4315     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4316 
4317     Register Dst = MI.getOperand(0).getReg();
4318     Register Src0 = MI.getOperand(1).getReg();
4319     Register Src1 = MI.getOperand(2).getReg();
4320     const DebugLoc &DL = MI.getDebugLoc();
4321     Register SrcCond = MI.getOperand(3).getReg();
4322 
4323     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4324     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4325     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4326     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4327 
4328     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4329       .addReg(SrcCond);
4330     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4331       .addImm(0)
4332       .addReg(Src0, 0, AMDGPU::sub0)
4333       .addImm(0)
4334       .addReg(Src1, 0, AMDGPU::sub0)
4335       .addReg(SrcCondCopy);
4336     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4337       .addImm(0)
4338       .addReg(Src0, 0, AMDGPU::sub1)
4339       .addImm(0)
4340       .addReg(Src1, 0, AMDGPU::sub1)
4341       .addReg(SrcCondCopy);
4342 
4343     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4344       .addReg(DstLo)
4345       .addImm(AMDGPU::sub0)
4346       .addReg(DstHi)
4347       .addImm(AMDGPU::sub1);
4348     MI.eraseFromParent();
4349     return BB;
4350   }
4351   case AMDGPU::SI_BR_UNDEF: {
4352     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4353     const DebugLoc &DL = MI.getDebugLoc();
4354     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4355                            .add(MI.getOperand(0));
4356     Br->getOperand(1).setIsUndef(true); // read undef SCC
4357     MI.eraseFromParent();
4358     return BB;
4359   }
4360   case AMDGPU::ADJCALLSTACKUP:
4361   case AMDGPU::ADJCALLSTACKDOWN: {
4362     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4363     MachineInstrBuilder MIB(*MF, &MI);
4364     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4365        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4366     return BB;
4367   }
4368   case AMDGPU::SI_CALL_ISEL: {
4369     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4370     const DebugLoc &DL = MI.getDebugLoc();
4371 
4372     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4373 
4374     MachineInstrBuilder MIB;
4375     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4376 
4377     for (const MachineOperand &MO : MI.operands())
4378       MIB.add(MO);
4379 
4380     MIB.cloneMemRefs(MI);
4381     MI.eraseFromParent();
4382     return BB;
4383   }
4384   case AMDGPU::V_ADD_CO_U32_e32:
4385   case AMDGPU::V_SUB_CO_U32_e32:
4386   case AMDGPU::V_SUBREV_CO_U32_e32: {
4387     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4388     const DebugLoc &DL = MI.getDebugLoc();
4389     unsigned Opc = MI.getOpcode();
4390 
4391     bool NeedClampOperand = false;
4392     if (TII->pseudoToMCOpcode(Opc) == -1) {
4393       Opc = AMDGPU::getVOPe64(Opc);
4394       NeedClampOperand = true;
4395     }
4396 
4397     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4398     if (TII->isVOP3(*I)) {
4399       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4400       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4401       I.addReg(TRI->getVCC(), RegState::Define);
4402     }
4403     I.add(MI.getOperand(1))
4404      .add(MI.getOperand(2));
4405     if (NeedClampOperand)
4406       I.addImm(0); // clamp bit for e64 encoding
4407 
4408     TII->legalizeOperands(*I);
4409 
4410     MI.eraseFromParent();
4411     return BB;
4412   }
4413   case AMDGPU::V_ADDC_U32_e32:
4414   case AMDGPU::V_SUBB_U32_e32:
4415   case AMDGPU::V_SUBBREV_U32_e32:
4416     // These instructions have an implicit use of vcc which counts towards the
4417     // constant bus limit.
4418     TII->legalizeOperands(MI);
4419     return BB;
4420   case AMDGPU::DS_GWS_INIT:
4421   case AMDGPU::DS_GWS_SEMA_BR:
4422   case AMDGPU::DS_GWS_BARRIER:
4423     if (Subtarget->needsAlignedVGPRs()) {
4424       // Add implicit aligned super-reg to force alignment on the data operand.
4425       const DebugLoc &DL = MI.getDebugLoc();
4426       MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4427       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
4428       MachineOperand *Op = TII->getNamedOperand(MI, AMDGPU::OpName::data0);
4429       Register DataReg = Op->getReg();
4430       bool IsAGPR = TRI->isAGPR(MRI, DataReg);
4431       Register Undef = MRI.createVirtualRegister(
4432           IsAGPR ? &AMDGPU::AGPR_32RegClass : &AMDGPU::VGPR_32RegClass);
4433       BuildMI(*BB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), Undef);
4434       Register NewVR =
4435           MRI.createVirtualRegister(IsAGPR ? &AMDGPU::AReg_64_Align2RegClass
4436                                            : &AMDGPU::VReg_64_Align2RegClass);
4437       BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), NewVR)
4438           .addReg(DataReg, 0, Op->getSubReg())
4439           .addImm(AMDGPU::sub0)
4440           .addReg(Undef)
4441           .addImm(AMDGPU::sub1);
4442       Op->setReg(NewVR);
4443       Op->setSubReg(AMDGPU::sub0);
4444       MI.addOperand(MachineOperand::CreateReg(NewVR, false, true));
4445     }
4446     LLVM_FALLTHROUGH;
4447   case AMDGPU::DS_GWS_SEMA_V:
4448   case AMDGPU::DS_GWS_SEMA_P:
4449   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4450     // A s_waitcnt 0 is required to be the instruction immediately following.
4451     if (getSubtarget()->hasGWSAutoReplay()) {
4452       bundleInstWithWaitcnt(MI);
4453       return BB;
4454     }
4455 
4456     return emitGWSMemViolTestLoop(MI, BB);
4457   case AMDGPU::S_SETREG_B32: {
4458     // Try to optimize cases that only set the denormal mode or rounding mode.
4459     //
4460     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4461     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4462     // instead.
4463     //
4464     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4465     // allow you to have a no side effect instruction in the output of a
4466     // sideeffecting pattern.
4467     unsigned ID, Offset, Width;
4468     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4469     if (ID != AMDGPU::Hwreg::ID_MODE)
4470       return BB;
4471 
4472     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4473     const unsigned SetMask = WidthMask << Offset;
4474 
4475     if (getSubtarget()->hasDenormModeInst()) {
4476       unsigned SetDenormOp = 0;
4477       unsigned SetRoundOp = 0;
4478 
4479       // The dedicated instructions can only set the whole denorm or round mode
4480       // at once, not a subset of bits in either.
4481       if (SetMask ==
4482           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4483         // If this fully sets both the round and denorm mode, emit the two
4484         // dedicated instructions for these.
4485         SetRoundOp = AMDGPU::S_ROUND_MODE;
4486         SetDenormOp = AMDGPU::S_DENORM_MODE;
4487       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4488         SetRoundOp = AMDGPU::S_ROUND_MODE;
4489       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4490         SetDenormOp = AMDGPU::S_DENORM_MODE;
4491       }
4492 
4493       if (SetRoundOp || SetDenormOp) {
4494         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4495         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4496         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4497           unsigned ImmVal = Def->getOperand(1).getImm();
4498           if (SetRoundOp) {
4499             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4500                 .addImm(ImmVal & 0xf);
4501 
4502             // If we also have the denorm mode, get just the denorm mode bits.
4503             ImmVal >>= 4;
4504           }
4505 
4506           if (SetDenormOp) {
4507             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4508                 .addImm(ImmVal & 0xf);
4509           }
4510 
4511           MI.eraseFromParent();
4512           return BB;
4513         }
4514       }
4515     }
4516 
4517     // If only FP bits are touched, used the no side effects pseudo.
4518     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4519                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4520       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4521 
4522     return BB;
4523   }
4524   default:
4525     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4526   }
4527 }
4528 
4529 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4530   return isTypeLegal(VT.getScalarType());
4531 }
4532 
4533 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4534   // This currently forces unfolding various combinations of fsub into fma with
4535   // free fneg'd operands. As long as we have fast FMA (controlled by
4536   // isFMAFasterThanFMulAndFAdd), we should perform these.
4537 
4538   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4539   // most of these combines appear to be cycle neutral but save on instruction
4540   // count / code size.
4541   return true;
4542 }
4543 
4544 bool SITargetLowering::enableAggressiveFMAFusion(LLT Ty) const { return true; }
4545 
4546 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4547                                          EVT VT) const {
4548   if (!VT.isVector()) {
4549     return MVT::i1;
4550   }
4551   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4552 }
4553 
4554 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4555   // TODO: Should i16 be used always if legal? For now it would force VALU
4556   // shifts.
4557   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4558 }
4559 
4560 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4561   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4562              ? Ty.changeElementSize(16)
4563              : Ty.changeElementSize(32);
4564 }
4565 
4566 // Answering this is somewhat tricky and depends on the specific device which
4567 // have different rates for fma or all f64 operations.
4568 //
4569 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4570 // regardless of which device (although the number of cycles differs between
4571 // devices), so it is always profitable for f64.
4572 //
4573 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4574 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4575 // which we can always do even without fused FP ops since it returns the same
4576 // result as the separate operations and since it is always full
4577 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4578 // however does not support denormals, so we do report fma as faster if we have
4579 // a fast fma device and require denormals.
4580 //
4581 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4582                                                   EVT VT) const {
4583   VT = VT.getScalarType();
4584 
4585   switch (VT.getSimpleVT().SimpleTy) {
4586   case MVT::f32: {
4587     // If mad is not available this depends only on if f32 fma is full rate.
4588     if (!Subtarget->hasMadMacF32Insts())
4589       return Subtarget->hasFastFMAF32();
4590 
4591     // Otherwise f32 mad is always full rate and returns the same result as
4592     // the separate operations so should be preferred over fma.
4593     // However does not support denormals.
4594     if (hasFP32Denormals(MF))
4595       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4596 
4597     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4598     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4599   }
4600   case MVT::f64:
4601     return true;
4602   case MVT::f16:
4603     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4604   default:
4605     break;
4606   }
4607 
4608   return false;
4609 }
4610 
4611 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4612                                                   LLT Ty) const {
4613   switch (Ty.getScalarSizeInBits()) {
4614   case 16:
4615     return isFMAFasterThanFMulAndFAdd(MF, MVT::f16);
4616   case 32:
4617     return isFMAFasterThanFMulAndFAdd(MF, MVT::f32);
4618   case 64:
4619     return isFMAFasterThanFMulAndFAdd(MF, MVT::f64);
4620   default:
4621     break;
4622   }
4623 
4624   return false;
4625 }
4626 
4627 bool SITargetLowering::isFMADLegal(const MachineInstr &MI, LLT Ty) const {
4628   if (!Ty.isScalar())
4629     return false;
4630 
4631   if (Ty.getScalarSizeInBits() == 16)
4632     return Subtarget->hasMadF16() && !hasFP64FP16Denormals(*MI.getMF());
4633   if (Ty.getScalarSizeInBits() == 32)
4634     return Subtarget->hasMadMacF32Insts() && !hasFP32Denormals(*MI.getMF());
4635 
4636   return false;
4637 }
4638 
4639 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4640                                    const SDNode *N) const {
4641   // TODO: Check future ftz flag
4642   // v_mad_f32/v_mac_f32 do not support denormals.
4643   EVT VT = N->getValueType(0);
4644   if (VT == MVT::f32)
4645     return Subtarget->hasMadMacF32Insts() &&
4646            !hasFP32Denormals(DAG.getMachineFunction());
4647   if (VT == MVT::f16) {
4648     return Subtarget->hasMadF16() &&
4649            !hasFP64FP16Denormals(DAG.getMachineFunction());
4650   }
4651 
4652   return false;
4653 }
4654 
4655 //===----------------------------------------------------------------------===//
4656 // Custom DAG Lowering Operations
4657 //===----------------------------------------------------------------------===//
4658 
4659 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4660 // wider vector type is legal.
4661 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4662                                              SelectionDAG &DAG) const {
4663   unsigned Opc = Op.getOpcode();
4664   EVT VT = Op.getValueType();
4665   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4666 
4667   SDValue Lo, Hi;
4668   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4669 
4670   SDLoc SL(Op);
4671   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4672                              Op->getFlags());
4673   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4674                              Op->getFlags());
4675 
4676   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4677 }
4678 
4679 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4680 // wider vector type is legal.
4681 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4682                                               SelectionDAG &DAG) const {
4683   unsigned Opc = Op.getOpcode();
4684   EVT VT = Op.getValueType();
4685   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 ||
4686          VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v8f32 ||
4687          VT == MVT::v16f32 || VT == MVT::v32f32);
4688 
4689   SDValue Lo0, Hi0;
4690   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4691   SDValue Lo1, Hi1;
4692   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4693 
4694   SDLoc SL(Op);
4695 
4696   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4697                              Op->getFlags());
4698   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4699                              Op->getFlags());
4700 
4701   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4702 }
4703 
4704 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4705                                               SelectionDAG &DAG) const {
4706   unsigned Opc = Op.getOpcode();
4707   EVT VT = Op.getValueType();
4708   assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v8i16 ||
4709          VT == MVT::v8f16 || VT == MVT::v4f32 || VT == MVT::v8f32 ||
4710          VT == MVT::v16f32 || VT == MVT::v32f32);
4711 
4712   SDValue Lo0, Hi0;
4713   SDValue Op0 = Op.getOperand(0);
4714   std::tie(Lo0, Hi0) = Op0.getValueType().isVector()
4715                          ? DAG.SplitVectorOperand(Op.getNode(), 0)
4716                          : std::make_pair(Op0, Op0);
4717   SDValue Lo1, Hi1;
4718   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4719   SDValue Lo2, Hi2;
4720   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4721 
4722   SDLoc SL(Op);
4723   auto ResVT = DAG.GetSplitDestVTs(VT);
4724 
4725   SDValue OpLo = DAG.getNode(Opc, SL, ResVT.first, Lo0, Lo1, Lo2,
4726                              Op->getFlags());
4727   SDValue OpHi = DAG.getNode(Opc, SL, ResVT.second, Hi0, Hi1, Hi2,
4728                              Op->getFlags());
4729 
4730   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4731 }
4732 
4733 
4734 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4735   switch (Op.getOpcode()) {
4736   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4737   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4738   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4739   case ISD::LOAD: {
4740     SDValue Result = LowerLOAD(Op, DAG);
4741     assert((!Result.getNode() ||
4742             Result.getNode()->getNumValues() == 2) &&
4743            "Load should return a value and a chain");
4744     return Result;
4745   }
4746 
4747   case ISD::FSIN:
4748   case ISD::FCOS:
4749     return LowerTrig(Op, DAG);
4750   case ISD::SELECT: return LowerSELECT(Op, DAG);
4751   case ISD::FDIV: return LowerFDIV(Op, DAG);
4752   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4753   case ISD::STORE: return LowerSTORE(Op, DAG);
4754   case ISD::GlobalAddress: {
4755     MachineFunction &MF = DAG.getMachineFunction();
4756     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4757     return LowerGlobalAddress(MFI, Op, DAG);
4758   }
4759   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4760   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4761   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4762   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4763   case ISD::INSERT_SUBVECTOR:
4764     return lowerINSERT_SUBVECTOR(Op, DAG);
4765   case ISD::INSERT_VECTOR_ELT:
4766     return lowerINSERT_VECTOR_ELT(Op, DAG);
4767   case ISD::EXTRACT_VECTOR_ELT:
4768     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4769   case ISD::VECTOR_SHUFFLE:
4770     return lowerVECTOR_SHUFFLE(Op, DAG);
4771   case ISD::BUILD_VECTOR:
4772     return lowerBUILD_VECTOR(Op, DAG);
4773   case ISD::FP_ROUND:
4774     return lowerFP_ROUND(Op, DAG);
4775   case ISD::FPTRUNC_ROUND: {
4776     unsigned Opc;
4777     SDLoc DL(Op);
4778 
4779     if (Op.getOperand(0)->getValueType(0) != MVT::f32)
4780       return SDValue();
4781 
4782     // Get the rounding mode from the last operand
4783     int RoundMode = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4784     if (RoundMode == (int)RoundingMode::TowardPositive)
4785       Opc = AMDGPUISD::FPTRUNC_ROUND_UPWARD;
4786     else if (RoundMode == (int)RoundingMode::TowardNegative)
4787       Opc = AMDGPUISD::FPTRUNC_ROUND_DOWNWARD;
4788     else
4789       return SDValue();
4790 
4791     return DAG.getNode(Opc, DL, Op.getNode()->getVTList(), Op->getOperand(0));
4792   }
4793   case ISD::TRAP:
4794     return lowerTRAP(Op, DAG);
4795   case ISD::DEBUGTRAP:
4796     return lowerDEBUGTRAP(Op, DAG);
4797   case ISD::FABS:
4798   case ISD::FNEG:
4799   case ISD::FCANONICALIZE:
4800   case ISD::BSWAP:
4801     return splitUnaryVectorOp(Op, DAG);
4802   case ISD::FMINNUM:
4803   case ISD::FMAXNUM:
4804     return lowerFMINNUM_FMAXNUM(Op, DAG);
4805   case ISD::FMA:
4806     return splitTernaryVectorOp(Op, DAG);
4807   case ISD::FP_TO_SINT:
4808   case ISD::FP_TO_UINT:
4809     return LowerFP_TO_INT(Op, DAG);
4810   case ISD::SHL:
4811   case ISD::SRA:
4812   case ISD::SRL:
4813   case ISD::ADD:
4814   case ISD::SUB:
4815   case ISD::MUL:
4816   case ISD::SMIN:
4817   case ISD::SMAX:
4818   case ISD::UMIN:
4819   case ISD::UMAX:
4820   case ISD::FADD:
4821   case ISD::FMUL:
4822   case ISD::FMINNUM_IEEE:
4823   case ISD::FMAXNUM_IEEE:
4824   case ISD::UADDSAT:
4825   case ISD::USUBSAT:
4826   case ISD::SADDSAT:
4827   case ISD::SSUBSAT:
4828     return splitBinaryVectorOp(Op, DAG);
4829   case ISD::SMULO:
4830   case ISD::UMULO:
4831     return lowerXMULO(Op, DAG);
4832   case ISD::SMUL_LOHI:
4833   case ISD::UMUL_LOHI:
4834     return lowerXMUL_LOHI(Op, DAG);
4835   case ISD::DYNAMIC_STACKALLOC:
4836     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4837   }
4838   return SDValue();
4839 }
4840 
4841 // Used for D16: Casts the result of an instruction into the right vector,
4842 // packs values if loads return unpacked values.
4843 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4844                                        const SDLoc &DL,
4845                                        SelectionDAG &DAG, bool Unpacked) {
4846   if (!LoadVT.isVector())
4847     return Result;
4848 
4849   // Cast back to the original packed type or to a larger type that is a
4850   // multiple of 32 bit for D16. Widening the return type is a required for
4851   // legalization.
4852   EVT FittingLoadVT = LoadVT;
4853   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4854     FittingLoadVT =
4855         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4856                          LoadVT.getVectorNumElements() + 1);
4857   }
4858 
4859   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4860     // Truncate to v2i16/v4i16.
4861     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4862 
4863     // Workaround legalizer not scalarizing truncate after vector op
4864     // legalization but not creating intermediate vector trunc.
4865     SmallVector<SDValue, 4> Elts;
4866     DAG.ExtractVectorElements(Result, Elts);
4867     for (SDValue &Elt : Elts)
4868       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4869 
4870     // Pad illegal v1i16/v3fi6 to v4i16
4871     if ((LoadVT.getVectorNumElements() % 2) == 1)
4872       Elts.push_back(DAG.getUNDEF(MVT::i16));
4873 
4874     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4875 
4876     // Bitcast to original type (v2f16/v4f16).
4877     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4878   }
4879 
4880   // Cast back to the original packed type.
4881   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4882 }
4883 
4884 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4885                                               MemSDNode *M,
4886                                               SelectionDAG &DAG,
4887                                               ArrayRef<SDValue> Ops,
4888                                               bool IsIntrinsic) const {
4889   SDLoc DL(M);
4890 
4891   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4892   EVT LoadVT = M->getValueType(0);
4893 
4894   EVT EquivLoadVT = LoadVT;
4895   if (LoadVT.isVector()) {
4896     if (Unpacked) {
4897       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4898                                      LoadVT.getVectorNumElements());
4899     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4900       // Widen v3f16 to legal type
4901       EquivLoadVT =
4902           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4903                            LoadVT.getVectorNumElements() + 1);
4904     }
4905   }
4906 
4907   // Change from v4f16/v2f16 to EquivLoadVT.
4908   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4909 
4910   SDValue Load
4911     = DAG.getMemIntrinsicNode(
4912       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4913       VTList, Ops, M->getMemoryVT(),
4914       M->getMemOperand());
4915 
4916   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4917 
4918   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4919 }
4920 
4921 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4922                                              SelectionDAG &DAG,
4923                                              ArrayRef<SDValue> Ops) const {
4924   SDLoc DL(M);
4925   EVT LoadVT = M->getValueType(0);
4926   EVT EltType = LoadVT.getScalarType();
4927   EVT IntVT = LoadVT.changeTypeToInteger();
4928 
4929   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4930 
4931   unsigned Opc =
4932       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4933 
4934   if (IsD16) {
4935     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4936   }
4937 
4938   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4939   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4940     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4941 
4942   if (isTypeLegal(LoadVT)) {
4943     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4944                                M->getMemOperand(), DAG);
4945   }
4946 
4947   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4948   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4949   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4950                                         M->getMemOperand(), DAG);
4951   return DAG.getMergeValues(
4952       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4953       DL);
4954 }
4955 
4956 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4957                                   SDNode *N, SelectionDAG &DAG) {
4958   EVT VT = N->getValueType(0);
4959   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4960   unsigned CondCode = CD->getZExtValue();
4961   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4962     return DAG.getUNDEF(VT);
4963 
4964   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4965 
4966   SDValue LHS = N->getOperand(1);
4967   SDValue RHS = N->getOperand(2);
4968 
4969   SDLoc DL(N);
4970 
4971   EVT CmpVT = LHS.getValueType();
4972   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4973     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4974       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4975     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4976     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4977   }
4978 
4979   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4980 
4981   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4982   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4983 
4984   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4985                               DAG.getCondCode(CCOpcode));
4986   if (VT.bitsEq(CCVT))
4987     return SetCC;
4988   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4989 }
4990 
4991 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4992                                   SDNode *N, SelectionDAG &DAG) {
4993   EVT VT = N->getValueType(0);
4994   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4995 
4996   unsigned CondCode = CD->getZExtValue();
4997   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4998     return DAG.getUNDEF(VT);
4999 
5000   SDValue Src0 = N->getOperand(1);
5001   SDValue Src1 = N->getOperand(2);
5002   EVT CmpVT = Src0.getValueType();
5003   SDLoc SL(N);
5004 
5005   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
5006     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
5007     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
5008   }
5009 
5010   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
5011   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
5012   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
5013   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
5014   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
5015                               Src1, DAG.getCondCode(CCOpcode));
5016   if (VT.bitsEq(CCVT))
5017     return SetCC;
5018   return DAG.getZExtOrTrunc(SetCC, SL, VT);
5019 }
5020 
5021 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
5022                                     SelectionDAG &DAG) {
5023   EVT VT = N->getValueType(0);
5024   SDValue Src = N->getOperand(1);
5025   SDLoc SL(N);
5026 
5027   if (Src.getOpcode() == ISD::SETCC) {
5028     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
5029     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
5030                        Src.getOperand(1), Src.getOperand(2));
5031   }
5032   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
5033     // (ballot 0) -> 0
5034     if (Arg->isZero())
5035       return DAG.getConstant(0, SL, VT);
5036 
5037     // (ballot 1) -> EXEC/EXEC_LO
5038     if (Arg->isOne()) {
5039       Register Exec;
5040       if (VT.getScalarSizeInBits() == 32)
5041         Exec = AMDGPU::EXEC_LO;
5042       else if (VT.getScalarSizeInBits() == 64)
5043         Exec = AMDGPU::EXEC;
5044       else
5045         return SDValue();
5046 
5047       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
5048     }
5049   }
5050 
5051   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
5052   // ISD::SETNE)
5053   return DAG.getNode(
5054       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
5055       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
5056 }
5057 
5058 void SITargetLowering::ReplaceNodeResults(SDNode *N,
5059                                           SmallVectorImpl<SDValue> &Results,
5060                                           SelectionDAG &DAG) const {
5061   switch (N->getOpcode()) {
5062   case ISD::INSERT_VECTOR_ELT: {
5063     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
5064       Results.push_back(Res);
5065     return;
5066   }
5067   case ISD::EXTRACT_VECTOR_ELT: {
5068     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
5069       Results.push_back(Res);
5070     return;
5071   }
5072   case ISD::INTRINSIC_WO_CHAIN: {
5073     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5074     switch (IID) {
5075     case Intrinsic::amdgcn_cvt_pkrtz: {
5076       SDValue Src0 = N->getOperand(1);
5077       SDValue Src1 = N->getOperand(2);
5078       SDLoc SL(N);
5079       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
5080                                 Src0, Src1);
5081       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
5082       return;
5083     }
5084     case Intrinsic::amdgcn_cvt_pknorm_i16:
5085     case Intrinsic::amdgcn_cvt_pknorm_u16:
5086     case Intrinsic::amdgcn_cvt_pk_i16:
5087     case Intrinsic::amdgcn_cvt_pk_u16: {
5088       SDValue Src0 = N->getOperand(1);
5089       SDValue Src1 = N->getOperand(2);
5090       SDLoc SL(N);
5091       unsigned Opcode;
5092 
5093       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
5094         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
5095       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
5096         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
5097       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
5098         Opcode = AMDGPUISD::CVT_PK_I16_I32;
5099       else
5100         Opcode = AMDGPUISD::CVT_PK_U16_U32;
5101 
5102       EVT VT = N->getValueType(0);
5103       if (isTypeLegal(VT))
5104         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
5105       else {
5106         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
5107         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
5108       }
5109       return;
5110     }
5111     }
5112     break;
5113   }
5114   case ISD::INTRINSIC_W_CHAIN: {
5115     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
5116       if (Res.getOpcode() == ISD::MERGE_VALUES) {
5117         // FIXME: Hacky
5118         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
5119           Results.push_back(Res.getOperand(I));
5120         }
5121       } else {
5122         Results.push_back(Res);
5123         Results.push_back(Res.getValue(1));
5124       }
5125       return;
5126     }
5127 
5128     break;
5129   }
5130   case ISD::SELECT: {
5131     SDLoc SL(N);
5132     EVT VT = N->getValueType(0);
5133     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
5134     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
5135     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
5136 
5137     EVT SelectVT = NewVT;
5138     if (NewVT.bitsLT(MVT::i32)) {
5139       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
5140       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
5141       SelectVT = MVT::i32;
5142     }
5143 
5144     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
5145                                     N->getOperand(0), LHS, RHS);
5146 
5147     if (NewVT != SelectVT)
5148       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
5149     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
5150     return;
5151   }
5152   case ISD::FNEG: {
5153     if (N->getValueType(0) != MVT::v2f16)
5154       break;
5155 
5156     SDLoc SL(N);
5157     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5158 
5159     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
5160                              BC,
5161                              DAG.getConstant(0x80008000, SL, MVT::i32));
5162     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5163     return;
5164   }
5165   case ISD::FABS: {
5166     if (N->getValueType(0) != MVT::v2f16)
5167       break;
5168 
5169     SDLoc SL(N);
5170     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
5171 
5172     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
5173                              BC,
5174                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
5175     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
5176     return;
5177   }
5178   default:
5179     break;
5180   }
5181 }
5182 
5183 /// Helper function for LowerBRCOND
5184 static SDNode *findUser(SDValue Value, unsigned Opcode) {
5185 
5186   SDNode *Parent = Value.getNode();
5187   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
5188        I != E; ++I) {
5189 
5190     if (I.getUse().get() != Value)
5191       continue;
5192 
5193     if (I->getOpcode() == Opcode)
5194       return *I;
5195   }
5196   return nullptr;
5197 }
5198 
5199 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
5200   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
5201     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
5202     case Intrinsic::amdgcn_if:
5203       return AMDGPUISD::IF;
5204     case Intrinsic::amdgcn_else:
5205       return AMDGPUISD::ELSE;
5206     case Intrinsic::amdgcn_loop:
5207       return AMDGPUISD::LOOP;
5208     case Intrinsic::amdgcn_end_cf:
5209       llvm_unreachable("should not occur");
5210     default:
5211       return 0;
5212     }
5213   }
5214 
5215   // break, if_break, else_break are all only used as inputs to loop, not
5216   // directly as branch conditions.
5217   return 0;
5218 }
5219 
5220 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
5221   const Triple &TT = getTargetMachine().getTargetTriple();
5222   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5223           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5224          AMDGPU::shouldEmitConstantsToTextSection(TT);
5225 }
5226 
5227 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
5228   // FIXME: Either avoid relying on address space here or change the default
5229   // address space for functions to avoid the explicit check.
5230   return (GV->getValueType()->isFunctionTy() ||
5231           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
5232          !shouldEmitFixup(GV) &&
5233          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
5234 }
5235 
5236 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
5237   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
5238 }
5239 
5240 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
5241   if (!GV->hasExternalLinkage())
5242     return true;
5243 
5244   const auto OS = getTargetMachine().getTargetTriple().getOS();
5245   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
5246 }
5247 
5248 /// This transforms the control flow intrinsics to get the branch destination as
5249 /// last parameter, also switches branch target with BR if the need arise
5250 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
5251                                       SelectionDAG &DAG) const {
5252   SDLoc DL(BRCOND);
5253 
5254   SDNode *Intr = BRCOND.getOperand(1).getNode();
5255   SDValue Target = BRCOND.getOperand(2);
5256   SDNode *BR = nullptr;
5257   SDNode *SetCC = nullptr;
5258 
5259   if (Intr->getOpcode() == ISD::SETCC) {
5260     // As long as we negate the condition everything is fine
5261     SetCC = Intr;
5262     Intr = SetCC->getOperand(0).getNode();
5263 
5264   } else {
5265     // Get the target from BR if we don't negate the condition
5266     BR = findUser(BRCOND, ISD::BR);
5267     assert(BR && "brcond missing unconditional branch user");
5268     Target = BR->getOperand(1);
5269   }
5270 
5271   unsigned CFNode = isCFIntrinsic(Intr);
5272   if (CFNode == 0) {
5273     // This is a uniform branch so we don't need to legalize.
5274     return BRCOND;
5275   }
5276 
5277   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5278                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5279 
5280   assert(!SetCC ||
5281         (SetCC->getConstantOperandVal(1) == 1 &&
5282          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5283                                                              ISD::SETNE));
5284 
5285   // operands of the new intrinsic call
5286   SmallVector<SDValue, 4> Ops;
5287   if (HaveChain)
5288     Ops.push_back(BRCOND.getOperand(0));
5289 
5290   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5291   Ops.push_back(Target);
5292 
5293   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5294 
5295   // build the new intrinsic call
5296   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5297 
5298   if (!HaveChain) {
5299     SDValue Ops[] =  {
5300       SDValue(Result, 0),
5301       BRCOND.getOperand(0)
5302     };
5303 
5304     Result = DAG.getMergeValues(Ops, DL).getNode();
5305   }
5306 
5307   if (BR) {
5308     // Give the branch instruction our target
5309     SDValue Ops[] = {
5310       BR->getOperand(0),
5311       BRCOND.getOperand(2)
5312     };
5313     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5314     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5315   }
5316 
5317   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5318 
5319   // Copy the intrinsic results to registers
5320   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5321     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5322     if (!CopyToReg)
5323       continue;
5324 
5325     Chain = DAG.getCopyToReg(
5326       Chain, DL,
5327       CopyToReg->getOperand(1),
5328       SDValue(Result, i - 1),
5329       SDValue());
5330 
5331     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5332   }
5333 
5334   // Remove the old intrinsic from the chain
5335   DAG.ReplaceAllUsesOfValueWith(
5336     SDValue(Intr, Intr->getNumValues() - 1),
5337     Intr->getOperand(0));
5338 
5339   return Chain;
5340 }
5341 
5342 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5343                                           SelectionDAG &DAG) const {
5344   MVT VT = Op.getSimpleValueType();
5345   SDLoc DL(Op);
5346   // Checking the depth
5347   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5348     return DAG.getConstant(0, DL, VT);
5349 
5350   MachineFunction &MF = DAG.getMachineFunction();
5351   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5352   // Check for kernel and shader functions
5353   if (Info->isEntryFunction())
5354     return DAG.getConstant(0, DL, VT);
5355 
5356   MachineFrameInfo &MFI = MF.getFrameInfo();
5357   // There is a call to @llvm.returnaddress in this function
5358   MFI.setReturnAddressIsTaken(true);
5359 
5360   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5361   // Get the return address reg and mark it as an implicit live-in
5362   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5363 
5364   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5365 }
5366 
5367 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5368                                             SDValue Op,
5369                                             const SDLoc &DL,
5370                                             EVT VT) const {
5371   return Op.getValueType().bitsLE(VT) ?
5372       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5373     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5374                 DAG.getTargetConstant(0, DL, MVT::i32));
5375 }
5376 
5377 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5378   assert(Op.getValueType() == MVT::f16 &&
5379          "Do not know how to custom lower FP_ROUND for non-f16 type");
5380 
5381   SDValue Src = Op.getOperand(0);
5382   EVT SrcVT = Src.getValueType();
5383   if (SrcVT != MVT::f64)
5384     return Op;
5385 
5386   SDLoc DL(Op);
5387 
5388   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5389   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5390   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5391 }
5392 
5393 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5394                                                SelectionDAG &DAG) const {
5395   EVT VT = Op.getValueType();
5396   const MachineFunction &MF = DAG.getMachineFunction();
5397   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5398   bool IsIEEEMode = Info->getMode().IEEE;
5399 
5400   // FIXME: Assert during selection that this is only selected for
5401   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5402   // mode functions, but this happens to be OK since it's only done in cases
5403   // where there is known no sNaN.
5404   if (IsIEEEMode)
5405     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5406 
5407   if (VT == MVT::v4f16 || VT == MVT::v8f16)
5408     return splitBinaryVectorOp(Op, DAG);
5409   return Op;
5410 }
5411 
5412 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5413   EVT VT = Op.getValueType();
5414   SDLoc SL(Op);
5415   SDValue LHS = Op.getOperand(0);
5416   SDValue RHS = Op.getOperand(1);
5417   bool isSigned = Op.getOpcode() == ISD::SMULO;
5418 
5419   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5420     const APInt &C = RHSC->getAPIntValue();
5421     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5422     if (C.isPowerOf2()) {
5423       // smulo(x, signed_min) is same as umulo(x, signed_min).
5424       bool UseArithShift = isSigned && !C.isMinSignedValue();
5425       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5426       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5427       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5428           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5429                       SL, VT, Result, ShiftAmt),
5430           LHS, ISD::SETNE);
5431       return DAG.getMergeValues({ Result, Overflow }, SL);
5432     }
5433   }
5434 
5435   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5436   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5437                             SL, VT, LHS, RHS);
5438 
5439   SDValue Sign = isSigned
5440     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5441                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5442     : DAG.getConstant(0, SL, VT);
5443   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5444 
5445   return DAG.getMergeValues({ Result, Overflow }, SL);
5446 }
5447 
5448 SDValue SITargetLowering::lowerXMUL_LOHI(SDValue Op, SelectionDAG &DAG) const {
5449   if (Op->isDivergent()) {
5450     // Select to V_MAD_[IU]64_[IU]32.
5451     return Op;
5452   }
5453   if (Subtarget->hasSMulHi()) {
5454     // Expand to S_MUL_I32 + S_MUL_HI_[IU]32.
5455     return SDValue();
5456   }
5457   // The multiply is uniform but we would have to use V_MUL_HI_[IU]32 to
5458   // calculate the high part, so we might as well do the whole thing with
5459   // V_MAD_[IU]64_[IU]32.
5460   return Op;
5461 }
5462 
5463 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5464   if (!Subtarget->isTrapHandlerEnabled() ||
5465       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA)
5466     return lowerTrapEndpgm(Op, DAG);
5467 
5468   if (Optional<uint8_t> HsaAbiVer = AMDGPU::getHsaAbiVersion(Subtarget)) {
5469     switch (*HsaAbiVer) {
5470     case ELF::ELFABIVERSION_AMDGPU_HSA_V2:
5471     case ELF::ELFABIVERSION_AMDGPU_HSA_V3:
5472       return lowerTrapHsaQueuePtr(Op, DAG);
5473     case ELF::ELFABIVERSION_AMDGPU_HSA_V4:
5474     case ELF::ELFABIVERSION_AMDGPU_HSA_V5:
5475       return Subtarget->supportsGetDoorbellID() ?
5476           lowerTrapHsa(Op, DAG) : lowerTrapHsaQueuePtr(Op, DAG);
5477     }
5478   }
5479 
5480   llvm_unreachable("Unknown trap handler");
5481 }
5482 
5483 SDValue SITargetLowering::lowerTrapEndpgm(
5484     SDValue Op, SelectionDAG &DAG) const {
5485   SDLoc SL(Op);
5486   SDValue Chain = Op.getOperand(0);
5487   return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5488 }
5489 
5490 SDValue SITargetLowering::loadImplicitKernelArgument(SelectionDAG &DAG, MVT VT,
5491     const SDLoc &DL, Align Alignment, ImplicitParameter Param) const {
5492   MachineFunction &MF = DAG.getMachineFunction();
5493   uint64_t Offset = getImplicitParameterOffset(MF, Param);
5494   SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, DAG.getEntryNode(), Offset);
5495   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5496   return DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, PtrInfo, Alignment,
5497                      MachineMemOperand::MODereferenceable |
5498                          MachineMemOperand::MOInvariant);
5499 }
5500 
5501 SDValue SITargetLowering::lowerTrapHsaQueuePtr(
5502     SDValue Op, SelectionDAG &DAG) const {
5503   SDLoc SL(Op);
5504   SDValue Chain = Op.getOperand(0);
5505 
5506   SDValue QueuePtr;
5507   // For code object version 5, QueuePtr is passed through implicit kernarg.
5508   if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) {
5509     QueuePtr =
5510         loadImplicitKernelArgument(DAG, MVT::i64, SL, Align(8), QUEUE_PTR);
5511   } else {
5512     MachineFunction &MF = DAG.getMachineFunction();
5513     SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5514     Register UserSGPR = Info->getQueuePtrUserSGPR();
5515 
5516     if (UserSGPR == AMDGPU::NoRegister) {
5517       // We probably are in a function incorrectly marked with
5518       // amdgpu-no-queue-ptr. This is undefined. We don't want to delete the
5519       // trap, so just use a null pointer.
5520       QueuePtr = DAG.getConstant(0, SL, MVT::i64);
5521     } else {
5522       QueuePtr = CreateLiveInRegister(DAG, &AMDGPU::SReg_64RegClass, UserSGPR,
5523                                       MVT::i64);
5524     }
5525   }
5526 
5527   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5528   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5529                                    QueuePtr, SDValue());
5530 
5531   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5532   SDValue Ops[] = {
5533     ToReg,
5534     DAG.getTargetConstant(TrapID, SL, MVT::i16),
5535     SGPR01,
5536     ToReg.getValue(1)
5537   };
5538   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5539 }
5540 
5541 SDValue SITargetLowering::lowerTrapHsa(
5542     SDValue Op, SelectionDAG &DAG) const {
5543   SDLoc SL(Op);
5544   SDValue Chain = Op.getOperand(0);
5545 
5546   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSATrap);
5547   SDValue Ops[] = {
5548     Chain,
5549     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5550   };
5551   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5552 }
5553 
5554 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5555   SDLoc SL(Op);
5556   SDValue Chain = Op.getOperand(0);
5557   MachineFunction &MF = DAG.getMachineFunction();
5558 
5559   if (!Subtarget->isTrapHandlerEnabled() ||
5560       Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbi::AMDHSA) {
5561     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5562                                      "debugtrap handler not supported",
5563                                      Op.getDebugLoc(),
5564                                      DS_Warning);
5565     LLVMContext &Ctx = MF.getFunction().getContext();
5566     Ctx.diagnose(NoTrap);
5567     return Chain;
5568   }
5569 
5570   uint64_t TrapID = static_cast<uint64_t>(GCNSubtarget::TrapID::LLVMAMDHSADebugTrap);
5571   SDValue Ops[] = {
5572     Chain,
5573     DAG.getTargetConstant(TrapID, SL, MVT::i16)
5574   };
5575   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5576 }
5577 
5578 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5579                                              SelectionDAG &DAG) const {
5580   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5581   if (Subtarget->hasApertureRegs()) {
5582     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5583         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5584         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5585     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5586         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5587         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5588     unsigned Encoding =
5589         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5590         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5591         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5592 
5593     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5594     SDValue ApertureReg = SDValue(
5595         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5596     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5597     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5598   }
5599 
5600   // For code object version 5, private_base and shared_base are passed through
5601   // implicit kernargs.
5602   if (AMDGPU::getAmdhsaCodeObjectVersion() == 5) {
5603     ImplicitParameter Param =
5604         (AS == AMDGPUAS::LOCAL_ADDRESS) ? SHARED_BASE : PRIVATE_BASE;
5605     return loadImplicitKernelArgument(DAG, MVT::i32, DL, Align(4), Param);
5606   }
5607 
5608   MachineFunction &MF = DAG.getMachineFunction();
5609   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5610   Register UserSGPR = Info->getQueuePtrUserSGPR();
5611   if (UserSGPR == AMDGPU::NoRegister) {
5612     // We probably are in a function incorrectly marked with
5613     // amdgpu-no-queue-ptr. This is undefined.
5614     return DAG.getUNDEF(MVT::i32);
5615   }
5616 
5617   SDValue QueuePtr = CreateLiveInRegister(
5618     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5619 
5620   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5621   // private_segment_aperture_base_hi.
5622   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5623 
5624   SDValue Ptr =
5625       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5626 
5627   // TODO: Use custom target PseudoSourceValue.
5628   // TODO: We should use the value from the IR intrinsic call, but it might not
5629   // be available and how do we get it?
5630   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5631   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5632                      commonAlignment(Align(64), StructOffset),
5633                      MachineMemOperand::MODereferenceable |
5634                          MachineMemOperand::MOInvariant);
5635 }
5636 
5637 /// Return true if the value is a known valid address, such that a null check is
5638 /// not necessary.
5639 static bool isKnownNonNull(SDValue Val, SelectionDAG &DAG,
5640                            const AMDGPUTargetMachine &TM, unsigned AddrSpace) {
5641   if (isa<FrameIndexSDNode>(Val) || isa<GlobalAddressSDNode>(Val) ||
5642       isa<BasicBlockSDNode>(Val))
5643     return true;
5644 
5645   if (auto *ConstVal = dyn_cast<ConstantSDNode>(Val))
5646     return ConstVal->getSExtValue() != TM.getNullPointerValue(AddrSpace);
5647 
5648   // TODO: Search through arithmetic, handle arguments and loads
5649   // marked nonnull.
5650   return false;
5651 }
5652 
5653 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5654                                              SelectionDAG &DAG) const {
5655   SDLoc SL(Op);
5656   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5657 
5658   SDValue Src = ASC->getOperand(0);
5659   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5660   unsigned SrcAS = ASC->getSrcAddressSpace();
5661 
5662   const AMDGPUTargetMachine &TM =
5663     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5664 
5665   // flat -> local/private
5666   if (SrcAS == AMDGPUAS::FLAT_ADDRESS) {
5667     unsigned DestAS = ASC->getDestAddressSpace();
5668 
5669     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5670         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5671       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5672 
5673       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5674         return Ptr;
5675 
5676       unsigned NullVal = TM.getNullPointerValue(DestAS);
5677       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5678       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5679 
5680       return DAG.getNode(ISD::SELECT, SL, MVT::i32, NonNull, Ptr,
5681                          SegmentNullPtr);
5682     }
5683   }
5684 
5685   // local/private -> flat
5686   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5687     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5688         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5689 
5690       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5691       SDValue CvtPtr =
5692           DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5693       CvtPtr = DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr);
5694 
5695       if (isKnownNonNull(Src, DAG, TM, SrcAS))
5696         return CvtPtr;
5697 
5698       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5699       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5700 
5701       SDValue NonNull
5702         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5703 
5704       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, CvtPtr,
5705                          FlatNullPtr);
5706     }
5707   }
5708 
5709   if (SrcAS == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5710       Op.getValueType() == MVT::i64) {
5711     const SIMachineFunctionInfo *Info =
5712         DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>();
5713     SDValue Hi = DAG.getConstant(Info->get32BitAddressHighBits(), SL, MVT::i32);
5714     SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Hi);
5715     return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
5716   }
5717 
5718   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5719       Src.getValueType() == MVT::i64)
5720     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5721 
5722   // global <-> flat are no-ops and never emitted.
5723 
5724   const MachineFunction &MF = DAG.getMachineFunction();
5725   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5726     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5727   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5728 
5729   return DAG.getUNDEF(ASC->getValueType(0));
5730 }
5731 
5732 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5733 // the small vector and inserting them into the big vector. That is better than
5734 // the default expansion of doing it via a stack slot. Even though the use of
5735 // the stack slot would be optimized away afterwards, the stack slot itself
5736 // remains.
5737 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5738                                                 SelectionDAG &DAG) const {
5739   SDValue Vec = Op.getOperand(0);
5740   SDValue Ins = Op.getOperand(1);
5741   SDValue Idx = Op.getOperand(2);
5742   EVT VecVT = Vec.getValueType();
5743   EVT InsVT = Ins.getValueType();
5744   EVT EltVT = VecVT.getVectorElementType();
5745   unsigned InsNumElts = InsVT.getVectorNumElements();
5746   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5747   SDLoc SL(Op);
5748 
5749   for (unsigned I = 0; I != InsNumElts; ++I) {
5750     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5751                               DAG.getConstant(I, SL, MVT::i32));
5752     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5753                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5754   }
5755   return Vec;
5756 }
5757 
5758 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5759                                                  SelectionDAG &DAG) const {
5760   SDValue Vec = Op.getOperand(0);
5761   SDValue InsVal = Op.getOperand(1);
5762   SDValue Idx = Op.getOperand(2);
5763   EVT VecVT = Vec.getValueType();
5764   EVT EltVT = VecVT.getVectorElementType();
5765   unsigned VecSize = VecVT.getSizeInBits();
5766   unsigned EltSize = EltVT.getSizeInBits();
5767 
5768 
5769   assert(VecSize <= 64);
5770 
5771   unsigned NumElts = VecVT.getVectorNumElements();
5772   SDLoc SL(Op);
5773   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5774 
5775   if (NumElts == 4 && EltSize == 16 && KIdx) {
5776     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5777 
5778     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5779                                  DAG.getConstant(0, SL, MVT::i32));
5780     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5781                                  DAG.getConstant(1, SL, MVT::i32));
5782 
5783     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5784     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5785 
5786     unsigned Idx = KIdx->getZExtValue();
5787     bool InsertLo = Idx < 2;
5788     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5789       InsertLo ? LoVec : HiVec,
5790       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5791       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5792 
5793     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5794 
5795     SDValue Concat = InsertLo ?
5796       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5797       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5798 
5799     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5800   }
5801 
5802   if (isa<ConstantSDNode>(Idx))
5803     return SDValue();
5804 
5805   MVT IntVT = MVT::getIntegerVT(VecSize);
5806 
5807   // Avoid stack access for dynamic indexing.
5808   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5809 
5810   // Create a congruent vector with the target value in each element so that
5811   // the required element can be masked and ORed into the target vector.
5812   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5813                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5814 
5815   assert(isPowerOf2_32(EltSize));
5816   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5817 
5818   // Convert vector index to bit-index.
5819   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5820 
5821   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5822   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5823                             DAG.getConstant(0xffff, SL, IntVT),
5824                             ScaledIdx);
5825 
5826   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5827   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5828                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5829 
5830   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5831   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5832 }
5833 
5834 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5835                                                   SelectionDAG &DAG) const {
5836   SDLoc SL(Op);
5837 
5838   EVT ResultVT = Op.getValueType();
5839   SDValue Vec = Op.getOperand(0);
5840   SDValue Idx = Op.getOperand(1);
5841   EVT VecVT = Vec.getValueType();
5842   unsigned VecSize = VecVT.getSizeInBits();
5843   EVT EltVT = VecVT.getVectorElementType();
5844 
5845   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5846 
5847   // Make sure we do any optimizations that will make it easier to fold
5848   // source modifiers before obscuring it with bit operations.
5849 
5850   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5851   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5852     return Combined;
5853 
5854   if (VecSize == 128) {
5855     SDValue Lo, Hi;
5856     EVT LoVT, HiVT;
5857     SDValue V2 = DAG.getBitcast(MVT::v2i64, Vec);
5858     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5859     Lo =
5860         DAG.getBitcast(LoVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5861                                          V2, DAG.getConstant(0, SL, MVT::i32)));
5862     Hi =
5863         DAG.getBitcast(HiVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i64,
5864                                          V2, DAG.getConstant(1, SL, MVT::i32)));
5865     EVT IdxVT = Idx.getValueType();
5866     unsigned NElem = VecVT.getVectorNumElements();
5867     assert(isPowerOf2_32(NElem));
5868     SDValue IdxMask = DAG.getConstant(NElem / 2 - 1, SL, IdxVT);
5869     SDValue NewIdx = DAG.getNode(ISD::AND, SL, IdxVT, Idx, IdxMask);
5870     SDValue Half = DAG.getSelectCC(SL, Idx, IdxMask, Hi, Lo, ISD::SETUGT);
5871     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Half, NewIdx);
5872   }
5873 
5874   assert(VecSize <= 64);
5875 
5876   unsigned EltSize = EltVT.getSizeInBits();
5877   assert(isPowerOf2_32(EltSize));
5878 
5879   MVT IntVT = MVT::getIntegerVT(VecSize);
5880   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5881 
5882   // Convert vector index to bit-index (* EltSize)
5883   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5884 
5885   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5886   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5887 
5888   if (ResultVT == MVT::f16) {
5889     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5890     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5891   }
5892 
5893   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5894 }
5895 
5896 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5897   assert(Elt % 2 == 0);
5898   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5899 }
5900 
5901 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5902                                               SelectionDAG &DAG) const {
5903   SDLoc SL(Op);
5904   EVT ResultVT = Op.getValueType();
5905   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5906 
5907   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5908   EVT EltVT = PackVT.getVectorElementType();
5909   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5910 
5911   // vector_shuffle <0,1,6,7> lhs, rhs
5912   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5913   //
5914   // vector_shuffle <6,7,2,3> lhs, rhs
5915   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5916   //
5917   // vector_shuffle <6,7,0,1> lhs, rhs
5918   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5919 
5920   // Avoid scalarizing when both halves are reading from consecutive elements.
5921   SmallVector<SDValue, 4> Pieces;
5922   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5923     if (elementPairIsContiguous(SVN->getMask(), I)) {
5924       const int Idx = SVN->getMaskElt(I);
5925       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5926       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5927       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5928                                     PackVT, SVN->getOperand(VecIdx),
5929                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5930       Pieces.push_back(SubVec);
5931     } else {
5932       const int Idx0 = SVN->getMaskElt(I);
5933       const int Idx1 = SVN->getMaskElt(I + 1);
5934       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5935       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5936       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5937       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5938 
5939       SDValue Vec0 = SVN->getOperand(VecIdx0);
5940       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5941                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5942 
5943       SDValue Vec1 = SVN->getOperand(VecIdx1);
5944       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5945                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5946       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5947     }
5948   }
5949 
5950   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5951 }
5952 
5953 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5954                                             SelectionDAG &DAG) const {
5955   SDLoc SL(Op);
5956   EVT VT = Op.getValueType();
5957 
5958   if (VT == MVT::v4i16 || VT == MVT::v4f16 ||
5959       VT == MVT::v8i16 || VT == MVT::v8f16) {
5960     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(),
5961                                   VT.getVectorNumElements() / 2);
5962     MVT HalfIntVT = MVT::getIntegerVT(HalfVT.getSizeInBits());
5963 
5964     // Turn into pair of packed build_vectors.
5965     // TODO: Special case for constants that can be materialized with s_mov_b64.
5966     SmallVector<SDValue, 4> LoOps, HiOps;
5967     for (unsigned I = 0, E = VT.getVectorNumElements() / 2; I != E; ++I) {
5968       LoOps.push_back(Op.getOperand(I));
5969       HiOps.push_back(Op.getOperand(I + E));
5970     }
5971     SDValue Lo = DAG.getBuildVector(HalfVT, SL, LoOps);
5972     SDValue Hi = DAG.getBuildVector(HalfVT, SL, HiOps);
5973 
5974     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Lo);
5975     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, HalfIntVT, Hi);
5976 
5977     SDValue Blend = DAG.getBuildVector(MVT::getVectorVT(HalfIntVT, 2), SL,
5978                                        { CastLo, CastHi });
5979     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5980   }
5981 
5982   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5983   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5984 
5985   SDValue Lo = Op.getOperand(0);
5986   SDValue Hi = Op.getOperand(1);
5987 
5988   // Avoid adding defined bits with the zero_extend.
5989   if (Hi.isUndef()) {
5990     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5991     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5992     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5993   }
5994 
5995   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5996   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5997 
5998   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5999                               DAG.getConstant(16, SL, MVT::i32));
6000   if (Lo.isUndef())
6001     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
6002 
6003   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
6004   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
6005 
6006   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
6007   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
6008 }
6009 
6010 bool
6011 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
6012   // We can fold offsets for anything that doesn't require a GOT relocation.
6013   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
6014           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
6015           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
6016          !shouldEmitGOTReloc(GA->getGlobal());
6017 }
6018 
6019 static SDValue
6020 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
6021                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
6022                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
6023   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
6024   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
6025   // lowered to the following code sequence:
6026   //
6027   // For constant address space:
6028   //   s_getpc_b64 s[0:1]
6029   //   s_add_u32 s0, s0, $symbol
6030   //   s_addc_u32 s1, s1, 0
6031   //
6032   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
6033   //   a fixup or relocation is emitted to replace $symbol with a literal
6034   //   constant, which is a pc-relative offset from the encoding of the $symbol
6035   //   operand to the global variable.
6036   //
6037   // For global address space:
6038   //   s_getpc_b64 s[0:1]
6039   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
6040   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
6041   //
6042   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
6043   //   fixups or relocations are emitted to replace $symbol@*@lo and
6044   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
6045   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
6046   //   operand to the global variable.
6047   //
6048   // What we want here is an offset from the value returned by s_getpc
6049   // (which is the address of the s_add_u32 instruction) to the global
6050   // variable, but since the encoding of $symbol starts 4 bytes after the start
6051   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
6052   // small. This requires us to add 4 to the global variable offset in order to
6053   // compute the correct address. Similarly for the s_addc_u32 instruction, the
6054   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
6055   // instruction.
6056   SDValue PtrLo =
6057       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
6058   SDValue PtrHi;
6059   if (GAFlags == SIInstrInfo::MO_NONE) {
6060     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
6061   } else {
6062     PtrHi =
6063         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
6064   }
6065   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
6066 }
6067 
6068 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
6069                                              SDValue Op,
6070                                              SelectionDAG &DAG) const {
6071   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
6072   SDLoc DL(GSD);
6073   EVT PtrVT = Op.getValueType();
6074 
6075   const GlobalValue *GV = GSD->getGlobal();
6076   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
6077        shouldUseLDSConstAddress(GV)) ||
6078       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
6079       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
6080     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
6081         GV->hasExternalLinkage()) {
6082       Type *Ty = GV->getValueType();
6083       // HIP uses an unsized array `extern __shared__ T s[]` or similar
6084       // zero-sized type in other languages to declare the dynamic shared
6085       // memory which size is not known at the compile time. They will be
6086       // allocated by the runtime and placed directly after the static
6087       // allocated ones. They all share the same offset.
6088       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
6089         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
6090         // Adjust alignment for that dynamic shared memory array.
6091         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
6092         return SDValue(
6093             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
6094       }
6095     }
6096     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
6097   }
6098 
6099   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
6100     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
6101                                             SIInstrInfo::MO_ABS32_LO);
6102     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
6103   }
6104 
6105   if (shouldEmitFixup(GV))
6106     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
6107   else if (shouldEmitPCReloc(GV))
6108     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
6109                                    SIInstrInfo::MO_REL32);
6110 
6111   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
6112                                             SIInstrInfo::MO_GOTPCREL32);
6113 
6114   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
6115   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
6116   const DataLayout &DataLayout = DAG.getDataLayout();
6117   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
6118   MachinePointerInfo PtrInfo
6119     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
6120 
6121   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
6122                      MachineMemOperand::MODereferenceable |
6123                          MachineMemOperand::MOInvariant);
6124 }
6125 
6126 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
6127                                    const SDLoc &DL, SDValue V) const {
6128   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
6129   // the destination register.
6130   //
6131   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
6132   // so we will end up with redundant moves to m0.
6133   //
6134   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
6135 
6136   // A Null SDValue creates a glue result.
6137   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
6138                                   V, Chain);
6139   return SDValue(M0, 0);
6140 }
6141 
6142 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
6143                                                  SDValue Op,
6144                                                  MVT VT,
6145                                                  unsigned Offset) const {
6146   SDLoc SL(Op);
6147   SDValue Param = lowerKernargMemParameter(
6148       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
6149   // The local size values will have the hi 16-bits as zero.
6150   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
6151                      DAG.getValueType(VT));
6152 }
6153 
6154 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6155                                         EVT VT) {
6156   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6157                                       "non-hsa intrinsic with hsa target",
6158                                       DL.getDebugLoc());
6159   DAG.getContext()->diagnose(BadIntrin);
6160   return DAG.getUNDEF(VT);
6161 }
6162 
6163 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
6164                                          EVT VT) {
6165   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
6166                                       "intrinsic not supported on subtarget",
6167                                       DL.getDebugLoc());
6168   DAG.getContext()->diagnose(BadIntrin);
6169   return DAG.getUNDEF(VT);
6170 }
6171 
6172 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
6173                                     ArrayRef<SDValue> Elts) {
6174   assert(!Elts.empty());
6175   MVT Type;
6176   unsigned NumElts = Elts.size();
6177 
6178   if (NumElts <= 8) {
6179     Type = MVT::getVectorVT(MVT::f32, NumElts);
6180   } else {
6181     assert(Elts.size() <= 16);
6182     Type = MVT::v16f32;
6183     NumElts = 16;
6184   }
6185 
6186   SmallVector<SDValue, 16> VecElts(NumElts);
6187   for (unsigned i = 0; i < Elts.size(); ++i) {
6188     SDValue Elt = Elts[i];
6189     if (Elt.getValueType() != MVT::f32)
6190       Elt = DAG.getBitcast(MVT::f32, Elt);
6191     VecElts[i] = Elt;
6192   }
6193   for (unsigned i = Elts.size(); i < NumElts; ++i)
6194     VecElts[i] = DAG.getUNDEF(MVT::f32);
6195 
6196   if (NumElts == 1)
6197     return VecElts[0];
6198   return DAG.getBuildVector(Type, DL, VecElts);
6199 }
6200 
6201 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
6202                               SDValue Src, int ExtraElts) {
6203   EVT SrcVT = Src.getValueType();
6204 
6205   SmallVector<SDValue, 8> Elts;
6206 
6207   if (SrcVT.isVector())
6208     DAG.ExtractVectorElements(Src, Elts);
6209   else
6210     Elts.push_back(Src);
6211 
6212   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
6213   while (ExtraElts--)
6214     Elts.push_back(Undef);
6215 
6216   return DAG.getBuildVector(CastVT, DL, Elts);
6217 }
6218 
6219 // Re-construct the required return value for a image load intrinsic.
6220 // This is more complicated due to the optional use TexFailCtrl which means the required
6221 // return type is an aggregate
6222 static SDValue constructRetValue(SelectionDAG &DAG,
6223                                  MachineSDNode *Result,
6224                                  ArrayRef<EVT> ResultTypes,
6225                                  bool IsTexFail, bool Unpacked, bool IsD16,
6226                                  int DMaskPop, int NumVDataDwords,
6227                                  const SDLoc &DL) {
6228   // Determine the required return type. This is the same regardless of IsTexFail flag
6229   EVT ReqRetVT = ResultTypes[0];
6230   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
6231   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6232     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
6233 
6234   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
6235     DMaskPop : (DMaskPop + 1) / 2;
6236 
6237   MVT DataDwordVT = NumDataDwords == 1 ?
6238     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
6239 
6240   MVT MaskPopVT = MaskPopDwords == 1 ?
6241     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
6242 
6243   SDValue Data(Result, 0);
6244   SDValue TexFail;
6245 
6246   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
6247     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
6248     if (MaskPopVT.isVector()) {
6249       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
6250                          SDValue(Result, 0), ZeroIdx);
6251     } else {
6252       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
6253                          SDValue(Result, 0), ZeroIdx);
6254     }
6255   }
6256 
6257   if (DataDwordVT.isVector())
6258     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
6259                           NumDataDwords - MaskPopDwords);
6260 
6261   if (IsD16)
6262     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
6263 
6264   EVT LegalReqRetVT = ReqRetVT;
6265   if (!ReqRetVT.isVector()) {
6266     if (!Data.getValueType().isInteger())
6267       Data = DAG.getNode(ISD::BITCAST, DL,
6268                          Data.getValueType().changeTypeToInteger(), Data);
6269     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
6270   } else {
6271     // We need to widen the return vector to a legal type
6272     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
6273         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
6274       LegalReqRetVT =
6275           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
6276                            ReqRetVT.getVectorNumElements() + 1);
6277     }
6278   }
6279   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
6280 
6281   if (IsTexFail) {
6282     TexFail =
6283         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
6284                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
6285 
6286     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
6287   }
6288 
6289   if (Result->getNumValues() == 1)
6290     return Data;
6291 
6292   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
6293 }
6294 
6295 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
6296                          SDValue *LWE, bool &IsTexFail) {
6297   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
6298 
6299   uint64_t Value = TexFailCtrlConst->getZExtValue();
6300   if (Value) {
6301     IsTexFail = true;
6302   }
6303 
6304   SDLoc DL(TexFailCtrlConst);
6305   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
6306   Value &= ~(uint64_t)0x1;
6307   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
6308   Value &= ~(uint64_t)0x2;
6309 
6310   return Value == 0;
6311 }
6312 
6313 static void packImage16bitOpsToDwords(SelectionDAG &DAG, SDValue Op,
6314                                       MVT PackVectorVT,
6315                                       SmallVectorImpl<SDValue> &PackedAddrs,
6316                                       unsigned DimIdx, unsigned EndIdx,
6317                                       unsigned NumGradients) {
6318   SDLoc DL(Op);
6319   for (unsigned I = DimIdx; I < EndIdx; I++) {
6320     SDValue Addr = Op.getOperand(I);
6321 
6322     // Gradients are packed with undef for each coordinate.
6323     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
6324     // 1D: undef,dx/dh; undef,dx/dv
6325     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
6326     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
6327     if (((I + 1) >= EndIdx) ||
6328         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
6329                                          I == DimIdx + NumGradients - 1))) {
6330       if (Addr.getValueType() != MVT::i16)
6331         Addr = DAG.getBitcast(MVT::i16, Addr);
6332       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
6333     } else {
6334       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
6335       I++;
6336     }
6337     Addr = DAG.getBitcast(MVT::f32, Addr);
6338     PackedAddrs.push_back(Addr);
6339   }
6340 }
6341 
6342 SDValue SITargetLowering::lowerImage(SDValue Op,
6343                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
6344                                      SelectionDAG &DAG, bool WithChain) const {
6345   SDLoc DL(Op);
6346   MachineFunction &MF = DAG.getMachineFunction();
6347   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
6348   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
6349       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
6350   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
6351   unsigned IntrOpcode = Intr->BaseOpcode;
6352   bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget);
6353 
6354   SmallVector<EVT, 3> ResultTypes(Op->values());
6355   SmallVector<EVT, 3> OrigResultTypes(Op->values());
6356   bool IsD16 = false;
6357   bool IsG16 = false;
6358   bool IsA16 = false;
6359   SDValue VData;
6360   int NumVDataDwords;
6361   bool AdjustRetType = false;
6362 
6363   // Offset of intrinsic arguments
6364   const unsigned ArgOffset = WithChain ? 2 : 1;
6365 
6366   unsigned DMask;
6367   unsigned DMaskLanes = 0;
6368 
6369   if (BaseOpcode->Atomic) {
6370     VData = Op.getOperand(2);
6371 
6372     bool Is64Bit = VData.getValueType() == MVT::i64;
6373     if (BaseOpcode->AtomicX2) {
6374       SDValue VData2 = Op.getOperand(3);
6375       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6376                                  {VData, VData2});
6377       if (Is64Bit)
6378         VData = DAG.getBitcast(MVT::v4i32, VData);
6379 
6380       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6381       DMask = Is64Bit ? 0xf : 0x3;
6382       NumVDataDwords = Is64Bit ? 4 : 2;
6383     } else {
6384       DMask = Is64Bit ? 0x3 : 0x1;
6385       NumVDataDwords = Is64Bit ? 2 : 1;
6386     }
6387   } else {
6388     auto *DMaskConst =
6389         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6390     DMask = DMaskConst->getZExtValue();
6391     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6392 
6393     if (BaseOpcode->Store) {
6394       VData = Op.getOperand(2);
6395 
6396       MVT StoreVT = VData.getSimpleValueType();
6397       if (StoreVT.getScalarType() == MVT::f16) {
6398         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6399           return Op; // D16 is unsupported for this instruction
6400 
6401         IsD16 = true;
6402         VData = handleD16VData(VData, DAG, true);
6403       }
6404 
6405       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6406     } else {
6407       // Work out the num dwords based on the dmask popcount and underlying type
6408       // and whether packing is supported.
6409       MVT LoadVT = ResultTypes[0].getSimpleVT();
6410       if (LoadVT.getScalarType() == MVT::f16) {
6411         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6412           return Op; // D16 is unsupported for this instruction
6413 
6414         IsD16 = true;
6415       }
6416 
6417       // Confirm that the return type is large enough for the dmask specified
6418       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6419           (!LoadVT.isVector() && DMaskLanes > 1))
6420           return Op;
6421 
6422       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6423       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6424       // instructions.
6425       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6426           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6427         NumVDataDwords = (DMaskLanes + 1) / 2;
6428       else
6429         NumVDataDwords = DMaskLanes;
6430 
6431       AdjustRetType = true;
6432     }
6433   }
6434 
6435   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6436   SmallVector<SDValue, 4> VAddrs;
6437 
6438   // Check for 16 bit addresses or derivatives and pack if true.
6439   MVT VAddrVT =
6440       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6441   MVT VAddrScalarVT = VAddrVT.getScalarType();
6442   MVT GradPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6443   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6444 
6445   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6446   VAddrScalarVT = VAddrVT.getScalarType();
6447   MVT AddrPackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6448   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6449 
6450   // Push back extra arguments.
6451   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) {
6452     if (IsA16 && (Op.getOperand(ArgOffset + I).getValueType() == MVT::f16)) {
6453       assert(I == Intr->BiasIndex && "Got unexpected 16-bit extra argument");
6454       // Special handling of bias when A16 is on. Bias is of type half but
6455       // occupies full 32-bit.
6456       SDValue Bias = DAG.getBuildVector(
6457           MVT::v2f16, DL,
6458           {Op.getOperand(ArgOffset + I), DAG.getUNDEF(MVT::f16)});
6459       VAddrs.push_back(Bias);
6460     } else {
6461       assert((!IsA16 || Intr->NumBiasArgs == 0 || I != Intr->BiasIndex) &&
6462              "Bias needs to be converted to 16 bit in A16 mode");
6463       VAddrs.push_back(Op.getOperand(ArgOffset + I));
6464     }
6465   }
6466 
6467   if (BaseOpcode->Gradients && !ST->hasG16() && (IsA16 != IsG16)) {
6468     // 16 bit gradients are supported, but are tied to the A16 control
6469     // so both gradients and addresses must be 16 bit
6470     LLVM_DEBUG(
6471         dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6472                   "require 16 bit args for both gradients and addresses");
6473     return Op;
6474   }
6475 
6476   if (IsA16) {
6477     if (!ST->hasA16()) {
6478       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6479                            "support 16 bit addresses\n");
6480       return Op;
6481     }
6482   }
6483 
6484   // We've dealt with incorrect input so we know that if IsA16, IsG16
6485   // are set then we have to compress/pack operands (either address,
6486   // gradient or both)
6487   // In the case where a16 and gradients are tied (no G16 support) then we
6488   // have already verified that both IsA16 and IsG16 are true
6489   if (BaseOpcode->Gradients && IsG16 && ST->hasG16()) {
6490     // Activate g16
6491     const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6492         AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6493     IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6494   }
6495 
6496   // Add gradients (packed or unpacked)
6497   if (IsG16) {
6498     // Pack the gradients
6499     // const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6500     packImage16bitOpsToDwords(DAG, Op, GradPackVectorVT, VAddrs,
6501                               ArgOffset + Intr->GradientStart,
6502                               ArgOffset + Intr->CoordStart, Intr->NumGradients);
6503   } else {
6504     for (unsigned I = ArgOffset + Intr->GradientStart;
6505          I < ArgOffset + Intr->CoordStart; I++)
6506       VAddrs.push_back(Op.getOperand(I));
6507   }
6508 
6509   // Add addresses (packed or unpacked)
6510   if (IsA16) {
6511     packImage16bitOpsToDwords(DAG, Op, AddrPackVectorVT, VAddrs,
6512                               ArgOffset + Intr->CoordStart, VAddrEnd,
6513                               0 /* No gradients */);
6514   } else {
6515     // Add uncompressed address
6516     for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6517       VAddrs.push_back(Op.getOperand(I));
6518   }
6519 
6520   // If the register allocator cannot place the address registers contiguously
6521   // without introducing moves, then using the non-sequential address encoding
6522   // is always preferable, since it saves VALU instructions and is usually a
6523   // wash in terms of code size or even better.
6524   //
6525   // However, we currently have no way of hinting to the register allocator that
6526   // MIMG addresses should be placed contiguously when it is possible to do so,
6527   // so force non-NSA for the common 2-address case as a heuristic.
6528   //
6529   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6530   // allocation when possible.
6531   bool UseNSA = ST->hasFeature(AMDGPU::FeatureNSAEncoding) &&
6532                 VAddrs.size() >= 3 &&
6533                 VAddrs.size() <= (unsigned)ST->getNSAMaxSize();
6534   SDValue VAddr;
6535   if (!UseNSA)
6536     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6537 
6538   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6539   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6540   SDValue Unorm;
6541   if (!BaseOpcode->Sampler) {
6542     Unorm = True;
6543   } else {
6544     auto UnormConst =
6545         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6546 
6547     Unorm = UnormConst->getZExtValue() ? True : False;
6548   }
6549 
6550   SDValue TFE;
6551   SDValue LWE;
6552   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6553   bool IsTexFail = false;
6554   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6555     return Op;
6556 
6557   if (IsTexFail) {
6558     if (!DMaskLanes) {
6559       // Expecting to get an error flag since TFC is on - and dmask is 0
6560       // Force dmask to be at least 1 otherwise the instruction will fail
6561       DMask = 0x1;
6562       DMaskLanes = 1;
6563       NumVDataDwords = 1;
6564     }
6565     NumVDataDwords += 1;
6566     AdjustRetType = true;
6567   }
6568 
6569   // Has something earlier tagged that the return type needs adjusting
6570   // This happens if the instruction is a load or has set TexFailCtrl flags
6571   if (AdjustRetType) {
6572     // NumVDataDwords reflects the true number of dwords required in the return type
6573     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6574       // This is a no-op load. This can be eliminated
6575       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6576       if (isa<MemSDNode>(Op))
6577         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6578       return Undef;
6579     }
6580 
6581     EVT NewVT = NumVDataDwords > 1 ?
6582                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6583                 : MVT::i32;
6584 
6585     ResultTypes[0] = NewVT;
6586     if (ResultTypes.size() == 3) {
6587       // Original result was aggregate type used for TexFailCtrl results
6588       // The actual instruction returns as a vector type which has now been
6589       // created. Remove the aggregate result.
6590       ResultTypes.erase(&ResultTypes[1]);
6591     }
6592   }
6593 
6594   unsigned CPol = cast<ConstantSDNode>(
6595       Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue();
6596   if (BaseOpcode->Atomic)
6597     CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization
6598   if (CPol & ~AMDGPU::CPol::ALL)
6599     return Op;
6600 
6601   SmallVector<SDValue, 26> Ops;
6602   if (BaseOpcode->Store || BaseOpcode->Atomic)
6603     Ops.push_back(VData); // vdata
6604   if (UseNSA)
6605     append_range(Ops, VAddrs);
6606   else
6607     Ops.push_back(VAddr);
6608   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6609   if (BaseOpcode->Sampler)
6610     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6611   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6612   if (IsGFX10Plus)
6613     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6614   Ops.push_back(Unorm);
6615   Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32));
6616   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6617                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6618   if (IsGFX10Plus)
6619     Ops.push_back(IsA16 ? True : False);
6620   if (!Subtarget->hasGFX90AInsts()) {
6621     Ops.push_back(TFE); //tfe
6622   } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) {
6623     report_fatal_error("TFE is not supported on this GPU");
6624   }
6625   Ops.push_back(LWE); // lwe
6626   if (!IsGFX10Plus)
6627     Ops.push_back(DimInfo->DA ? True : False);
6628   if (BaseOpcode->HasD16)
6629     Ops.push_back(IsD16 ? True : False);
6630   if (isa<MemSDNode>(Op))
6631     Ops.push_back(Op.getOperand(0)); // chain
6632 
6633   int NumVAddrDwords =
6634       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6635   int Opcode = -1;
6636 
6637   if (IsGFX10Plus) {
6638     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6639                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6640                                           : AMDGPU::MIMGEncGfx10Default,
6641                                    NumVDataDwords, NumVAddrDwords);
6642   } else {
6643     if (Subtarget->hasGFX90AInsts()) {
6644       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a,
6645                                      NumVDataDwords, NumVAddrDwords);
6646       if (Opcode == -1)
6647         report_fatal_error(
6648             "requested image instruction is not supported on this GPU");
6649     }
6650     if (Opcode == -1 &&
6651         Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6652       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6653                                      NumVDataDwords, NumVAddrDwords);
6654     if (Opcode == -1)
6655       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6656                                      NumVDataDwords, NumVAddrDwords);
6657   }
6658   assert(Opcode != -1);
6659 
6660   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6661   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6662     MachineMemOperand *MemRef = MemOp->getMemOperand();
6663     DAG.setNodeMemRefs(NewNode, {MemRef});
6664   }
6665 
6666   if (BaseOpcode->AtomicX2) {
6667     SmallVector<SDValue, 1> Elt;
6668     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6669     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6670   }
6671   if (BaseOpcode->Store)
6672     return SDValue(NewNode, 0);
6673   return constructRetValue(DAG, NewNode,
6674                            OrigResultTypes, IsTexFail,
6675                            Subtarget->hasUnpackedD16VMem(), IsD16,
6676                            DMaskLanes, NumVDataDwords, DL);
6677 }
6678 
6679 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6680                                        SDValue Offset, SDValue CachePolicy,
6681                                        SelectionDAG &DAG) const {
6682   MachineFunction &MF = DAG.getMachineFunction();
6683 
6684   const DataLayout &DataLayout = DAG.getDataLayout();
6685   Align Alignment =
6686       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6687 
6688   MachineMemOperand *MMO = MF.getMachineMemOperand(
6689       MachinePointerInfo(),
6690       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6691           MachineMemOperand::MOInvariant,
6692       VT.getStoreSize(), Alignment);
6693 
6694   if (!Offset->isDivergent()) {
6695     SDValue Ops[] = {
6696         Rsrc,
6697         Offset, // Offset
6698         CachePolicy
6699     };
6700 
6701     // Widen vec3 load to vec4.
6702     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6703       EVT WidenedVT =
6704           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6705       auto WidenedOp = DAG.getMemIntrinsicNode(
6706           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6707           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6708       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6709                                    DAG.getVectorIdxConstant(0, DL));
6710       return Subvector;
6711     }
6712 
6713     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6714                                    DAG.getVTList(VT), Ops, VT, MMO);
6715   }
6716 
6717   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6718   // assume that the buffer is unswizzled.
6719   SmallVector<SDValue, 4> Loads;
6720   unsigned NumLoads = 1;
6721   MVT LoadVT = VT.getSimpleVT();
6722   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6723   assert((LoadVT.getScalarType() == MVT::i32 ||
6724           LoadVT.getScalarType() == MVT::f32));
6725 
6726   if (NumElts == 8 || NumElts == 16) {
6727     NumLoads = NumElts / 4;
6728     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6729   }
6730 
6731   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6732   SDValue Ops[] = {
6733       DAG.getEntryNode(),                               // Chain
6734       Rsrc,                                             // rsrc
6735       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6736       {},                                               // voffset
6737       {},                                               // soffset
6738       {},                                               // offset
6739       CachePolicy,                                      // cachepolicy
6740       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6741   };
6742 
6743   // Use the alignment to ensure that the required offsets will fit into the
6744   // immediate offsets.
6745   setBufferOffsets(Offset, DAG, &Ops[3],
6746                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6747 
6748   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6749   for (unsigned i = 0; i < NumLoads; ++i) {
6750     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6751     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6752                                         LoadVT, MMO, DAG));
6753   }
6754 
6755   if (NumElts == 8 || NumElts == 16)
6756     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6757 
6758   return Loads[0];
6759 }
6760 
6761 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6762                                                   SelectionDAG &DAG) const {
6763   MachineFunction &MF = DAG.getMachineFunction();
6764   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6765 
6766   EVT VT = Op.getValueType();
6767   SDLoc DL(Op);
6768   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6769 
6770   // TODO: Should this propagate fast-math-flags?
6771 
6772   switch (IntrinsicID) {
6773   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6774     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6775       return emitNonHSAIntrinsicError(DAG, DL, VT);
6776     return getPreloadedValue(DAG, *MFI, VT,
6777                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6778   }
6779   case Intrinsic::amdgcn_dispatch_ptr:
6780   case Intrinsic::amdgcn_queue_ptr: {
6781     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6782       DiagnosticInfoUnsupported BadIntrin(
6783           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6784           DL.getDebugLoc());
6785       DAG.getContext()->diagnose(BadIntrin);
6786       return DAG.getUNDEF(VT);
6787     }
6788 
6789     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6790       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6791     return getPreloadedValue(DAG, *MFI, VT, RegID);
6792   }
6793   case Intrinsic::amdgcn_implicitarg_ptr: {
6794     if (MFI->isEntryFunction())
6795       return getImplicitArgPtr(DAG, DL);
6796     return getPreloadedValue(DAG, *MFI, VT,
6797                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6798   }
6799   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6800     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6801       // This only makes sense to call in a kernel, so just lower to null.
6802       return DAG.getConstant(0, DL, VT);
6803     }
6804 
6805     return getPreloadedValue(DAG, *MFI, VT,
6806                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6807   }
6808   case Intrinsic::amdgcn_dispatch_id: {
6809     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6810   }
6811   case Intrinsic::amdgcn_rcp:
6812     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6813   case Intrinsic::amdgcn_rsq:
6814     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6815   case Intrinsic::amdgcn_rsq_legacy:
6816     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6817       return emitRemovedIntrinsicError(DAG, DL, VT);
6818     return SDValue();
6819   case Intrinsic::amdgcn_rcp_legacy:
6820     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6821       return emitRemovedIntrinsicError(DAG, DL, VT);
6822     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6823   case Intrinsic::amdgcn_rsq_clamp: {
6824     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6825       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6826 
6827     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6828     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6829     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6830 
6831     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6832     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6833                               DAG.getConstantFP(Max, DL, VT));
6834     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6835                        DAG.getConstantFP(Min, DL, VT));
6836   }
6837   case Intrinsic::r600_read_ngroups_x:
6838     if (Subtarget->isAmdHsaOS())
6839       return emitNonHSAIntrinsicError(DAG, DL, VT);
6840 
6841     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6842                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6843                                     false);
6844   case Intrinsic::r600_read_ngroups_y:
6845     if (Subtarget->isAmdHsaOS())
6846       return emitNonHSAIntrinsicError(DAG, DL, VT);
6847 
6848     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6849                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6850                                     false);
6851   case Intrinsic::r600_read_ngroups_z:
6852     if (Subtarget->isAmdHsaOS())
6853       return emitNonHSAIntrinsicError(DAG, DL, VT);
6854 
6855     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6856                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6857                                     false);
6858   case Intrinsic::r600_read_global_size_x:
6859     if (Subtarget->isAmdHsaOS())
6860       return emitNonHSAIntrinsicError(DAG, DL, VT);
6861 
6862     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6863                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6864                                     Align(4), false);
6865   case Intrinsic::r600_read_global_size_y:
6866     if (Subtarget->isAmdHsaOS())
6867       return emitNonHSAIntrinsicError(DAG, DL, VT);
6868 
6869     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6870                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6871                                     Align(4), false);
6872   case Intrinsic::r600_read_global_size_z:
6873     if (Subtarget->isAmdHsaOS())
6874       return emitNonHSAIntrinsicError(DAG, DL, VT);
6875 
6876     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6877                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6878                                     Align(4), false);
6879   case Intrinsic::r600_read_local_size_x:
6880     if (Subtarget->isAmdHsaOS())
6881       return emitNonHSAIntrinsicError(DAG, DL, VT);
6882 
6883     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6884                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6885   case Intrinsic::r600_read_local_size_y:
6886     if (Subtarget->isAmdHsaOS())
6887       return emitNonHSAIntrinsicError(DAG, DL, VT);
6888 
6889     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6890                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6891   case Intrinsic::r600_read_local_size_z:
6892     if (Subtarget->isAmdHsaOS())
6893       return emitNonHSAIntrinsicError(DAG, DL, VT);
6894 
6895     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6896                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6897   case Intrinsic::amdgcn_workgroup_id_x:
6898     return getPreloadedValue(DAG, *MFI, VT,
6899                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6900   case Intrinsic::amdgcn_workgroup_id_y:
6901     return getPreloadedValue(DAG, *MFI, VT,
6902                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6903   case Intrinsic::amdgcn_workgroup_id_z:
6904     return getPreloadedValue(DAG, *MFI, VT,
6905                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6906   case Intrinsic::amdgcn_workitem_id_x:
6907     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 0) == 0)
6908       return DAG.getConstant(0, DL, MVT::i32);
6909 
6910     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6911                           SDLoc(DAG.getEntryNode()),
6912                           MFI->getArgInfo().WorkItemIDX);
6913   case Intrinsic::amdgcn_workitem_id_y:
6914     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 1) == 0)
6915       return DAG.getConstant(0, DL, MVT::i32);
6916 
6917     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6918                           SDLoc(DAG.getEntryNode()),
6919                           MFI->getArgInfo().WorkItemIDY);
6920   case Intrinsic::amdgcn_workitem_id_z:
6921     if (Subtarget->getMaxWorkitemID(MF.getFunction(), 2) == 0)
6922       return DAG.getConstant(0, DL, MVT::i32);
6923 
6924     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6925                           SDLoc(DAG.getEntryNode()),
6926                           MFI->getArgInfo().WorkItemIDZ);
6927   case Intrinsic::amdgcn_wavefrontsize:
6928     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6929                            SDLoc(Op), MVT::i32);
6930   case Intrinsic::amdgcn_s_buffer_load: {
6931     unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
6932     if (CPol & ~AMDGPU::CPol::ALL)
6933       return Op;
6934     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6935                         DAG);
6936   }
6937   case Intrinsic::amdgcn_fdiv_fast:
6938     return lowerFDIV_FAST(Op, DAG);
6939   case Intrinsic::amdgcn_sin:
6940     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6941 
6942   case Intrinsic::amdgcn_cos:
6943     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6944 
6945   case Intrinsic::amdgcn_mul_u24:
6946     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6947   case Intrinsic::amdgcn_mul_i24:
6948     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6949 
6950   case Intrinsic::amdgcn_log_clamp: {
6951     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6952       return SDValue();
6953 
6954     return emitRemovedIntrinsicError(DAG, DL, VT);
6955   }
6956   case Intrinsic::amdgcn_ldexp:
6957     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6958                        Op.getOperand(1), Op.getOperand(2));
6959 
6960   case Intrinsic::amdgcn_fract:
6961     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6962 
6963   case Intrinsic::amdgcn_class:
6964     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6965                        Op.getOperand(1), Op.getOperand(2));
6966   case Intrinsic::amdgcn_div_fmas:
6967     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6968                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6969                        Op.getOperand(4));
6970 
6971   case Intrinsic::amdgcn_div_fixup:
6972     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6973                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6974 
6975   case Intrinsic::amdgcn_div_scale: {
6976     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6977 
6978     // Translate to the operands expected by the machine instruction. The
6979     // first parameter must be the same as the first instruction.
6980     SDValue Numerator = Op.getOperand(1);
6981     SDValue Denominator = Op.getOperand(2);
6982 
6983     // Note this order is opposite of the machine instruction's operations,
6984     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6985     // intrinsic has the numerator as the first operand to match a normal
6986     // division operation.
6987 
6988     SDValue Src0 = Param->isAllOnes() ? Numerator : Denominator;
6989 
6990     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6991                        Denominator, Numerator);
6992   }
6993   case Intrinsic::amdgcn_icmp: {
6994     // There is a Pat that handles this variant, so return it as-is.
6995     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6996         Op.getConstantOperandVal(2) == 0 &&
6997         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6998       return Op;
6999     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
7000   }
7001   case Intrinsic::amdgcn_fcmp: {
7002     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
7003   }
7004   case Intrinsic::amdgcn_ballot:
7005     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
7006   case Intrinsic::amdgcn_fmed3:
7007     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
7008                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
7009   case Intrinsic::amdgcn_fdot2:
7010     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
7011                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
7012                        Op.getOperand(4));
7013   case Intrinsic::amdgcn_fmul_legacy:
7014     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
7015                        Op.getOperand(1), Op.getOperand(2));
7016   case Intrinsic::amdgcn_sffbh:
7017     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
7018   case Intrinsic::amdgcn_sbfe:
7019     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
7020                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
7021   case Intrinsic::amdgcn_ubfe:
7022     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
7023                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
7024   case Intrinsic::amdgcn_cvt_pkrtz:
7025   case Intrinsic::amdgcn_cvt_pknorm_i16:
7026   case Intrinsic::amdgcn_cvt_pknorm_u16:
7027   case Intrinsic::amdgcn_cvt_pk_i16:
7028   case Intrinsic::amdgcn_cvt_pk_u16: {
7029     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
7030     EVT VT = Op.getValueType();
7031     unsigned Opcode;
7032 
7033     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
7034       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
7035     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
7036       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
7037     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
7038       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
7039     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
7040       Opcode = AMDGPUISD::CVT_PK_I16_I32;
7041     else
7042       Opcode = AMDGPUISD::CVT_PK_U16_U32;
7043 
7044     if (isTypeLegal(VT))
7045       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
7046 
7047     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
7048                                Op.getOperand(1), Op.getOperand(2));
7049     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
7050   }
7051   case Intrinsic::amdgcn_fmad_ftz:
7052     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
7053                        Op.getOperand(2), Op.getOperand(3));
7054 
7055   case Intrinsic::amdgcn_if_break:
7056     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
7057                                       Op->getOperand(1), Op->getOperand(2)), 0);
7058 
7059   case Intrinsic::amdgcn_groupstaticsize: {
7060     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
7061     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
7062       return Op;
7063 
7064     const Module *M = MF.getFunction().getParent();
7065     const GlobalValue *GV =
7066         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
7067     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
7068                                             SIInstrInfo::MO_ABS32_LO);
7069     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
7070   }
7071   case Intrinsic::amdgcn_is_shared:
7072   case Intrinsic::amdgcn_is_private: {
7073     SDLoc SL(Op);
7074     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
7075       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
7076     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
7077     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
7078                                  Op.getOperand(1));
7079 
7080     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
7081                                 DAG.getConstant(1, SL, MVT::i32));
7082     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
7083   }
7084   case Intrinsic::amdgcn_perm:
7085     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, Op.getOperand(1),
7086                        Op.getOperand(2), Op.getOperand(3));
7087   case Intrinsic::amdgcn_reloc_constant: {
7088     Module *M = const_cast<Module *>(MF.getFunction().getParent());
7089     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
7090     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
7091     auto RelocSymbol = cast<GlobalVariable>(
7092         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
7093     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
7094                                             SIInstrInfo::MO_ABS32_LO);
7095     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
7096   }
7097   default:
7098     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7099             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7100       return lowerImage(Op, ImageDimIntr, DAG, false);
7101 
7102     return Op;
7103   }
7104 }
7105 
7106 /// Update \p MMO based on the offset inputs to an intrinsic.
7107 static void updateBufferMMO(MachineMemOperand *MMO, SDValue VOffset,
7108                             SDValue SOffset, SDValue Offset,
7109                             SDValue VIndex = SDValue()) {
7110   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
7111       !isa<ConstantSDNode>(Offset)) {
7112     // The combined offset is not known to be constant, so we cannot represent
7113     // it in the MMO. Give up.
7114     MMO->setValue((Value *)nullptr);
7115     return;
7116   }
7117 
7118   if (VIndex && (!isa<ConstantSDNode>(VIndex) ||
7119                  !cast<ConstantSDNode>(VIndex)->isZero())) {
7120     // The strided index component of the address is not known to be zero, so we
7121     // cannot represent it in the MMO. Give up.
7122     MMO->setValue((Value *)nullptr);
7123     return;
7124   }
7125 
7126   MMO->setOffset(cast<ConstantSDNode>(VOffset)->getSExtValue() +
7127                  cast<ConstantSDNode>(SOffset)->getSExtValue() +
7128                  cast<ConstantSDNode>(Offset)->getSExtValue());
7129 }
7130 
7131 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
7132                                                      SelectionDAG &DAG,
7133                                                      unsigned NewOpcode) const {
7134   SDLoc DL(Op);
7135 
7136   SDValue VData = Op.getOperand(2);
7137   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7138   SDValue Ops[] = {
7139     Op.getOperand(0), // Chain
7140     VData,            // vdata
7141     Op.getOperand(3), // rsrc
7142     DAG.getConstant(0, DL, MVT::i32), // vindex
7143     Offsets.first,    // voffset
7144     Op.getOperand(5), // soffset
7145     Offsets.second,   // offset
7146     Op.getOperand(6), // cachepolicy
7147     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7148   };
7149 
7150   auto *M = cast<MemSDNode>(Op);
7151   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
7152 
7153   EVT MemVT = VData.getValueType();
7154   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7155                                  M->getMemOperand());
7156 }
7157 
7158 // Return a value to use for the idxen operand by examining the vindex operand.
7159 static unsigned getIdxEn(SDValue VIndex) {
7160   if (auto VIndexC = dyn_cast<ConstantSDNode>(VIndex))
7161     // No need to set idxen if vindex is known to be zero.
7162     return VIndexC->getZExtValue() != 0;
7163   return 1;
7164 }
7165 
7166 SDValue
7167 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
7168                                                 unsigned NewOpcode) const {
7169   SDLoc DL(Op);
7170 
7171   SDValue VData = Op.getOperand(2);
7172   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7173   SDValue Ops[] = {
7174     Op.getOperand(0), // Chain
7175     VData,            // vdata
7176     Op.getOperand(3), // rsrc
7177     Op.getOperand(4), // vindex
7178     Offsets.first,    // voffset
7179     Op.getOperand(6), // soffset
7180     Offsets.second,   // offset
7181     Op.getOperand(7), // cachepolicy
7182     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7183   };
7184 
7185   auto *M = cast<MemSDNode>(Op);
7186   updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7187 
7188   EVT MemVT = VData.getValueType();
7189   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
7190                                  M->getMemOperand());
7191 }
7192 
7193 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
7194                                                  SelectionDAG &DAG) const {
7195   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7196   SDLoc DL(Op);
7197 
7198   switch (IntrID) {
7199   case Intrinsic::amdgcn_ds_ordered_add:
7200   case Intrinsic::amdgcn_ds_ordered_swap: {
7201     MemSDNode *M = cast<MemSDNode>(Op);
7202     SDValue Chain = M->getOperand(0);
7203     SDValue M0 = M->getOperand(2);
7204     SDValue Value = M->getOperand(3);
7205     unsigned IndexOperand = M->getConstantOperandVal(7);
7206     unsigned WaveRelease = M->getConstantOperandVal(8);
7207     unsigned WaveDone = M->getConstantOperandVal(9);
7208 
7209     unsigned OrderedCountIndex = IndexOperand & 0x3f;
7210     IndexOperand &= ~0x3f;
7211     unsigned CountDw = 0;
7212 
7213     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
7214       CountDw = (IndexOperand >> 24) & 0xf;
7215       IndexOperand &= ~(0xf << 24);
7216 
7217       if (CountDw < 1 || CountDw > 4) {
7218         report_fatal_error(
7219             "ds_ordered_count: dword count must be between 1 and 4");
7220       }
7221     }
7222 
7223     if (IndexOperand)
7224       report_fatal_error("ds_ordered_count: bad index operand");
7225 
7226     if (WaveDone && !WaveRelease)
7227       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
7228 
7229     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
7230     unsigned ShaderType =
7231         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
7232     unsigned Offset0 = OrderedCountIndex << 2;
7233     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
7234                        (Instruction << 4);
7235 
7236     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
7237       Offset1 |= (CountDw - 1) << 6;
7238 
7239     unsigned Offset = Offset0 | (Offset1 << 8);
7240 
7241     SDValue Ops[] = {
7242       Chain,
7243       Value,
7244       DAG.getTargetConstant(Offset, DL, MVT::i16),
7245       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
7246     };
7247     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
7248                                    M->getVTList(), Ops, M->getMemoryVT(),
7249                                    M->getMemOperand());
7250   }
7251   case Intrinsic::amdgcn_ds_fadd: {
7252     MemSDNode *M = cast<MemSDNode>(Op);
7253     unsigned Opc;
7254     switch (IntrID) {
7255     case Intrinsic::amdgcn_ds_fadd:
7256       Opc = ISD::ATOMIC_LOAD_FADD;
7257       break;
7258     }
7259 
7260     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
7261                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
7262                          M->getMemOperand());
7263   }
7264   case Intrinsic::amdgcn_atomic_inc:
7265   case Intrinsic::amdgcn_atomic_dec:
7266   case Intrinsic::amdgcn_ds_fmin:
7267   case Intrinsic::amdgcn_ds_fmax: {
7268     MemSDNode *M = cast<MemSDNode>(Op);
7269     unsigned Opc;
7270     switch (IntrID) {
7271     case Intrinsic::amdgcn_atomic_inc:
7272       Opc = AMDGPUISD::ATOMIC_INC;
7273       break;
7274     case Intrinsic::amdgcn_atomic_dec:
7275       Opc = AMDGPUISD::ATOMIC_DEC;
7276       break;
7277     case Intrinsic::amdgcn_ds_fmin:
7278       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
7279       break;
7280     case Intrinsic::amdgcn_ds_fmax:
7281       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
7282       break;
7283     default:
7284       llvm_unreachable("Unknown intrinsic!");
7285     }
7286     SDValue Ops[] = {
7287       M->getOperand(0), // Chain
7288       M->getOperand(2), // Ptr
7289       M->getOperand(3)  // Value
7290     };
7291 
7292     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
7293                                    M->getMemoryVT(), M->getMemOperand());
7294   }
7295   case Intrinsic::amdgcn_buffer_load:
7296   case Intrinsic::amdgcn_buffer_load_format: {
7297     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
7298     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7299     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7300     SDValue Ops[] = {
7301       Op.getOperand(0), // Chain
7302       Op.getOperand(2), // rsrc
7303       Op.getOperand(3), // vindex
7304       SDValue(),        // voffset -- will be set by setBufferOffsets
7305       SDValue(),        // soffset -- will be set by setBufferOffsets
7306       SDValue(),        // offset -- will be set by setBufferOffsets
7307       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7308       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7309     };
7310     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
7311 
7312     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
7313         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
7314 
7315     EVT VT = Op.getValueType();
7316     EVT IntVT = VT.changeTypeToInteger();
7317     auto *M = cast<MemSDNode>(Op);
7318     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7319     EVT LoadVT = Op.getValueType();
7320 
7321     if (LoadVT.getScalarType() == MVT::f16)
7322       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
7323                                  M, DAG, Ops);
7324 
7325     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
7326     if (LoadVT.getScalarType() == MVT::i8 ||
7327         LoadVT.getScalarType() == MVT::i16)
7328       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
7329 
7330     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
7331                                M->getMemOperand(), DAG);
7332   }
7333   case Intrinsic::amdgcn_raw_buffer_load:
7334   case Intrinsic::amdgcn_raw_buffer_load_format: {
7335     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
7336 
7337     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7338     SDValue Ops[] = {
7339       Op.getOperand(0), // Chain
7340       Op.getOperand(2), // rsrc
7341       DAG.getConstant(0, DL, MVT::i32), // vindex
7342       Offsets.first,    // voffset
7343       Op.getOperand(4), // soffset
7344       Offsets.second,   // offset
7345       Op.getOperand(5), // cachepolicy, swizzled buffer
7346       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7347     };
7348 
7349     auto *M = cast<MemSDNode>(Op);
7350     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5]);
7351     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
7352   }
7353   case Intrinsic::amdgcn_struct_buffer_load:
7354   case Intrinsic::amdgcn_struct_buffer_load_format: {
7355     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
7356 
7357     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7358     SDValue Ops[] = {
7359       Op.getOperand(0), // Chain
7360       Op.getOperand(2), // rsrc
7361       Op.getOperand(3), // vindex
7362       Offsets.first,    // voffset
7363       Op.getOperand(5), // soffset
7364       Offsets.second,   // offset
7365       Op.getOperand(6), // cachepolicy, swizzled buffer
7366       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7367     };
7368 
7369     auto *M = cast<MemSDNode>(Op);
7370     updateBufferMMO(M->getMemOperand(), Ops[3], Ops[4], Ops[5], Ops[2]);
7371     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7372   }
7373   case Intrinsic::amdgcn_tbuffer_load: {
7374     MemSDNode *M = cast<MemSDNode>(Op);
7375     EVT LoadVT = Op.getValueType();
7376 
7377     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7378     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7379     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7380     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7381     unsigned IdxEn = getIdxEn(Op.getOperand(3));
7382     SDValue Ops[] = {
7383       Op.getOperand(0),  // Chain
7384       Op.getOperand(2),  // rsrc
7385       Op.getOperand(3),  // vindex
7386       Op.getOperand(4),  // voffset
7387       Op.getOperand(5),  // soffset
7388       Op.getOperand(6),  // offset
7389       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7390       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7391       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7392     };
7393 
7394     if (LoadVT.getScalarType() == MVT::f16)
7395       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7396                                  M, DAG, Ops);
7397     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7398                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7399                                DAG);
7400   }
7401   case Intrinsic::amdgcn_raw_tbuffer_load: {
7402     MemSDNode *M = cast<MemSDNode>(Op);
7403     EVT LoadVT = Op.getValueType();
7404     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7405 
7406     SDValue Ops[] = {
7407       Op.getOperand(0),  // Chain
7408       Op.getOperand(2),  // rsrc
7409       DAG.getConstant(0, DL, MVT::i32), // vindex
7410       Offsets.first,     // voffset
7411       Op.getOperand(4),  // soffset
7412       Offsets.second,    // offset
7413       Op.getOperand(5),  // format
7414       Op.getOperand(6),  // cachepolicy, swizzled buffer
7415       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7416     };
7417 
7418     if (LoadVT.getScalarType() == MVT::f16)
7419       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7420                                  M, DAG, Ops);
7421     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7422                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7423                                DAG);
7424   }
7425   case Intrinsic::amdgcn_struct_tbuffer_load: {
7426     MemSDNode *M = cast<MemSDNode>(Op);
7427     EVT LoadVT = Op.getValueType();
7428     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7429 
7430     SDValue Ops[] = {
7431       Op.getOperand(0),  // Chain
7432       Op.getOperand(2),  // rsrc
7433       Op.getOperand(3),  // vindex
7434       Offsets.first,     // voffset
7435       Op.getOperand(5),  // soffset
7436       Offsets.second,    // offset
7437       Op.getOperand(6),  // format
7438       Op.getOperand(7),  // cachepolicy, swizzled buffer
7439       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7440     };
7441 
7442     if (LoadVT.getScalarType() == MVT::f16)
7443       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7444                                  M, DAG, Ops);
7445     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7446                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7447                                DAG);
7448   }
7449   case Intrinsic::amdgcn_buffer_atomic_swap:
7450   case Intrinsic::amdgcn_buffer_atomic_add:
7451   case Intrinsic::amdgcn_buffer_atomic_sub:
7452   case Intrinsic::amdgcn_buffer_atomic_csub:
7453   case Intrinsic::amdgcn_buffer_atomic_smin:
7454   case Intrinsic::amdgcn_buffer_atomic_umin:
7455   case Intrinsic::amdgcn_buffer_atomic_smax:
7456   case Intrinsic::amdgcn_buffer_atomic_umax:
7457   case Intrinsic::amdgcn_buffer_atomic_and:
7458   case Intrinsic::amdgcn_buffer_atomic_or:
7459   case Intrinsic::amdgcn_buffer_atomic_xor:
7460   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7461     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7462     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7463     SDValue Ops[] = {
7464       Op.getOperand(0), // Chain
7465       Op.getOperand(2), // vdata
7466       Op.getOperand(3), // rsrc
7467       Op.getOperand(4), // vindex
7468       SDValue(),        // voffset -- will be set by setBufferOffsets
7469       SDValue(),        // soffset -- will be set by setBufferOffsets
7470       SDValue(),        // offset -- will be set by setBufferOffsets
7471       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7472       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7473     };
7474     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7475 
7476     EVT VT = Op.getValueType();
7477 
7478     auto *M = cast<MemSDNode>(Op);
7479     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
7480     unsigned Opcode = 0;
7481 
7482     switch (IntrID) {
7483     case Intrinsic::amdgcn_buffer_atomic_swap:
7484       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7485       break;
7486     case Intrinsic::amdgcn_buffer_atomic_add:
7487       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7488       break;
7489     case Intrinsic::amdgcn_buffer_atomic_sub:
7490       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7491       break;
7492     case Intrinsic::amdgcn_buffer_atomic_csub:
7493       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7494       break;
7495     case Intrinsic::amdgcn_buffer_atomic_smin:
7496       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7497       break;
7498     case Intrinsic::amdgcn_buffer_atomic_umin:
7499       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7500       break;
7501     case Intrinsic::amdgcn_buffer_atomic_smax:
7502       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7503       break;
7504     case Intrinsic::amdgcn_buffer_atomic_umax:
7505       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7506       break;
7507     case Intrinsic::amdgcn_buffer_atomic_and:
7508       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7509       break;
7510     case Intrinsic::amdgcn_buffer_atomic_or:
7511       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7512       break;
7513     case Intrinsic::amdgcn_buffer_atomic_xor:
7514       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7515       break;
7516     case Intrinsic::amdgcn_buffer_atomic_fadd:
7517       if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7518         DiagnosticInfoUnsupported
7519           NoFpRet(DAG.getMachineFunction().getFunction(),
7520                   "return versions of fp atomics not supported",
7521                   DL.getDebugLoc(), DS_Error);
7522         DAG.getContext()->diagnose(NoFpRet);
7523         return SDValue();
7524       }
7525       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7526       break;
7527     default:
7528       llvm_unreachable("unhandled atomic opcode");
7529     }
7530 
7531     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7532                                    M->getMemOperand());
7533   }
7534   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7535     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7536   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7537     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7538   case Intrinsic::amdgcn_raw_buffer_atomic_fmin:
7539     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7540   case Intrinsic::amdgcn_struct_buffer_atomic_fmin:
7541     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN);
7542   case Intrinsic::amdgcn_raw_buffer_atomic_fmax:
7543     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7544   case Intrinsic::amdgcn_struct_buffer_atomic_fmax:
7545     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX);
7546   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7547     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7548   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7549     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7550   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7551     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7552   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7553     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7554   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7555     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7556   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7557     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7558   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7559     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7560   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7561     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7562   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7563     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7564   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7565     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7566   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7567     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7568   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7569     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7570   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7571     return lowerStructBufferAtomicIntrin(Op, DAG,
7572                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7573   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7574     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7575   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7576     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7577   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7578     return lowerStructBufferAtomicIntrin(Op, DAG,
7579                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7580   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7581     return lowerStructBufferAtomicIntrin(Op, DAG,
7582                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7583   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7584     return lowerStructBufferAtomicIntrin(Op, DAG,
7585                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7586   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7587     return lowerStructBufferAtomicIntrin(Op, DAG,
7588                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7589   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7590     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7591   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7592     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7593   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7594     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7595   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7596     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7597   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7598     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7599 
7600   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7601     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7602     unsigned IdxEn = getIdxEn(Op.getOperand(5));
7603     SDValue Ops[] = {
7604       Op.getOperand(0), // Chain
7605       Op.getOperand(2), // src
7606       Op.getOperand(3), // cmp
7607       Op.getOperand(4), // rsrc
7608       Op.getOperand(5), // vindex
7609       SDValue(),        // voffset -- will be set by setBufferOffsets
7610       SDValue(),        // soffset -- will be set by setBufferOffsets
7611       SDValue(),        // offset -- will be set by setBufferOffsets
7612       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7613       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7614     };
7615     setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7616 
7617     EVT VT = Op.getValueType();
7618     auto *M = cast<MemSDNode>(Op);
7619     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7620 
7621     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7622                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7623   }
7624   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7625     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7626     SDValue Ops[] = {
7627       Op.getOperand(0), // Chain
7628       Op.getOperand(2), // src
7629       Op.getOperand(3), // cmp
7630       Op.getOperand(4), // rsrc
7631       DAG.getConstant(0, DL, MVT::i32), // vindex
7632       Offsets.first,    // voffset
7633       Op.getOperand(6), // soffset
7634       Offsets.second,   // offset
7635       Op.getOperand(7), // cachepolicy
7636       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7637     };
7638     EVT VT = Op.getValueType();
7639     auto *M = cast<MemSDNode>(Op);
7640     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7]);
7641 
7642     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7643                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7644   }
7645   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7646     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7647     SDValue Ops[] = {
7648       Op.getOperand(0), // Chain
7649       Op.getOperand(2), // src
7650       Op.getOperand(3), // cmp
7651       Op.getOperand(4), // rsrc
7652       Op.getOperand(5), // vindex
7653       Offsets.first,    // voffset
7654       Op.getOperand(7), // soffset
7655       Offsets.second,   // offset
7656       Op.getOperand(8), // cachepolicy
7657       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7658     };
7659     EVT VT = Op.getValueType();
7660     auto *M = cast<MemSDNode>(Op);
7661     updateBufferMMO(M->getMemOperand(), Ops[5], Ops[6], Ops[7], Ops[4]);
7662 
7663     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7664                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7665   }
7666   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7667     MemSDNode *M = cast<MemSDNode>(Op);
7668     SDValue NodePtr = M->getOperand(2);
7669     SDValue RayExtent = M->getOperand(3);
7670     SDValue RayOrigin = M->getOperand(4);
7671     SDValue RayDir = M->getOperand(5);
7672     SDValue RayInvDir = M->getOperand(6);
7673     SDValue TDescr = M->getOperand(7);
7674 
7675     assert(NodePtr.getValueType() == MVT::i32 ||
7676            NodePtr.getValueType() == MVT::i64);
7677     assert(RayDir.getValueType() == MVT::v3f16 ||
7678            RayDir.getValueType() == MVT::v3f32);
7679 
7680     if (!Subtarget->hasGFX10_AEncoding()) {
7681       emitRemovedIntrinsicError(DAG, DL, Op.getValueType());
7682       return SDValue();
7683     }
7684 
7685     const bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7686     const bool Is64 = NodePtr.getValueType() == MVT::i64;
7687     const unsigned NumVDataDwords = 4;
7688     const unsigned NumVAddrDwords = IsA16 ? (Is64 ? 9 : 8) : (Is64 ? 12 : 11);
7689     const bool UseNSA = Subtarget->hasNSAEncoding() &&
7690                         NumVAddrDwords <= Subtarget->getNSAMaxSize();
7691     const unsigned BaseOpcodes[2][2] = {
7692         {AMDGPU::IMAGE_BVH_INTERSECT_RAY, AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16},
7693         {AMDGPU::IMAGE_BVH64_INTERSECT_RAY,
7694          AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16}};
7695     int Opcode;
7696     if (UseNSA) {
7697       Opcode = AMDGPU::getMIMGOpcode(BaseOpcodes[Is64][IsA16],
7698                                      AMDGPU::MIMGEncGfx10NSA, NumVDataDwords,
7699                                      NumVAddrDwords);
7700     } else {
7701       Opcode = AMDGPU::getMIMGOpcode(
7702           BaseOpcodes[Is64][IsA16], AMDGPU::MIMGEncGfx10Default, NumVDataDwords,
7703           PowerOf2Ceil(NumVAddrDwords));
7704     }
7705     assert(Opcode != -1);
7706 
7707     SmallVector<SDValue, 16> Ops;
7708 
7709     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7710       SmallVector<SDValue, 3> Lanes;
7711       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7712       if (Lanes[0].getValueSizeInBits() == 32) {
7713         for (unsigned I = 0; I < 3; ++I)
7714           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7715       } else {
7716         if (IsAligned) {
7717           Ops.push_back(
7718             DAG.getBitcast(MVT::i32,
7719                            DAG.getBuildVector(MVT::v2f16, DL,
7720                                               { Lanes[0], Lanes[1] })));
7721           Ops.push_back(Lanes[2]);
7722         } else {
7723           SDValue Elt0 = Ops.pop_back_val();
7724           Ops.push_back(
7725             DAG.getBitcast(MVT::i32,
7726                            DAG.getBuildVector(MVT::v2f16, DL,
7727                                               { Elt0, Lanes[0] })));
7728           Ops.push_back(
7729             DAG.getBitcast(MVT::i32,
7730                            DAG.getBuildVector(MVT::v2f16, DL,
7731                                               { Lanes[1], Lanes[2] })));
7732         }
7733       }
7734     };
7735 
7736     if (Is64)
7737       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7738     else
7739       Ops.push_back(NodePtr);
7740 
7741     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7742     packLanes(RayOrigin, true);
7743     packLanes(RayDir, true);
7744     packLanes(RayInvDir, false);
7745 
7746     if (!UseNSA) {
7747       // Build a single vector containing all the operands so far prepared.
7748       if (NumVAddrDwords > 8) {
7749         SDValue Undef = DAG.getUNDEF(MVT::i32);
7750         Ops.append(16 - Ops.size(), Undef);
7751       }
7752       assert(Ops.size() == 8 || Ops.size() == 16);
7753       SDValue MergedOps = DAG.getBuildVector(
7754           Ops.size() == 16 ? MVT::v16i32 : MVT::v8i32, DL, Ops);
7755       Ops.clear();
7756       Ops.push_back(MergedOps);
7757     }
7758 
7759     Ops.push_back(TDescr);
7760     if (IsA16)
7761       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7762     Ops.push_back(M->getChain());
7763 
7764     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7765     MachineMemOperand *MemRef = M->getMemOperand();
7766     DAG.setNodeMemRefs(NewNode, {MemRef});
7767     return SDValue(NewNode, 0);
7768   }
7769   case Intrinsic::amdgcn_global_atomic_fadd:
7770     if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) {
7771       DiagnosticInfoUnsupported
7772         NoFpRet(DAG.getMachineFunction().getFunction(),
7773                 "return versions of fp atomics not supported",
7774                 DL.getDebugLoc(), DS_Error);
7775       DAG.getContext()->diagnose(NoFpRet);
7776       return SDValue();
7777     }
7778     LLVM_FALLTHROUGH;
7779   case Intrinsic::amdgcn_global_atomic_fmin:
7780   case Intrinsic::amdgcn_global_atomic_fmax:
7781   case Intrinsic::amdgcn_flat_atomic_fadd:
7782   case Intrinsic::amdgcn_flat_atomic_fmin:
7783   case Intrinsic::amdgcn_flat_atomic_fmax: {
7784     MemSDNode *M = cast<MemSDNode>(Op);
7785     SDValue Ops[] = {
7786       M->getOperand(0), // Chain
7787       M->getOperand(2), // Ptr
7788       M->getOperand(3)  // Value
7789     };
7790     unsigned Opcode = 0;
7791     switch (IntrID) {
7792     case Intrinsic::amdgcn_global_atomic_fadd:
7793     case Intrinsic::amdgcn_flat_atomic_fadd: {
7794       EVT VT = Op.getOperand(3).getValueType();
7795       return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7796                            DAG.getVTList(VT, MVT::Other), Ops,
7797                            M->getMemOperand());
7798     }
7799     case Intrinsic::amdgcn_global_atomic_fmin:
7800     case Intrinsic::amdgcn_flat_atomic_fmin: {
7801       Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN;
7802       break;
7803     }
7804     case Intrinsic::amdgcn_global_atomic_fmax:
7805     case Intrinsic::amdgcn_flat_atomic_fmax: {
7806       Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX;
7807       break;
7808     }
7809     default:
7810       llvm_unreachable("unhandled atomic opcode");
7811     }
7812     return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op),
7813                                    M->getVTList(), Ops, M->getMemoryVT(),
7814                                    M->getMemOperand());
7815   }
7816   default:
7817 
7818     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7819             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7820       return lowerImage(Op, ImageDimIntr, DAG, true);
7821 
7822     return SDValue();
7823   }
7824 }
7825 
7826 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7827 // dwordx4 if on SI.
7828 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7829                                               SDVTList VTList,
7830                                               ArrayRef<SDValue> Ops, EVT MemVT,
7831                                               MachineMemOperand *MMO,
7832                                               SelectionDAG &DAG) const {
7833   EVT VT = VTList.VTs[0];
7834   EVT WidenedVT = VT;
7835   EVT WidenedMemVT = MemVT;
7836   if (!Subtarget->hasDwordx3LoadStores() &&
7837       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7838     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7839                                  WidenedVT.getVectorElementType(), 4);
7840     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7841                                     WidenedMemVT.getVectorElementType(), 4);
7842     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7843   }
7844 
7845   assert(VTList.NumVTs == 2);
7846   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7847 
7848   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7849                                        WidenedMemVT, MMO);
7850   if (WidenedVT != VT) {
7851     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7852                                DAG.getVectorIdxConstant(0, DL));
7853     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7854   }
7855   return NewOp;
7856 }
7857 
7858 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7859                                          bool ImageStore) const {
7860   EVT StoreVT = VData.getValueType();
7861 
7862   // No change for f16 and legal vector D16 types.
7863   if (!StoreVT.isVector())
7864     return VData;
7865 
7866   SDLoc DL(VData);
7867   unsigned NumElements = StoreVT.getVectorNumElements();
7868 
7869   if (Subtarget->hasUnpackedD16VMem()) {
7870     // We need to unpack the packed data to store.
7871     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7872     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7873 
7874     EVT EquivStoreVT =
7875         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7876     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7877     return DAG.UnrollVectorOp(ZExt.getNode());
7878   }
7879 
7880   // The sq block of gfx8.1 does not estimate register use correctly for d16
7881   // image store instructions. The data operand is computed as if it were not a
7882   // d16 image instruction.
7883   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7884     // Bitcast to i16
7885     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7886     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7887 
7888     // Decompose into scalars
7889     SmallVector<SDValue, 4> Elts;
7890     DAG.ExtractVectorElements(IntVData, Elts);
7891 
7892     // Group pairs of i16 into v2i16 and bitcast to i32
7893     SmallVector<SDValue, 4> PackedElts;
7894     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7895       SDValue Pair =
7896           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7897       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7898       PackedElts.push_back(IntPair);
7899     }
7900     if ((NumElements % 2) == 1) {
7901       // Handle v3i16
7902       unsigned I = Elts.size() / 2;
7903       SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL,
7904                                         {Elts[I * 2], DAG.getUNDEF(MVT::i16)});
7905       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7906       PackedElts.push_back(IntPair);
7907     }
7908 
7909     // Pad using UNDEF
7910     PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32));
7911 
7912     // Build final vector
7913     EVT VecVT =
7914         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7915     return DAG.getBuildVector(VecVT, DL, PackedElts);
7916   }
7917 
7918   if (NumElements == 3) {
7919     EVT IntStoreVT =
7920         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7921     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7922 
7923     EVT WidenedStoreVT = EVT::getVectorVT(
7924         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7925     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7926                                          WidenedStoreVT.getStoreSizeInBits());
7927     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7928     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7929   }
7930 
7931   assert(isTypeLegal(StoreVT));
7932   return VData;
7933 }
7934 
7935 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7936                                               SelectionDAG &DAG) const {
7937   SDLoc DL(Op);
7938   SDValue Chain = Op.getOperand(0);
7939   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7940   MachineFunction &MF = DAG.getMachineFunction();
7941 
7942   switch (IntrinsicID) {
7943   case Intrinsic::amdgcn_exp_compr: {
7944     SDValue Src0 = Op.getOperand(4);
7945     SDValue Src1 = Op.getOperand(5);
7946     // Hack around illegal type on SI by directly selecting it.
7947     if (isTypeLegal(Src0.getValueType()))
7948       return SDValue();
7949 
7950     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7951     SDValue Undef = DAG.getUNDEF(MVT::f32);
7952     const SDValue Ops[] = {
7953       Op.getOperand(2), // tgt
7954       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7955       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7956       Undef, // src2
7957       Undef, // src3
7958       Op.getOperand(7), // vm
7959       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7960       Op.getOperand(3), // en
7961       Op.getOperand(0) // Chain
7962     };
7963 
7964     unsigned Opc = Done->isZero() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7965     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7966   }
7967   case Intrinsic::amdgcn_s_barrier: {
7968     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7969       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7970       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7971       if (WGSize <= ST.getWavefrontSize())
7972         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7973                                           Op.getOperand(0)), 0);
7974     }
7975     return SDValue();
7976   };
7977   case Intrinsic::amdgcn_tbuffer_store: {
7978     SDValue VData = Op.getOperand(2);
7979     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7980     if (IsD16)
7981       VData = handleD16VData(VData, DAG);
7982     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7983     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7984     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7985     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7986     unsigned IdxEn = getIdxEn(Op.getOperand(4));
7987     SDValue Ops[] = {
7988       Chain,
7989       VData,             // vdata
7990       Op.getOperand(3),  // rsrc
7991       Op.getOperand(4),  // vindex
7992       Op.getOperand(5),  // voffset
7993       Op.getOperand(6),  // soffset
7994       Op.getOperand(7),  // offset
7995       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7996       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7997       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7998     };
7999     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
8000                            AMDGPUISD::TBUFFER_STORE_FORMAT;
8001     MemSDNode *M = cast<MemSDNode>(Op);
8002     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8003                                    M->getMemoryVT(), M->getMemOperand());
8004   }
8005 
8006   case Intrinsic::amdgcn_struct_tbuffer_store: {
8007     SDValue VData = Op.getOperand(2);
8008     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8009     if (IsD16)
8010       VData = handleD16VData(VData, DAG);
8011     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
8012     SDValue Ops[] = {
8013       Chain,
8014       VData,             // vdata
8015       Op.getOperand(3),  // rsrc
8016       Op.getOperand(4),  // vindex
8017       Offsets.first,     // voffset
8018       Op.getOperand(6),  // soffset
8019       Offsets.second,    // offset
8020       Op.getOperand(7),  // format
8021       Op.getOperand(8),  // cachepolicy, swizzled buffer
8022       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8023     };
8024     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
8025                            AMDGPUISD::TBUFFER_STORE_FORMAT;
8026     MemSDNode *M = cast<MemSDNode>(Op);
8027     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8028                                    M->getMemoryVT(), M->getMemOperand());
8029   }
8030 
8031   case Intrinsic::amdgcn_raw_tbuffer_store: {
8032     SDValue VData = Op.getOperand(2);
8033     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8034     if (IsD16)
8035       VData = handleD16VData(VData, DAG);
8036     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
8037     SDValue Ops[] = {
8038       Chain,
8039       VData,             // vdata
8040       Op.getOperand(3),  // rsrc
8041       DAG.getConstant(0, DL, MVT::i32), // vindex
8042       Offsets.first,     // voffset
8043       Op.getOperand(5),  // soffset
8044       Offsets.second,    // offset
8045       Op.getOperand(6),  // format
8046       Op.getOperand(7),  // cachepolicy, swizzled buffer
8047       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8048     };
8049     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
8050                            AMDGPUISD::TBUFFER_STORE_FORMAT;
8051     MemSDNode *M = cast<MemSDNode>(Op);
8052     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8053                                    M->getMemoryVT(), M->getMemOperand());
8054   }
8055 
8056   case Intrinsic::amdgcn_buffer_store:
8057   case Intrinsic::amdgcn_buffer_store_format: {
8058     SDValue VData = Op.getOperand(2);
8059     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
8060     if (IsD16)
8061       VData = handleD16VData(VData, DAG);
8062     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
8063     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
8064     unsigned IdxEn = getIdxEn(Op.getOperand(4));
8065     SDValue Ops[] = {
8066       Chain,
8067       VData,
8068       Op.getOperand(3), // rsrc
8069       Op.getOperand(4), // vindex
8070       SDValue(), // voffset -- will be set by setBufferOffsets
8071       SDValue(), // soffset -- will be set by setBufferOffsets
8072       SDValue(), // offset -- will be set by setBufferOffsets
8073       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
8074       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
8075     };
8076     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
8077 
8078     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
8079                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8080     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8081     MemSDNode *M = cast<MemSDNode>(Op);
8082     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8083 
8084     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8085     EVT VDataType = VData.getValueType().getScalarType();
8086     if (VDataType == MVT::i8 || VDataType == MVT::i16)
8087       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8088 
8089     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8090                                    M->getMemoryVT(), M->getMemOperand());
8091   }
8092 
8093   case Intrinsic::amdgcn_raw_buffer_store:
8094   case Intrinsic::amdgcn_raw_buffer_store_format: {
8095     const bool IsFormat =
8096         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
8097 
8098     SDValue VData = Op.getOperand(2);
8099     EVT VDataVT = VData.getValueType();
8100     EVT EltType = VDataVT.getScalarType();
8101     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8102     if (IsD16) {
8103       VData = handleD16VData(VData, DAG);
8104       VDataVT = VData.getValueType();
8105     }
8106 
8107     if (!isTypeLegal(VDataVT)) {
8108       VData =
8109           DAG.getNode(ISD::BITCAST, DL,
8110                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8111     }
8112 
8113     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
8114     SDValue Ops[] = {
8115       Chain,
8116       VData,
8117       Op.getOperand(3), // rsrc
8118       DAG.getConstant(0, DL, MVT::i32), // vindex
8119       Offsets.first,    // voffset
8120       Op.getOperand(5), // soffset
8121       Offsets.second,   // offset
8122       Op.getOperand(6), // cachepolicy, swizzled buffer
8123       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
8124     };
8125     unsigned Opc =
8126         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
8127     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8128     MemSDNode *M = cast<MemSDNode>(Op);
8129     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6]);
8130 
8131     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8132     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8133       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
8134 
8135     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8136                                    M->getMemoryVT(), M->getMemOperand());
8137   }
8138 
8139   case Intrinsic::amdgcn_struct_buffer_store:
8140   case Intrinsic::amdgcn_struct_buffer_store_format: {
8141     const bool IsFormat =
8142         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
8143 
8144     SDValue VData = Op.getOperand(2);
8145     EVT VDataVT = VData.getValueType();
8146     EVT EltType = VDataVT.getScalarType();
8147     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
8148 
8149     if (IsD16) {
8150       VData = handleD16VData(VData, DAG);
8151       VDataVT = VData.getValueType();
8152     }
8153 
8154     if (!isTypeLegal(VDataVT)) {
8155       VData =
8156           DAG.getNode(ISD::BITCAST, DL,
8157                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
8158     }
8159 
8160     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
8161     SDValue Ops[] = {
8162       Chain,
8163       VData,
8164       Op.getOperand(3), // rsrc
8165       Op.getOperand(4), // vindex
8166       Offsets.first,    // voffset
8167       Op.getOperand(6), // soffset
8168       Offsets.second,   // offset
8169       Op.getOperand(7), // cachepolicy, swizzled buffer
8170       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
8171     };
8172     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
8173                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
8174     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
8175     MemSDNode *M = cast<MemSDNode>(Op);
8176     updateBufferMMO(M->getMemOperand(), Ops[4], Ops[5], Ops[6], Ops[3]);
8177 
8178     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
8179     EVT VDataType = VData.getValueType().getScalarType();
8180     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
8181       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
8182 
8183     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
8184                                    M->getMemoryVT(), M->getMemOperand());
8185   }
8186   case Intrinsic::amdgcn_end_cf:
8187     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
8188                                       Op->getOperand(2), Chain), 0);
8189 
8190   default: {
8191     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
8192             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
8193       return lowerImage(Op, ImageDimIntr, DAG, true);
8194 
8195     return Op;
8196   }
8197   }
8198 }
8199 
8200 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
8201 // offset (the offset that is included in bounds checking and swizzling, to be
8202 // split between the instruction's voffset and immoffset fields) and soffset
8203 // (the offset that is excluded from bounds checking and swizzling, to go in
8204 // the instruction's soffset field).  This function takes the first kind of
8205 // offset and figures out how to split it between voffset and immoffset.
8206 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
8207     SDValue Offset, SelectionDAG &DAG) const {
8208   SDLoc DL(Offset);
8209   const unsigned MaxImm = 4095;
8210   SDValue N0 = Offset;
8211   ConstantSDNode *C1 = nullptr;
8212 
8213   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
8214     N0 = SDValue();
8215   else if (DAG.isBaseWithConstantOffset(N0)) {
8216     C1 = cast<ConstantSDNode>(N0.getOperand(1));
8217     N0 = N0.getOperand(0);
8218   }
8219 
8220   if (C1) {
8221     unsigned ImmOffset = C1->getZExtValue();
8222     // If the immediate value is too big for the immoffset field, put the value
8223     // and -4096 into the immoffset field so that the value that is copied/added
8224     // for the voffset field is a multiple of 4096, and it stands more chance
8225     // of being CSEd with the copy/add for another similar load/store.
8226     // However, do not do that rounding down to a multiple of 4096 if that is a
8227     // negative number, as it appears to be illegal to have a negative offset
8228     // in the vgpr, even if adding the immediate offset makes it positive.
8229     unsigned Overflow = ImmOffset & ~MaxImm;
8230     ImmOffset -= Overflow;
8231     if ((int32_t)Overflow < 0) {
8232       Overflow += ImmOffset;
8233       ImmOffset = 0;
8234     }
8235     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
8236     if (Overflow) {
8237       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
8238       if (!N0)
8239         N0 = OverflowVal;
8240       else {
8241         SDValue Ops[] = { N0, OverflowVal };
8242         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
8243       }
8244     }
8245   }
8246   if (!N0)
8247     N0 = DAG.getConstant(0, DL, MVT::i32);
8248   if (!C1)
8249     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
8250   return {N0, SDValue(C1, 0)};
8251 }
8252 
8253 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
8254 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
8255 // pointed to by Offsets.
8256 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
8257                                         SelectionDAG &DAG, SDValue *Offsets,
8258                                         Align Alignment) const {
8259   SDLoc DL(CombinedOffset);
8260   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
8261     uint32_t Imm = C->getZExtValue();
8262     uint32_t SOffset, ImmOffset;
8263     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
8264                                  Alignment)) {
8265       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
8266       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8267       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8268       return;
8269     }
8270   }
8271   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
8272     SDValue N0 = CombinedOffset.getOperand(0);
8273     SDValue N1 = CombinedOffset.getOperand(1);
8274     uint32_t SOffset, ImmOffset;
8275     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
8276     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
8277                                                 Subtarget, Alignment)) {
8278       Offsets[0] = N0;
8279       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
8280       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
8281       return;
8282     }
8283   }
8284   Offsets[0] = CombinedOffset;
8285   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
8286   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
8287 }
8288 
8289 // Handle 8 bit and 16 bit buffer loads
8290 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
8291                                                      EVT LoadVT, SDLoc DL,
8292                                                      ArrayRef<SDValue> Ops,
8293                                                      MemSDNode *M) const {
8294   EVT IntVT = LoadVT.changeTypeToInteger();
8295   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
8296          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
8297 
8298   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
8299   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
8300                                                Ops, IntVT,
8301                                                M->getMemOperand());
8302   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
8303   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
8304 
8305   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
8306 }
8307 
8308 // Handle 8 bit and 16 bit buffer stores
8309 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
8310                                                       EVT VDataType, SDLoc DL,
8311                                                       SDValue Ops[],
8312                                                       MemSDNode *M) const {
8313   if (VDataType == MVT::f16)
8314     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
8315 
8316   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
8317   Ops[1] = BufferStoreExt;
8318   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
8319                                  AMDGPUISD::BUFFER_STORE_SHORT;
8320   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
8321   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
8322                                      M->getMemOperand());
8323 }
8324 
8325 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
8326                                  ISD::LoadExtType ExtType, SDValue Op,
8327                                  const SDLoc &SL, EVT VT) {
8328   if (VT.bitsLT(Op.getValueType()))
8329     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
8330 
8331   switch (ExtType) {
8332   case ISD::SEXTLOAD:
8333     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
8334   case ISD::ZEXTLOAD:
8335     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
8336   case ISD::EXTLOAD:
8337     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
8338   case ISD::NON_EXTLOAD:
8339     return Op;
8340   }
8341 
8342   llvm_unreachable("invalid ext type");
8343 }
8344 
8345 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
8346   SelectionDAG &DAG = DCI.DAG;
8347   if (Ld->getAlignment() < 4 || Ld->isDivergent())
8348     return SDValue();
8349 
8350   // FIXME: Constant loads should all be marked invariant.
8351   unsigned AS = Ld->getAddressSpace();
8352   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
8353       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
8354       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
8355     return SDValue();
8356 
8357   // Don't do this early, since it may interfere with adjacent load merging for
8358   // illegal types. We can avoid losing alignment information for exotic types
8359   // pre-legalize.
8360   EVT MemVT = Ld->getMemoryVT();
8361   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
8362       MemVT.getSizeInBits() >= 32)
8363     return SDValue();
8364 
8365   SDLoc SL(Ld);
8366 
8367   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
8368          "unexpected vector extload");
8369 
8370   // TODO: Drop only high part of range.
8371   SDValue Ptr = Ld->getBasePtr();
8372   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
8373                                 MVT::i32, SL, Ld->getChain(), Ptr,
8374                                 Ld->getOffset(),
8375                                 Ld->getPointerInfo(), MVT::i32,
8376                                 Ld->getAlignment(),
8377                                 Ld->getMemOperand()->getFlags(),
8378                                 Ld->getAAInfo(),
8379                                 nullptr); // Drop ranges
8380 
8381   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
8382   if (MemVT.isFloatingPoint()) {
8383     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
8384            "unexpected fp extload");
8385     TruncVT = MemVT.changeTypeToInteger();
8386   }
8387 
8388   SDValue Cvt = NewLoad;
8389   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
8390     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
8391                       DAG.getValueType(TruncVT));
8392   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
8393              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
8394     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
8395   } else {
8396     assert(Ld->getExtensionType() == ISD::EXTLOAD);
8397   }
8398 
8399   EVT VT = Ld->getValueType(0);
8400   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8401 
8402   DCI.AddToWorklist(Cvt.getNode());
8403 
8404   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
8405   // the appropriate extension from the 32-bit load.
8406   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
8407   DCI.AddToWorklist(Cvt.getNode());
8408 
8409   // Handle conversion back to floating point if necessary.
8410   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
8411 
8412   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
8413 }
8414 
8415 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8416   SDLoc DL(Op);
8417   LoadSDNode *Load = cast<LoadSDNode>(Op);
8418   ISD::LoadExtType ExtType = Load->getExtensionType();
8419   EVT MemVT = Load->getMemoryVT();
8420 
8421   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
8422     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
8423       return SDValue();
8424 
8425     // FIXME: Copied from PPC
8426     // First, load into 32 bits, then truncate to 1 bit.
8427 
8428     SDValue Chain = Load->getChain();
8429     SDValue BasePtr = Load->getBasePtr();
8430     MachineMemOperand *MMO = Load->getMemOperand();
8431 
8432     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8433 
8434     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8435                                    BasePtr, RealMemVT, MMO);
8436 
8437     if (!MemVT.isVector()) {
8438       SDValue Ops[] = {
8439         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8440         NewLD.getValue(1)
8441       };
8442 
8443       return DAG.getMergeValues(Ops, DL);
8444     }
8445 
8446     SmallVector<SDValue, 3> Elts;
8447     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8448       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8449                                 DAG.getConstant(I, DL, MVT::i32));
8450 
8451       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8452     }
8453 
8454     SDValue Ops[] = {
8455       DAG.getBuildVector(MemVT, DL, Elts),
8456       NewLD.getValue(1)
8457     };
8458 
8459     return DAG.getMergeValues(Ops, DL);
8460   }
8461 
8462   if (!MemVT.isVector())
8463     return SDValue();
8464 
8465   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8466          "Custom lowering for non-i32 vectors hasn't been implemented.");
8467 
8468   unsigned Alignment = Load->getAlignment();
8469   unsigned AS = Load->getAddressSpace();
8470   if (Subtarget->hasLDSMisalignedBug() &&
8471       AS == AMDGPUAS::FLAT_ADDRESS &&
8472       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8473     return SplitVectorLoad(Op, DAG);
8474   }
8475 
8476   MachineFunction &MF = DAG.getMachineFunction();
8477   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8478   // If there is a possibility that flat instruction access scratch memory
8479   // then we need to use the same legalization rules we use for private.
8480   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8481       !Subtarget->hasMultiDwordFlatScratchAddressing())
8482     AS = MFI->hasFlatScratchInit() ?
8483          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8484 
8485   unsigned NumElements = MemVT.getVectorNumElements();
8486 
8487   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8488       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8489     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8490       if (MemVT.isPow2VectorType())
8491         return SDValue();
8492       return WidenOrSplitVectorLoad(Op, DAG);
8493     }
8494     // Non-uniform loads will be selected to MUBUF instructions, so they
8495     // have the same legalization requirements as global and private
8496     // loads.
8497     //
8498   }
8499 
8500   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8501       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8502       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8503     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8504         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8505         Alignment >= 4 && NumElements < 32) {
8506       if (MemVT.isPow2VectorType())
8507         return SDValue();
8508       return WidenOrSplitVectorLoad(Op, DAG);
8509     }
8510     // Non-uniform loads will be selected to MUBUF instructions, so they
8511     // have the same legalization requirements as global and private
8512     // loads.
8513     //
8514   }
8515   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8516       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8517       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8518       AS == AMDGPUAS::FLAT_ADDRESS) {
8519     if (NumElements > 4)
8520       return SplitVectorLoad(Op, DAG);
8521     // v3 loads not supported on SI.
8522     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8523       return WidenOrSplitVectorLoad(Op, DAG);
8524 
8525     // v3 and v4 loads are supported for private and global memory.
8526     return SDValue();
8527   }
8528   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8529     // Depending on the setting of the private_element_size field in the
8530     // resource descriptor, we can only make private accesses up to a certain
8531     // size.
8532     switch (Subtarget->getMaxPrivateElementSize()) {
8533     case 4: {
8534       SDValue Ops[2];
8535       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8536       return DAG.getMergeValues(Ops, DL);
8537     }
8538     case 8:
8539       if (NumElements > 2)
8540         return SplitVectorLoad(Op, DAG);
8541       return SDValue();
8542     case 16:
8543       // Same as global/flat
8544       if (NumElements > 4)
8545         return SplitVectorLoad(Op, DAG);
8546       // v3 loads not supported on SI.
8547       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8548         return WidenOrSplitVectorLoad(Op, DAG);
8549 
8550       return SDValue();
8551     default:
8552       llvm_unreachable("unsupported private_element_size");
8553     }
8554   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8555     bool Fast = false;
8556     auto Flags = Load->getMemOperand()->getFlags();
8557     if (allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8558                                            Load->getAlign(), Flags, &Fast) &&
8559         Fast)
8560       return SDValue();
8561 
8562     if (MemVT.isVector())
8563       return SplitVectorLoad(Op, DAG);
8564   }
8565 
8566   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8567                                       MemVT, *Load->getMemOperand())) {
8568     SDValue Ops[2];
8569     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8570     return DAG.getMergeValues(Ops, DL);
8571   }
8572 
8573   return SDValue();
8574 }
8575 
8576 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8577   EVT VT = Op.getValueType();
8578   if (VT.getSizeInBits() == 128)
8579     return splitTernaryVectorOp(Op, DAG);
8580 
8581   assert(VT.getSizeInBits() == 64);
8582 
8583   SDLoc DL(Op);
8584   SDValue Cond = Op.getOperand(0);
8585 
8586   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8587   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8588 
8589   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8590   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8591 
8592   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8593   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8594 
8595   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8596 
8597   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8598   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8599 
8600   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8601 
8602   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8603   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8604 }
8605 
8606 // Catch division cases where we can use shortcuts with rcp and rsq
8607 // instructions.
8608 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8609                                               SelectionDAG &DAG) const {
8610   SDLoc SL(Op);
8611   SDValue LHS = Op.getOperand(0);
8612   SDValue RHS = Op.getOperand(1);
8613   EVT VT = Op.getValueType();
8614   const SDNodeFlags Flags = Op->getFlags();
8615 
8616   bool AllowInaccurateRcp = Flags.hasApproximateFuncs();
8617 
8618   // Without !fpmath accuracy information, we can't do more because we don't
8619   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8620   if (!AllowInaccurateRcp)
8621     return SDValue();
8622 
8623   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8624     if (CLHS->isExactlyValue(1.0)) {
8625       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8626       // the CI documentation has a worst case error of 1 ulp.
8627       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8628       // use it as long as we aren't trying to use denormals.
8629       //
8630       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8631 
8632       // 1.0 / sqrt(x) -> rsq(x)
8633 
8634       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8635       // error seems really high at 2^29 ULP.
8636       if (RHS.getOpcode() == ISD::FSQRT)
8637         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8638 
8639       // 1.0 / x -> rcp(x)
8640       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8641     }
8642 
8643     // Same as for 1.0, but expand the sign out of the constant.
8644     if (CLHS->isExactlyValue(-1.0)) {
8645       // -1.0 / x -> rcp (fneg x)
8646       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8647       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8648     }
8649   }
8650 
8651   // Turn into multiply by the reciprocal.
8652   // x / y -> x * (1.0 / y)
8653   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8654   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8655 }
8656 
8657 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op,
8658                                                 SelectionDAG &DAG) const {
8659   SDLoc SL(Op);
8660   SDValue X = Op.getOperand(0);
8661   SDValue Y = Op.getOperand(1);
8662   EVT VT = Op.getValueType();
8663   const SDNodeFlags Flags = Op->getFlags();
8664 
8665   bool AllowInaccurateDiv = Flags.hasApproximateFuncs() ||
8666                             DAG.getTarget().Options.UnsafeFPMath;
8667   if (!AllowInaccurateDiv)
8668     return SDValue();
8669 
8670   SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y);
8671   SDValue One = DAG.getConstantFP(1.0, SL, VT);
8672 
8673   SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y);
8674   SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8675 
8676   R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R);
8677   SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One);
8678   R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R);
8679   SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R);
8680   SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X);
8681   return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret);
8682 }
8683 
8684 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8685                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8686                           SDNodeFlags Flags) {
8687   if (GlueChain->getNumValues() <= 1) {
8688     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8689   }
8690 
8691   assert(GlueChain->getNumValues() == 3);
8692 
8693   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8694   switch (Opcode) {
8695   default: llvm_unreachable("no chain equivalent for opcode");
8696   case ISD::FMUL:
8697     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8698     break;
8699   }
8700 
8701   return DAG.getNode(Opcode, SL, VTList,
8702                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8703                      Flags);
8704 }
8705 
8706 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8707                            EVT VT, SDValue A, SDValue B, SDValue C,
8708                            SDValue GlueChain, SDNodeFlags Flags) {
8709   if (GlueChain->getNumValues() <= 1) {
8710     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8711   }
8712 
8713   assert(GlueChain->getNumValues() == 3);
8714 
8715   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8716   switch (Opcode) {
8717   default: llvm_unreachable("no chain equivalent for opcode");
8718   case ISD::FMA:
8719     Opcode = AMDGPUISD::FMA_W_CHAIN;
8720     break;
8721   }
8722 
8723   return DAG.getNode(Opcode, SL, VTList,
8724                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8725                      Flags);
8726 }
8727 
8728 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8729   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8730     return FastLowered;
8731 
8732   SDLoc SL(Op);
8733   SDValue Src0 = Op.getOperand(0);
8734   SDValue Src1 = Op.getOperand(1);
8735 
8736   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8737   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8738 
8739   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8740   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8741 
8742   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8743   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8744 
8745   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8746 }
8747 
8748 // Faster 2.5 ULP division that does not support denormals.
8749 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8750   SDLoc SL(Op);
8751   SDValue LHS = Op.getOperand(1);
8752   SDValue RHS = Op.getOperand(2);
8753 
8754   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8755 
8756   const APFloat K0Val(BitsToFloat(0x6f800000));
8757   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8758 
8759   const APFloat K1Val(BitsToFloat(0x2f800000));
8760   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8761 
8762   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8763 
8764   EVT SetCCVT =
8765     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8766 
8767   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8768 
8769   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8770 
8771   // TODO: Should this propagate fast-math-flags?
8772   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8773 
8774   // rcp does not support denormals.
8775   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8776 
8777   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8778 
8779   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8780 }
8781 
8782 // Returns immediate value for setting the F32 denorm mode when using the
8783 // S_DENORM_MODE instruction.
8784 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8785                                     const SDLoc &SL, const GCNSubtarget *ST) {
8786   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8787   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8788                                 ? FP_DENORM_FLUSH_NONE
8789                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8790 
8791   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8792   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8793 }
8794 
8795 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8796   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8797     return FastLowered;
8798 
8799   // The selection matcher assumes anything with a chain selecting to a
8800   // mayRaiseFPException machine instruction. Since we're introducing a chain
8801   // here, we need to explicitly report nofpexcept for the regular fdiv
8802   // lowering.
8803   SDNodeFlags Flags = Op->getFlags();
8804   Flags.setNoFPExcept(true);
8805 
8806   SDLoc SL(Op);
8807   SDValue LHS = Op.getOperand(0);
8808   SDValue RHS = Op.getOperand(1);
8809 
8810   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8811 
8812   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8813 
8814   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8815                                           {RHS, RHS, LHS}, Flags);
8816   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8817                                         {LHS, RHS, LHS}, Flags);
8818 
8819   // Denominator is scaled to not be denormal, so using rcp is ok.
8820   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8821                                   DenominatorScaled, Flags);
8822   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8823                                      DenominatorScaled, Flags);
8824 
8825   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8826                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8827                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8828   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8829 
8830   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8831 
8832   if (!HasFP32Denormals) {
8833     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8834     // lowering. The chain dependence is insufficient, and we need glue. We do
8835     // not need the glue variants in a strictfp function.
8836 
8837     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8838 
8839     SDNode *EnableDenorm;
8840     if (Subtarget->hasDenormModeInst()) {
8841       const SDValue EnableDenormValue =
8842           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8843 
8844       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8845                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8846     } else {
8847       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8848                                                         SL, MVT::i32);
8849       EnableDenorm =
8850           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8851                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8852     }
8853 
8854     SDValue Ops[3] = {
8855       NegDivScale0,
8856       SDValue(EnableDenorm, 0),
8857       SDValue(EnableDenorm, 1)
8858     };
8859 
8860     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8861   }
8862 
8863   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8864                              ApproxRcp, One, NegDivScale0, Flags);
8865 
8866   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8867                              ApproxRcp, Fma0, Flags);
8868 
8869   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8870                            Fma1, Fma1, Flags);
8871 
8872   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8873                              NumeratorScaled, Mul, Flags);
8874 
8875   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8876                              Fma2, Fma1, Mul, Fma2, Flags);
8877 
8878   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8879                              NumeratorScaled, Fma3, Flags);
8880 
8881   if (!HasFP32Denormals) {
8882     SDNode *DisableDenorm;
8883     if (Subtarget->hasDenormModeInst()) {
8884       const SDValue DisableDenormValue =
8885           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8886 
8887       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8888                                   Fma4.getValue(1), DisableDenormValue,
8889                                   Fma4.getValue(2)).getNode();
8890     } else {
8891       const SDValue DisableDenormValue =
8892           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8893 
8894       DisableDenorm = DAG.getMachineNode(
8895           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8896           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8897     }
8898 
8899     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8900                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8901     DAG.setRoot(OutputChain);
8902   }
8903 
8904   SDValue Scale = NumeratorScaled.getValue(1);
8905   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8906                              {Fma4, Fma1, Fma3, Scale}, Flags);
8907 
8908   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8909 }
8910 
8911 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8912   if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG))
8913     return FastLowered;
8914 
8915   SDLoc SL(Op);
8916   SDValue X = Op.getOperand(0);
8917   SDValue Y = Op.getOperand(1);
8918 
8919   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8920 
8921   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8922 
8923   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8924 
8925   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8926 
8927   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8928 
8929   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8930 
8931   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8932 
8933   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8934 
8935   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8936 
8937   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8938   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8939 
8940   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8941                              NegDivScale0, Mul, DivScale1);
8942 
8943   SDValue Scale;
8944 
8945   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8946     // Workaround a hardware bug on SI where the condition output from div_scale
8947     // is not usable.
8948 
8949     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8950 
8951     // Figure out if the scale to use for div_fmas.
8952     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8953     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8954     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8955     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8956 
8957     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8958     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8959 
8960     SDValue Scale0Hi
8961       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8962     SDValue Scale1Hi
8963       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8964 
8965     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8966     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8967     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8968   } else {
8969     Scale = DivScale1.getValue(1);
8970   }
8971 
8972   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8973                              Fma4, Fma3, Mul, Scale);
8974 
8975   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8976 }
8977 
8978 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8979   EVT VT = Op.getValueType();
8980 
8981   if (VT == MVT::f32)
8982     return LowerFDIV32(Op, DAG);
8983 
8984   if (VT == MVT::f64)
8985     return LowerFDIV64(Op, DAG);
8986 
8987   if (VT == MVT::f16)
8988     return LowerFDIV16(Op, DAG);
8989 
8990   llvm_unreachable("Unexpected type for fdiv");
8991 }
8992 
8993 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8994   SDLoc DL(Op);
8995   StoreSDNode *Store = cast<StoreSDNode>(Op);
8996   EVT VT = Store->getMemoryVT();
8997 
8998   if (VT == MVT::i1) {
8999     return DAG.getTruncStore(Store->getChain(), DL,
9000        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
9001        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
9002   }
9003 
9004   assert(VT.isVector() &&
9005          Store->getValue().getValueType().getScalarType() == MVT::i32);
9006 
9007   unsigned AS = Store->getAddressSpace();
9008   if (Subtarget->hasLDSMisalignedBug() &&
9009       AS == AMDGPUAS::FLAT_ADDRESS &&
9010       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
9011     return SplitVectorStore(Op, DAG);
9012   }
9013 
9014   MachineFunction &MF = DAG.getMachineFunction();
9015   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
9016   // If there is a possibility that flat instruction access scratch memory
9017   // then we need to use the same legalization rules we use for private.
9018   if (AS == AMDGPUAS::FLAT_ADDRESS &&
9019       !Subtarget->hasMultiDwordFlatScratchAddressing())
9020     AS = MFI->hasFlatScratchInit() ?
9021          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
9022 
9023   unsigned NumElements = VT.getVectorNumElements();
9024   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
9025       AS == AMDGPUAS::FLAT_ADDRESS) {
9026     if (NumElements > 4)
9027       return SplitVectorStore(Op, DAG);
9028     // v3 stores not supported on SI.
9029     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
9030       return SplitVectorStore(Op, DAG);
9031 
9032     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
9033                                         VT, *Store->getMemOperand()))
9034       return expandUnalignedStore(Store, DAG);
9035 
9036     return SDValue();
9037   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
9038     switch (Subtarget->getMaxPrivateElementSize()) {
9039     case 4:
9040       return scalarizeVectorStore(Store, DAG);
9041     case 8:
9042       if (NumElements > 2)
9043         return SplitVectorStore(Op, DAG);
9044       return SDValue();
9045     case 16:
9046       if (NumElements > 4 ||
9047           (NumElements == 3 && !Subtarget->enableFlatScratch()))
9048         return SplitVectorStore(Op, DAG);
9049       return SDValue();
9050     default:
9051       llvm_unreachable("unsupported private_element_size");
9052     }
9053   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
9054     bool Fast = false;
9055     auto Flags = Store->getMemOperand()->getFlags();
9056     if (allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
9057                                            Store->getAlign(), Flags, &Fast) &&
9058         Fast)
9059       return SDValue();
9060 
9061     if (VT.isVector())
9062       return SplitVectorStore(Op, DAG);
9063 
9064     return expandUnalignedStore(Store, DAG);
9065   }
9066 
9067   // Probably an invalid store. If so we'll end up emitting a selection error.
9068   return SDValue();
9069 }
9070 
9071 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
9072   SDLoc DL(Op);
9073   EVT VT = Op.getValueType();
9074   SDValue Arg = Op.getOperand(0);
9075   SDValue TrigVal;
9076 
9077   // Propagate fast-math flags so that the multiply we introduce can be folded
9078   // if Arg is already the result of a multiply by constant.
9079   auto Flags = Op->getFlags();
9080 
9081   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
9082 
9083   if (Subtarget->hasTrigReducedRange()) {
9084     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9085     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
9086   } else {
9087     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
9088   }
9089 
9090   switch (Op.getOpcode()) {
9091   case ISD::FCOS:
9092     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
9093   case ISD::FSIN:
9094     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
9095   default:
9096     llvm_unreachable("Wrong trig opcode");
9097   }
9098 }
9099 
9100 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
9101   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
9102   assert(AtomicNode->isCompareAndSwap());
9103   unsigned AS = AtomicNode->getAddressSpace();
9104 
9105   // No custom lowering required for local address space
9106   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
9107     return Op;
9108 
9109   // Non-local address space requires custom lowering for atomic compare
9110   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
9111   SDLoc DL(Op);
9112   SDValue ChainIn = Op.getOperand(0);
9113   SDValue Addr = Op.getOperand(1);
9114   SDValue Old = Op.getOperand(2);
9115   SDValue New = Op.getOperand(3);
9116   EVT VT = Op.getValueType();
9117   MVT SimpleVT = VT.getSimpleVT();
9118   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
9119 
9120   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
9121   SDValue Ops[] = { ChainIn, Addr, NewOld };
9122 
9123   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
9124                                  Ops, VT, AtomicNode->getMemOperand());
9125 }
9126 
9127 //===----------------------------------------------------------------------===//
9128 // Custom DAG optimizations
9129 //===----------------------------------------------------------------------===//
9130 
9131 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
9132                                                      DAGCombinerInfo &DCI) const {
9133   EVT VT = N->getValueType(0);
9134   EVT ScalarVT = VT.getScalarType();
9135   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
9136     return SDValue();
9137 
9138   SelectionDAG &DAG = DCI.DAG;
9139   SDLoc DL(N);
9140 
9141   SDValue Src = N->getOperand(0);
9142   EVT SrcVT = Src.getValueType();
9143 
9144   // TODO: We could try to match extracting the higher bytes, which would be
9145   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
9146   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
9147   // about in practice.
9148   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
9149     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
9150       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
9151       DCI.AddToWorklist(Cvt.getNode());
9152 
9153       // For the f16 case, fold to a cast to f32 and then cast back to f16.
9154       if (ScalarVT != MVT::f32) {
9155         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
9156                           DAG.getTargetConstant(0, DL, MVT::i32));
9157       }
9158       return Cvt;
9159     }
9160   }
9161 
9162   return SDValue();
9163 }
9164 
9165 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
9166 
9167 // This is a variant of
9168 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
9169 //
9170 // The normal DAG combiner will do this, but only if the add has one use since
9171 // that would increase the number of instructions.
9172 //
9173 // This prevents us from seeing a constant offset that can be folded into a
9174 // memory instruction's addressing mode. If we know the resulting add offset of
9175 // a pointer can be folded into an addressing offset, we can replace the pointer
9176 // operand with the add of new constant offset. This eliminates one of the uses,
9177 // and may allow the remaining use to also be simplified.
9178 //
9179 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
9180                                                unsigned AddrSpace,
9181                                                EVT MemVT,
9182                                                DAGCombinerInfo &DCI) const {
9183   SDValue N0 = N->getOperand(0);
9184   SDValue N1 = N->getOperand(1);
9185 
9186   // We only do this to handle cases where it's profitable when there are
9187   // multiple uses of the add, so defer to the standard combine.
9188   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
9189       N0->hasOneUse())
9190     return SDValue();
9191 
9192   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
9193   if (!CN1)
9194     return SDValue();
9195 
9196   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9197   if (!CAdd)
9198     return SDValue();
9199 
9200   // If the resulting offset is too large, we can't fold it into the addressing
9201   // mode offset.
9202   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
9203   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
9204 
9205   AddrMode AM;
9206   AM.HasBaseReg = true;
9207   AM.BaseOffs = Offset.getSExtValue();
9208   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
9209     return SDValue();
9210 
9211   SelectionDAG &DAG = DCI.DAG;
9212   SDLoc SL(N);
9213   EVT VT = N->getValueType(0);
9214 
9215   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
9216   SDValue COffset = DAG.getConstant(Offset, SL, VT);
9217 
9218   SDNodeFlags Flags;
9219   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
9220                           (N0.getOpcode() == ISD::OR ||
9221                            N0->getFlags().hasNoUnsignedWrap()));
9222 
9223   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
9224 }
9225 
9226 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
9227 /// by the chain and intrinsic ID. Theoretically we would also need to check the
9228 /// specific intrinsic, but they all place the pointer operand first.
9229 static unsigned getBasePtrIndex(const MemSDNode *N) {
9230   switch (N->getOpcode()) {
9231   case ISD::STORE:
9232   case ISD::INTRINSIC_W_CHAIN:
9233   case ISD::INTRINSIC_VOID:
9234     return 2;
9235   default:
9236     return 1;
9237   }
9238 }
9239 
9240 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
9241                                                   DAGCombinerInfo &DCI) const {
9242   SelectionDAG &DAG = DCI.DAG;
9243   SDLoc SL(N);
9244 
9245   unsigned PtrIdx = getBasePtrIndex(N);
9246   SDValue Ptr = N->getOperand(PtrIdx);
9247 
9248   // TODO: We could also do this for multiplies.
9249   if (Ptr.getOpcode() == ISD::SHL) {
9250     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
9251                                           N->getMemoryVT(), DCI);
9252     if (NewPtr) {
9253       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
9254 
9255       NewOps[PtrIdx] = NewPtr;
9256       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
9257     }
9258   }
9259 
9260   return SDValue();
9261 }
9262 
9263 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
9264   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
9265          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
9266          (Opc == ISD::XOR && Val == 0);
9267 }
9268 
9269 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
9270 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
9271 // integer combine opportunities since most 64-bit operations are decomposed
9272 // this way.  TODO: We won't want this for SALU especially if it is an inline
9273 // immediate.
9274 SDValue SITargetLowering::splitBinaryBitConstantOp(
9275   DAGCombinerInfo &DCI,
9276   const SDLoc &SL,
9277   unsigned Opc, SDValue LHS,
9278   const ConstantSDNode *CRHS) const {
9279   uint64_t Val = CRHS->getZExtValue();
9280   uint32_t ValLo = Lo_32(Val);
9281   uint32_t ValHi = Hi_32(Val);
9282   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9283 
9284     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
9285          bitOpWithConstantIsReducible(Opc, ValHi)) ||
9286         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
9287     // If we need to materialize a 64-bit immediate, it will be split up later
9288     // anyway. Avoid creating the harder to understand 64-bit immediate
9289     // materialization.
9290     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
9291   }
9292 
9293   return SDValue();
9294 }
9295 
9296 // Returns true if argument is a boolean value which is not serialized into
9297 // memory or argument and does not require v_cndmask_b32 to be deserialized.
9298 static bool isBoolSGPR(SDValue V) {
9299   if (V.getValueType() != MVT::i1)
9300     return false;
9301   switch (V.getOpcode()) {
9302   default:
9303     break;
9304   case ISD::SETCC:
9305   case AMDGPUISD::FP_CLASS:
9306     return true;
9307   case ISD::AND:
9308   case ISD::OR:
9309   case ISD::XOR:
9310     return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1));
9311   }
9312   return false;
9313 }
9314 
9315 // If a constant has all zeroes or all ones within each byte return it.
9316 // Otherwise return 0.
9317 static uint32_t getConstantPermuteMask(uint32_t C) {
9318   // 0xff for any zero byte in the mask
9319   uint32_t ZeroByteMask = 0;
9320   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
9321   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
9322   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
9323   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
9324   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
9325   if ((NonZeroByteMask & C) != NonZeroByteMask)
9326     return 0; // Partial bytes selected.
9327   return C;
9328 }
9329 
9330 // Check if a node selects whole bytes from its operand 0 starting at a byte
9331 // boundary while masking the rest. Returns select mask as in the v_perm_b32
9332 // or -1 if not succeeded.
9333 // Note byte select encoding:
9334 // value 0-3 selects corresponding source byte;
9335 // value 0xc selects zero;
9336 // value 0xff selects 0xff.
9337 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
9338   assert(V.getValueSizeInBits() == 32);
9339 
9340   if (V.getNumOperands() != 2)
9341     return ~0;
9342 
9343   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
9344   if (!N1)
9345     return ~0;
9346 
9347   uint32_t C = N1->getZExtValue();
9348 
9349   switch (V.getOpcode()) {
9350   default:
9351     break;
9352   case ISD::AND:
9353     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9354       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
9355     }
9356     break;
9357 
9358   case ISD::OR:
9359     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
9360       return (0x03020100 & ~ConstMask) | ConstMask;
9361     }
9362     break;
9363 
9364   case ISD::SHL:
9365     if (C % 8)
9366       return ~0;
9367 
9368     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
9369 
9370   case ISD::SRL:
9371     if (C % 8)
9372       return ~0;
9373 
9374     return uint32_t(0x0c0c0c0c03020100ull >> C);
9375   }
9376 
9377   return ~0;
9378 }
9379 
9380 SDValue SITargetLowering::performAndCombine(SDNode *N,
9381                                             DAGCombinerInfo &DCI) const {
9382   if (DCI.isBeforeLegalize())
9383     return SDValue();
9384 
9385   SelectionDAG &DAG = DCI.DAG;
9386   EVT VT = N->getValueType(0);
9387   SDValue LHS = N->getOperand(0);
9388   SDValue RHS = N->getOperand(1);
9389 
9390 
9391   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9392   if (VT == MVT::i64 && CRHS) {
9393     if (SDValue Split
9394         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
9395       return Split;
9396   }
9397 
9398   if (CRHS && VT == MVT::i32) {
9399     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
9400     // nb = number of trailing zeroes in mask
9401     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
9402     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
9403     uint64_t Mask = CRHS->getZExtValue();
9404     unsigned Bits = countPopulation(Mask);
9405     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
9406         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
9407       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
9408         unsigned Shift = CShift->getZExtValue();
9409         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
9410         unsigned Offset = NB + Shift;
9411         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
9412           SDLoc SL(N);
9413           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
9414                                     LHS->getOperand(0),
9415                                     DAG.getConstant(Offset, SL, MVT::i32),
9416                                     DAG.getConstant(Bits, SL, MVT::i32));
9417           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9418           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
9419                                     DAG.getValueType(NarrowVT));
9420           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
9421                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
9422           return Shl;
9423         }
9424       }
9425     }
9426 
9427     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9428     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
9429         isa<ConstantSDNode>(LHS.getOperand(2))) {
9430       uint32_t Sel = getConstantPermuteMask(Mask);
9431       if (!Sel)
9432         return SDValue();
9433 
9434       // Select 0xc for all zero bytes
9435       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9436       SDLoc DL(N);
9437       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9438                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9439     }
9440   }
9441 
9442   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9443   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9444   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9445     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9446     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9447 
9448     SDValue X = LHS.getOperand(0);
9449     SDValue Y = RHS.getOperand(0);
9450     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9451       return SDValue();
9452 
9453     if (LCC == ISD::SETO) {
9454       if (X != LHS.getOperand(1))
9455         return SDValue();
9456 
9457       if (RCC == ISD::SETUNE) {
9458         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9459         if (!C1 || !C1->isInfinity() || C1->isNegative())
9460           return SDValue();
9461 
9462         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9463                               SIInstrFlags::N_SUBNORMAL |
9464                               SIInstrFlags::N_ZERO |
9465                               SIInstrFlags::P_ZERO |
9466                               SIInstrFlags::P_SUBNORMAL |
9467                               SIInstrFlags::P_NORMAL;
9468 
9469         static_assert(((~(SIInstrFlags::S_NAN |
9470                           SIInstrFlags::Q_NAN |
9471                           SIInstrFlags::N_INFINITY |
9472                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9473                       "mask not equal");
9474 
9475         SDLoc DL(N);
9476         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9477                            X, DAG.getConstant(Mask, DL, MVT::i32));
9478       }
9479     }
9480   }
9481 
9482   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9483     std::swap(LHS, RHS);
9484 
9485   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9486       RHS.hasOneUse()) {
9487     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9488     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9489     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9490     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9491     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9492         (RHS.getOperand(0) == LHS.getOperand(0) &&
9493          LHS.getOperand(0) == LHS.getOperand(1))) {
9494       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9495       unsigned NewMask = LCC == ISD::SETO ?
9496         Mask->getZExtValue() & ~OrdMask :
9497         Mask->getZExtValue() & OrdMask;
9498 
9499       SDLoc DL(N);
9500       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9501                          DAG.getConstant(NewMask, DL, MVT::i32));
9502     }
9503   }
9504 
9505   if (VT == MVT::i32 &&
9506       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9507     // and x, (sext cc from i1) => select cc, x, 0
9508     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9509       std::swap(LHS, RHS);
9510     if (isBoolSGPR(RHS.getOperand(0)))
9511       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9512                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9513   }
9514 
9515   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9516   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9517   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9518       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9519     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9520     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9521     if (LHSMask != ~0u && RHSMask != ~0u) {
9522       // Canonicalize the expression in an attempt to have fewer unique masks
9523       // and therefore fewer registers used to hold the masks.
9524       if (LHSMask > RHSMask) {
9525         std::swap(LHSMask, RHSMask);
9526         std::swap(LHS, RHS);
9527       }
9528 
9529       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9530       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9531       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9532       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9533 
9534       // Check of we need to combine values from two sources within a byte.
9535       if (!(LHSUsedLanes & RHSUsedLanes) &&
9536           // If we select high and lower word keep it for SDWA.
9537           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9538           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9539         // Each byte in each mask is either selector mask 0-3, or has higher
9540         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9541         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9542         // mask which is not 0xff wins. By anding both masks we have a correct
9543         // result except that 0x0c shall be corrected to give 0x0c only.
9544         uint32_t Mask = LHSMask & RHSMask;
9545         for (unsigned I = 0; I < 32; I += 8) {
9546           uint32_t ByteSel = 0xff << I;
9547           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9548             Mask &= (0x0c << I) & 0xffffffff;
9549         }
9550 
9551         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9552         // or 0x0c.
9553         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9554         SDLoc DL(N);
9555 
9556         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9557                            LHS.getOperand(0), RHS.getOperand(0),
9558                            DAG.getConstant(Sel, DL, MVT::i32));
9559       }
9560     }
9561   }
9562 
9563   return SDValue();
9564 }
9565 
9566 SDValue SITargetLowering::performOrCombine(SDNode *N,
9567                                            DAGCombinerInfo &DCI) const {
9568   SelectionDAG &DAG = DCI.DAG;
9569   SDValue LHS = N->getOperand(0);
9570   SDValue RHS = N->getOperand(1);
9571 
9572   EVT VT = N->getValueType(0);
9573   if (VT == MVT::i1) {
9574     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9575     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9576         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9577       SDValue Src = LHS.getOperand(0);
9578       if (Src != RHS.getOperand(0))
9579         return SDValue();
9580 
9581       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9582       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9583       if (!CLHS || !CRHS)
9584         return SDValue();
9585 
9586       // Only 10 bits are used.
9587       static const uint32_t MaxMask = 0x3ff;
9588 
9589       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9590       SDLoc DL(N);
9591       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9592                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9593     }
9594 
9595     return SDValue();
9596   }
9597 
9598   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9599   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9600       LHS.getOpcode() == AMDGPUISD::PERM &&
9601       isa<ConstantSDNode>(LHS.getOperand(2))) {
9602     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9603     if (!Sel)
9604       return SDValue();
9605 
9606     Sel |= LHS.getConstantOperandVal(2);
9607     SDLoc DL(N);
9608     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9609                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9610   }
9611 
9612   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9613   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9614   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9615       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) {
9616     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9617     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9618     if (LHSMask != ~0u && RHSMask != ~0u) {
9619       // Canonicalize the expression in an attempt to have fewer unique masks
9620       // and therefore fewer registers used to hold the masks.
9621       if (LHSMask > RHSMask) {
9622         std::swap(LHSMask, RHSMask);
9623         std::swap(LHS, RHS);
9624       }
9625 
9626       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9627       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9628       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9629       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9630 
9631       // Check of we need to combine values from two sources within a byte.
9632       if (!(LHSUsedLanes & RHSUsedLanes) &&
9633           // If we select high and lower word keep it for SDWA.
9634           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9635           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9636         // Kill zero bytes selected by other mask. Zero value is 0xc.
9637         LHSMask &= ~RHSUsedLanes;
9638         RHSMask &= ~LHSUsedLanes;
9639         // Add 4 to each active LHS lane
9640         LHSMask |= LHSUsedLanes & 0x04040404;
9641         // Combine masks
9642         uint32_t Sel = LHSMask | RHSMask;
9643         SDLoc DL(N);
9644 
9645         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9646                            LHS.getOperand(0), RHS.getOperand(0),
9647                            DAG.getConstant(Sel, DL, MVT::i32));
9648       }
9649     }
9650   }
9651 
9652   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9653     return SDValue();
9654 
9655   // TODO: This could be a generic combine with a predicate for extracting the
9656   // high half of an integer being free.
9657 
9658   // (or i64:x, (zero_extend i32:y)) ->
9659   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9660   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9661       RHS.getOpcode() != ISD::ZERO_EXTEND)
9662     std::swap(LHS, RHS);
9663 
9664   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9665     SDValue ExtSrc = RHS.getOperand(0);
9666     EVT SrcVT = ExtSrc.getValueType();
9667     if (SrcVT == MVT::i32) {
9668       SDLoc SL(N);
9669       SDValue LowLHS, HiBits;
9670       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9671       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9672 
9673       DCI.AddToWorklist(LowOr.getNode());
9674       DCI.AddToWorklist(HiBits.getNode());
9675 
9676       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9677                                 LowOr, HiBits);
9678       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9679     }
9680   }
9681 
9682   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9683   if (CRHS) {
9684     if (SDValue Split
9685           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR,
9686                                      N->getOperand(0), CRHS))
9687       return Split;
9688   }
9689 
9690   return SDValue();
9691 }
9692 
9693 SDValue SITargetLowering::performXorCombine(SDNode *N,
9694                                             DAGCombinerInfo &DCI) const {
9695   if (SDValue RV = reassociateScalarOps(N, DCI.DAG))
9696     return RV;
9697 
9698   EVT VT = N->getValueType(0);
9699   if (VT != MVT::i64)
9700     return SDValue();
9701 
9702   SDValue LHS = N->getOperand(0);
9703   SDValue RHS = N->getOperand(1);
9704 
9705   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9706   if (CRHS) {
9707     if (SDValue Split
9708           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9709       return Split;
9710   }
9711 
9712   return SDValue();
9713 }
9714 
9715 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9716                                                    DAGCombinerInfo &DCI) const {
9717   if (!Subtarget->has16BitInsts() ||
9718       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9719     return SDValue();
9720 
9721   EVT VT = N->getValueType(0);
9722   if (VT != MVT::i32)
9723     return SDValue();
9724 
9725   SDValue Src = N->getOperand(0);
9726   if (Src.getValueType() != MVT::i16)
9727     return SDValue();
9728 
9729   return SDValue();
9730 }
9731 
9732 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9733                                                         DAGCombinerInfo &DCI)
9734                                                         const {
9735   SDValue Src = N->getOperand(0);
9736   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9737 
9738   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9739       VTSign->getVT() == MVT::i8) ||
9740       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9741       VTSign->getVT() == MVT::i16)) &&
9742       Src.hasOneUse()) {
9743     auto *M = cast<MemSDNode>(Src);
9744     SDValue Ops[] = {
9745       Src.getOperand(0), // Chain
9746       Src.getOperand(1), // rsrc
9747       Src.getOperand(2), // vindex
9748       Src.getOperand(3), // voffset
9749       Src.getOperand(4), // soffset
9750       Src.getOperand(5), // offset
9751       Src.getOperand(6),
9752       Src.getOperand(7)
9753     };
9754     // replace with BUFFER_LOAD_BYTE/SHORT
9755     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9756                                          Src.getOperand(0).getValueType());
9757     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9758                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9759     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9760                                                           ResList,
9761                                                           Ops, M->getMemoryVT(),
9762                                                           M->getMemOperand());
9763     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9764                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9765   }
9766   return SDValue();
9767 }
9768 
9769 SDValue SITargetLowering::performClassCombine(SDNode *N,
9770                                               DAGCombinerInfo &DCI) const {
9771   SelectionDAG &DAG = DCI.DAG;
9772   SDValue Mask = N->getOperand(1);
9773 
9774   // fp_class x, 0 -> false
9775   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9776     if (CMask->isZero())
9777       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9778   }
9779 
9780   if (N->getOperand(0).isUndef())
9781     return DAG.getUNDEF(MVT::i1);
9782 
9783   return SDValue();
9784 }
9785 
9786 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9787                                             DAGCombinerInfo &DCI) const {
9788   EVT VT = N->getValueType(0);
9789   SDValue N0 = N->getOperand(0);
9790 
9791   if (N0.isUndef())
9792     return N0;
9793 
9794   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9795                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9796     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9797                            N->getFlags());
9798   }
9799 
9800   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9801     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9802                            N0.getOperand(0), N->getFlags());
9803   }
9804 
9805   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9806 }
9807 
9808 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9809                                        unsigned MaxDepth) const {
9810   unsigned Opcode = Op.getOpcode();
9811   if (Opcode == ISD::FCANONICALIZE)
9812     return true;
9813 
9814   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9815     auto F = CFP->getValueAPF();
9816     if (F.isNaN() && F.isSignaling())
9817       return false;
9818     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9819   }
9820 
9821   // If source is a result of another standard FP operation it is already in
9822   // canonical form.
9823   if (MaxDepth == 0)
9824     return false;
9825 
9826   switch (Opcode) {
9827   // These will flush denorms if required.
9828   case ISD::FADD:
9829   case ISD::FSUB:
9830   case ISD::FMUL:
9831   case ISD::FCEIL:
9832   case ISD::FFLOOR:
9833   case ISD::FMA:
9834   case ISD::FMAD:
9835   case ISD::FSQRT:
9836   case ISD::FDIV:
9837   case ISD::FREM:
9838   case ISD::FP_ROUND:
9839   case ISD::FP_EXTEND:
9840   case AMDGPUISD::FMUL_LEGACY:
9841   case AMDGPUISD::FMAD_FTZ:
9842   case AMDGPUISD::RCP:
9843   case AMDGPUISD::RSQ:
9844   case AMDGPUISD::RSQ_CLAMP:
9845   case AMDGPUISD::RCP_LEGACY:
9846   case AMDGPUISD::RCP_IFLAG:
9847   case AMDGPUISD::DIV_SCALE:
9848   case AMDGPUISD::DIV_FMAS:
9849   case AMDGPUISD::DIV_FIXUP:
9850   case AMDGPUISD::FRACT:
9851   case AMDGPUISD::LDEXP:
9852   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9853   case AMDGPUISD::CVT_F32_UBYTE0:
9854   case AMDGPUISD::CVT_F32_UBYTE1:
9855   case AMDGPUISD::CVT_F32_UBYTE2:
9856   case AMDGPUISD::CVT_F32_UBYTE3:
9857     return true;
9858 
9859   // It can/will be lowered or combined as a bit operation.
9860   // Need to check their input recursively to handle.
9861   case ISD::FNEG:
9862   case ISD::FABS:
9863   case ISD::FCOPYSIGN:
9864     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9865 
9866   case ISD::FSIN:
9867   case ISD::FCOS:
9868   case ISD::FSINCOS:
9869     return Op.getValueType().getScalarType() != MVT::f16;
9870 
9871   case ISD::FMINNUM:
9872   case ISD::FMAXNUM:
9873   case ISD::FMINNUM_IEEE:
9874   case ISD::FMAXNUM_IEEE:
9875   case AMDGPUISD::CLAMP:
9876   case AMDGPUISD::FMED3:
9877   case AMDGPUISD::FMAX3:
9878   case AMDGPUISD::FMIN3: {
9879     // FIXME: Shouldn't treat the generic operations different based these.
9880     // However, we aren't really required to flush the result from
9881     // minnum/maxnum..
9882 
9883     // snans will be quieted, so we only need to worry about denormals.
9884     if (Subtarget->supportsMinMaxDenormModes() ||
9885         denormalsEnabledForType(DAG, Op.getValueType()))
9886       return true;
9887 
9888     // Flushing may be required.
9889     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9890     // targets need to check their input recursively.
9891 
9892     // FIXME: Does this apply with clamp? It's implemented with max.
9893     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9894       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9895         return false;
9896     }
9897 
9898     return true;
9899   }
9900   case ISD::SELECT: {
9901     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9902            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9903   }
9904   case ISD::BUILD_VECTOR: {
9905     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9906       SDValue SrcOp = Op.getOperand(i);
9907       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9908         return false;
9909     }
9910 
9911     return true;
9912   }
9913   case ISD::EXTRACT_VECTOR_ELT:
9914   case ISD::EXTRACT_SUBVECTOR: {
9915     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9916   }
9917   case ISD::INSERT_VECTOR_ELT: {
9918     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9919            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9920   }
9921   case ISD::UNDEF:
9922     // Could be anything.
9923     return false;
9924 
9925   case ISD::BITCAST:
9926     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9927   case ISD::TRUNCATE: {
9928     // Hack round the mess we make when legalizing extract_vector_elt
9929     if (Op.getValueType() == MVT::i16) {
9930       SDValue TruncSrc = Op.getOperand(0);
9931       if (TruncSrc.getValueType() == MVT::i32 &&
9932           TruncSrc.getOpcode() == ISD::BITCAST &&
9933           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9934         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9935       }
9936     }
9937     return false;
9938   }
9939   case ISD::INTRINSIC_WO_CHAIN: {
9940     unsigned IntrinsicID
9941       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9942     // TODO: Handle more intrinsics
9943     switch (IntrinsicID) {
9944     case Intrinsic::amdgcn_cvt_pkrtz:
9945     case Intrinsic::amdgcn_cubeid:
9946     case Intrinsic::amdgcn_frexp_mant:
9947     case Intrinsic::amdgcn_fdot2:
9948     case Intrinsic::amdgcn_rcp:
9949     case Intrinsic::amdgcn_rsq:
9950     case Intrinsic::amdgcn_rsq_clamp:
9951     case Intrinsic::amdgcn_rcp_legacy:
9952     case Intrinsic::amdgcn_rsq_legacy:
9953     case Intrinsic::amdgcn_trig_preop:
9954       return true;
9955     default:
9956       break;
9957     }
9958 
9959     LLVM_FALLTHROUGH;
9960   }
9961   default:
9962     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9963            DAG.isKnownNeverSNaN(Op);
9964   }
9965 
9966   llvm_unreachable("invalid operation");
9967 }
9968 
9969 bool SITargetLowering::isCanonicalized(Register Reg, MachineFunction &MF,
9970                                        unsigned MaxDepth) const {
9971   MachineRegisterInfo &MRI = MF.getRegInfo();
9972   MachineInstr *MI = MRI.getVRegDef(Reg);
9973   unsigned Opcode = MI->getOpcode();
9974 
9975   if (Opcode == AMDGPU::G_FCANONICALIZE)
9976     return true;
9977 
9978   Optional<FPValueAndVReg> FCR;
9979   // Constant splat (can be padded with undef) or scalar constant.
9980   if (mi_match(Reg, MRI, MIPatternMatch::m_GFCstOrSplat(FCR))) {
9981     if (FCR->Value.isSignaling())
9982       return false;
9983     return !FCR->Value.isDenormal() ||
9984            denormalsEnabledForType(MRI.getType(FCR->VReg), MF);
9985   }
9986 
9987   if (MaxDepth == 0)
9988     return false;
9989 
9990   switch (Opcode) {
9991   case AMDGPU::G_FMINNUM_IEEE:
9992   case AMDGPU::G_FMAXNUM_IEEE: {
9993     if (Subtarget->supportsMinMaxDenormModes() ||
9994         denormalsEnabledForType(MRI.getType(Reg), MF))
9995       return true;
9996     for (const MachineOperand &MO : llvm::drop_begin(MI->operands()))
9997       if (!isCanonicalized(MO.getReg(), MF, MaxDepth - 1))
9998         return false;
9999     return true;
10000   }
10001   default:
10002     return denormalsEnabledForType(MRI.getType(Reg), MF) &&
10003            isKnownNeverSNaN(Reg, MRI);
10004   }
10005 
10006   llvm_unreachable("invalid operation");
10007 }
10008 
10009 // Constant fold canonicalize.
10010 SDValue SITargetLowering::getCanonicalConstantFP(
10011   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
10012   // Flush denormals to 0 if not enabled.
10013   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
10014     return DAG.getConstantFP(0.0, SL, VT);
10015 
10016   if (C.isNaN()) {
10017     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
10018     if (C.isSignaling()) {
10019       // Quiet a signaling NaN.
10020       // FIXME: Is this supposed to preserve payload bits?
10021       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
10022     }
10023 
10024     // Make sure it is the canonical NaN bitpattern.
10025     //
10026     // TODO: Can we use -1 as the canonical NaN value since it's an inline
10027     // immediate?
10028     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
10029       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
10030   }
10031 
10032   // Already canonical.
10033   return DAG.getConstantFP(C, SL, VT);
10034 }
10035 
10036 static bool vectorEltWillFoldAway(SDValue Op) {
10037   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
10038 }
10039 
10040 SDValue SITargetLowering::performFCanonicalizeCombine(
10041   SDNode *N,
10042   DAGCombinerInfo &DCI) const {
10043   SelectionDAG &DAG = DCI.DAG;
10044   SDValue N0 = N->getOperand(0);
10045   EVT VT = N->getValueType(0);
10046 
10047   // fcanonicalize undef -> qnan
10048   if (N0.isUndef()) {
10049     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
10050     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
10051   }
10052 
10053   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
10054     EVT VT = N->getValueType(0);
10055     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
10056   }
10057 
10058   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
10059   //                                                   (fcanonicalize k)
10060   //
10061   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
10062 
10063   // TODO: This could be better with wider vectors that will be split to v2f16,
10064   // and to consider uses since there aren't that many packed operations.
10065   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
10066       isTypeLegal(MVT::v2f16)) {
10067     SDLoc SL(N);
10068     SDValue NewElts[2];
10069     SDValue Lo = N0.getOperand(0);
10070     SDValue Hi = N0.getOperand(1);
10071     EVT EltVT = Lo.getValueType();
10072 
10073     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
10074       for (unsigned I = 0; I != 2; ++I) {
10075         SDValue Op = N0.getOperand(I);
10076         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
10077           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
10078                                               CFP->getValueAPF());
10079         } else if (Op.isUndef()) {
10080           // Handled below based on what the other operand is.
10081           NewElts[I] = Op;
10082         } else {
10083           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
10084         }
10085       }
10086 
10087       // If one half is undef, and one is constant, prefer a splat vector rather
10088       // than the normal qNaN. If it's a register, prefer 0.0 since that's
10089       // cheaper to use and may be free with a packed operation.
10090       if (NewElts[0].isUndef()) {
10091         if (isa<ConstantFPSDNode>(NewElts[1]))
10092           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
10093             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
10094       }
10095 
10096       if (NewElts[1].isUndef()) {
10097         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
10098           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
10099       }
10100 
10101       return DAG.getBuildVector(VT, SL, NewElts);
10102     }
10103   }
10104 
10105   unsigned SrcOpc = N0.getOpcode();
10106 
10107   // If it's free to do so, push canonicalizes further up the source, which may
10108   // find a canonical source.
10109   //
10110   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
10111   // sNaNs.
10112   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
10113     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
10114     if (CRHS && N0.hasOneUse()) {
10115       SDLoc SL(N);
10116       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
10117                                    N0.getOperand(0));
10118       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
10119       DCI.AddToWorklist(Canon0.getNode());
10120 
10121       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
10122     }
10123   }
10124 
10125   return isCanonicalized(DAG, N0) ? N0 : SDValue();
10126 }
10127 
10128 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
10129   switch (Opc) {
10130   case ISD::FMAXNUM:
10131   case ISD::FMAXNUM_IEEE:
10132     return AMDGPUISD::FMAX3;
10133   case ISD::SMAX:
10134     return AMDGPUISD::SMAX3;
10135   case ISD::UMAX:
10136     return AMDGPUISD::UMAX3;
10137   case ISD::FMINNUM:
10138   case ISD::FMINNUM_IEEE:
10139     return AMDGPUISD::FMIN3;
10140   case ISD::SMIN:
10141     return AMDGPUISD::SMIN3;
10142   case ISD::UMIN:
10143     return AMDGPUISD::UMIN3;
10144   default:
10145     llvm_unreachable("Not a min/max opcode");
10146   }
10147 }
10148 
10149 SDValue SITargetLowering::performIntMed3ImmCombine(
10150   SelectionDAG &DAG, const SDLoc &SL,
10151   SDValue Op0, SDValue Op1, bool Signed) const {
10152   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
10153   if (!K1)
10154     return SDValue();
10155 
10156   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
10157   if (!K0)
10158     return SDValue();
10159 
10160   if (Signed) {
10161     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
10162       return SDValue();
10163   } else {
10164     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
10165       return SDValue();
10166   }
10167 
10168   EVT VT = K0->getValueType(0);
10169   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
10170   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
10171     return DAG.getNode(Med3Opc, SL, VT,
10172                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
10173   }
10174 
10175   // If there isn't a 16-bit med3 operation, convert to 32-bit.
10176   if (VT == MVT::i16) {
10177     MVT NVT = MVT::i32;
10178     unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
10179 
10180     SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
10181     SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
10182     SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
10183 
10184     SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
10185     return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
10186   }
10187 
10188   return SDValue();
10189 }
10190 
10191 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
10192   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
10193     return C;
10194 
10195   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
10196     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
10197       return C;
10198   }
10199 
10200   return nullptr;
10201 }
10202 
10203 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
10204                                                   const SDLoc &SL,
10205                                                   SDValue Op0,
10206                                                   SDValue Op1) const {
10207   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
10208   if (!K1)
10209     return SDValue();
10210 
10211   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
10212   if (!K0)
10213     return SDValue();
10214 
10215   // Ordered >= (although NaN inputs should have folded away by now).
10216   if (K0->getValueAPF() > K1->getValueAPF())
10217     return SDValue();
10218 
10219   const MachineFunction &MF = DAG.getMachineFunction();
10220   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10221 
10222   // TODO: Check IEEE bit enabled?
10223   EVT VT = Op0.getValueType();
10224   if (Info->getMode().DX10Clamp) {
10225     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
10226     // hardware fmed3 behavior converting to a min.
10227     // FIXME: Should this be allowing -0.0?
10228     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
10229       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
10230   }
10231 
10232   // med3 for f16 is only available on gfx9+, and not available for v2f16.
10233   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
10234     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
10235     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
10236     // then give the other result, which is different from med3 with a NaN
10237     // input.
10238     SDValue Var = Op0.getOperand(0);
10239     if (!DAG.isKnownNeverSNaN(Var))
10240       return SDValue();
10241 
10242     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10243 
10244     if ((!K0->hasOneUse() ||
10245          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
10246         (!K1->hasOneUse() ||
10247          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
10248       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
10249                          Var, SDValue(K0, 0), SDValue(K1, 0));
10250     }
10251   }
10252 
10253   return SDValue();
10254 }
10255 
10256 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
10257                                                DAGCombinerInfo &DCI) const {
10258   SelectionDAG &DAG = DCI.DAG;
10259 
10260   EVT VT = N->getValueType(0);
10261   unsigned Opc = N->getOpcode();
10262   SDValue Op0 = N->getOperand(0);
10263   SDValue Op1 = N->getOperand(1);
10264 
10265   // Only do this if the inner op has one use since this will just increases
10266   // register pressure for no benefit.
10267 
10268   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
10269       !VT.isVector() &&
10270       (VT == MVT::i32 || VT == MVT::f32 ||
10271        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
10272     // max(max(a, b), c) -> max3(a, b, c)
10273     // min(min(a, b), c) -> min3(a, b, c)
10274     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
10275       SDLoc DL(N);
10276       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10277                          DL,
10278                          N->getValueType(0),
10279                          Op0.getOperand(0),
10280                          Op0.getOperand(1),
10281                          Op1);
10282     }
10283 
10284     // Try commuted.
10285     // max(a, max(b, c)) -> max3(a, b, c)
10286     // min(a, min(b, c)) -> min3(a, b, c)
10287     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
10288       SDLoc DL(N);
10289       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
10290                          DL,
10291                          N->getValueType(0),
10292                          Op0,
10293                          Op1.getOperand(0),
10294                          Op1.getOperand(1));
10295     }
10296   }
10297 
10298   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
10299   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
10300     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
10301       return Med3;
10302   }
10303 
10304   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
10305     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
10306       return Med3;
10307   }
10308 
10309   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
10310   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
10311        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
10312        (Opc == AMDGPUISD::FMIN_LEGACY &&
10313         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
10314       (VT == MVT::f32 || VT == MVT::f64 ||
10315        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
10316        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
10317       Op0.hasOneUse()) {
10318     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
10319       return Res;
10320   }
10321 
10322   return SDValue();
10323 }
10324 
10325 static bool isClampZeroToOne(SDValue A, SDValue B) {
10326   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
10327     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
10328       // FIXME: Should this be allowing -0.0?
10329       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
10330              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
10331     }
10332   }
10333 
10334   return false;
10335 }
10336 
10337 // FIXME: Should only worry about snans for version with chain.
10338 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
10339                                               DAGCombinerInfo &DCI) const {
10340   EVT VT = N->getValueType(0);
10341   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
10342   // NaNs. With a NaN input, the order of the operands may change the result.
10343 
10344   SelectionDAG &DAG = DCI.DAG;
10345   SDLoc SL(N);
10346 
10347   SDValue Src0 = N->getOperand(0);
10348   SDValue Src1 = N->getOperand(1);
10349   SDValue Src2 = N->getOperand(2);
10350 
10351   if (isClampZeroToOne(Src0, Src1)) {
10352     // const_a, const_b, x -> clamp is safe in all cases including signaling
10353     // nans.
10354     // FIXME: Should this be allowing -0.0?
10355     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
10356   }
10357 
10358   const MachineFunction &MF = DAG.getMachineFunction();
10359   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10360 
10361   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
10362   // handling no dx10-clamp?
10363   if (Info->getMode().DX10Clamp) {
10364     // If NaNs is clamped to 0, we are free to reorder the inputs.
10365 
10366     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10367       std::swap(Src0, Src1);
10368 
10369     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
10370       std::swap(Src1, Src2);
10371 
10372     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
10373       std::swap(Src0, Src1);
10374 
10375     if (isClampZeroToOne(Src1, Src2))
10376       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
10377   }
10378 
10379   return SDValue();
10380 }
10381 
10382 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
10383                                                  DAGCombinerInfo &DCI) const {
10384   SDValue Src0 = N->getOperand(0);
10385   SDValue Src1 = N->getOperand(1);
10386   if (Src0.isUndef() && Src1.isUndef())
10387     return DCI.DAG.getUNDEF(N->getValueType(0));
10388   return SDValue();
10389 }
10390 
10391 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
10392 // expanded into a set of cmp/select instructions.
10393 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
10394                                                 unsigned NumElem,
10395                                                 bool IsDivergentIdx) {
10396   if (UseDivergentRegisterIndexing)
10397     return false;
10398 
10399   unsigned VecSize = EltSize * NumElem;
10400 
10401   // Sub-dword vectors of size 2 dword or less have better implementation.
10402   if (VecSize <= 64 && EltSize < 32)
10403     return false;
10404 
10405   // Always expand the rest of sub-dword instructions, otherwise it will be
10406   // lowered via memory.
10407   if (EltSize < 32)
10408     return true;
10409 
10410   // Always do this if var-idx is divergent, otherwise it will become a loop.
10411   if (IsDivergentIdx)
10412     return true;
10413 
10414   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10415   unsigned NumInsts = NumElem /* Number of compares */ +
10416                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10417   return NumInsts <= 16;
10418 }
10419 
10420 static bool shouldExpandVectorDynExt(SDNode *N) {
10421   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10422   if (isa<ConstantSDNode>(Idx))
10423     return false;
10424 
10425   SDValue Vec = N->getOperand(0);
10426   EVT VecVT = Vec.getValueType();
10427   EVT EltVT = VecVT.getVectorElementType();
10428   unsigned EltSize = EltVT.getSizeInBits();
10429   unsigned NumElem = VecVT.getVectorNumElements();
10430 
10431   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
10432                                                     Idx->isDivergent());
10433 }
10434 
10435 SDValue SITargetLowering::performExtractVectorEltCombine(
10436   SDNode *N, DAGCombinerInfo &DCI) const {
10437   SDValue Vec = N->getOperand(0);
10438   SelectionDAG &DAG = DCI.DAG;
10439 
10440   EVT VecVT = Vec.getValueType();
10441   EVT EltVT = VecVT.getVectorElementType();
10442 
10443   if ((Vec.getOpcode() == ISD::FNEG ||
10444        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10445     SDLoc SL(N);
10446     EVT EltVT = N->getValueType(0);
10447     SDValue Idx = N->getOperand(1);
10448     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10449                               Vec.getOperand(0), Idx);
10450     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10451   }
10452 
10453   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10454   //    =>
10455   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10456   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10457   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10458   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10459     SDLoc SL(N);
10460     EVT EltVT = N->getValueType(0);
10461     SDValue Idx = N->getOperand(1);
10462     unsigned Opc = Vec.getOpcode();
10463 
10464     switch(Opc) {
10465     default:
10466       break;
10467       // TODO: Support other binary operations.
10468     case ISD::FADD:
10469     case ISD::FSUB:
10470     case ISD::FMUL:
10471     case ISD::ADD:
10472     case ISD::UMIN:
10473     case ISD::UMAX:
10474     case ISD::SMIN:
10475     case ISD::SMAX:
10476     case ISD::FMAXNUM:
10477     case ISD::FMINNUM:
10478     case ISD::FMAXNUM_IEEE:
10479     case ISD::FMINNUM_IEEE: {
10480       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10481                                  Vec.getOperand(0), Idx);
10482       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10483                                  Vec.getOperand(1), Idx);
10484 
10485       DCI.AddToWorklist(Elt0.getNode());
10486       DCI.AddToWorklist(Elt1.getNode());
10487       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10488     }
10489     }
10490   }
10491 
10492   unsigned VecSize = VecVT.getSizeInBits();
10493   unsigned EltSize = EltVT.getSizeInBits();
10494 
10495   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10496   if (::shouldExpandVectorDynExt(N)) {
10497     SDLoc SL(N);
10498     SDValue Idx = N->getOperand(1);
10499     SDValue V;
10500     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10501       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10502       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10503       if (I == 0)
10504         V = Elt;
10505       else
10506         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10507     }
10508     return V;
10509   }
10510 
10511   if (!DCI.isBeforeLegalize())
10512     return SDValue();
10513 
10514   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10515   // elements. This exposes more load reduction opportunities by replacing
10516   // multiple small extract_vector_elements with a single 32-bit extract.
10517   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10518   if (isa<MemSDNode>(Vec) &&
10519       EltSize <= 16 &&
10520       EltVT.isByteSized() &&
10521       VecSize > 32 &&
10522       VecSize % 32 == 0 &&
10523       Idx) {
10524     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10525 
10526     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10527     unsigned EltIdx = BitIndex / 32;
10528     unsigned LeftoverBitIdx = BitIndex % 32;
10529     SDLoc SL(N);
10530 
10531     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10532     DCI.AddToWorklist(Cast.getNode());
10533 
10534     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10535                               DAG.getConstant(EltIdx, SL, MVT::i32));
10536     DCI.AddToWorklist(Elt.getNode());
10537     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10538                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10539     DCI.AddToWorklist(Srl.getNode());
10540 
10541     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10542     DCI.AddToWorklist(Trunc.getNode());
10543     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10544   }
10545 
10546   return SDValue();
10547 }
10548 
10549 SDValue
10550 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10551                                                 DAGCombinerInfo &DCI) const {
10552   SDValue Vec = N->getOperand(0);
10553   SDValue Idx = N->getOperand(2);
10554   EVT VecVT = Vec.getValueType();
10555   EVT EltVT = VecVT.getVectorElementType();
10556 
10557   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10558   // => BUILD_VECTOR n x select (e, const-idx)
10559   if (!::shouldExpandVectorDynExt(N))
10560     return SDValue();
10561 
10562   SelectionDAG &DAG = DCI.DAG;
10563   SDLoc SL(N);
10564   SDValue Ins = N->getOperand(1);
10565   EVT IdxVT = Idx.getValueType();
10566 
10567   SmallVector<SDValue, 16> Ops;
10568   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10569     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10570     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10571     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10572     Ops.push_back(V);
10573   }
10574 
10575   return DAG.getBuildVector(VecVT, SL, Ops);
10576 }
10577 
10578 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10579                                           const SDNode *N0,
10580                                           const SDNode *N1) const {
10581   EVT VT = N0->getValueType(0);
10582 
10583   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10584   // support denormals ever.
10585   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10586        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10587         getSubtarget()->hasMadF16())) &&
10588        isOperationLegal(ISD::FMAD, VT))
10589     return ISD::FMAD;
10590 
10591   const TargetOptions &Options = DAG.getTarget().Options;
10592   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10593        (N0->getFlags().hasAllowContract() &&
10594         N1->getFlags().hasAllowContract())) &&
10595       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10596     return ISD::FMA;
10597   }
10598 
10599   return 0;
10600 }
10601 
10602 // For a reassociatable opcode perform:
10603 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10604 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10605                                                SelectionDAG &DAG) const {
10606   EVT VT = N->getValueType(0);
10607   if (VT != MVT::i32 && VT != MVT::i64)
10608     return SDValue();
10609 
10610   if (DAG.isBaseWithConstantOffset(SDValue(N, 0)))
10611     return SDValue();
10612 
10613   unsigned Opc = N->getOpcode();
10614   SDValue Op0 = N->getOperand(0);
10615   SDValue Op1 = N->getOperand(1);
10616 
10617   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10618     return SDValue();
10619 
10620   if (Op0->isDivergent())
10621     std::swap(Op0, Op1);
10622 
10623   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10624     return SDValue();
10625 
10626   SDValue Op2 = Op1.getOperand(1);
10627   Op1 = Op1.getOperand(0);
10628   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10629     return SDValue();
10630 
10631   if (Op1->isDivergent())
10632     std::swap(Op1, Op2);
10633 
10634   SDLoc SL(N);
10635   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10636   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10637 }
10638 
10639 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10640                            EVT VT,
10641                            SDValue N0, SDValue N1, SDValue N2,
10642                            bool Signed) {
10643   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10644   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10645   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10646   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10647 }
10648 
10649 SDValue SITargetLowering::performAddCombine(SDNode *N,
10650                                             DAGCombinerInfo &DCI) const {
10651   SelectionDAG &DAG = DCI.DAG;
10652   EVT VT = N->getValueType(0);
10653   SDLoc SL(N);
10654   SDValue LHS = N->getOperand(0);
10655   SDValue RHS = N->getOperand(1);
10656 
10657   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10658       && Subtarget->hasMad64_32() &&
10659       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10660       VT.getScalarSizeInBits() <= 64) {
10661     if (LHS.getOpcode() != ISD::MUL)
10662       std::swap(LHS, RHS);
10663 
10664     SDValue MulLHS = LHS.getOperand(0);
10665     SDValue MulRHS = LHS.getOperand(1);
10666     SDValue AddRHS = RHS;
10667 
10668     // TODO: Maybe restrict if SGPR inputs.
10669     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10670         numBitsUnsigned(MulRHS, DAG) <= 32) {
10671       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10672       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10673       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10674       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10675     }
10676 
10677     if (numBitsSigned(MulLHS, DAG) <= 32 && numBitsSigned(MulRHS, DAG) <= 32) {
10678       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10679       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10680       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10681       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10682     }
10683 
10684     return SDValue();
10685   }
10686 
10687   if (SDValue V = reassociateScalarOps(N, DAG)) {
10688     return V;
10689   }
10690 
10691   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10692     return SDValue();
10693 
10694   // add x, zext (setcc) => addcarry x, 0, setcc
10695   // add x, sext (setcc) => subcarry x, 0, setcc
10696   unsigned Opc = LHS.getOpcode();
10697   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10698       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10699     std::swap(RHS, LHS);
10700 
10701   Opc = RHS.getOpcode();
10702   switch (Opc) {
10703   default: break;
10704   case ISD::ZERO_EXTEND:
10705   case ISD::SIGN_EXTEND:
10706   case ISD::ANY_EXTEND: {
10707     auto Cond = RHS.getOperand(0);
10708     // If this won't be a real VOPC output, we would still need to insert an
10709     // extra instruction anyway.
10710     if (!isBoolSGPR(Cond))
10711       break;
10712     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10713     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10714     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10715     return DAG.getNode(Opc, SL, VTList, Args);
10716   }
10717   case ISD::ADDCARRY: {
10718     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10719     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10720     if (!C || C->getZExtValue() != 0) break;
10721     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10722     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10723   }
10724   }
10725   return SDValue();
10726 }
10727 
10728 SDValue SITargetLowering::performSubCombine(SDNode *N,
10729                                             DAGCombinerInfo &DCI) const {
10730   SelectionDAG &DAG = DCI.DAG;
10731   EVT VT = N->getValueType(0);
10732 
10733   if (VT != MVT::i32)
10734     return SDValue();
10735 
10736   SDLoc SL(N);
10737   SDValue LHS = N->getOperand(0);
10738   SDValue RHS = N->getOperand(1);
10739 
10740   // sub x, zext (setcc) => subcarry x, 0, setcc
10741   // sub x, sext (setcc) => addcarry x, 0, setcc
10742   unsigned Opc = RHS.getOpcode();
10743   switch (Opc) {
10744   default: break;
10745   case ISD::ZERO_EXTEND:
10746   case ISD::SIGN_EXTEND:
10747   case ISD::ANY_EXTEND: {
10748     auto Cond = RHS.getOperand(0);
10749     // If this won't be a real VOPC output, we would still need to insert an
10750     // extra instruction anyway.
10751     if (!isBoolSGPR(Cond))
10752       break;
10753     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10754     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10755     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10756     return DAG.getNode(Opc, SL, VTList, Args);
10757   }
10758   }
10759 
10760   if (LHS.getOpcode() == ISD::SUBCARRY) {
10761     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10762     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10763     if (!C || !C->isZero())
10764       return SDValue();
10765     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10766     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10767   }
10768   return SDValue();
10769 }
10770 
10771 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10772   DAGCombinerInfo &DCI) const {
10773 
10774   if (N->getValueType(0) != MVT::i32)
10775     return SDValue();
10776 
10777   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10778   if (!C || C->getZExtValue() != 0)
10779     return SDValue();
10780 
10781   SelectionDAG &DAG = DCI.DAG;
10782   SDValue LHS = N->getOperand(0);
10783 
10784   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10785   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10786   unsigned LHSOpc = LHS.getOpcode();
10787   unsigned Opc = N->getOpcode();
10788   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10789       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10790     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10791     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10792   }
10793   return SDValue();
10794 }
10795 
10796 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10797                                              DAGCombinerInfo &DCI) const {
10798   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10799     return SDValue();
10800 
10801   SelectionDAG &DAG = DCI.DAG;
10802   EVT VT = N->getValueType(0);
10803 
10804   SDLoc SL(N);
10805   SDValue LHS = N->getOperand(0);
10806   SDValue RHS = N->getOperand(1);
10807 
10808   // These should really be instruction patterns, but writing patterns with
10809   // source modifiers is a pain.
10810 
10811   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10812   if (LHS.getOpcode() == ISD::FADD) {
10813     SDValue A = LHS.getOperand(0);
10814     if (A == LHS.getOperand(1)) {
10815       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10816       if (FusedOp != 0) {
10817         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10818         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10819       }
10820     }
10821   }
10822 
10823   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10824   if (RHS.getOpcode() == ISD::FADD) {
10825     SDValue A = RHS.getOperand(0);
10826     if (A == RHS.getOperand(1)) {
10827       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10828       if (FusedOp != 0) {
10829         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10830         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10831       }
10832     }
10833   }
10834 
10835   return SDValue();
10836 }
10837 
10838 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10839                                              DAGCombinerInfo &DCI) const {
10840   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10841     return SDValue();
10842 
10843   SelectionDAG &DAG = DCI.DAG;
10844   SDLoc SL(N);
10845   EVT VT = N->getValueType(0);
10846   assert(!VT.isVector());
10847 
10848   // Try to get the fneg to fold into the source modifier. This undoes generic
10849   // DAG combines and folds them into the mad.
10850   //
10851   // Only do this if we are not trying to support denormals. v_mad_f32 does
10852   // not support denormals ever.
10853   SDValue LHS = N->getOperand(0);
10854   SDValue RHS = N->getOperand(1);
10855   if (LHS.getOpcode() == ISD::FADD) {
10856     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10857     SDValue A = LHS.getOperand(0);
10858     if (A == LHS.getOperand(1)) {
10859       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10860       if (FusedOp != 0){
10861         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10862         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10863 
10864         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10865       }
10866     }
10867   }
10868 
10869   if (RHS.getOpcode() == ISD::FADD) {
10870     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10871 
10872     SDValue A = RHS.getOperand(0);
10873     if (A == RHS.getOperand(1)) {
10874       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10875       if (FusedOp != 0){
10876         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10877         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10878       }
10879     }
10880   }
10881 
10882   return SDValue();
10883 }
10884 
10885 SDValue SITargetLowering::performFMACombine(SDNode *N,
10886                                             DAGCombinerInfo &DCI) const {
10887   SelectionDAG &DAG = DCI.DAG;
10888   EVT VT = N->getValueType(0);
10889   SDLoc SL(N);
10890 
10891   if (!Subtarget->hasDot7Insts() || VT != MVT::f32)
10892     return SDValue();
10893 
10894   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10895   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10896   SDValue Op1 = N->getOperand(0);
10897   SDValue Op2 = N->getOperand(1);
10898   SDValue FMA = N->getOperand(2);
10899 
10900   if (FMA.getOpcode() != ISD::FMA ||
10901       Op1.getOpcode() != ISD::FP_EXTEND ||
10902       Op2.getOpcode() != ISD::FP_EXTEND)
10903     return SDValue();
10904 
10905   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10906   // regardless of the denorm mode setting. Therefore,
10907   // unsafe-fp-math/fp-contract is sufficient to allow generating fdot2.
10908   const TargetOptions &Options = DAG.getTarget().Options;
10909   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10910       (N->getFlags().hasAllowContract() &&
10911        FMA->getFlags().hasAllowContract())) {
10912     Op1 = Op1.getOperand(0);
10913     Op2 = Op2.getOperand(0);
10914     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10915         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10916       return SDValue();
10917 
10918     SDValue Vec1 = Op1.getOperand(0);
10919     SDValue Idx1 = Op1.getOperand(1);
10920     SDValue Vec2 = Op2.getOperand(0);
10921 
10922     SDValue FMAOp1 = FMA.getOperand(0);
10923     SDValue FMAOp2 = FMA.getOperand(1);
10924     SDValue FMAAcc = FMA.getOperand(2);
10925 
10926     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10927         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10928       return SDValue();
10929 
10930     FMAOp1 = FMAOp1.getOperand(0);
10931     FMAOp2 = FMAOp2.getOperand(0);
10932     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10933         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10934       return SDValue();
10935 
10936     SDValue Vec3 = FMAOp1.getOperand(0);
10937     SDValue Vec4 = FMAOp2.getOperand(0);
10938     SDValue Idx2 = FMAOp1.getOperand(1);
10939 
10940     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10941         // Idx1 and Idx2 cannot be the same.
10942         Idx1 == Idx2)
10943       return SDValue();
10944 
10945     if (Vec1 == Vec2 || Vec3 == Vec4)
10946       return SDValue();
10947 
10948     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10949       return SDValue();
10950 
10951     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10952         (Vec1 == Vec4 && Vec2 == Vec3)) {
10953       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10954                          DAG.getTargetConstant(0, SL, MVT::i1));
10955     }
10956   }
10957   return SDValue();
10958 }
10959 
10960 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10961                                               DAGCombinerInfo &DCI) const {
10962   SelectionDAG &DAG = DCI.DAG;
10963   SDLoc SL(N);
10964 
10965   SDValue LHS = N->getOperand(0);
10966   SDValue RHS = N->getOperand(1);
10967   EVT VT = LHS.getValueType();
10968   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10969 
10970   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10971   if (!CRHS) {
10972     CRHS = dyn_cast<ConstantSDNode>(LHS);
10973     if (CRHS) {
10974       std::swap(LHS, RHS);
10975       CC = getSetCCSwappedOperands(CC);
10976     }
10977   }
10978 
10979   if (CRHS) {
10980     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10981         isBoolSGPR(LHS.getOperand(0))) {
10982       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10983       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10984       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10985       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10986       if ((CRHS->isAllOnes() &&
10987            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10988           (CRHS->isZero() &&
10989            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10990         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10991                            DAG.getConstant(-1, SL, MVT::i1));
10992       if ((CRHS->isAllOnes() &&
10993            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10994           (CRHS->isZero() &&
10995            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10996         return LHS.getOperand(0);
10997     }
10998 
10999     const APInt &CRHSVal = CRHS->getAPIntValue();
11000     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
11001         LHS.getOpcode() == ISD::SELECT &&
11002         isa<ConstantSDNode>(LHS.getOperand(1)) &&
11003         isa<ConstantSDNode>(LHS.getOperand(2)) &&
11004         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
11005         isBoolSGPR(LHS.getOperand(0))) {
11006       // Given CT != FT:
11007       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
11008       // setcc (select cc, CT, CF), CF, ne => cc
11009       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
11010       // setcc (select cc, CT, CF), CT, eq => cc
11011       const APInt &CT = LHS.getConstantOperandAPInt(1);
11012       const APInt &CF = LHS.getConstantOperandAPInt(2);
11013 
11014       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
11015           (CT == CRHSVal && CC == ISD::SETNE))
11016         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
11017                            DAG.getConstant(-1, SL, MVT::i1));
11018       if ((CF == CRHSVal && CC == ISD::SETNE) ||
11019           (CT == CRHSVal && CC == ISD::SETEQ))
11020         return LHS.getOperand(0);
11021     }
11022   }
11023 
11024   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
11025                                            VT != MVT::f16))
11026     return SDValue();
11027 
11028   // Match isinf/isfinite pattern
11029   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
11030   // (fcmp one (fabs x), inf) -> (fp_class x,
11031   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
11032   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
11033     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
11034     if (!CRHS)
11035       return SDValue();
11036 
11037     const APFloat &APF = CRHS->getValueAPF();
11038     if (APF.isInfinity() && !APF.isNegative()) {
11039       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
11040                                  SIInstrFlags::N_INFINITY;
11041       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
11042                                     SIInstrFlags::P_ZERO |
11043                                     SIInstrFlags::N_NORMAL |
11044                                     SIInstrFlags::P_NORMAL |
11045                                     SIInstrFlags::N_SUBNORMAL |
11046                                     SIInstrFlags::P_SUBNORMAL;
11047       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
11048       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
11049                          DAG.getConstant(Mask, SL, MVT::i32));
11050     }
11051   }
11052 
11053   return SDValue();
11054 }
11055 
11056 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
11057                                                      DAGCombinerInfo &DCI) const {
11058   SelectionDAG &DAG = DCI.DAG;
11059   SDLoc SL(N);
11060   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
11061 
11062   SDValue Src = N->getOperand(0);
11063   SDValue Shift = N->getOperand(0);
11064 
11065   // TODO: Extend type shouldn't matter (assuming legal types).
11066   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
11067     Shift = Shift.getOperand(0);
11068 
11069   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
11070     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
11071     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
11072     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
11073     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
11074     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
11075     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
11076       SDValue Shifted = DAG.getZExtOrTrunc(Shift.getOperand(0),
11077                                  SDLoc(Shift.getOperand(0)), MVT::i32);
11078 
11079       unsigned ShiftOffset = 8 * Offset;
11080       if (Shift.getOpcode() == ISD::SHL)
11081         ShiftOffset -= C->getZExtValue();
11082       else
11083         ShiftOffset += C->getZExtValue();
11084 
11085       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
11086         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
11087                            MVT::f32, Shifted);
11088       }
11089     }
11090   }
11091 
11092   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11093   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
11094   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
11095     // We simplified Src. If this node is not dead, visit it again so it is
11096     // folded properly.
11097     if (N->getOpcode() != ISD::DELETED_NODE)
11098       DCI.AddToWorklist(N);
11099     return SDValue(N, 0);
11100   }
11101 
11102   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
11103   if (SDValue DemandedSrc =
11104           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
11105     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
11106 
11107   return SDValue();
11108 }
11109 
11110 SDValue SITargetLowering::performClampCombine(SDNode *N,
11111                                               DAGCombinerInfo &DCI) const {
11112   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
11113   if (!CSrc)
11114     return SDValue();
11115 
11116   const MachineFunction &MF = DCI.DAG.getMachineFunction();
11117   const APFloat &F = CSrc->getValueAPF();
11118   APFloat Zero = APFloat::getZero(F.getSemantics());
11119   if (F < Zero ||
11120       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
11121     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
11122   }
11123 
11124   APFloat One(F.getSemantics(), "1.0");
11125   if (F > One)
11126     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
11127 
11128   return SDValue(CSrc, 0);
11129 }
11130 
11131 
11132 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
11133                                             DAGCombinerInfo &DCI) const {
11134   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
11135     return SDValue();
11136   switch (N->getOpcode()) {
11137   case ISD::ADD:
11138     return performAddCombine(N, DCI);
11139   case ISD::SUB:
11140     return performSubCombine(N, DCI);
11141   case ISD::ADDCARRY:
11142   case ISD::SUBCARRY:
11143     return performAddCarrySubCarryCombine(N, DCI);
11144   case ISD::FADD:
11145     return performFAddCombine(N, DCI);
11146   case ISD::FSUB:
11147     return performFSubCombine(N, DCI);
11148   case ISD::SETCC:
11149     return performSetCCCombine(N, DCI);
11150   case ISD::FMAXNUM:
11151   case ISD::FMINNUM:
11152   case ISD::FMAXNUM_IEEE:
11153   case ISD::FMINNUM_IEEE:
11154   case ISD::SMAX:
11155   case ISD::SMIN:
11156   case ISD::UMAX:
11157   case ISD::UMIN:
11158   case AMDGPUISD::FMIN_LEGACY:
11159   case AMDGPUISD::FMAX_LEGACY:
11160     return performMinMaxCombine(N, DCI);
11161   case ISD::FMA:
11162     return performFMACombine(N, DCI);
11163   case ISD::AND:
11164     return performAndCombine(N, DCI);
11165   case ISD::OR:
11166     return performOrCombine(N, DCI);
11167   case ISD::XOR:
11168     return performXorCombine(N, DCI);
11169   case ISD::ZERO_EXTEND:
11170     return performZeroExtendCombine(N, DCI);
11171   case ISD::SIGN_EXTEND_INREG:
11172     return performSignExtendInRegCombine(N , DCI);
11173   case AMDGPUISD::FP_CLASS:
11174     return performClassCombine(N, DCI);
11175   case ISD::FCANONICALIZE:
11176     return performFCanonicalizeCombine(N, DCI);
11177   case AMDGPUISD::RCP:
11178     return performRcpCombine(N, DCI);
11179   case AMDGPUISD::FRACT:
11180   case AMDGPUISD::RSQ:
11181   case AMDGPUISD::RCP_LEGACY:
11182   case AMDGPUISD::RCP_IFLAG:
11183   case AMDGPUISD::RSQ_CLAMP:
11184   case AMDGPUISD::LDEXP: {
11185     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
11186     SDValue Src = N->getOperand(0);
11187     if (Src.isUndef())
11188       return Src;
11189     break;
11190   }
11191   case ISD::SINT_TO_FP:
11192   case ISD::UINT_TO_FP:
11193     return performUCharToFloatCombine(N, DCI);
11194   case AMDGPUISD::CVT_F32_UBYTE0:
11195   case AMDGPUISD::CVT_F32_UBYTE1:
11196   case AMDGPUISD::CVT_F32_UBYTE2:
11197   case AMDGPUISD::CVT_F32_UBYTE3:
11198     return performCvtF32UByteNCombine(N, DCI);
11199   case AMDGPUISD::FMED3:
11200     return performFMed3Combine(N, DCI);
11201   case AMDGPUISD::CVT_PKRTZ_F16_F32:
11202     return performCvtPkRTZCombine(N, DCI);
11203   case AMDGPUISD::CLAMP:
11204     return performClampCombine(N, DCI);
11205   case ISD::SCALAR_TO_VECTOR: {
11206     SelectionDAG &DAG = DCI.DAG;
11207     EVT VT = N->getValueType(0);
11208 
11209     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
11210     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
11211       SDLoc SL(N);
11212       SDValue Src = N->getOperand(0);
11213       EVT EltVT = Src.getValueType();
11214       if (EltVT == MVT::f16)
11215         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
11216 
11217       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
11218       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
11219     }
11220 
11221     break;
11222   }
11223   case ISD::EXTRACT_VECTOR_ELT:
11224     return performExtractVectorEltCombine(N, DCI);
11225   case ISD::INSERT_VECTOR_ELT:
11226     return performInsertVectorEltCombine(N, DCI);
11227   case ISD::LOAD: {
11228     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
11229       return Widended;
11230     LLVM_FALLTHROUGH;
11231   }
11232   default: {
11233     if (!DCI.isBeforeLegalize()) {
11234       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
11235         return performMemSDNodeCombine(MemNode, DCI);
11236     }
11237 
11238     break;
11239   }
11240   }
11241 
11242   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
11243 }
11244 
11245 /// Helper function for adjustWritemask
11246 static unsigned SubIdx2Lane(unsigned Idx) {
11247   switch (Idx) {
11248   default: return ~0u;
11249   case AMDGPU::sub0: return 0;
11250   case AMDGPU::sub1: return 1;
11251   case AMDGPU::sub2: return 2;
11252   case AMDGPU::sub3: return 3;
11253   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
11254   }
11255 }
11256 
11257 /// Adjust the writemask of MIMG instructions
11258 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
11259                                           SelectionDAG &DAG) const {
11260   unsigned Opcode = Node->getMachineOpcode();
11261 
11262   // Subtract 1 because the vdata output is not a MachineSDNode operand.
11263   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
11264   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
11265     return Node; // not implemented for D16
11266 
11267   SDNode *Users[5] = { nullptr };
11268   unsigned Lane = 0;
11269   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
11270   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
11271   unsigned NewDmask = 0;
11272   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
11273   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
11274   bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) ||
11275                   Node->getConstantOperandVal(LWEIdx))
11276                      ? true
11277                      : false;
11278   unsigned TFCLane = 0;
11279   bool HasChain = Node->getNumValues() > 1;
11280 
11281   if (OldDmask == 0) {
11282     // These are folded out, but on the chance it happens don't assert.
11283     return Node;
11284   }
11285 
11286   unsigned OldBitsSet = countPopulation(OldDmask);
11287   // Work out which is the TFE/LWE lane if that is enabled.
11288   if (UsesTFC) {
11289     TFCLane = OldBitsSet;
11290   }
11291 
11292   // Try to figure out the used register components
11293   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
11294        I != E; ++I) {
11295 
11296     // Don't look at users of the chain.
11297     if (I.getUse().getResNo() != 0)
11298       continue;
11299 
11300     // Abort if we can't understand the usage
11301     if (!I->isMachineOpcode() ||
11302         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
11303       return Node;
11304 
11305     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
11306     // Note that subregs are packed, i.e. Lane==0 is the first bit set
11307     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
11308     // set, etc.
11309     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
11310     if (Lane == ~0u)
11311       return Node;
11312 
11313     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
11314     if (UsesTFC && Lane == TFCLane) {
11315       Users[Lane] = *I;
11316     } else {
11317       // Set which texture component corresponds to the lane.
11318       unsigned Comp;
11319       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
11320         Comp = countTrailingZeros(Dmask);
11321         Dmask &= ~(1 << Comp);
11322       }
11323 
11324       // Abort if we have more than one user per component.
11325       if (Users[Lane])
11326         return Node;
11327 
11328       Users[Lane] = *I;
11329       NewDmask |= 1 << Comp;
11330     }
11331   }
11332 
11333   // Don't allow 0 dmask, as hardware assumes one channel enabled.
11334   bool NoChannels = !NewDmask;
11335   if (NoChannels) {
11336     if (!UsesTFC) {
11337       // No uses of the result and not using TFC. Then do nothing.
11338       return Node;
11339     }
11340     // If the original dmask has one channel - then nothing to do
11341     if (OldBitsSet == 1)
11342       return Node;
11343     // Use an arbitrary dmask - required for the instruction to work
11344     NewDmask = 1;
11345   }
11346   // Abort if there's no change
11347   if (NewDmask == OldDmask)
11348     return Node;
11349 
11350   unsigned BitsSet = countPopulation(NewDmask);
11351 
11352   // Check for TFE or LWE - increase the number of channels by one to account
11353   // for the extra return value
11354   // This will need adjustment for D16 if this is also included in
11355   // adjustWriteMask (this function) but at present D16 are excluded.
11356   unsigned NewChannels = BitsSet + UsesTFC;
11357 
11358   int NewOpcode =
11359       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
11360   assert(NewOpcode != -1 &&
11361          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
11362          "failed to find equivalent MIMG op");
11363 
11364   // Adjust the writemask in the node
11365   SmallVector<SDValue, 12> Ops;
11366   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
11367   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
11368   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
11369 
11370   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
11371 
11372   MVT ResultVT = NewChannels == 1 ?
11373     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
11374                            NewChannels == 5 ? 8 : NewChannels);
11375   SDVTList NewVTList = HasChain ?
11376     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
11377 
11378 
11379   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
11380                                               NewVTList, Ops);
11381 
11382   if (HasChain) {
11383     // Update chain.
11384     DAG.setNodeMemRefs(NewNode, Node->memoperands());
11385     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
11386   }
11387 
11388   if (NewChannels == 1) {
11389     assert(Node->hasNUsesOfValue(1, 0));
11390     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
11391                                       SDLoc(Node), Users[Lane]->getValueType(0),
11392                                       SDValue(NewNode, 0));
11393     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
11394     return nullptr;
11395   }
11396 
11397   // Update the users of the node with the new indices
11398   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
11399     SDNode *User = Users[i];
11400     if (!User) {
11401       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
11402       // Users[0] is still nullptr because channel 0 doesn't really have a use.
11403       if (i || !NoChannels)
11404         continue;
11405     } else {
11406       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
11407       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
11408     }
11409 
11410     switch (Idx) {
11411     default: break;
11412     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11413     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11414     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11415     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11416     }
11417   }
11418 
11419   DAG.RemoveDeadNode(Node);
11420   return nullptr;
11421 }
11422 
11423 static bool isFrameIndexOp(SDValue Op) {
11424   if (Op.getOpcode() == ISD::AssertZext)
11425     Op = Op.getOperand(0);
11426 
11427   return isa<FrameIndexSDNode>(Op);
11428 }
11429 
11430 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11431 /// with frame index operands.
11432 /// LLVM assumes that inputs are to these instructions are registers.
11433 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11434                                                         SelectionDAG &DAG) const {
11435   if (Node->getOpcode() == ISD::CopyToReg) {
11436     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11437     SDValue SrcVal = Node->getOperand(2);
11438 
11439     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11440     // to try understanding copies to physical registers.
11441     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11442       SDLoc SL(Node);
11443       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11444       SDValue VReg = DAG.getRegister(
11445         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11446 
11447       SDNode *Glued = Node->getGluedNode();
11448       SDValue ToVReg
11449         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11450                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11451       SDValue ToResultReg
11452         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11453                            VReg, ToVReg.getValue(1));
11454       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11455       DAG.RemoveDeadNode(Node);
11456       return ToResultReg.getNode();
11457     }
11458   }
11459 
11460   SmallVector<SDValue, 8> Ops;
11461   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11462     if (!isFrameIndexOp(Node->getOperand(i))) {
11463       Ops.push_back(Node->getOperand(i));
11464       continue;
11465     }
11466 
11467     SDLoc DL(Node);
11468     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11469                                      Node->getOperand(i).getValueType(),
11470                                      Node->getOperand(i)), 0));
11471   }
11472 
11473   return DAG.UpdateNodeOperands(Node, Ops);
11474 }
11475 
11476 /// Fold the instructions after selecting them.
11477 /// Returns null if users were already updated.
11478 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11479                                           SelectionDAG &DAG) const {
11480   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11481   unsigned Opcode = Node->getMachineOpcode();
11482 
11483   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11484       !TII->isGather4(Opcode) &&
11485       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11486     return adjustWritemask(Node, DAG);
11487   }
11488 
11489   if (Opcode == AMDGPU::INSERT_SUBREG ||
11490       Opcode == AMDGPU::REG_SEQUENCE) {
11491     legalizeTargetIndependentNode(Node, DAG);
11492     return Node;
11493   }
11494 
11495   switch (Opcode) {
11496   case AMDGPU::V_DIV_SCALE_F32_e64:
11497   case AMDGPU::V_DIV_SCALE_F64_e64: {
11498     // Satisfy the operand register constraint when one of the inputs is
11499     // undefined. Ordinarily each undef value will have its own implicit_def of
11500     // a vreg, so force these to use a single register.
11501     SDValue Src0 = Node->getOperand(1);
11502     SDValue Src1 = Node->getOperand(3);
11503     SDValue Src2 = Node->getOperand(5);
11504 
11505     if ((Src0.isMachineOpcode() &&
11506          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11507         (Src0 == Src1 || Src0 == Src2))
11508       break;
11509 
11510     MVT VT = Src0.getValueType().getSimpleVT();
11511     const TargetRegisterClass *RC =
11512         getRegClassFor(VT, Src0.getNode()->isDivergent());
11513 
11514     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11515     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11516 
11517     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11518                                       UndefReg, Src0, SDValue());
11519 
11520     // src0 must be the same register as src1 or src2, even if the value is
11521     // undefined, so make sure we don't violate this constraint.
11522     if (Src0.isMachineOpcode() &&
11523         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11524       if (Src1.isMachineOpcode() &&
11525           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11526         Src0 = Src1;
11527       else if (Src2.isMachineOpcode() &&
11528                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11529         Src0 = Src2;
11530       else {
11531         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11532         Src0 = UndefReg;
11533         Src1 = UndefReg;
11534       }
11535     } else
11536       break;
11537 
11538     SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end());
11539     Ops[1] = Src0;
11540     Ops[3] = Src1;
11541     Ops[5] = Src2;
11542     Ops.push_back(ImpDef.getValue(1));
11543     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11544   }
11545   default:
11546     break;
11547   }
11548 
11549   return Node;
11550 }
11551 
11552 // Any MIMG instructions that use tfe or lwe require an initialization of the
11553 // result register that will be written in the case of a memory access failure.
11554 // The required code is also added to tie this init code to the result of the
11555 // img instruction.
11556 void SITargetLowering::AddIMGInit(MachineInstr &MI) const {
11557   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11558   const SIRegisterInfo &TRI = TII->getRegisterInfo();
11559   MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
11560   MachineBasicBlock &MBB = *MI.getParent();
11561 
11562   MachineOperand *TFE = TII->getNamedOperand(MI, AMDGPU::OpName::tfe);
11563   MachineOperand *LWE = TII->getNamedOperand(MI, AMDGPU::OpName::lwe);
11564   MachineOperand *D16 = TII->getNamedOperand(MI, AMDGPU::OpName::d16);
11565 
11566   if (!TFE && !LWE) // intersect_ray
11567     return;
11568 
11569   unsigned TFEVal = TFE ? TFE->getImm() : 0;
11570   unsigned LWEVal = LWE->getImm();
11571   unsigned D16Val = D16 ? D16->getImm() : 0;
11572 
11573   if (!TFEVal && !LWEVal)
11574     return;
11575 
11576   // At least one of TFE or LWE are non-zero
11577   // We have to insert a suitable initialization of the result value and
11578   // tie this to the dest of the image instruction.
11579 
11580   const DebugLoc &DL = MI.getDebugLoc();
11581 
11582   int DstIdx =
11583       AMDGPU::getNamedOperandIdx(MI.getOpcode(), AMDGPU::OpName::vdata);
11584 
11585   // Calculate which dword we have to initialize to 0.
11586   MachineOperand *MO_Dmask = TII->getNamedOperand(MI, AMDGPU::OpName::dmask);
11587 
11588   // check that dmask operand is found.
11589   assert(MO_Dmask && "Expected dmask operand in instruction");
11590 
11591   unsigned dmask = MO_Dmask->getImm();
11592   // Determine the number of active lanes taking into account the
11593   // Gather4 special case
11594   unsigned ActiveLanes = TII->isGather4(MI) ? 4 : countPopulation(dmask);
11595 
11596   bool Packed = !Subtarget->hasUnpackedD16VMem();
11597 
11598   unsigned InitIdx =
11599       D16Val && Packed ? ((ActiveLanes + 1) >> 1) + 1 : ActiveLanes + 1;
11600 
11601   // Abandon attempt if the dst size isn't large enough
11602   // - this is in fact an error but this is picked up elsewhere and
11603   // reported correctly.
11604   uint32_t DstSize = TRI.getRegSizeInBits(*TII->getOpRegClass(MI, DstIdx)) / 32;
11605   if (DstSize < InitIdx)
11606     return;
11607 
11608   // Create a register for the initialization value.
11609   Register PrevDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11610   unsigned NewDst = 0; // Final initialized value will be in here
11611 
11612   // If PRTStrictNull feature is enabled (the default) then initialize
11613   // all the result registers to 0, otherwise just the error indication
11614   // register (VGPRn+1)
11615   unsigned SizeLeft = Subtarget->usePRTStrictNull() ? InitIdx : 1;
11616   unsigned CurrIdx = Subtarget->usePRTStrictNull() ? 0 : (InitIdx - 1);
11617 
11618   BuildMI(MBB, MI, DL, TII->get(AMDGPU::IMPLICIT_DEF), PrevDst);
11619   for (; SizeLeft; SizeLeft--, CurrIdx++) {
11620     NewDst = MRI.createVirtualRegister(TII->getOpRegClass(MI, DstIdx));
11621     // Initialize dword
11622     Register SubReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
11623     BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), SubReg)
11624       .addImm(0);
11625     // Insert into the super-reg
11626     BuildMI(MBB, MI, DL, TII->get(TargetOpcode::INSERT_SUBREG), NewDst)
11627       .addReg(PrevDst)
11628       .addReg(SubReg)
11629       .addImm(SIRegisterInfo::getSubRegFromChannel(CurrIdx));
11630 
11631     PrevDst = NewDst;
11632   }
11633 
11634   // Add as an implicit operand
11635   MI.addOperand(MachineOperand::CreateReg(NewDst, false, true));
11636 
11637   // Tie the just added implicit operand to the dst
11638   MI.tieOperands(DstIdx, MI.getNumOperands() - 1);
11639 }
11640 
11641 /// Assign the register class depending on the number of
11642 /// bits set in the writemask
11643 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11644                                                      SDNode *Node) const {
11645   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11646 
11647   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11648 
11649   if (TII->isVOP3(MI.getOpcode())) {
11650     // Make sure constant bus requirements are respected.
11651     TII->legalizeOperandsVOP3(MRI, MI);
11652 
11653     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11654     // This saves a chain-copy of registers and better balance register
11655     // use between vgpr and agpr as agpr tuples tend to be big.
11656     if (MI.getDesc().OpInfo) {
11657       unsigned Opc = MI.getOpcode();
11658       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11659       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11660                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11661         if (I == -1)
11662           break;
11663         MachineOperand &Op = MI.getOperand(I);
11664         if (!Op.isReg() || !Op.getReg().isVirtual())
11665           continue;
11666         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11667         if (!TRI->hasAGPRs(RC))
11668           continue;
11669         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11670         if (!Src || !Src->isCopy() ||
11671             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11672           continue;
11673         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11674         // All uses of agpr64 and agpr32 can also accept vgpr except for
11675         // v_accvgpr_read, but we do not produce agpr reads during selection,
11676         // so no use checks are needed.
11677         MRI.setRegClass(Op.getReg(), NewRC);
11678       }
11679 
11680       // Resolve the rest of AV operands to AGPRs.
11681       if (auto *Src2 = TII->getNamedOperand(MI, AMDGPU::OpName::src2)) {
11682         if (Src2->isReg() && Src2->getReg().isVirtual()) {
11683           auto *RC = TRI->getRegClassForReg(MRI, Src2->getReg());
11684           if (TRI->isVectorSuperClass(RC)) {
11685             auto *NewRC = TRI->getEquivalentAGPRClass(RC);
11686             MRI.setRegClass(Src2->getReg(), NewRC);
11687             if (Src2->isTied())
11688               MRI.setRegClass(MI.getOperand(0).getReg(), NewRC);
11689           }
11690         }
11691       }
11692     }
11693 
11694     return;
11695   }
11696 
11697   // Replace unused atomics with the no return version.
11698   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11699   if (NoRetAtomicOp != -1) {
11700     if (!Node->hasAnyUseOfValue(0)) {
11701       int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
11702                                                AMDGPU::OpName::cpol);
11703       if (CPolIdx != -1) {
11704         MachineOperand &CPol = MI.getOperand(CPolIdx);
11705         CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC);
11706       }
11707       MI.removeOperand(0);
11708       MI.setDesc(TII->get(NoRetAtomicOp));
11709       return;
11710     }
11711 
11712     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11713     // instruction, because the return type of these instructions is a vec2 of
11714     // the memory type, so it can be tied to the input operand.
11715     // This means these instructions always have a use, so we need to add a
11716     // special case to check if the atomic has only one extract_subreg use,
11717     // which itself has no uses.
11718     if ((Node->hasNUsesOfValue(1, 0) &&
11719          Node->use_begin()->isMachineOpcode() &&
11720          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11721          !Node->use_begin()->hasAnyUseOfValue(0))) {
11722       Register Def = MI.getOperand(0).getReg();
11723 
11724       // Change this into a noret atomic.
11725       MI.setDesc(TII->get(NoRetAtomicOp));
11726       MI.removeOperand(0);
11727 
11728       // If we only remove the def operand from the atomic instruction, the
11729       // extract_subreg will be left with a use of a vreg without a def.
11730       // So we need to insert an implicit_def to avoid machine verifier
11731       // errors.
11732       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11733               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11734     }
11735     return;
11736   }
11737 
11738   if (TII->isMIMG(MI) && !MI.mayStore())
11739     AddIMGInit(MI);
11740 }
11741 
11742 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11743                               uint64_t Val) {
11744   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11745   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11746 }
11747 
11748 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11749                                                 const SDLoc &DL,
11750                                                 SDValue Ptr) const {
11751   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11752 
11753   // Build the half of the subregister with the constants before building the
11754   // full 128-bit register. If we are building multiple resource descriptors,
11755   // this will allow CSEing of the 2-component register.
11756   const SDValue Ops0[] = {
11757     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11758     buildSMovImm32(DAG, DL, 0),
11759     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11760     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11761     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11762   };
11763 
11764   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11765                                                 MVT::v2i32, Ops0), 0);
11766 
11767   // Combine the constants and the pointer.
11768   const SDValue Ops1[] = {
11769     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11770     Ptr,
11771     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11772     SubRegHi,
11773     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11774   };
11775 
11776   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11777 }
11778 
11779 /// Return a resource descriptor with the 'Add TID' bit enabled
11780 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11781 ///        of the resource descriptor) to create an offset, which is added to
11782 ///        the resource pointer.
11783 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11784                                            SDValue Ptr, uint32_t RsrcDword1,
11785                                            uint64_t RsrcDword2And3) const {
11786   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11787   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11788   if (RsrcDword1) {
11789     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11790                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11791                     0);
11792   }
11793 
11794   SDValue DataLo = buildSMovImm32(DAG, DL,
11795                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11796   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11797 
11798   const SDValue Ops[] = {
11799     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11800     PtrLo,
11801     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11802     PtrHi,
11803     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11804     DataLo,
11805     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11806     DataHi,
11807     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11808   };
11809 
11810   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11811 }
11812 
11813 //===----------------------------------------------------------------------===//
11814 //                         SI Inline Assembly Support
11815 //===----------------------------------------------------------------------===//
11816 
11817 std::pair<unsigned, const TargetRegisterClass *>
11818 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_,
11819                                                StringRef Constraint,
11820                                                MVT VT) const {
11821   const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_);
11822 
11823   const TargetRegisterClass *RC = nullptr;
11824   if (Constraint.size() == 1) {
11825     const unsigned BitWidth = VT.getSizeInBits();
11826     switch (Constraint[0]) {
11827     default:
11828       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11829     case 's':
11830     case 'r':
11831       switch (BitWidth) {
11832       case 16:
11833         RC = &AMDGPU::SReg_32RegClass;
11834         break;
11835       case 64:
11836         RC = &AMDGPU::SGPR_64RegClass;
11837         break;
11838       default:
11839         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11840         if (!RC)
11841           return std::make_pair(0U, nullptr);
11842         break;
11843       }
11844       break;
11845     case 'v':
11846       switch (BitWidth) {
11847       case 16:
11848         RC = &AMDGPU::VGPR_32RegClass;
11849         break;
11850       default:
11851         RC = TRI->getVGPRClassForBitWidth(BitWidth);
11852         if (!RC)
11853           return std::make_pair(0U, nullptr);
11854         break;
11855       }
11856       break;
11857     case 'a':
11858       if (!Subtarget->hasMAIInsts())
11859         break;
11860       switch (BitWidth) {
11861       case 16:
11862         RC = &AMDGPU::AGPR_32RegClass;
11863         break;
11864       default:
11865         RC = TRI->getAGPRClassForBitWidth(BitWidth);
11866         if (!RC)
11867           return std::make_pair(0U, nullptr);
11868         break;
11869       }
11870       break;
11871     }
11872     // We actually support i128, i16 and f16 as inline parameters
11873     // even if they are not reported as legal
11874     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11875                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11876       return std::make_pair(0U, RC);
11877   }
11878 
11879   if (Constraint.startswith("{") && Constraint.endswith("}")) {
11880     StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
11881     if (RegName.consume_front("v")) {
11882       RC = &AMDGPU::VGPR_32RegClass;
11883     } else if (RegName.consume_front("s")) {
11884       RC = &AMDGPU::SGPR_32RegClass;
11885     } else if (RegName.consume_front("a")) {
11886       RC = &AMDGPU::AGPR_32RegClass;
11887     }
11888 
11889     if (RC) {
11890       uint32_t Idx;
11891       if (RegName.consume_front("[")) {
11892         uint32_t End;
11893         bool Failed = RegName.consumeInteger(10, Idx);
11894         Failed |= !RegName.consume_front(":");
11895         Failed |= RegName.consumeInteger(10, End);
11896         Failed |= !RegName.consume_back("]");
11897         if (!Failed) {
11898           uint32_t Width = (End - Idx + 1) * 32;
11899           MCRegister Reg = RC->getRegister(Idx);
11900           if (SIRegisterInfo::isVGPRClass(RC))
11901             RC = TRI->getVGPRClassForBitWidth(Width);
11902           else if (SIRegisterInfo::isSGPRClass(RC))
11903             RC = TRI->getSGPRClassForBitWidth(Width);
11904           else if (SIRegisterInfo::isAGPRClass(RC))
11905             RC = TRI->getAGPRClassForBitWidth(Width);
11906           if (RC) {
11907             Reg = TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, RC);
11908             return std::make_pair(Reg, RC);
11909           }
11910         }
11911       } else {
11912         bool Failed = RegName.getAsInteger(10, Idx);
11913         if (!Failed && Idx < RC->getNumRegs())
11914           return std::make_pair(RC->getRegister(Idx), RC);
11915       }
11916     }
11917   }
11918 
11919   auto Ret = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11920   if (Ret.first)
11921     Ret.second = TRI->getPhysRegClass(Ret.first);
11922 
11923   return Ret;
11924 }
11925 
11926 static bool isImmConstraint(StringRef Constraint) {
11927   if (Constraint.size() == 1) {
11928     switch (Constraint[0]) {
11929     default: break;
11930     case 'I':
11931     case 'J':
11932     case 'A':
11933     case 'B':
11934     case 'C':
11935       return true;
11936     }
11937   } else if (Constraint == "DA" ||
11938              Constraint == "DB") {
11939     return true;
11940   }
11941   return false;
11942 }
11943 
11944 SITargetLowering::ConstraintType
11945 SITargetLowering::getConstraintType(StringRef Constraint) const {
11946   if (Constraint.size() == 1) {
11947     switch (Constraint[0]) {
11948     default: break;
11949     case 's':
11950     case 'v':
11951     case 'a':
11952       return C_RegisterClass;
11953     }
11954   }
11955   if (isImmConstraint(Constraint)) {
11956     return C_Other;
11957   }
11958   return TargetLowering::getConstraintType(Constraint);
11959 }
11960 
11961 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11962   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11963     Val = Val & maskTrailingOnes<uint64_t>(Size);
11964   }
11965   return Val;
11966 }
11967 
11968 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11969                                                     std::string &Constraint,
11970                                                     std::vector<SDValue> &Ops,
11971                                                     SelectionDAG &DAG) const {
11972   if (isImmConstraint(Constraint)) {
11973     uint64_t Val;
11974     if (getAsmOperandConstVal(Op, Val) &&
11975         checkAsmConstraintVal(Op, Constraint, Val)) {
11976       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11977       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11978     }
11979   } else {
11980     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11981   }
11982 }
11983 
11984 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11985   unsigned Size = Op.getScalarValueSizeInBits();
11986   if (Size > 64)
11987     return false;
11988 
11989   if (Size == 16 && !Subtarget->has16BitInsts())
11990     return false;
11991 
11992   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11993     Val = C->getSExtValue();
11994     return true;
11995   }
11996   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11997     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11998     return true;
11999   }
12000   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
12001     if (Size != 16 || Op.getNumOperands() != 2)
12002       return false;
12003     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
12004       return false;
12005     if (ConstantSDNode *C = V->getConstantSplatNode()) {
12006       Val = C->getSExtValue();
12007       return true;
12008     }
12009     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
12010       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
12011       return true;
12012     }
12013   }
12014 
12015   return false;
12016 }
12017 
12018 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
12019                                              const std::string &Constraint,
12020                                              uint64_t Val) const {
12021   if (Constraint.size() == 1) {
12022     switch (Constraint[0]) {
12023     case 'I':
12024       return AMDGPU::isInlinableIntLiteral(Val);
12025     case 'J':
12026       return isInt<16>(Val);
12027     case 'A':
12028       return checkAsmConstraintValA(Op, Val);
12029     case 'B':
12030       return isInt<32>(Val);
12031     case 'C':
12032       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
12033              AMDGPU::isInlinableIntLiteral(Val);
12034     default:
12035       break;
12036     }
12037   } else if (Constraint.size() == 2) {
12038     if (Constraint == "DA") {
12039       int64_t HiBits = static_cast<int32_t>(Val >> 32);
12040       int64_t LoBits = static_cast<int32_t>(Val);
12041       return checkAsmConstraintValA(Op, HiBits, 32) &&
12042              checkAsmConstraintValA(Op, LoBits, 32);
12043     }
12044     if (Constraint == "DB") {
12045       return true;
12046     }
12047   }
12048   llvm_unreachable("Invalid asm constraint");
12049 }
12050 
12051 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
12052                                               uint64_t Val,
12053                                               unsigned MaxSize) const {
12054   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
12055   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
12056   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
12057       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
12058       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
12059     return true;
12060   }
12061   return false;
12062 }
12063 
12064 static int getAlignedAGPRClassID(unsigned UnalignedClassID) {
12065   switch (UnalignedClassID) {
12066   case AMDGPU::VReg_64RegClassID:
12067     return AMDGPU::VReg_64_Align2RegClassID;
12068   case AMDGPU::VReg_96RegClassID:
12069     return AMDGPU::VReg_96_Align2RegClassID;
12070   case AMDGPU::VReg_128RegClassID:
12071     return AMDGPU::VReg_128_Align2RegClassID;
12072   case AMDGPU::VReg_160RegClassID:
12073     return AMDGPU::VReg_160_Align2RegClassID;
12074   case AMDGPU::VReg_192RegClassID:
12075     return AMDGPU::VReg_192_Align2RegClassID;
12076   case AMDGPU::VReg_224RegClassID:
12077     return AMDGPU::VReg_224_Align2RegClassID;
12078   case AMDGPU::VReg_256RegClassID:
12079     return AMDGPU::VReg_256_Align2RegClassID;
12080   case AMDGPU::VReg_512RegClassID:
12081     return AMDGPU::VReg_512_Align2RegClassID;
12082   case AMDGPU::VReg_1024RegClassID:
12083     return AMDGPU::VReg_1024_Align2RegClassID;
12084   case AMDGPU::AReg_64RegClassID:
12085     return AMDGPU::AReg_64_Align2RegClassID;
12086   case AMDGPU::AReg_96RegClassID:
12087     return AMDGPU::AReg_96_Align2RegClassID;
12088   case AMDGPU::AReg_128RegClassID:
12089     return AMDGPU::AReg_128_Align2RegClassID;
12090   case AMDGPU::AReg_160RegClassID:
12091     return AMDGPU::AReg_160_Align2RegClassID;
12092   case AMDGPU::AReg_192RegClassID:
12093     return AMDGPU::AReg_192_Align2RegClassID;
12094   case AMDGPU::AReg_256RegClassID:
12095     return AMDGPU::AReg_256_Align2RegClassID;
12096   case AMDGPU::AReg_512RegClassID:
12097     return AMDGPU::AReg_512_Align2RegClassID;
12098   case AMDGPU::AReg_1024RegClassID:
12099     return AMDGPU::AReg_1024_Align2RegClassID;
12100   default:
12101     return -1;
12102   }
12103 }
12104 
12105 // Figure out which registers should be reserved for stack access. Only after
12106 // the function is legalized do we know all of the non-spill stack objects or if
12107 // calls are present.
12108 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
12109   MachineRegisterInfo &MRI = MF.getRegInfo();
12110   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12111   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
12112   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12113   const SIInstrInfo *TII = ST.getInstrInfo();
12114 
12115   if (Info->isEntryFunction()) {
12116     // Callable functions have fixed registers used for stack access.
12117     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
12118   }
12119 
12120   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
12121                              Info->getStackPtrOffsetReg()));
12122   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
12123     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
12124 
12125   // We need to worry about replacing the default register with itself in case
12126   // of MIR testcases missing the MFI.
12127   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
12128     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
12129 
12130   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
12131     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
12132 
12133   Info->limitOccupancy(MF);
12134 
12135   if (ST.isWave32() && !MF.empty()) {
12136     for (auto &MBB : MF) {
12137       for (auto &MI : MBB) {
12138         TII->fixImplicitOperands(MI);
12139       }
12140     }
12141   }
12142 
12143   // FIXME: This is a hack to fixup AGPR classes to use the properly aligned
12144   // classes if required. Ideally the register class constraints would differ
12145   // per-subtarget, but there's no easy way to achieve that right now. This is
12146   // not a problem for VGPRs because the correctly aligned VGPR class is implied
12147   // from using them as the register class for legal types.
12148   if (ST.needsAlignedVGPRs()) {
12149     for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
12150       const Register Reg = Register::index2VirtReg(I);
12151       const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg);
12152       if (!RC)
12153         continue;
12154       int NewClassID = getAlignedAGPRClassID(RC->getID());
12155       if (NewClassID != -1)
12156         MRI.setRegClass(Reg, TRI->getRegClass(NewClassID));
12157     }
12158   }
12159 
12160   TargetLoweringBase::finalizeLowering(MF);
12161 }
12162 
12163 void SITargetLowering::computeKnownBitsForFrameIndex(
12164   const int FI, KnownBits &Known, const MachineFunction &MF) const {
12165   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
12166 
12167   // Set the high bits to zero based on the maximum allowed scratch size per
12168   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
12169   // calculation won't overflow, so assume the sign bit is never set.
12170   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
12171 }
12172 
12173 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
12174                                    KnownBits &Known, unsigned Dim) {
12175   unsigned MaxValue =
12176       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
12177   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
12178 }
12179 
12180 void SITargetLowering::computeKnownBitsForTargetInstr(
12181     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
12182     const MachineRegisterInfo &MRI, unsigned Depth) const {
12183   const MachineInstr *MI = MRI.getVRegDef(R);
12184   switch (MI->getOpcode()) {
12185   case AMDGPU::G_INTRINSIC: {
12186     switch (MI->getIntrinsicID()) {
12187     case Intrinsic::amdgcn_workitem_id_x:
12188       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
12189       break;
12190     case Intrinsic::amdgcn_workitem_id_y:
12191       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
12192       break;
12193     case Intrinsic::amdgcn_workitem_id_z:
12194       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
12195       break;
12196     case Intrinsic::amdgcn_mbcnt_lo:
12197     case Intrinsic::amdgcn_mbcnt_hi: {
12198       // These return at most the wavefront size - 1.
12199       unsigned Size = MRI.getType(R).getSizeInBits();
12200       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
12201       break;
12202     }
12203     case Intrinsic::amdgcn_groupstaticsize: {
12204       // We can report everything over the maximum size as 0. We can't report
12205       // based on the actual size because we don't know if it's accurate or not
12206       // at any given point.
12207       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
12208       break;
12209     }
12210     }
12211     break;
12212   }
12213   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
12214     Known.Zero.setHighBits(24);
12215     break;
12216   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
12217     Known.Zero.setHighBits(16);
12218     break;
12219   }
12220 }
12221 
12222 Align SITargetLowering::computeKnownAlignForTargetInstr(
12223   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
12224   unsigned Depth) const {
12225   const MachineInstr *MI = MRI.getVRegDef(R);
12226   switch (MI->getOpcode()) {
12227   case AMDGPU::G_INTRINSIC:
12228   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
12229     // FIXME: Can this move to generic code? What about the case where the call
12230     // site specifies a lower alignment?
12231     Intrinsic::ID IID = MI->getIntrinsicID();
12232     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
12233     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
12234     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
12235       return *RetAlign;
12236     return Align(1);
12237   }
12238   default:
12239     return Align(1);
12240   }
12241 }
12242 
12243 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12244   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
12245   const Align CacheLineAlign = Align(64);
12246 
12247   // Pre-GFX10 target did not benefit from loop alignment
12248   if (!ML || DisableLoopAlignment ||
12249       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
12250       getSubtarget()->hasInstFwdPrefetchBug())
12251     return PrefAlign;
12252 
12253   // On GFX10 I$ is 4 x 64 bytes cache lines.
12254   // By default prefetcher keeps one cache line behind and reads two ahead.
12255   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
12256   // behind and one ahead.
12257   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
12258   // If loop fits 64 bytes it always spans no more than two cache lines and
12259   // does not need an alignment.
12260   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
12261   // Else if loop is less or equal 192 bytes we need two lines behind.
12262 
12263   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
12264   const MachineBasicBlock *Header = ML->getHeader();
12265   if (Header->getAlignment() != PrefAlign)
12266     return Header->getAlignment(); // Already processed.
12267 
12268   unsigned LoopSize = 0;
12269   for (const MachineBasicBlock *MBB : ML->blocks()) {
12270     // If inner loop block is aligned assume in average half of the alignment
12271     // size to be added as nops.
12272     if (MBB != Header)
12273       LoopSize += MBB->getAlignment().value() / 2;
12274 
12275     for (const MachineInstr &MI : *MBB) {
12276       LoopSize += TII->getInstSizeInBytes(MI);
12277       if (LoopSize > 192)
12278         return PrefAlign;
12279     }
12280   }
12281 
12282   if (LoopSize <= 64)
12283     return PrefAlign;
12284 
12285   if (LoopSize <= 128)
12286     return CacheLineAlign;
12287 
12288   // If any of parent loops is surrounded by prefetch instructions do not
12289   // insert new for inner loop, which would reset parent's settings.
12290   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
12291     if (MachineBasicBlock *Exit = P->getExitBlock()) {
12292       auto I = Exit->getFirstNonDebugInstr();
12293       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
12294         return CacheLineAlign;
12295     }
12296   }
12297 
12298   MachineBasicBlock *Pre = ML->getLoopPreheader();
12299   MachineBasicBlock *Exit = ML->getExitBlock();
12300 
12301   if (Pre && Exit) {
12302     auto PreTerm = Pre->getFirstTerminator();
12303     if (PreTerm == Pre->begin() ||
12304         std::prev(PreTerm)->getOpcode() != AMDGPU::S_INST_PREFETCH)
12305       BuildMI(*Pre, PreTerm, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH))
12306           .addImm(1); // prefetch 2 lines behind PC
12307 
12308     auto ExitHead = Exit->getFirstNonDebugInstr();
12309     if (ExitHead == Exit->end() ||
12310         ExitHead->getOpcode() != AMDGPU::S_INST_PREFETCH)
12311       BuildMI(*Exit, ExitHead, DebugLoc(), TII->get(AMDGPU::S_INST_PREFETCH))
12312           .addImm(2); // prefetch 1 line behind PC
12313   }
12314 
12315   return CacheLineAlign;
12316 }
12317 
12318 LLVM_ATTRIBUTE_UNUSED
12319 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
12320   assert(N->getOpcode() == ISD::CopyFromReg);
12321   do {
12322     // Follow the chain until we find an INLINEASM node.
12323     N = N->getOperand(0).getNode();
12324     if (N->getOpcode() == ISD::INLINEASM ||
12325         N->getOpcode() == ISD::INLINEASM_BR)
12326       return true;
12327   } while (N->getOpcode() == ISD::CopyFromReg);
12328   return false;
12329 }
12330 
12331 bool SITargetLowering::isSDNodeSourceOfDivergence(
12332     const SDNode *N, FunctionLoweringInfo *FLI,
12333     LegacyDivergenceAnalysis *KDA) const {
12334   switch (N->getOpcode()) {
12335   case ISD::CopyFromReg: {
12336     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
12337     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
12338     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12339     Register Reg = R->getReg();
12340 
12341     // FIXME: Why does this need to consider isLiveIn?
12342     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
12343       return !TRI->isSGPRReg(MRI, Reg);
12344 
12345     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
12346       return KDA->isDivergent(V);
12347 
12348     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
12349     return !TRI->isSGPRReg(MRI, Reg);
12350   }
12351   case ISD::LOAD: {
12352     const LoadSDNode *L = cast<LoadSDNode>(N);
12353     unsigned AS = L->getAddressSpace();
12354     // A flat load may access private memory.
12355     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
12356   }
12357   case ISD::CALLSEQ_END:
12358     return true;
12359   case ISD::INTRINSIC_WO_CHAIN:
12360     return AMDGPU::isIntrinsicSourceOfDivergence(
12361         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
12362   case ISD::INTRINSIC_W_CHAIN:
12363     return AMDGPU::isIntrinsicSourceOfDivergence(
12364         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
12365   case AMDGPUISD::ATOMIC_CMP_SWAP:
12366   case AMDGPUISD::ATOMIC_INC:
12367   case AMDGPUISD::ATOMIC_DEC:
12368   case AMDGPUISD::ATOMIC_LOAD_FMIN:
12369   case AMDGPUISD::ATOMIC_LOAD_FMAX:
12370   case AMDGPUISD::BUFFER_ATOMIC_SWAP:
12371   case AMDGPUISD::BUFFER_ATOMIC_ADD:
12372   case AMDGPUISD::BUFFER_ATOMIC_SUB:
12373   case AMDGPUISD::BUFFER_ATOMIC_SMIN:
12374   case AMDGPUISD::BUFFER_ATOMIC_UMIN:
12375   case AMDGPUISD::BUFFER_ATOMIC_SMAX:
12376   case AMDGPUISD::BUFFER_ATOMIC_UMAX:
12377   case AMDGPUISD::BUFFER_ATOMIC_AND:
12378   case AMDGPUISD::BUFFER_ATOMIC_OR:
12379   case AMDGPUISD::BUFFER_ATOMIC_XOR:
12380   case AMDGPUISD::BUFFER_ATOMIC_INC:
12381   case AMDGPUISD::BUFFER_ATOMIC_DEC:
12382   case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP:
12383   case AMDGPUISD::BUFFER_ATOMIC_CSUB:
12384   case AMDGPUISD::BUFFER_ATOMIC_FADD:
12385   case AMDGPUISD::BUFFER_ATOMIC_FMIN:
12386   case AMDGPUISD::BUFFER_ATOMIC_FMAX:
12387     // Target-specific read-modify-write atomics are sources of divergence.
12388     return true;
12389   default:
12390     if (auto *A = dyn_cast<AtomicSDNode>(N)) {
12391       // Generic read-modify-write atomics are sources of divergence.
12392       return A->readMem() && A->writeMem();
12393     }
12394     return false;
12395   }
12396 }
12397 
12398 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
12399                                                EVT VT) const {
12400   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
12401   case MVT::f32:
12402     return hasFP32Denormals(DAG.getMachineFunction());
12403   case MVT::f64:
12404   case MVT::f16:
12405     return hasFP64FP16Denormals(DAG.getMachineFunction());
12406   default:
12407     return false;
12408   }
12409 }
12410 
12411 bool SITargetLowering::denormalsEnabledForType(LLT Ty,
12412                                                MachineFunction &MF) const {
12413   switch (Ty.getScalarSizeInBits()) {
12414   case 32:
12415     return hasFP32Denormals(MF);
12416   case 64:
12417   case 16:
12418     return hasFP64FP16Denormals(MF);
12419   default:
12420     return false;
12421   }
12422 }
12423 
12424 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
12425                                                     const SelectionDAG &DAG,
12426                                                     bool SNaN,
12427                                                     unsigned Depth) const {
12428   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
12429     const MachineFunction &MF = DAG.getMachineFunction();
12430     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
12431 
12432     if (Info->getMode().DX10Clamp)
12433       return true; // Clamped to 0.
12434     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
12435   }
12436 
12437   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
12438                                                             SNaN, Depth);
12439 }
12440 
12441 // Global FP atomic instructions have a hardcoded FP mode and do not support
12442 // FP32 denormals, and only support v2f16 denormals.
12443 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
12444   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
12445   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
12446   if (&Flt == &APFloat::IEEEsingle())
12447     return DenormMode == DenormalMode::getPreserveSign();
12448   return DenormMode == DenormalMode::getIEEE();
12449 }
12450 
12451 TargetLowering::AtomicExpansionKind
12452 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
12453   unsigned AS = RMW->getPointerAddressSpace();
12454   if (AS == AMDGPUAS::PRIVATE_ADDRESS)
12455     return AtomicExpansionKind::NotAtomic;
12456 
12457   auto ReportUnsafeHWInst = [&](TargetLowering::AtomicExpansionKind Kind) {
12458     OptimizationRemarkEmitter ORE(RMW->getFunction());
12459     LLVMContext &Ctx = RMW->getFunction()->getContext();
12460     SmallVector<StringRef> SSNs;
12461     Ctx.getSyncScopeNames(SSNs);
12462     auto MemScope = SSNs[RMW->getSyncScopeID()].empty()
12463                         ? "system"
12464                         : SSNs[RMW->getSyncScopeID()];
12465     ORE.emit([&]() {
12466       return OptimizationRemark(DEBUG_TYPE, "Passed", RMW)
12467              << "Hardware instruction generated for atomic "
12468              << RMW->getOperationName(RMW->getOperation())
12469              << " operation at memory scope " << MemScope
12470              << " due to an unsafe request.";
12471     });
12472     return Kind;
12473   };
12474 
12475   switch (RMW->getOperation()) {
12476   case AtomicRMWInst::FAdd: {
12477     Type *Ty = RMW->getType();
12478 
12479     // We don't have a way to support 16-bit atomics now, so just leave them
12480     // as-is.
12481     if (Ty->isHalfTy())
12482       return AtomicExpansionKind::None;
12483 
12484     if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy()))
12485       return AtomicExpansionKind::CmpXChg;
12486 
12487     if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) &&
12488          Subtarget->hasAtomicFaddInsts()) {
12489       if (Subtarget->hasGFX940Insts())
12490         return AtomicExpansionKind::None;
12491 
12492       // The amdgpu-unsafe-fp-atomics attribute enables generation of unsafe
12493       // floating point atomic instructions. May generate more efficient code,
12494       // but may not respect rounding and denormal modes, and may give incorrect
12495       // results for certain memory destinations.
12496       if (RMW->getFunction()
12497               ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12498               .getValueAsString() != "true")
12499         return AtomicExpansionKind::CmpXChg;
12500 
12501       if (Subtarget->hasGFX90AInsts()) {
12502         if (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS)
12503           return AtomicExpansionKind::CmpXChg;
12504 
12505         auto SSID = RMW->getSyncScopeID();
12506         if (SSID == SyncScope::System ||
12507             SSID == RMW->getContext().getOrInsertSyncScopeID("one-as"))
12508           return AtomicExpansionKind::CmpXChg;
12509 
12510         return ReportUnsafeHWInst(AtomicExpansionKind::None);
12511       }
12512 
12513       if (AS == AMDGPUAS::FLAT_ADDRESS)
12514         return AtomicExpansionKind::CmpXChg;
12515 
12516       return RMW->use_empty() ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12517                               : AtomicExpansionKind::CmpXChg;
12518     }
12519 
12520     // DS FP atomics do respect the denormal mode, but the rounding mode is
12521     // fixed to round-to-nearest-even.
12522     // The only exception is DS_ADD_F64 which never flushes regardless of mode.
12523     if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomicAdd()) {
12524       if (!Ty->isDoubleTy())
12525         return AtomicExpansionKind::None;
12526 
12527       if (fpModeMatchesGlobalFPAtomicMode(RMW))
12528         return AtomicExpansionKind::None;
12529 
12530       return RMW->getFunction()
12531                          ->getFnAttribute("amdgpu-unsafe-fp-atomics")
12532                          .getValueAsString() == "true"
12533                  ? ReportUnsafeHWInst(AtomicExpansionKind::None)
12534                  : AtomicExpansionKind::CmpXChg;
12535     }
12536 
12537     return AtomicExpansionKind::CmpXChg;
12538   }
12539   default:
12540     break;
12541   }
12542 
12543   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
12544 }
12545 
12546 TargetLowering::AtomicExpansionKind
12547 SITargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
12548   return LI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12549              ? AtomicExpansionKind::NotAtomic
12550              : AtomicExpansionKind::None;
12551 }
12552 
12553 TargetLowering::AtomicExpansionKind
12554 SITargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
12555   return SI->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12556              ? AtomicExpansionKind::NotAtomic
12557              : AtomicExpansionKind::None;
12558 }
12559 
12560 TargetLowering::AtomicExpansionKind
12561 SITargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *CmpX) const {
12562   return CmpX->getPointerAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS
12563              ? AtomicExpansionKind::NotAtomic
12564              : AtomicExpansionKind::None;
12565 }
12566 
12567 const TargetRegisterClass *
12568 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
12569   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
12570   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
12571   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
12572     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
12573                                                : &AMDGPU::SReg_32RegClass;
12574   if (!TRI->isSGPRClass(RC) && !isDivergent)
12575     return TRI->getEquivalentSGPRClass(RC);
12576   else if (TRI->isSGPRClass(RC) && isDivergent)
12577     return TRI->getEquivalentVGPRClass(RC);
12578 
12579   return RC;
12580 }
12581 
12582 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
12583 // uniform values (as produced by the mask results of control flow intrinsics)
12584 // used outside of divergent blocks. The phi users need to also be treated as
12585 // always uniform.
12586 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
12587                       unsigned WaveSize) {
12588   // FIXME: We assume we never cast the mask results of a control flow
12589   // intrinsic.
12590   // Early exit if the type won't be consistent as a compile time hack.
12591   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
12592   if (!IT || IT->getBitWidth() != WaveSize)
12593     return false;
12594 
12595   if (!isa<Instruction>(V))
12596     return false;
12597   if (!Visited.insert(V).second)
12598     return false;
12599   bool Result = false;
12600   for (auto U : V->users()) {
12601     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
12602       if (V == U->getOperand(1)) {
12603         switch (Intrinsic->getIntrinsicID()) {
12604         default:
12605           Result = false;
12606           break;
12607         case Intrinsic::amdgcn_if_break:
12608         case Intrinsic::amdgcn_if:
12609         case Intrinsic::amdgcn_else:
12610           Result = true;
12611           break;
12612         }
12613       }
12614       if (V == U->getOperand(0)) {
12615         switch (Intrinsic->getIntrinsicID()) {
12616         default:
12617           Result = false;
12618           break;
12619         case Intrinsic::amdgcn_end_cf:
12620         case Intrinsic::amdgcn_loop:
12621           Result = true;
12622           break;
12623         }
12624       }
12625     } else {
12626       Result = hasCFUser(U, Visited, WaveSize);
12627     }
12628     if (Result)
12629       break;
12630   }
12631   return Result;
12632 }
12633 
12634 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
12635                                                const Value *V) const {
12636   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
12637     if (CI->isInlineAsm()) {
12638       // FIXME: This cannot give a correct answer. This should only trigger in
12639       // the case where inline asm returns mixed SGPR and VGPR results, used
12640       // outside the defining block. We don't have a specific result to
12641       // consider, so this assumes if any value is SGPR, the overall register
12642       // also needs to be SGPR.
12643       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
12644       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
12645           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
12646       for (auto &TC : TargetConstraints) {
12647         if (TC.Type == InlineAsm::isOutput) {
12648           ComputeConstraintToUse(TC, SDValue());
12649           const TargetRegisterClass *RC = getRegForInlineAsmConstraint(
12650               SIRI, TC.ConstraintCode, TC.ConstraintVT).second;
12651           if (RC && SIRI->isSGPRClass(RC))
12652             return true;
12653         }
12654       }
12655     }
12656   }
12657   SmallPtrSet<const Value *, 16> Visited;
12658   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
12659 }
12660 
12661 std::pair<InstructionCost, MVT>
12662 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
12663                                           Type *Ty) const {
12664   std::pair<InstructionCost, MVT> Cost =
12665       TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
12666   auto Size = DL.getTypeSizeInBits(Ty);
12667   // Maximum load or store can handle 8 dwords for scalar and 4 for
12668   // vector ALU. Let's assume anything above 8 dwords is expensive
12669   // even if legal.
12670   if (Size <= 256)
12671     return Cost;
12672 
12673   Cost.first += (Size + 255) / 256;
12674   return Cost;
12675 }
12676 
12677 bool SITargetLowering::hasMemSDNodeUser(SDNode *N) const {
12678   SDNode::use_iterator I = N->use_begin(), E = N->use_end();
12679   for (; I != E; ++I) {
12680     if (MemSDNode *M = dyn_cast<MemSDNode>(*I)) {
12681       if (getBasePtrIndex(M) == I.getOperandNo())
12682         return true;
12683     }
12684   }
12685   return false;
12686 }
12687 
12688 bool SITargetLowering::isReassocProfitable(SelectionDAG &DAG, SDValue N0,
12689                                            SDValue N1) const {
12690   if (!N0.hasOneUse())
12691     return false;
12692   // Take care of the opportunity to keep N0 uniform
12693   if (N0->isDivergent() || !N1->isDivergent())
12694     return true;
12695   // Check if we have a good chance to form the memory access pattern with the
12696   // base and offset
12697   return (DAG.isBaseWithConstantOffset(N0) &&
12698           hasMemSDNodeUser(*N0->use_begin()));
12699 }
12700 
12701 MachineMemOperand::Flags
12702 SITargetLowering::getTargetMMOFlags(const Instruction &I) const {
12703   // Propagate metadata set by AMDGPUAnnotateUniformValues to the MMO of a load.
12704   if (I.getMetadata("amdgpu.noclobber"))
12705     return MONoClobber;
12706   return MachineMemOperand::MONone;
12707 }
12708